diff --git a/src/main/java/net/minecraftforge/classloading/FMLForgePlugin.java b/src/main/java/net/minecraftforge/classloading/FMLForgePlugin.java index c26924404..c1b962646 100644 --- a/src/main/java/net/minecraftforge/classloading/FMLForgePlugin.java +++ b/src/main/java/net/minecraftforge/classloading/FMLForgePlugin.java @@ -40,7 +40,7 @@ public class FMLForgePlugin implements IFMLLoadingPlugin @Override public String getModContainerClass() { - return "net.minecraftforge.common.ForgeModContainer"; + return "net.minecraftforge.common.ForgeMod"; } @Override diff --git a/src/main/java/net/minecraftforge/client/CloudRenderer.java b/src/main/java/net/minecraftforge/client/CloudRenderer.java index 68a420eab..89f1764e2 100644 --- a/src/main/java/net/minecraftforge/client/CloudRenderer.java +++ b/src/main/java/net/minecraftforge/client/CloudRenderer.java @@ -270,7 +270,7 @@ public class CloudRenderer implements ISelectiveResourceReloadListener public void checkSettings() { - boolean newEnabled = ForgeModContainer.forgeCloudsEnabled + boolean newEnabled = ForgeMod.forgeCloudsEnabled && mc.gameSettings.shouldRenderClouds() != 0 && mc.world != null && mc.world.provider.isSurfaceWorld(); @@ -489,4 +489,29 @@ public class CloudRenderer implements ISelectiveResourceReloadListener reloadTextures(); } } + + private static CloudRenderer cloudRenderer; + private static CloudRenderer getCloudRenderer() + { + if (cloudRenderer == null) + cloudRenderer = new CloudRenderer(); + return cloudRenderer; + } + + public static void updateCloudSettings() + { + getCloudRenderer().checkSettings(); + } + + public static boolean renderClouds(int cloudTicks, float partialTicks, WorldClient world, Minecraft client) + { + IRenderHandler renderer = world.provider.getCloudRenderer(); + if (renderer != null) + { + renderer.render(partialTicks, world, client); + return true; + } + return getCloudRenderer().render(cloudTicks, partialTicks); + } + } diff --git a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java index 60db7b275..d89504f1a 100644 --- a/src/main/java/net/minecraftforge/client/ForgeHooksClient.java +++ b/src/main/java/net/minecraftforge/client/ForgeHooksClient.java @@ -125,7 +125,7 @@ import net.minecraftforge.client.model.animation.Animation; import net.minecraftforge.client.resource.IResourceType; import net.minecraftforge.client.resource.SelectiveReloadStateHandler; import net.minecraftforge.client.resource.VanillaResourceType; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.model.IModelPart; @@ -284,7 +284,7 @@ public class ForgeHooksClient skyInit = true; GameSettings settings = Minecraft.getMinecraft().gameSettings; - int[] ranges = ForgeModContainer.blendRanges; + int[] ranges = ForgeMod.blendRanges; int distance = 0; if (settings.fancyGraphics && ranges.length > 0) { diff --git a/src/main/java/net/minecraftforge/client/IRenderHandler.java b/src/main/java/net/minecraftforge/client/IRenderHandler.java index 0425096be..978f35638 100644 --- a/src/main/java/net/minecraftforge/client/IRenderHandler.java +++ b/src/main/java/net/minecraftforge/client/IRenderHandler.java @@ -19,13 +19,13 @@ package net.minecraftforge.client; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; +import net.minecraftforge.api.distmarker.OnlyIn; public abstract class IRenderHandler { - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public abstract void render(float partialTicks, WorldClient world, Minecraft mc); } diff --git a/src/main/java/net/minecraftforge/client/event/GuiScreenEvent.java b/src/main/java/net/minecraftforge/client/event/GuiScreenEvent.java index 14daae971..4a5b4b56f 100644 --- a/src/main/java/net/minecraftforge/client/event/GuiScreenEvent.java +++ b/src/main/java/net/minecraftforge/client/event/GuiScreenEvent.java @@ -24,6 +24,8 @@ import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.InventoryEffectRenderer; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.lwjgl.input.Mouse; import net.minecraft.client.gui.GuiButton; @@ -32,15 +34,13 @@ import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.eventbus.api.Cancelable; import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; /** * Event classes for GuiScreen events. * * @author bspkrs */ -@SideOnly(Side.CLIENT) +@OnlyIn(Dist.CLIENT) public class GuiScreenEvent extends Event { private final GuiScreen gui; diff --git a/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java b/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java index 1472198f5..c1fb8b6d2 100644 --- a/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java +++ b/src/main/java/net/minecraftforge/client/gui/ForgeGuiFactory.java @@ -31,7 +31,7 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.common.ForgeChunkManager; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; @@ -50,7 +50,7 @@ import net.minecraftforge.fml.client.config.GuiConfigEntries.BooleanEntry; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.ModContainer; -import static net.minecraftforge.common.ForgeModContainer.VERSION_CHECK_CAT; +import static net.minecraftforge.common.ForgeMod.VERSION_CHECK_CAT; /** * This is the base GuiConfig screen class that all the other Forge-specific config screens will be called from. @@ -87,8 +87,8 @@ import static net.minecraftforge.common.ForgeModContainer.VERSION_CHECK_CAT; * - etc. * * Other things to check out: - * ForgeModContainer.syncConfig() - * ForgeModContainer.onConfigChanged() + * ForgeMod.syncConfig() + * ForgeMod.onConfigChanged() * ForgeChunkManager.syncConfigDefaults() * ForgeChunkManager.loadConfiguration() */ @@ -141,10 +141,10 @@ public class ForgeGuiFactory implements IModGuiFactory // This GuiConfig object specifies the configID of the object and as such will force-save when it is closed. The parent // GuiConfig object's entryList will also be refreshed to reflect the changes. return new GuiConfig(this.owningScreen, - (new ConfigElement(ForgeModContainer.getConfig().getCategory(Configuration.CATEGORY_GENERAL))).getChildElements(), + (new ConfigElement(ForgeMod.getConfig().getCategory(Configuration.CATEGORY_GENERAL))).getChildElements(), this.owningScreen.modID, Configuration.CATEGORY_GENERAL, this.configElement.requiresWorldRestart() || this.owningScreen.allRequireWorldRestart, this.configElement.requiresMcRestart() || this.owningScreen.allRequireMcRestart, - GuiConfig.getAbridgedConfigPath(ForgeModContainer.getConfig().toString())); + GuiConfig.getAbridgedConfigPath(ForgeMod.getConfig().toString())); } } @@ -165,10 +165,10 @@ public class ForgeGuiFactory implements IModGuiFactory // This GuiConfig object specifies the configID of the object and as such will force-save when it is closed. The parent // GuiConfig object's entryList will also be refreshed to reflect the changes. return new GuiConfig(this.owningScreen, - (new ConfigElement(ForgeModContainer.getConfig().getCategory(Configuration.CATEGORY_CLIENT))).getChildElements(), + (new ConfigElement(ForgeMod.getConfig().getCategory(Configuration.CATEGORY_CLIENT))).getChildElements(), this.owningScreen.modID, Configuration.CATEGORY_CLIENT, this.configElement.requiresWorldRestart() || this.owningScreen.allRequireWorldRestart, this.configElement.requiresMcRestart() || this.owningScreen.allRequireMcRestart, - GuiConfig.getAbridgedConfigPath(ForgeModContainer.getConfig().toString())); + GuiConfig.getAbridgedConfigPath(ForgeMod.getConfig().toString())); } } @@ -216,18 +216,18 @@ public class ForgeGuiFactory implements IModGuiFactory @Override protected GuiScreen buildChildScreen() { - ConfigCategory cfg = ForgeModContainer.getConfig().getCategory(VERSION_CHECK_CAT); + ConfigCategory cfg = ForgeMod.getConfig().getCategory(VERSION_CHECK_CAT); Map values = new HashMap(cfg.getValues()); values.remove("Global"); - Property global = ForgeModContainer.getConfig().get(VERSION_CHECK_CAT, "Global", true); + Property global = ForgeMod.getConfig().get(VERSION_CHECK_CAT, "Global", true); List props = new ArrayList(); for (ModContainer mod : ForgeVersion.gatherMods().keySet()) { values.remove(mod.getModId()); - props.add(ForgeModContainer.getConfig().get(VERSION_CHECK_CAT, mod.getModId(), true)); //Get or make the value in the config + props.add(ForgeMod.getConfig().get(VERSION_CHECK_CAT, mod.getModId(), true)); //Get or make the value in the config } props.addAll(values.values()); // Add any left overs from the config props.sort(Comparator.comparing(Property::getName)); @@ -244,7 +244,7 @@ public class ForgeGuiFactory implements IModGuiFactory return new GuiConfig(this.owningScreen, list, this.owningScreen.modID, VERSION_CHECK_CAT, true, true, - GuiConfig.getAbridgedConfigPath(ForgeModContainer.getConfig().toString())); + GuiConfig.getAbridgedConfigPath(ForgeMod.getConfig().toString())); } } diff --git a/src/main/java/net/minecraftforge/client/gui/NotificationModUpdateScreen.java b/src/main/java/net/minecraftforge/client/gui/NotificationModUpdateScreen.java index 362f8240f..a3d53900f 100644 --- a/src/main/java/net/minecraftforge/client/gui/NotificationModUpdateScreen.java +++ b/src/main/java/net/minecraftforge/client/gui/NotificationModUpdateScreen.java @@ -25,15 +25,15 @@ import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.ForgeVersion.Status; import net.minecraftforge.fml.VersionChecker; import net.minecraftforge.fml.client.ClientModLoader; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; -@SideOnly(Side.CLIENT) +@OnlyIn(Dist.CLIENT) public class NotificationModUpdateScreen extends GuiScreen { @@ -64,7 +64,7 @@ public class NotificationModUpdateScreen extends GuiScreen @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { - if (showNotification == null || !showNotification.shouldDraw() || ForgeModContainer.disableVersionCheck) + if (showNotification == null || !showNotification.shouldDraw() || ForgeMod.disableVersionCheck) { return; } diff --git a/src/main/java/net/minecraftforge/client/model/FancyMissingModel.java b/src/main/java/net/minecraftforge/client/model/FancyMissingModel.java index 36b81dc85..094a210f3 100644 --- a/src/main/java/net/minecraftforge/client/model/FancyMissingModel.java +++ b/src/main/java/net/minecraftforge/client/model/FancyMissingModel.java @@ -20,7 +20,7 @@ package net.minecraftforge.client.model; import java.util.function.Function; -import java.util.Optional; + import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -36,7 +36,7 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; import org.apache.commons.lang3.tuple.Pair; @@ -201,7 +201,7 @@ final class FancyMissingModel implements IModel case HEAD: break; case GUI: - if (ForgeModContainer.zoomInMissingModelTextInGui) + if (ForgeMod.zoomInMissingModelTextInGui) { transform = new TRSRTransformation(null, new Quat4f(1, 1, 1, 1), new Vector3f(4, 4, 4), null); big = false; diff --git a/src/main/java/net/minecraftforge/client/model/ModelLoader.java b/src/main/java/net/minecraftforge/client/model/ModelLoader.java index bc0b88a6e..7ed46494e 100644 --- a/src/main/java/net/minecraftforge/client/model/ModelLoader.java +++ b/src/main/java/net/minecraftforge/client/model/ModelLoader.java @@ -72,7 +72,7 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.registry.IRegistry; import net.minecraftforge.client.model.animation.AnimationItemOverrideList; import net.minecraftforge.client.model.animation.ModelBlockAnimation; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.Models; import net.minecraftforge.common.model.TRSRTransformation; @@ -81,7 +81,6 @@ import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.Properties; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.client.ClientModLoader; -import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.ProgressManager; import net.minecraftforge.fml.common.ProgressManager.ProgressBar; diff --git a/src/main/java/net/minecraftforge/client/model/pipeline/ForgeBlockModelRenderer.java b/src/main/java/net/minecraftforge/client/model/pipeline/ForgeBlockModelRenderer.java index 1200d2bb8..455f5f2f6 100644 --- a/src/main/java/net/minecraftforge/client/model/pipeline/ForgeBlockModelRenderer.java +++ b/src/main/java/net/minecraftforge/client/model/pipeline/ForgeBlockModelRenderer.java @@ -30,7 +30,7 @@ import net.minecraft.client.renderer.color.BlockColors; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; public class ForgeBlockModelRenderer extends BlockModelRenderer { @@ -51,7 +51,7 @@ public class ForgeBlockModelRenderer extends BlockModelRenderer @Override public boolean renderModelFlat(IBlockAccess world, IBakedModel model, IBlockState state, BlockPos pos, BufferBuilder buffer, boolean checkSides, long rand) { - if(ForgeModContainer.forgeLightPipelineEnabled) + if(ForgeMod.forgeLightPipelineEnabled) { if(buffer != lastRendererFlat.get()) { @@ -72,7 +72,7 @@ public class ForgeBlockModelRenderer extends BlockModelRenderer @Override public boolean renderModelSmooth(IBlockAccess world, IBakedModel model, IBlockState state, BlockPos pos, BufferBuilder buffer, boolean checkSides, long rand) { - if(ForgeModContainer.forgeLightPipelineEnabled) + if(ForgeMod.forgeLightPipelineEnabled) { if(buffer != lastRendererSmooth.get()) { diff --git a/src/main/java/net/minecraftforge/common/DimensionManager.java b/src/main/java/net/minecraftforge/common/DimensionManager.java index 4ae05be68..1894ed161 100644 --- a/src/main/java/net/minecraftforge/common/DimensionManager.java +++ b/src/main/java/net/minecraftforge/common/DimensionManager.java @@ -57,12 +57,17 @@ import net.minecraft.world.WorldServer; import net.minecraft.world.WorldServerMulti; import net.minecraft.world.storage.ISaveHandler; import net.minecraftforge.event.world.WorldEvent; -import net.minecraftforge.fml.common.FMLLog; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable; public class DimensionManager { + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker DIMMGR = MarkerManager.getMarker("DIMS"); private static class Dimension { private final DimensionType type; @@ -187,11 +192,11 @@ public class DimensionManager int leakCount = leakedWorlds.count(System.identityHashCode(w)); if (leakCount == 5) { - FMLLog.log.debug("The world {} ({}) may have leaked: first encounter (5 occurrences).\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName()); + LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: first encounter (5 occurrences).\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName()); } else if (leakCount % 5 == 0) { - FMLLog.log.debug("The world {} ({}) may have leaked: seen {} times.\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName(), leakCount); + LOGGER.debug(DIMMGR,"The world {} ({}) may have leaked: seen {} times.\n", Integer.toHexString(System.identityHashCode(w)), w.getWorldInfo().getWorldName(), leakCount); } } } @@ -210,13 +215,13 @@ public class DimensionManager worlds.put(id, world); weakWorldMap.put(world, world); server.worldTickTimes.put(id, new long[100]); - FMLLog.log.info("Loading dimension {} ({}) ({})", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer()); + LOGGER.info(DIMMGR,"Loading dimension {} ({}) ({})", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer()); } else { worlds.remove(id); server.worldTickTimes.remove(id); - FMLLog.log.info("Unloading dimension {}", id); + LOGGER.info(DIMMGR,"Unloading dimension {}", id); } ArrayList tmp = new ArrayList(); @@ -253,7 +258,7 @@ public class DimensionManager } catch (Exception e) { - FMLLog.log.error("Cannot Hotload Dim: {}", dim, e); + LOGGER.error(DIMMGR,"Cannot Hotload Dim: {}", dim, e); return; // If a provider hasn't been registered then we can't hotload the dim } MinecraftServer mcServer = overworld.getMinecraftServer(); @@ -321,7 +326,7 @@ public class DimensionManager } catch (Exception e) { - FMLLog.log.error("An error occurred trying to create an instance of WorldProvider {} ({})", + LOGGER.error(DIMMGR,"An error occurred trying to create an instance of WorldProvider {} ({})", dim, getProviderType(dim), e); throw new RuntimeException(e); } @@ -357,7 +362,7 @@ public class DimensionManager if (unloadQueue.add(id)) { - FMLLog.log.debug("Queueing dimension {} to unload", id); + LOGGER.debug(DIMMGR,"Queueing dimension {} to unload", id); } } @@ -376,7 +381,7 @@ public class DimensionManager { int id = queueIterator.nextInt(); Dimension dimension = dimensions.get(id); - if (dimension.ticksWaited < ForgeModContainer.dimensionUnloadQueueDelay) + if (dimension.ticksWaited < ForgeMod.dimensionUnloadQueueDelay) { dimension.ticksWaited++; continue; @@ -387,7 +392,7 @@ public class DimensionManager // Don't unload the world if the status changed if (w == null || !canUnloadWorld(w)) { - FMLLog.log.debug("Aborting unload for dimension {} as status changed", id); + LOGGER.debug(DIMMGR,"Aborting unload for dimension {} as status changed", id); continue; } try @@ -396,7 +401,7 @@ public class DimensionManager } catch (MinecraftException e) { - FMLLog.log.error("Caught an exception while saving all chunks:", e); + LOGGER.error(DIMMGR,"Caught an exception while saving all chunks:", e); } finally { diff --git a/src/main/java/net/minecraftforge/common/ForgeChunkManager.java b/src/main/java/net/minecraftforge/common/ForgeChunkManager.java index 678f8beb8..6d5f53d4a 100644 --- a/src/main/java/net/minecraftforge/common/ForgeChunkManager.java +++ b/src/main/java/net/minecraftforge/common/ForgeChunkManager.java @@ -49,6 +49,7 @@ import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.common.util.Constants; +import net.minecraftforge.fml.ServerLifecycleHooks; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; @@ -626,7 +627,7 @@ public class ForgeChunkManager dormantChunkCache.remove(world); } // integrated server is shutting down - if (!FMLCommonHandler.instance().getMinecraftServerInstance().isServerRunning()) + if (!ServerLifecycleHooks.getCurrentServer().isServerRunning()) { playerTickets.clear(); tickets.clear(); diff --git a/src/main/java/net/minecraftforge/common/ForgeHooks.java b/src/main/java/net/minecraftforge/common/ForgeHooks.java index 54f2c3627..f3eeddc77 100644 --- a/src/main/java/net/minecraftforge/common/ForgeHooks.java +++ b/src/main/java/net/minecraftforge/common/ForgeHooks.java @@ -24,13 +24,16 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Deque; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Random; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -114,7 +117,6 @@ import net.minecraft.world.storage.loot.LootEntry; import net.minecraft.world.storage.loot.LootTable; import net.minecraft.world.storage.loot.LootTableManager; import net.minecraft.world.storage.loot.conditions.LootCondition; -import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.event.AnvilUpdateEvent; import net.minecraftforge.event.DifficultyChangeEvent; @@ -142,13 +144,17 @@ import net.minecraftforge.event.entity.player.AdvancementEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.NoteBlockEvent; import net.minecraftforge.fluids.IFluidBlock; -import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.LoaderState; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher.ConnectionType; import net.minecraftforge.fml.common.registry.ForgeRegistries; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.network.ConnectionType; +import net.minecraftforge.fml.loading.moddiscovery.ModFile; +import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo; +import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.RegistryManager; @@ -157,10 +163,15 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; public class ForgeHooks { + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker FORGEHOOKS = MarkerManager.getMarker("FORGEHOOKS"); //TODO: Loot tables? static class SeedEntry extends WeightedRandom.Item { @@ -645,7 +656,7 @@ public class ForgeHooks { boolean isSpectator = (entity instanceof EntityPlayer && ((EntityPlayer)entity).isSpectator()); if (isSpectator) return false; - if (!ForgeModContainer.fullBoundingBoxLadders) + if (!ForgeMod.fullBoundingBoxLadders) { return state.getBlock().isLadder(state, world, pos, entity); } @@ -1304,13 +1315,10 @@ public class ForgeHooks public static boolean loadAdvancements(Map map) { boolean errored = false; - setActiveModContainer(null); - //Loader.instance().getActiveModList().forEach((mod) -> loadFactories(mod)); - for (ModContainer mod : Loader.instance().getActiveModList()) + for (ModFileInfo mod : ModList.get().getModFiles()) { - errored |= !loadAdvancements(map, mod); + errored |= !loadAdvancements(map, mod.getFile()); } - setActiveModContainer(null); return errored; } @@ -1326,7 +1334,7 @@ public class ForgeHooks return null; } - private static void setActiveModContainer(ModContainer mod) + private static boolean loadAdvancements(Map map, ModFile mod) { if (Loader.instance().getLoaderState() != LoaderState.NOINIT) //Unit Tests.. Loader.instance().setActiveModContainer(mod); @@ -1357,12 +1365,12 @@ public class ForgeHooks } catch (JsonParseException jsonparseexception) { - FMLLog.log.error("Parsing error loading built-in advancement " + key, (Throwable)jsonparseexception); + LOGGER.error("Parsing error loading built-in advancement " + key, (Throwable)jsonparseexception); return false; } catch (IOException ioexception) { - FMLLog.log.error("Couldn't read advancement " + key + " from " + file, (Throwable)ioexception); + LOGGER.error("Couldn't read advancement " + key + " from " + file, (Throwable)ioexception); return false; } finally @@ -1385,13 +1393,11 @@ public class ForgeHooks if (type == ConnectionType.VANILLA) { IForgeRegistry vanilla = RegistryManager.VANILLA.getRegistry(IRecipe.class); - if (recipes.size() > 0) - recipes = recipes.stream().filter(e -> vanilla.containsValue(e)).collect(Collectors.toList()); - if (display.size() > 0) - display = display.stream().filter(e -> vanilla.containsValue(e)).collect(Collectors.toList()); + recipes = recipes.stream().filter(vanilla::containsValue).collect(Collectors.toList()); + display = display.stream().filter(vanilla::containsValue).collect(Collectors.toList()); } - if (recipes.size() > 0 || display.size() > 0) + if (!recipes.isEmpty() || !display.isEmpty()) connection.sendPacket(new SPacketRecipeBook(state, recipes, display, isGuiOpen, isFilteringCraftable)); } diff --git a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java index f02e20021..37b361055 100644 --- a/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java +++ b/src/main/java/net/minecraftforge/common/ForgeInternalHandler.java @@ -24,6 +24,7 @@ import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.WorldServer; +import net.minecraftforge.client.CloudRenderer; import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.world.WorldEvent; @@ -93,7 +94,7 @@ public class ForgeInternalHandler public void checkSettings(ClientTickEvent event) { if (event.phase == Phase.END) - FMLClientHandler.instance().updateCloudSettings(); + CloudRenderer.updateCloudSettings(); } } diff --git a/src/main/java/net/minecraftforge/common/ForgeMod.java b/src/main/java/net/minecraftforge/common/ForgeMod.java new file mode 100644 index 000000000..b2ffbfdd1 --- /dev/null +++ b/src/main/java/net/minecraftforge/common/ForgeMod.java @@ -0,0 +1,456 @@ +/* + * Minecraft Forge + * Copyright (c) 2016. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.common; + +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.biome.Biome; +import static net.minecraftforge.common.config.Configuration.CATEGORY_CLIENT; +import static net.minecraftforge.common.config.Configuration.CATEGORY_GENERAL; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import net.minecraftforge.fml.ModLoadingClassLoader; +import net.minecraftforge.fml.VersionChecker; +import net.minecraftforge.fml.WorldPersistenceHooks; +import net.minecraftforge.fml.javafmlmod.FMLModContainer; +import net.minecraftforge.fml.javafmlmod.ModLoadingContext; +import net.minecraftforge.fml.loading.DefaultModInfos; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import net.minecraft.item.Item; +import net.minecraft.item.crafting.Ingredient; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.stats.StatList; +import net.minecraft.world.storage.SaveHandler; +import net.minecraft.world.storage.WorldInfo; +import net.minecraftforge.common.config.ConfigCategory; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.common.model.animation.CapabilityAnimation; +import net.minecraftforge.energy.CapabilityEnergy; +import net.minecraftforge.event.RegistryEvent; +import net.minecraftforge.event.RegistryEvent.MissingMappings; +import net.minecraftforge.event.terraingen.DeferredBiomeDecorator; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +import net.minecraftforge.fml.common.registry.ForgeRegistries; +import net.minecraftforge.items.CapabilityItemHandler; +import net.minecraftforge.fluids.UniversalBucket; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.RecipeSorter; +import net.minecraftforge.server.command.ForgeCommand; + +import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.FMLLog; +import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; +import net.minecraftforge.fml.common.event.FMLModIdMappingEvent; +import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.PlayerEvent; + +public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook +{ + public static final String VERSION_CHECK_CAT = "version_checking"; + public static int clumpingThreshold = 64; + public static boolean removeErroringEntities = false; + public static boolean removeErroringTileEntities = false; + public static boolean fullBoundingBoxLadders = false; + public static double zombieSummonBaseChance = 0.1; + public static int[] blendRanges = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34 }; + public static float zombieBabyChance = 0.05f; + public static boolean shouldSortRecipies = true; + public static boolean disableVersionCheck = false; + public static boolean forgeLightPipelineEnabled = true; + @Deprecated // TODO remove in 1.13 + public static boolean replaceVanillaBucketModel = true; + public static boolean zoomInMissingModelTextInGui = false; + public static boolean forgeCloudsEnabled = true; + public static boolean disableStairSlabCulling = false; // Also known as the "DontCullStairsBecauseIUseACrappyTexturePackThatBreaksBasicBlockShapesSoICantTrustBasicBlockCulling" flag + public static boolean alwaysSetupTerrainOffThread = false; // In RenderGlobal.setupTerrain, always force the chunk render updates to be queued to the thread + public static int dimensionUnloadQueueDelay = 0; + public static boolean logCascadingWorldGeneration = true; // see Chunk#logCascadingWorldGeneration() + public static boolean fixVanillaCascading = false; // There are various places in vanilla that cause cascading worldgen. Enabling this WILL change where blocks are placed to prevent this. + // DO NOT contact Forge about worldgen not 'matching' vanilla if this flag is set. + + static final Logger log = LogManager.getLogger(ForgeVersion.MOD_ID); + + private static Configuration config; + private static ForgeMod INSTANCE; + public static ForgeMod getInstance() + { + return INSTANCE; + } + + private URL updateJSONUrl = null; + public UniversalBucket universalBucket; + + public ForgeMod() + { + INSTANCE = this; + ModLoadingContext.get().getModEventBus().addListener(this::preInit); + ModLoadingContext.get().getModEventBus().addListener(this::postInit); + ModLoadingContext.get().getModEventBus().addListener(this::onAvailable); + } + + public static Configuration getConfig() + { + return config; + } + + private static void remapGeneralPropertyToClient(String key) + { + ConfigCategory GENERAL = config.getCategory(CATEGORY_GENERAL); + if (GENERAL.containsKey(key)) + { + FMLLog.log.debug("Remapping property {} from category general to client", key); + Property property = GENERAL.get(key); + GENERAL.remove(key); + config.getCategory(CATEGORY_CLIENT).put(key, property); + } + } + + /** + * Synchronizes the local fields with the values in the Configuration object. + */ + private static void syncConfig(boolean load) + { + // By adding a property order list we are defining the order that the properties will appear both in the config file and on the GUIs. + // Property order lists are defined per-ConfigCategory. + List propOrder = new ArrayList(); + + if (!config.isChild) + { + if (load) + { + config.load(); + } + Property enableGlobalCfg = config.get(Configuration.CATEGORY_GENERAL, "enableGlobalConfig", false).setShowInGui(false); + if (enableGlobalCfg.getBoolean(false)) + { + Configuration.enableGlobalConfig(); + } + } + + Property prop; + + // clean up old properties that are not used anymore + if (config.getCategory(CATEGORY_GENERAL).containsKey("defaultSpawnFuzz")) config.getCategory(CATEGORY_GENERAL).remove("defaultSpawnFuzz"); + if (config.getCategory(CATEGORY_GENERAL).containsKey("spawnHasFuzz")) config.getCategory(CATEGORY_GENERAL).remove("spawnHasFuzz"); + if (config.getCategory(CATEGORY_GENERAL).containsKey("disableStitchedFileSaving")) config.getCategory(CATEGORY_GENERAL).remove("disableStitchedFileSaving"); + if (config.getCategory(CATEGORY_CLIENT).containsKey("java8Reminder")) config.getCategory(CATEGORY_CLIENT).remove("java8Reminder"); + if (config.getCategory(CATEGORY_CLIENT).containsKey("replaceVanillaBucketModel")) config.getCategory(CATEGORY_CLIENT).remove("replaceVanillaBucketModel"); + + // remap properties wrongly listed as general properties to client properties + remapGeneralPropertyToClient("biomeSkyBlendRange"); + remapGeneralPropertyToClient("forgeLightPipelineEnabled"); + + prop = config.get(CATEGORY_GENERAL, "disableVersionCheck", false); + prop.setComment("Set to true to disable Forge's version check mechanics. Forge queries a small json file on our server for version information. For more details see the ForgeVersion class in our github."); + // Language keys are a good idea to implement if you are using config GUIs. This allows you to use a .lang file that will hold the + // "pretty" version of the property name as well as allow others to provide their own localizations. + // This language key is also used to get the tooltip for a property. The tooltip language key is langKey + ".tooltip". + // If no tooltip language key is defined in your .lang file, the tooltip will default to the property comment field. + prop.setLanguageKey("forge.configgui.disableVersionCheck"); + disableVersionCheck = prop.getBoolean(disableVersionCheck); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "clumpingThreshold", 64, + "Controls the number threshold at which Packet51 is preferred over Packet52, default and minimum 64, maximum 1024", 64, 1024); + prop.setLanguageKey("forge.configgui.clumpingThreshold").setRequiresWorldRestart(true); + clumpingThreshold = prop.getInt(64); + if (clumpingThreshold > 1024 || clumpingThreshold < 64) + { + clumpingThreshold = 64; + prop.set(64); + } + propOrder.add(prop.getName()); + + prop = config.get(CATEGORY_GENERAL, "sortRecipies", true); + prop.setComment("Set to true to enable the post initialization sorting of crafting recipes using Forge's sorter. May cause desyncing on conflicting recipes. MUST RESTART MINECRAFT IF CHANGED FROM THE CONFIG GUI."); + prop.setLanguageKey("forge.configgui.sortRecipies").setRequiresMcRestart(true); + shouldSortRecipies = prop.getBoolean(true); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringEntities", false); + prop.setComment("Set this to true to remove any Entity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES."); + prop.setLanguageKey("forge.configgui.removeErroringEntities").setRequiresWorldRestart(true); + removeErroringEntities = prop.getBoolean(false); + propOrder.add(prop.getName()); + + if (removeErroringEntities) + { + FMLLog.log.warn("Enabling removal of erroring Entities - USE AT YOUR OWN RISK"); + } + + prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringTileEntities", false); + prop.setComment("Set this to true to remove any TileEntity that throws an error in its update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES."); + prop.setLanguageKey("forge.configgui.removeErroringTileEntities").setRequiresWorldRestart(true); + removeErroringTileEntities = prop.getBoolean(false); + propOrder.add(prop.getName()); + + if (removeErroringTileEntities) + { + FMLLog.log.warn("Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK"); + } + + prop = config.get(Configuration.CATEGORY_GENERAL, "fullBoundingBoxLadders", false); + prop.setComment("Set this to true to check the entire entity's collision bounding box for ladders instead of just the block they are in. Causes noticeable differences in mechanics so default is vanilla behavior. Default: false"); + prop.setLanguageKey("forge.configgui.fullBoundingBoxLadders").setRequiresWorldRestart(true); + fullBoundingBoxLadders = prop.getBoolean(false); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "zombieBaseSummonChance", 0.1, + "Base zombie summoning spawn chance. Allows changing the bonus zombie summoning mechanic.", 0.0D, 1.0D); + prop.setLanguageKey("forge.configgui.zombieBaseSummonChance").setRequiresWorldRestart(true); + zombieSummonBaseChance = prop.getDouble(0.1); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "zombieBabyChance", 0.05, + "Chance that a zombie (or subclass) is a baby. Allows changing the zombie spawning mechanic.", 0.0D, 1.0D); + prop.setLanguageKey("forge.configgui.zombieBabyChance").setRequiresWorldRestart(true); + zombieBabyChance = (float) prop.getDouble(0.05); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "logCascadingWorldGeneration", true, + "Log cascading chunk generation issues during terrain population."); + logCascadingWorldGeneration = prop.getBoolean(); + prop.setLanguageKey("forge.configgui.logCascadingWorldGeneration"); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "fixVanillaCascading", false, + "Fix vanilla issues that cause worldgen cascading. This DOES change vanilla worldgen so DO NOT report bugs related to world differences if this flag is on."); + fixVanillaCascading = prop.getBoolean(); + prop.setLanguageKey("forge.configgui.fixVanillaCascading"); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_GENERAL, "dimensionUnloadQueueDelay", 0, + "The time in ticks the server will wait when a dimension was queued to unload. " + + "This can be useful when rapidly loading and unloading dimensions, like e.g. throwing items through a nether portal a few time per second."); + dimensionUnloadQueueDelay = prop.getInt(0); + prop.setLanguageKey("forge.configgui.dimensionUnloadQueueDelay"); + propOrder.add(prop.getName()); + + config.setCategoryPropertyOrder(CATEGORY_GENERAL, propOrder); + + propOrder = new ArrayList(); + prop = config.get(VERSION_CHECK_CAT, "Global", true, "Enable the entire mod update check system. This only applies to mods using the Forge system."); + propOrder.add("Global"); + + config.setCategoryPropertyOrder(VERSION_CHECK_CAT, propOrder); + + // Client-Side only properties + propOrder = new ArrayList(); + + prop = config.get(Configuration.CATEGORY_CLIENT, "zoomInMissingModelTextInGui", false, + "Toggle off to make missing model text in the gui fit inside the slot."); + zoomInMissingModelTextInGui = prop.getBoolean(false); + prop.setLanguageKey("forge.configgui.zoomInMissingModelTextInGui"); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_CLIENT, "forgeCloudsEnabled", true, + "Enable uploading cloud geometry to the GPU for faster rendering."); + prop.setLanguageKey("forge.configgui.forgeCloudsEnabled"); + forgeCloudsEnabled = prop.getBoolean(); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_CLIENT, "disableStairSlabCulling", false, + "Disable culling of hidden faces next to stairs and slabs. Causes extra rendering, but may fix some resource packs that exploit this vanilla mechanic."); + disableStairSlabCulling = prop.getBoolean(false); + prop.setLanguageKey("forge.configgui.disableStairSlabCulling"); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_CLIENT, "alwaysSetupTerrainOffThread", false, + "Enable forge to queue all chunk updates to the Chunk Update thread. May increase FPS significantly, but may also cause weird rendering lag. Not recommended for computers " + + "without a significant number of cores available."); + alwaysSetupTerrainOffThread = prop.getBoolean(false); + prop.setLanguageKey("forge.configgui.alwaysSetupTerrainOffThread"); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_CLIENT, "biomeSkyBlendRange", new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34 }); + prop.setComment("Control the range of sky blending for colored skies in biomes."); + prop.setLanguageKey("forge.configgui.biomeSkyBlendRange"); + blendRanges = prop.getIntList(); + propOrder.add(prop.getName()); + + prop = config.get(Configuration.CATEGORY_CLIENT, "forgeLightPipelineEnabled", true, + "Enable the forge block rendering pipeline - fixes the lighting of custom models."); + forgeLightPipelineEnabled = prop.getBoolean(true); + prop.setLanguageKey("forge.configgui.forgeLightPipelineEnabled"); + propOrder.add(prop.getName()); + + config.setCategoryPropertyOrder(CATEGORY_CLIENT, propOrder); + + if (config.hasChanged()) + { + config.save(); + } + } + + /** + * By subscribing to the OnConfigChangedEvent we are able to execute code when our config screens are closed. + * This implementation uses the optional configID string to handle multiple Configurations using one event handler. + */ + public void onConfigChanged(OnConfigChangedEvent event) + { + if (getModId().equals(event.getModID())) + { + if ("chunkLoader".equals(event.getConfigID())) + { + ForgeChunkManager.syncConfigDefaults(); + ForgeChunkManager.loadConfiguration(); + } + else + { + boolean tmpStairs = disableStairSlabCulling; + + syncConfig(false); + + if (event.isWorldRunning() && tmpStairs != disableStairSlabCulling) + { + FMLCommonHandler.instance().reloadRenderers(); + } + + } + } + } + + public void missingMapping(RegistryEvent.MissingMappings event) + { + for (MissingMappings.Mapping entry : event.getAllMappings()) + { + if (entry.key.toString().equals("minecraft:totem")) //This item changed from 1.11 -> 1.11.2 + { + ResourceLocation newTotem = new ResourceLocation("minecraft:totem_of_undying"); + entry.remap(ForgeRegistries.ITEMS.getValue(newTotem)); + } + } + } + + public void playerLogin(PlayerEvent.PlayerLoggedInEvent event) + { + UsernameCache.setUsername(event.player.getPersistentID(), event.player.getGameProfile().getName()); + } + + + public void preInit(FMLPreInitializationEvent evt) + { + CapabilityItemHandler.register(); + CapabilityFluidHandler.register(); + CapabilityAnimation.register(); + CapabilityEnergy.register(); + MinecraftForge.EVENT_BUS.register(MinecraftForge.INTERNAL_HANDLER); +// ForgeChunkManager.captureConfig(evt.getModConfigurationDirectory()); + MinecraftForge.EVENT_BUS.register(this); + + if (!ForgeMod.disableVersionCheck) + { + VersionChecker.startVersionCheck(); + } + } + + public void registrItems(RegistryEvent.Register event) + { + // Add and register the forge universal bucket, if it's enabled + if(FluidRegistry.isUniversalBucketEnabled()) + { + universalBucket = new UniversalBucket(); + universalBucket.setUnlocalizedName("forge.bucketFilled"); + event.getRegistry().register(universalBucket.setRegistryName(ForgeVersion.MOD_ID, "bucketFilled")); + MinecraftForge.EVENT_BUS.register(universalBucket); + } + } + + public void postInit(FMLPostInitializationEvent evt) + { + registerAllBiomesAndGenerateEvents(); + //ForgeChunkManager.loadConfiguration(); + } + + private static void registerAllBiomesAndGenerateEvents() + { + for (Biome biome : ForgeRegistries.BIOMES.getValuesCollection()) + { + if (biome.decorator instanceof DeferredBiomeDecorator) + { + DeferredBiomeDecorator decorator = (DeferredBiomeDecorator)biome.decorator; + decorator.fireCreateEventAndReplace(biome); + } + + BiomeDictionary.ensureHasTypes(biome); + } + } + + public void onAvailable(FMLLoadCompleteEvent evt) + { + FluidRegistry.validateFluidRegistry(); + } + + @SubscribeEvent + public void serverStarting(FMLServerStartingEvent evt) + { + evt.registerServerCommand(new ForgeCommand()); + } + + @SubscribeEvent + public void serverStopping(FMLServerStoppingEvent evt) + { + WorldWorkerManager.clear(); + } + + @Override + public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info) + { + NBTTagCompound forgeData = new NBTTagCompound(); + NBTTagCompound dimData = DimensionManager.saveDimensionDataMap(); + forgeData.setTag("DimensionData", dimData); + FluidRegistry.writeDefaultFluidList(forgeData); + return forgeData; + } + + @Override + public void readData(SaveHandler handler, WorldInfo info, Map propertyMap, NBTTagCompound tag) + { + DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null); + FluidRegistry.loadFluidDefaults(tag); + } + + public void mappingChanged(FMLModIdMappingEvent evt) + { + OreDictionary.rebakeMap(); + StatList.reinit(); + Ingredient.invalidateAll(); + FMLCommonHandler.instance().reloadSearchTrees(); + } + + @Override + public String getModId() + { + return ForgeVersion.MOD_ID; + } +} diff --git a/src/main/java/net/minecraftforge/common/ForgeModContainer.java b/src/main/java/net/minecraftforge/common/ForgeModContainer.java index b2750bdba..f10269e8e 100644 --- a/src/main/java/net/minecraftforge/common/ForgeModContainer.java +++ b/src/main/java/net/minecraftforge/common/ForgeModContainer.java @@ -19,91 +19,13 @@ package net.minecraftforge.common; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.biome.Biome; -import static net.minecraftforge.common.config.Configuration.CATEGORY_CLIENT; -import static net.minecraftforge.common.config.Configuration.CATEGORY_GENERAL; +import net.minecraftforge.fml.ModLoadingClassLoader; +import net.minecraftforge.fml.javafmlmod.FMLModContainer; +import net.minecraftforge.fml.loading.DefaultModInfos; -import java.io.File; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import net.minecraft.crash.ICrashReportDetail; -import net.minecraft.item.Item; -import net.minecraft.item.crafting.Ingredient; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.stats.StatList; -import net.minecraft.world.storage.SaveHandler; -import net.minecraft.world.storage.WorldInfo; -import net.minecraftforge.classloading.FMLForgePlugin; -import net.minecraftforge.client.ForgeClientHandler; -import net.minecraftforge.common.config.Config; -import net.minecraftforge.common.config.ConfigCategory; -import net.minecraftforge.common.config.ConfigManager; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.common.model.animation.CapabilityAnimation; -import net.minecraftforge.common.network.ForgeNetworkHandler; -import net.minecraftforge.energy.CapabilityEnergy; -import net.minecraftforge.event.RegistryEvent; -import net.minecraftforge.event.RegistryEvent.MissingMappings; -import net.minecraftforge.event.terraingen.DeferredBiomeDecorator; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; -import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.fluids.UniversalBucket; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.RecipeSorter; -import net.minecraftforge.server.command.ForgeCommand; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - -import net.minecraftforge.fml.client.FMLFileResourcePack; -import net.minecraftforge.fml.client.FMLFolderResourcePack; -import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; -import net.minecraftforge.fml.common.DummyModContainer; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.ICrashCallable; -import net.minecraftforge.fml.common.LoadController; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; -import net.minecraftforge.fml.common.ModMetadata; -import net.minecraftforge.fml.common.WorldAccessContainer; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; -import net.minecraftforge.fml.common.discovery.json.JsonAnnotationLoader; -import net.minecraftforge.fml.common.event.FMLConstructionEvent; -import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; -import net.minecraftforge.fml.common.event.FMLModIdMappingEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.PlayerEvent; -import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.relauncher.Side; - -import javax.annotation.Nullable; - -@EventBusSubscriber(modid = "forge") -public class ForgeModContainer extends DummyModContainer implements WorldAccessContainer +public class ForgeModContainer extends FMLModContainer { +/* public static final String VERSION_CHECK_CAT = "version_checking"; public static int clumpingThreshold = 64; public static boolean removeErroringEntities = false; @@ -192,7 +114,7 @@ public class ForgeModContainer extends DummyModContainer implements WorldAccessC /** * Synchronizes the local fields with the values in the Configuration object. - */ + * / private static void syncConfig(boolean load) { // By adding a property order list we are defining the order that the properties will appear both in the config file and on the GUIs. @@ -376,7 +298,7 @@ public class ForgeModContainer extends DummyModContainer implements WorldAccessC /** * By subscribing to the OnConfigChangedEvent we are able to execute code when our config screens are closed. * This implementation uses the optional configID string to handle multiple Configurations using one event handler. - */ + * / @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { @@ -644,4 +566,10 @@ public class ForgeModContainer extends DummyModContainer implements WorldAccessC return updateJSONUrl; } + */ + public ForgeModContainer(ModLoadingClassLoader classLoader) + { + super(DefaultModInfos.forgeModInfo, "net.minecraftforge.common.ForgeMod", classLoader, null); + } + } diff --git a/src/main/java/net/minecraftforge/common/ForgeVersion.java b/src/main/java/net/minecraftforge/common/ForgeVersion.java index 57075a8ef..caa1ec6c8 100644 --- a/src/main/java/net/minecraftforge/common/ForgeVersion.java +++ b/src/main/java/net/minecraftforge/common/ForgeVersion.java @@ -31,7 +31,7 @@ import javax.annotation.Nullable; public class ForgeVersion { - // This is Forge's Mod Id, used for the ForgeModContainer and resource locations + // This is Forge's Mod Id, used for the ForgeMod and resource locations public static final String MOD_ID = "forge"; //This number is incremented every time we remove deprecated code/major API changes, never reset public static final int majorVersion = 14; diff --git a/src/main/java/net/minecraftforge/common/MinecraftForge.java b/src/main/java/net/minecraftforge/common/MinecraftForge.java index 7f748105a..0da0b313c 100644 --- a/src/main/java/net/minecraftforge/common/MinecraftForge.java +++ b/src/main/java/net/minecraftforge/common/MinecraftForge.java @@ -22,8 +22,6 @@ package net.minecraftforge.common; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.ICrashCallable; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import net.minecraftforge.eventbus.api.IEventBus; import java.util.Collections; @@ -111,11 +109,11 @@ public class MinecraftForge if (all.size() == 0) return; - ForgeModContainer.log.debug("Preloading CrashReport Classes"); + ForgeMod.log.debug("Preloading CrashReport Classes"); Collections.sort(all); //Sort it because I like pretty output ;) for (String name : all) { - ForgeModContainer.log.debug("\t{}", name); + ForgeMod.log.debug("\t{}", name); try { Class.forName(name.replace('/', '.'), false, MinecraftForge.class.getClassLoader()); diff --git a/src/main/java/net/minecraftforge/common/UsernameCache.java b/src/main/java/net/minecraftforge/common/UsernameCache.java index 66512fa37..704cce3d8 100644 --- a/src/main/java/net/minecraftforge/common/UsernameCache.java +++ b/src/main/java/net/minecraftforge/common/UsernameCache.java @@ -42,8 +42,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; -import net.minecraftforge.fml.relauncher.FMLInjectionData; - /** * Caches player's last known usernames *

diff --git a/src/main/java/net/minecraftforge/common/config/ConfigManager.java b/src/main/java/net/minecraftforge/common/config/ConfigManager.java index 5eb752c34..8bfe7a3d5 100644 --- a/src/main/java/net/minecraftforge/common/config/ConfigManager.java +++ b/src/main/java/net/minecraftforge/common/config/ConfigManager.java @@ -39,8 +39,6 @@ import net.minecraftforge.common.config.Config.Name; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.LoaderException; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation.EnumHolder; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/net/minecraftforge/common/config/Configuration.java b/src/main/java/net/minecraftforge/common/config/Configuration.java index 465104fda..667af6c38 100644 --- a/src/main/java/net/minecraftforge/common/config/Configuration.java +++ b/src/main/java/net/minecraftforge/common/config/Configuration.java @@ -57,7 +57,6 @@ import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.relauncher.FMLInjectionData; import org.apache.commons.io.IOUtils; /** diff --git a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java b/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java index c102755ba..869e3ea7e 100644 --- a/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java +++ b/src/main/java/net/minecraftforge/common/crafting/CraftingHelper.java @@ -20,28 +20,26 @@ package net.minecraftforge.common.crafting; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.FileSystem; -import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; -import java.util.function.BiFunction; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BooleanSupplier; -import java.util.function.Function; import javax.annotation.Nonnull; +import net.minecraft.client.util.RecipeBookClient; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.fml.ModList; +import net.minecraftforge.fml.SidedExecutor; +import net.minecraftforge.fml.loading.moddiscovery.ModFile; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -57,7 +55,6 @@ import com.google.gson.JsonSyntaxException; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.ShapedRecipes; @@ -68,10 +65,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.JsonUtils; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreIngredient; @@ -80,14 +73,20 @@ import net.minecraftforge.oredict.ShapelessOreRecipe; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.RegistryManager; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; public class CraftingHelper { private static final boolean DEBUG_LOAD_MINECRAFT = false; + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker CRAFTHELPER = MarkerManager.getMarker("CRAFTHELPER"); private static Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - private static Map conditions = Maps.newHashMap(); - private static Map ingredients = Maps.newHashMap(); - private static Map recipes = Maps.newHashMap(); + private static Map conditions = new HashMap<>(); + private static Map ingredients = new HashMap<>(); + private static Map recipes = new HashMap<>(); static { init(); @@ -420,7 +419,7 @@ public class CraftingHelper { registerC("forge:mod_loaded", (context, json) -> { String modid = JsonUtils.getString(json, "modid"); - return () -> Loader.isModLoaded(modid); + return () -> ModList.get().isLoaded(modid); }); registerC("minecraft:item_exists", (context, json) -> { String itemName = context.appendModId(JsonUtils.getString(json, "item")); @@ -548,7 +547,7 @@ public class CraftingHelper { register(new ResourceLocation(name), fac); } - static void loadFactories(JsonObject json, JsonContext context) + private static void loadFactories(JsonObject json, JsonContext context) { if (json.has("ingredients")) { @@ -581,11 +580,12 @@ public class CraftingHelper { } } + @SuppressWarnings("unchecked") private static T getClassInstance(String clsName, Class expected) { try { - Class cls = Class.forName(clsName); + Class cls = Class.forName(clsName, true, Thread.currentThread().getContextClassLoader()); if (!expected.isAssignableFrom(cls)) throw new JsonSyntaxException("Class '" + clsName + "' is not an " + expected.getSimpleName()); return (T)cls.newInstance(); @@ -612,229 +612,97 @@ public class CraftingHelper { reg.clear(); else if (revertFrozen) GameData.revert(RegistryManager.FROZEN, GameData.RECIPES, false); - //ModContainer old = Loader.instance().activeModContainer(); - Loader.instance().setActiveModContainer(null); - Loader.instance().getActiveModList().forEach(CraftingHelper::loadFactories); - Loader.instance().getActiveModList().forEach(CraftingHelper::loadRecipes); - Loader.instance().setActiveModContainer(null); + + ModList.get().forEachModFile(CraftingHelper::loadFactories); + ModList.get().forEachModFile(CraftingHelper::loadRecipes); GameData.fireRegistryEvents(rl -> rl.equals(GameData.RECIPES)); //reg.freeze(); - FMLCommonHandler.instance().resetClientRecipeBook(); + SidedExecutor.runOn(Dist.CLIENT, ()-> { + RecipeBookClient.rebuildTable(); + return null; + }); } - private static void loadFactories(ModContainer mod) + private static void loadFactories(final ModFile modFile) { - FileSystem fs = null; - BufferedReader reader = null; - try - { - JsonContext ctx = new JsonContext(mod.getModId()); - Path fPath = null; - if (mod.getSource().isFile()) - { - fs = FileSystems.newFileSystem(mod.getSource().toPath(), null); - fPath = fs.getPath("/assets/" + ctx.getModId() + "/recipes/_factories.json"); - } - else if (mod.getSource().isDirectory()) - { - fPath = mod.getSource().toPath().resolve("assets/" + ctx.getModId() + "/recipes/_factories.json"); - } + modFile.getModInfos().forEach(modInfo-> { + final String modId = modInfo.getModId(); + JsonContext ctx = new JsonContext(modId); + final Path fPath = modFile.getLocator().findPath(modFile, "assets", modId, "recipes","_factories.json"); if (fPath != null && Files.exists(fPath)) { - reader = Files.newBufferedReader(fPath); - JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); - loadFactories(json, ctx); - } - } - catch (IOException e) - { - e.printStackTrace(); - } - finally - { - IOUtils.closeQuietly(fs); - IOUtils.closeQuietly(reader); - } - } - - private static boolean loadRecipes(ModContainer mod) - { - JsonContext ctx = new JsonContext(mod.getModId()); - - return findFiles(mod, "assets/" + mod.getModId() + "/recipes", - root -> - { - Path fPath = root.resolve("_constants.json"); - if (fPath != null && Files.exists(fPath)) + try (final BufferedReader reader = Files.newBufferedReader(fPath)) { - BufferedReader reader = null; - try - { - reader = Files.newBufferedReader(fPath); - JsonObject[] json = JsonUtils.fromJson(GSON, reader, JsonObject[].class); - ctx.loadConstants(json); - } - catch (IOException e) - { - FMLLog.log.error("Error loading _constants.json: ", e); - return false; - } - finally - { - IOUtils.closeQuietly(reader); - } - } - return true; - }, - (root, file) -> - { - Loader.instance().setActiveModContainer(mod); - - String relative = root.relativize(file).toString(); - if (!"json".equals(FilenameUtils.getExtension(file.toString())) || relative.startsWith("_")) - return true; - - String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/"); - ResourceLocation key = new ResourceLocation(ctx.getModId(), name); - - BufferedReader reader = null; - try - { - reader = Files.newBufferedReader(file); JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); - if (json.has("conditions") && !CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), ctx)) - return true; - IRecipe recipe = CraftingHelper.getRecipe(json, ctx); - ForgeRegistries.RECIPES.register(recipe.setRegistryName(key)); + loadFactories(json, ctx); } - catch (JsonParseException e) + catch (final IOException e) { - FMLLog.log.error("Parsing error loading recipe {}", key, e); - return false; + LOGGER.error(CRAFTHELPER,"Encountered error reading recipe factories for {}", modId, e); } - catch (IOException e) - { - FMLLog.log.error("Couldn't read recipe {} from {}", key, file, e); - return false; - } - finally - { - IOUtils.closeQuietly(reader); - } - return true; - }, - true, true - ); + } + }); } - /** - * @deprecated Use {@link CraftingHelper#findFiles(ModContainer, String, Function, BiFunction, boolean, boolean)} instead. - */ - @Deprecated - public static boolean findFiles(ModContainer mod, String base, Function preprocessor, BiFunction processor) + private static boolean loadRecipes(final ModFile modFile) { - return findFiles(mod, base, preprocessor, processor, false, false); - } - - /** - * @deprecated Use {@link CraftingHelper#findFiles(ModContainer, String, Function, BiFunction, boolean, boolean)} instead. - */ - @Deprecated - public static boolean findFiles(ModContainer mod, String base, Function preprocessor, BiFunction processor, boolean defaultUnfoundRoot) - { - return findFiles(mod, base, preprocessor, processor, defaultUnfoundRoot, false); - } - - public static boolean findFiles(ModContainer mod, String base, Function preprocessor, BiFunction processor, boolean defaultUnfoundRoot, boolean visitAllFiles) - { - FileSystem fs = null; - try - { - File source = mod.getSource(); - - if ("minecraft".equals(mod.getModId())) + final AtomicBoolean errored = new AtomicBoolean(false); + modFile.getModInfos().forEach(modInfo-> { + final String modId = modInfo.getModId(); + JsonContext ctx = new JsonContext(modId); + final Path root = modFile.getLocator().findPath(modFile, "assets", modId, "recipes"); + if (!Files.exists(root)) return; + final Path constants = modFile.getLocator().findPath(modFile, "assets", modId, "recipes", "_constants.json"); + if (Files.exists(constants)) { - if (!DEBUG_LOAD_MINECRAFT) - return true; - - try + try (BufferedReader reader = Files.newBufferedReader(constants)) { - URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI(); - source = new File(tmp.resolve("..").getPath()); + JsonObject[] json = JsonUtils.fromJson(GSON, reader, JsonObject[].class); + ctx.loadConstants(json); } - catch (URISyntaxException e) + catch (final IOException e) { - FMLLog.log.error("Error finding Minecraft jar: ", e); - return false; + LOGGER.error(CRAFTHELPER, "Error loading _constants.json: ", e); + errored.set(true); } } - - Path root = null; - if (source.isFile()) + try { - try - { - fs = FileSystems.newFileSystem(source.toPath(), null); - root = fs.getPath("/" + base); - } - catch (IOException e) - { - FMLLog.log.error("Error loading FileSystem from jar: ", e); - return false; - } + Files.walk(root). + filter(p -> p.getFileName().toString().startsWith("_") || Objects.equals(FilenameUtils.getExtension(p.getFileName().toString()), "json")). + forEach(p -> { + final String relative = root.relativize(p).toString(); + final String name = FilenameUtils.removeExtension(relative).replaceAll("\\\\", "/"); + final ResourceLocation key = new ResourceLocation(modId, name); + try (BufferedReader reader = Files.newBufferedReader(constants)) + { + JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); + if (json.has("conditions") && !CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), ctx)) + return; + IRecipe recipe = CraftingHelper.getRecipe(json, ctx); + ForgeRegistries.RECIPES.register(recipe.setRegistryName(key)); + } + catch (final JsonParseException e) + { + LOGGER.error(CRAFTHELPER, "Parsing error loading recipe {}", key, e); + errored.set(true); + } + catch (final IOException e) + { + LOGGER.error(CRAFTHELPER, "Couldn't read recipe {} from {}", key, p, e); + errored.set(true); + } + + }); } - else if (source.isDirectory()) + catch (final IOException e) { - root = source.toPath().resolve(base); + LOGGER.error(CRAFTHELPER, "Error occurred walking file tree", e); + errored.set(true); } - - if (root == null || !Files.exists(root)) - return defaultUnfoundRoot; - - if (preprocessor != null) - { - Boolean cont = preprocessor.apply(root); - if (cont == null || !cont.booleanValue()) - return false; - } - - boolean success = true; - - if (processor != null) - { - Iterator itr = null; - try - { - itr = Files.walk(root).iterator(); - } - catch (IOException e) - { - FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e); - return false; - } - - while (itr != null && itr.hasNext()) - { - Boolean cont = processor.apply(root, itr.next()); - - if (visitAllFiles) - { - success &= cont != null && cont; - } - else if (cont == null || !cont) - { - return false; - } - } - } - - return success; - } - finally - { - IOUtils.closeQuietly(fs); - } + }); + return errored.get(); } } diff --git a/src/main/java/net/minecraftforge/common/model/TRSRTransformation.java b/src/main/java/net/minecraftforge/common/model/TRSRTransformation.java index 2afbb4d94..82342651b 100644 --- a/src/main/java/net/minecraftforge/common/model/TRSRTransformation.java +++ b/src/main/java/net/minecraftforge/common/model/TRSRTransformation.java @@ -39,14 +39,14 @@ import net.minecraft.client.renderer.block.model.ItemTransformVec3f; import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.Vec3i; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; import com.google.common.base.MoreObjects; +import java.util.Optional; import com.google.common.collect.Maps; /* @@ -93,50 +93,26 @@ public final class TRSRTransformation implements IModelState, ITransformation full = true; } - /** @deprecated use {@link #from(ItemTransformVec3f)} */ - @Deprecated // TODO: remove / make private - @SideOnly(Side.CLIENT) - public TRSRTransformation(ItemTransformVec3f transform) - { - this(toVecmath(transform.translation), quatFromXYZDegrees(toVecmath(transform.rotation)), toVecmath(transform.scale), null); - } - - /** @deprecated use {@link #from(ModelRotation)} */ - @Deprecated // TODO: remove - @SideOnly(Side.CLIENT) - public TRSRTransformation(ModelRotation rotation) - { - this(rotation.getMatrix()); - } - - /** @deprecated use {@link #from(EnumFacing)} */ - @Deprecated // TODO: remove - @SideOnly(Side.CLIENT) - public TRSRTransformation(EnumFacing facing) - { - this(getMatrix(facing)); - } - @Deprecated - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static TRSRTransformation from(ItemTransformVec3f transform) { return transform.equals(ItemTransformVec3f.DEFAULT) ? identity : new TRSRTransformation(transform); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static TRSRTransformation from(ModelRotation rotation) { return Cache.get(rotation); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static TRSRTransformation from(EnumFacing facing) { return Cache.get(getRotation(facing)); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static Matrix4f getMatrix(EnumFacing facing) { return getRotation(facing).getMatrix(); @@ -558,8 +534,8 @@ public final class TRSRTransformation implements IModelState, ITransformation * Don't use this if you don't need to, conversion is lossy (second rotation component is lost). */ @Deprecated - @SideOnly(Side.CLIENT) - public ItemTransformVec3f toItemTransform() + @OnlyIn(Dist.CLIENT) + public net.minecraft.client.renderer.block.model.ItemTransformVec3f toItemTransform() { return new ItemTransformVec3f(toLwjgl(toXYZDegrees(getLeftRot())), toLwjgl(getTranslation()), toLwjgl(getScale())); } @@ -712,19 +688,19 @@ public final class TRSRTransformation implements IModelState, ITransformation return Objects.equals(matrix, other.matrix); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static Vector3f toVecmath(org.lwjgl.util.vector.Vector3f vec) { return new Vector3f(vec.x, vec.y, vec.z); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static Vector4f toVecmath(org.lwjgl.util.vector.Vector4f vec) { return new Vector4f(vec.x, vec.y, vec.z, vec.w); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static Matrix4f toVecmath(org.lwjgl.util.vector.Matrix4f m) { return new Matrix4f( @@ -734,19 +710,19 @@ public final class TRSRTransformation implements IModelState, ITransformation m.m03, m.m13, m.m23, m.m33); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static org.lwjgl.util.vector.Vector3f toLwjgl(Vector3f vec) { return new org.lwjgl.util.vector.Vector3f(vec.x, vec.y, vec.z); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static org.lwjgl.util.vector.Vector4f toLwjgl(Vector4f vec) { return new org.lwjgl.util.vector.Vector4f(vec.x, vec.y, vec.z, vec.w); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static org.lwjgl.util.vector.Matrix4f toLwjgl(Matrix4f m) { org.lwjgl.util.vector.Matrix4f r = new org.lwjgl.util.vector.Matrix4f(); @@ -847,7 +823,7 @@ public final class TRSRTransformation implements IModelState, ITransformation } } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) private static final class Cache { private static final Map rotations = new EnumMap<>(ModelRotation.class); diff --git a/src/main/java/net/minecraftforge/common/model/animation/AnimationStateMachine.java b/src/main/java/net/minecraftforge/common/model/animation/AnimationStateMachine.java index fa21fe901..598301287 100644 --- a/src/main/java/net/minecraftforge/common/model/animation/AnimationStateMachine.java +++ b/src/main/java/net/minecraftforge/common/model/animation/AnimationStateMachine.java @@ -43,14 +43,14 @@ import com.google.gson.stream.JsonWriter; import net.minecraft.client.resources.IResource; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.animation.Event; import net.minecraftforge.common.animation.ITimeValue; import net.minecraftforge.common.animation.TimeValues; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.util.JsonUtils; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; @@ -213,7 +213,7 @@ public final class AnimationStateMachine implements IAnimationStateMachine /** * Load a new instance if AnimationStateMachine at specified location, with specified custom parameters. */ - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static IAnimationStateMachine load(IResourceManager manager, ResourceLocation location, ImmutableMap customParameters) { try (IResource resource = manager.getResource(location)) diff --git a/src/main/java/net/minecraftforge/common/model/animation/Clips.java b/src/main/java/net/minecraftforge/common/model/animation/Clips.java index 3888d6b00..1548ee7df 100644 --- a/src/main/java/net/minecraftforge/common/model/animation/Clips.java +++ b/src/main/java/net/minecraftforge/common/model/animation/Clips.java @@ -25,6 +25,7 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.IStringSerializable; import net.minecraft.util.math.MathHelper; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.animation.Event; @@ -33,8 +34,7 @@ import net.minecraftforge.common.model.IModelPart; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.Pair; @@ -88,7 +88,7 @@ public final class Clips /** * Retrieves the clip from the model. */ - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static IClip getModelClipNode(ResourceLocation modelLocation, String clipName) { IModel model = ModelLoaderRegistry.getModelOrMissing(modelLocation); diff --git a/src/main/java/net/minecraftforge/common/network/ForgeNetworkHandler.java b/src/main/java/net/minecraftforge/common/network/ForgeNetworkHandler.java index 2ab416200..3bcde471e 100644 --- a/src/main/java/net/minecraftforge/common/network/ForgeNetworkHandler.java +++ b/src/main/java/net/minecraftforge/common/network/ForgeNetworkHandler.java @@ -20,21 +20,22 @@ package net.minecraftforge.common.network; import java.util.EnumMap; -import net.minecraftforge.common.ForgeModContainer; + +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.fml.common.network.FMLEmbeddedChannel; import net.minecraftforge.fml.common.network.FMLOutboundHandler; import net.minecraftforge.fml.common.network.FMLOutboundHandler.OutboundTarget; import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; public class ForgeNetworkHandler { private static EnumMap channelPair; - public static void registerChannel(ForgeModContainer forgeModContainer, Side side) + public static void registerChannel(ForgeMod forgeMod, Side side) { - channelPair = NetworkRegistry.INSTANCE.newChannel(forgeModContainer, "FORGE", new ForgeRuntimeCodec()); + channelPair = NetworkRegistry.INSTANCE.newChannel(forgeMod, "FORGE", new ForgeRuntimeCodec()); if (side == Side.CLIENT) { addClientHandlers(); @@ -46,7 +47,7 @@ public class ForgeNetworkHandler serverChannel.pipeline().addAfter(handlerName, "ServerToClientConnection", new ServerToClientConnectionEstablishedHandler()); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) private static void addClientHandlers() { FMLEmbeddedChannel clientChannel = channelPair.get(Side.CLIENT); diff --git a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java index 93d808a0c..73b86a3c2 100644 --- a/src/main/java/net/minecraftforge/event/ForgeEventFactory.java +++ b/src/main/java/net/minecraftforge/event/ForgeEventFactory.java @@ -394,7 +394,7 @@ public class ForgeEventFactory public static void firePlayerLoadingEvent(EntityPlayer player, IPlayerFileData playerFileData, String uuidString) { SaveHandler sh = (SaveHandler) playerFileData; - File dir = ObfuscationReflectionHelper.getPrivateValue(SaveHandler.class, sh, "playersDirectory", "field_"+"75771_c"); + File dir = sh.getPlayersDirectory(); MinecraftForge.EVENT_BUS.post(new PlayerEvent.LoadFromFile(player, dir, uuidString)); } diff --git a/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java b/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java index 205489e41..e7cbe1bd0 100644 --- a/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java +++ b/src/main/java/net/minecraftforge/event/entity/player/PlayerInteractEvent.java @@ -31,7 +31,7 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.Cancelable; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/src/main/java/net/minecraftforge/fluids/BlockFluidBase.java b/src/main/java/net/minecraftforge/fluids/BlockFluidBase.java index d1b9bfc6d..659e1ecce 100644 --- a/src/main/java/net/minecraftforge/fluids/BlockFluidBase.java +++ b/src/main/java/net/minecraftforge/fluids/BlockFluidBase.java @@ -50,12 +50,13 @@ import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.OnlyIn; +import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.common.property.Properties; import net.minecraftforge.common.property.PropertyFloat; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; /** * This is a base implementation for Fluid blocks. @@ -409,7 +410,7 @@ public abstract class BlockFluidBase extends Block implements IFluidBlock } @Override - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) @Nonnull public BlockRenderLayer getBlockLayer() { @@ -763,7 +764,7 @@ public abstract class BlockFluidBase extends Block implements IFluidBlock } @Override - @SideOnly (Side.CLIENT) + @OnlyIn(Dist.CLIENT) public Vec3d getFogColor(World world, BlockPos pos, IBlockState state, Entity entity, Vec3d originalColor, float partialTicks) { if (!isWithinFluid(world, pos, ActiveRenderInfo.projectViewFromEntity(entity, partialTicks))) diff --git a/src/main/java/net/minecraftforge/fluids/FluidRegistry.java b/src/main/java/net/minecraftforge/fluids/FluidRegistry.java index bb3b7c480..90a57e859 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidRegistry.java +++ b/src/main/java/net/minecraftforge/fluids/FluidRegistry.java @@ -25,7 +25,6 @@ import java.util.Map.Entry; import java.util.Set; import net.minecraftforge.fml.ModThreadContext; -import net.minecraftforge.fml.common.LoaderState; import net.minecraft.block.Block; import net.minecraft.init.Blocks; @@ -44,11 +43,13 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.registries.IRegistryDelegate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable; @@ -57,6 +58,8 @@ import javax.annotation.Nullable; */ public abstract class FluidRegistry { + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker FLUIDS = MarkerManager.getMarker("FLUIDS"); static int maxID = 0; static BiMap fluids = HashBiMap.create(); @@ -124,13 +127,13 @@ public abstract class FluidRegistry String derivedName = defaultName.split(":",2)[1]; String localDefault = defaultFluidName.get(derivedName); if (localDefault == null) { - FMLLog.log.error("The fluid {} (specified as {}) is missing from this instance - it will be removed", derivedName, defaultName); + LOGGER.error(FLUIDS, "The fluid {} (specified as {}) is missing from this instance - it will be removed",derivedName,defaultName); continue; } fluid = masterFluidReference.get(localDefault); - FMLLog.log.error("The fluid {} specified as default is not present - it will be reverted to default {}", defaultName, localDefault); + LOGGER.error(FLUIDS, "The fluid {} specified as default is not present - it will be reverted to default {}",defaultName,localDefault); } - FMLLog.log.debug("The fluid {} has been selected as the default fluid for {}", defaultName, fluid.getName()); + LOGGER.debug(FLUIDS, "The fluid {} has been selected as the default fluid for {}",defaultName,fluid.getName()); Fluid oldFluid = localFluids.put(fluid.getName(), fluid); Integer id = localFluidIDs.remove(oldFluid); localFluidIDs.put(fluid, id); @@ -177,7 +180,7 @@ public abstract class FluidRegistry private static String uniqueName(Fluid fluid) { - return ModThreadContext.get().getCurrentContainer().getPrefix() +":"+fluid.getName(); + return ModThreadContext.get().getActiveContainer().getPrefix() +":"+fluid.getName(); } /** @@ -255,16 +258,7 @@ public abstract class FluidRegistry */ public static void enableUniversalBucket() { - if (Loader.instance().hasReachedState(LoaderState.PREINITIALIZATION)) - { - ModContainer modContainer = Loader.instance().activeModContainer(); - String modContainerName = modContainer == null ? null : modContainer.getName(); - FMLLog.log.error("Trying to activate the universal filled bucket too late. Call it statically in your Mods class. Mod: {}", modContainerName); - } - else - { - universalBucketEnabled = true; - } + universalBucketEnabled = true; } public static boolean isUniversalBucketEnabled() @@ -357,7 +351,7 @@ public abstract class FluidRegistry { String name = masterFluidReference.inverse().get(key); if (Strings.isNullOrEmpty(name)) { - FMLLog.log.error("The fluid registry is corrupted. A fluid {} {} is not properly registered. The mod that registered this is broken", key.getClass().getName(), key.getName()); + LOGGER.error(FLUIDS, "The fluid registry is corrupted. A fluid {} {} is not properly registered. The mod that registered this is broken",key.getClass().getName(),key.getName()); throw new IllegalStateException("The fluid registry is corrupted"); } return name; @@ -383,7 +377,7 @@ public abstract class FluidRegistry Set defaults = Sets.newHashSet(); if (tag.hasKey("DefaultFluidList",9)) { - FMLLog.log.debug("Loading persistent fluid defaults from world"); + LOGGER.debug(FLUIDS, "Loading persistent fluid defaults from world"); NBTTagList tl = tag.getTagList("DefaultFluidList", 8); for (int i = 0; i < tl.tagCount(); i++) { @@ -392,7 +386,7 @@ public abstract class FluidRegistry } else { - FMLLog.log.debug("World is missing persistent fluid defaults - using local defaults"); + LOGGER.debug(FLUIDS,"World is missing persistent fluid defaults - using local defaults"); } loadFluidDefaults(HashBiMap.create(fluidIDs), defaults); } @@ -422,13 +416,13 @@ public abstract class FluidRegistry if (!illegalFluids.isEmpty()) { - FMLLog.log.fatal("The fluid registry is corrupted. Something has inserted a fluid without registering it"); - FMLLog.log.fatal("There is {} unregistered fluids", illegalFluids.size()); + LOGGER.fatal(FLUIDS, "The fluid registry is corrupted. Something has inserted a fluid without registering it"); + LOGGER.fatal(FLUIDS, "There is {} unregistered fluids",illegalFluids.size()); for (Fluid f: illegalFluids) { - FMLLog.log.fatal(" Fluid name : {}, type: {}", f.getName(), f.getClass().getName()); + LOGGER.fatal(FLUIDS, " Fluid name : {}, type: {}",f.getName(),f.getClass().getName()); } - FMLLog.log.fatal("The mods that own these fluids need to register them properly"); + LOGGER.fatal(FLUIDS, "The mods that own these fluids need to register them properly"); throw new IllegalStateException("The fluid map contains fluids unknown to the master fluid registry"); } } diff --git a/src/main/java/net/minecraftforge/fluids/FluidUtil.java b/src/main/java/net/minecraftforge/fluids/FluidUtil.java index 0285136c5..b741355b2 100644 --- a/src/main/java/net/minecraftforge/fluids/FluidUtil.java +++ b/src/main/java/net/minecraftforge/fluids/FluidUtil.java @@ -39,7 +39,7 @@ import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandlerItem; @@ -742,7 +742,7 @@ public class FluidUtil if (FluidRegistry.isUniversalBucketEnabled() && FluidRegistry.getBucketFluids().contains(fluid)) { - UniversalBucket bucket = ForgeModContainer.getInstance().universalBucket; + UniversalBucket bucket = ForgeMod.getInstance().universalBucket; ItemStack filledBucket = new ItemStack(bucket); FluidStack fluidContents = new FluidStack(fluidStack, bucket.getCapacity()); diff --git a/src/main/java/net/minecraftforge/fluids/capability/wrappers/FluidBucketWrapper.java b/src/main/java/net/minecraftforge/fluids/capability/wrappers/FluidBucketWrapper.java index 024e9bc91..26e02e682 100644 --- a/src/main/java/net/minecraftforge/fluids/capability/wrappers/FluidBucketWrapper.java +++ b/src/main/java/net/minecraftforge/fluids/capability/wrappers/FluidBucketWrapper.java @@ -27,7 +27,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemBucketMilk; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -import net.minecraftforge.common.ForgeModContainer; +import net.minecraftforge.common.ForgeMod; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fluids.Fluid; @@ -85,9 +85,9 @@ public class FluidBucketWrapper implements IFluidHandlerItem, ICapabilityProvide { return FluidRegistry.getFluidStack("milk", Fluid.BUCKET_VOLUME); } - else if (item == ForgeModContainer.getInstance().universalBucket) + else if (item == ForgeMod.getInstance().universalBucket) { - return ForgeModContainer.getInstance().universalBucket.getFluid(container); + return ForgeMod.getInstance().universalBucket.getFluid(container); } else { diff --git a/src/main/java/net/minecraftforge/fml/AutomaticEventSubscriber.java b/src/main/java/net/minecraftforge/fml/AutomaticEventSubscriber.java index 44c691cf0..24b8a1fee 100644 --- a/src/main/java/net/minecraftforge/fml/AutomaticEventSubscriber.java +++ b/src/main/java/net/minecraftforge/fml/AutomaticEventSubscriber.java @@ -19,10 +19,9 @@ package net.minecraftforge.fml; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.language.ModFileScanData; import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation; @@ -47,6 +46,7 @@ public class AutomaticEventSubscriber private static final Logger LOGGER = LogManager.getLogger("FML"); public static void inject(final ModContainer mod, final ModFileScanData scanData, final ClassLoader loader) { + if (scanData == null) return; LOGGER.debug(LOADING,"Attempting to inject @EventBusSubscriber classes into the eventbus for {}", mod.getModId()); List ebsTargets = scanData.getAnnotations().stream(). filter(annotationData -> Objects.equals(annotationData.getAnnotationType(), Type.getType(Mod.EventBusSubscriber.class))). @@ -55,11 +55,11 @@ public class AutomaticEventSubscriber ebsTargets.forEach(ad -> { @SuppressWarnings("unchecked") final List sidesValue = (List)ad.getAnnotationData(). - getOrDefault("value", Arrays.asList(new ModAnnotation.EnumHolder(null, "CLIENT"), new ModAnnotation.EnumHolder(null, "SERVER"))); - final EnumSet sides = sidesValue.stream().map(eh -> Side.valueOf(eh.getValue())). - collect(Collectors.toCollection(() -> EnumSet.noneOf(Side.class))); + getOrDefault("value", Arrays.asList(new ModAnnotation.EnumHolder(null, "CLIENT"), new ModAnnotation.EnumHolder(null, "DEDICATED_SERVER"))); + final EnumSet sides = sidesValue.stream().map(eh -> Dist.valueOf(eh.getValue())). + collect(Collectors.toCollection(() -> EnumSet.noneOf(Dist.class))); final String modId = (String)ad.getAnnotationData().getOrDefault("modId", mod.getModId()); - if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.side)) { + if (Objects.equals(mod.getModId(), modId) && sides.contains(FMLEnvironment.dist)) { try { MinecraftForge.EVENT_BUS.register(Class.forName(ad.getClassType().getClassName(), true, loader)); diff --git a/src/main/java/net/minecraftforge/fml/client/BrandingControl.java b/src/main/java/net/minecraftforge/fml/BrandingControl.java similarity index 90% rename from src/main/java/net/minecraftforge/fml/client/BrandingControl.java rename to src/main/java/net/minecraftforge/fml/BrandingControl.java index 3efb7d580..80b6c901d 100644 --- a/src/main/java/net/minecraftforge/fml/client/BrandingControl.java +++ b/src/main/java/net/minecraftforge/fml/BrandingControl.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.client; +package net.minecraftforge.fml; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @@ -25,6 +25,7 @@ import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.ModList; import java.text.MessageFormat; +import java.util.Arrays; import java.util.List; import java.util.function.BiConsumer; import java.util.stream.Collectors; @@ -70,4 +71,9 @@ public class BrandingControl public static String getClientBranding() { return defaultClientBranding.stream().collect(Collectors.joining(",")); } + + public static final List defaultServerBranding = Arrays.asList("fml", "forge"); + public static String getServerBranding() { + return defaultServerBranding.stream().collect(Collectors.joining(",")); + } } diff --git a/src/main/java/net/minecraftforge/fml/CrashReportExtender.java b/src/main/java/net/minecraftforge/fml/CrashReportExtender.java index d912519a5..fa0607ee8 100644 --- a/src/main/java/net/minecraftforge/fml/CrashReportExtender.java +++ b/src/main/java/net/minecraftforge/fml/CrashReportExtender.java @@ -19,13 +19,9 @@ package net.minecraftforge.fml; -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraftforge.fml.common.ICrashCallable; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.relauncher.CoreModManager; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/net/minecraftforge/fml/FMLWorldPersistenceHook.java b/src/main/java/net/minecraftforge/fml/FMLWorldPersistenceHook.java new file mode 100644 index 000000000..09cb3c383 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/FMLWorldPersistenceHook.java @@ -0,0 +1,143 @@ +/* + * Minecraft Forge + * Copyright (c) 2016-2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +import com.google.common.collect.Multimap; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.storage.SaveHandler; +import net.minecraft.world.storage.WorldInfo; +import net.minecraftforge.registries.ForgeRegistry; +import net.minecraftforge.registries.GameData; +import net.minecraftforge.registries.RegistryManager; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; + +/** + * @author cpw + * + */ +public final class FMLWorldPersistenceHook implements WorldPersistenceHooks.WorldPersistenceHook +{ + + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker WORLDPERSISTENCE = MarkerManager.getMarker("WP"); + + @Override + public String getModId() + { + return "fml"; + } + + @Override + public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info) + { + NBTTagCompound fmlData = new NBTTagCompound(); + NBTTagList modList = new NBTTagList(); + ModList.get().getMods().forEach(mi-> + { + final NBTTagCompound mod = new NBTTagCompound(); + mod.setString("ModId", mi.getModId()); + mod.setString("ModVersion", mi.getVersion().getVersionString()); + modList.appendTag(mod); + }); + fmlData.setTag("LoadingModList", modList); + + NBTTagCompound registries = new NBTTagCompound(); + fmlData.setTag("Registries", registries); + LOGGER.debug(WORLDPERSISTENCE,"Gathering id map for writing to world save {}", info.getWorldName()); + + for (Map.Entry e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet()) + { + registries.setTag(e.getKey().toString(), e.getValue().write()); + } + return fmlData; + } + + @Override + public void readData(SaveHandler handler, WorldInfo info, Map propertyMap, NBTTagCompound tag) + { + if (tag.hasKey("LoadingModList")) + { + NBTTagList modList = tag.getTagList("LoadingModList", (byte)10); + for (int i = 0; i < modList.tagCount(); i++) + { + NBTTagCompound mod = modList.getCompoundTagAt(i); + String modId = mod.getString("ModId"); + String modVersion = mod.getString("ModVersion"); + Optional container = ModList.get().getModContainerById(modId); + if (!container.isPresent()) + { + LOGGER.error(WORLDPERSISTENCE,"This world was saved with mod {} which appears to be missing, things may not work well", modId); + continue; + } + if (!modVersion.equals(container.get().getModInfo().getVersion().getVersionString())) + { + LOGGER.info(WORLDPERSISTENCE,"This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, container.get().getModInfo().getVersion().getVersionString()); + } + } + } + + Multimap failedElements = null; + + if (tag.hasKey("ModItemData") || tag.hasKey("ItemData")) // Pre 1.7 + { + StartupQuery.notify("This save predates 1.7.10, it can no longer be loaded here. Please load in 1.7.10 or 1.8 first"); + StartupQuery.abort(); + } + else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list + { + Map snapshot = new HashMap<>(); + NBTTagCompound regs = tag.getCompoundTag("Registries"); + for (String key : regs.getKeySet()) + { + snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompoundTag(key))); + } + failedElements = GameData.injectSnapshot(snapshot, true, true); + } + + if (failedElements != null && !failedElements.isEmpty()) + { + StringBuilder buf = new StringBuilder(); + buf.append("Forge Mod Loader could not load this save.\n\n") + .append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n") + .append("You will not be able to load until they are present again.\n\n"); + + failedElements.asMap().forEach((name, entries) -> + { + buf.append("Missing ").append(name).append(":\n"); + entries.forEach(rl -> buf.append(" ").append(rl).append("\n")); + }); + + StartupQuery.notify(buf.toString()); + StartupQuery.abort(); + } + } +} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/PatchingTransformer.java b/src/main/java/net/minecraftforge/fml/LogicalSide.java similarity index 61% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/PatchingTransformer.java rename to src/main/java/net/minecraftforge/fml/LogicalSide.java index 94a31758e..df596a97c 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/PatchingTransformer.java +++ b/src/main/java/net/minecraftforge/fml/LogicalSide.java @@ -1,6 +1,6 @@ /* * Minecraft Forge - * Copyright (c) 2016-2018. + * Copyright (c) 2018. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -17,16 +17,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; - -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraftforge.fml.common.patcher.ClassPatchManager; - -public class PatchingTransformer implements IClassTransformer { - @Override - public byte[] transform(String name, String transformedName, byte[] bytes) - { - return ClassPatchManager.INSTANCE.applyPatch(name, transformedName, bytes); - } +package net.minecraftforge.fml; +public enum LogicalSide +{ + CLIENT, SERVER } diff --git a/src/main/java/net/minecraftforge/fml/ModContainer.java b/src/main/java/net/minecraftforge/fml/ModContainer.java index 979a5155d..0a28de436 100644 --- a/src/main/java/net/minecraftforge/fml/ModContainer.java +++ b/src/main/java/net/minecraftforge/fml/ModContainer.java @@ -20,6 +20,7 @@ package net.minecraftforge.fml; import net.minecraftforge.fml.language.IModInfo; +import net.minecraftforge.fml.network.Networking; import java.util.ArrayList; import java.util.HashMap; @@ -51,7 +52,6 @@ public abstract class ModContainer protected final Map> triggerMap; protected final Map> extensionPoints = new IdentityHashMap<>(); protected final List modLoadingError; - public ModContainer(IModInfo info) { this.modId = info.getModId(); diff --git a/src/main/java/net/minecraftforge/fml/ModList.java b/src/main/java/net/minecraftforge/fml/ModList.java index 4451b7237..032857e06 100644 --- a/src/main/java/net/minecraftforge/fml/ModList.java +++ b/src/main/java/net/minecraftforge/fml/ModList.java @@ -39,6 +39,7 @@ import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.FutureTask; +import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @@ -157,4 +158,9 @@ public class ModList return modFileScanData; } + + public void forEachModFile(Consumer fileConsumer) + { + modFiles.stream().map(ModFileInfo::getFile).forEach(fileConsumer); + } } diff --git a/src/main/java/net/minecraftforge/fml/ModLoader.java b/src/main/java/net/minecraftforge/fml/ModLoader.java index 58efba084..6f98f5724 100644 --- a/src/main/java/net/minecraftforge/fml/ModLoader.java +++ b/src/main/java/net/minecraftforge/fml/ModLoader.java @@ -19,7 +19,8 @@ package net.minecraftforge.fml; -import net.minecraftforge.api.Side; +import com.google.common.collect.Streams; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.CapabilityManager; @@ -32,6 +33,7 @@ import net.minecraftforge.registries.GameData; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.List; import java.util.Map; @@ -39,6 +41,9 @@ import java.util.Objects; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static net.minecraftforge.fml.Logging.CORE; public class ModLoader { @@ -69,16 +74,30 @@ public class ModLoader public void loadMods() { final ModList modList = ModList.of(loadingModList.getModFiles().stream().map(ModFileInfo::getFile).collect(Collectors.toList()), loadingModList.getMods()); - modList.setLoadedMods(loadingModList.getModFiles().stream(). + final ModContainer forgeModContainer; + try + { + forgeModContainer = (ModContainer)Class.forName("net.minecraftforge.common.ForgeModContainer", true, modClassLoader). + getConstructor(ModLoadingClassLoader.class).newInstance(modClassLoader); + } + catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException e) + { + LOGGER.error(CORE,"Unable to load the Forge Mod Container", e); + throw new RuntimeException(e); + } + final Stream modContainerStream = loadingModList.getModFiles().stream(). map(ModFileInfo::getFile). map(mf -> buildMods(mf, modClassLoader)). - flatMap(Collection::stream).collect(Collectors.toList())); + flatMap(Collection::stream); + modList.setLoadedMods(Streams.concat(Stream.of(forgeModContainer), modContainerStream).collect(Collectors.toList())); LifecycleEventProvider.CONSTRUCT.dispatch(); + WorldPersistenceHooks.addHook(new FMLWorldPersistenceHook()); + WorldPersistenceHooks.addHook((WorldPersistenceHooks.WorldPersistenceHook)forgeModContainer.getMod()); GameData.fireCreateRegistryEvents(); CapabilityManager.INSTANCE.injectCapabilities(modList.getAllScanData()); LifecycleEventProvider.PREINIT.dispatch(); GameData.fireRegistryEvents(rl -> !Objects.equals(rl, GameData.RECIPES)); - SidedExecutor.runOn(Side.CLIENT, ModLoader::fireClientEvents); + SidedExecutor.runOn(Dist.CLIENT, ModLoader::fireClientEvents); LifecycleEventProvider.SIDEDINIT.dispatch(); } @@ -97,5 +116,7 @@ public class ModLoader LifecycleEventProvider.INIT.dispatch(); LifecycleEventProvider.POSTINIT.dispatch(); LifecycleEventProvider.COMPLETE.dispatch(); + GameData.freezeData(); } + } diff --git a/src/main/java/net/minecraftforge/fml/ModThreadContext.java b/src/main/java/net/minecraftforge/fml/ModThreadContext.java index 90e0f6375..72f33d934 100644 --- a/src/main/java/net/minecraftforge/fml/ModThreadContext.java +++ b/src/main/java/net/minecraftforge/fml/ModThreadContext.java @@ -27,9 +27,13 @@ public class ModThreadContext return context.get(); } - private ModContainer currentContainer; + private ModContainer activeContainer; - public ModContainer getCurrentContainer() { - return currentContainer == null ? DefaultModContainers.MINECRAFT : currentContainer; + public void setActiveContainer(final ModContainer container) { + this.activeContainer = container; + } + + public ModContainer getActiveContainer() { + return activeContainer == null ? DefaultModContainers.MINECRAFT : activeContainer; } } diff --git a/src/main/java/net/minecraftforge/fml/RegistryObject.java b/src/main/java/net/minecraftforge/fml/RegistryObject.java index 5a9fab30d..211e0a5aa 100644 --- a/src/main/java/net/minecraftforge/fml/RegistryObject.java +++ b/src/main/java/net/minecraftforge/fml/RegistryObject.java @@ -20,7 +20,6 @@ package net.minecraftforge.fml; import net.minecraft.util.ResourceLocation; -import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.IForgeRegistry; import net.minecraftforge.registries.IForgeRegistryEntry; import net.minecraftforge.registries.RegistryManager; diff --git a/src/main/java/net/minecraftforge/fml/ServerLifecycleHooks.java b/src/main/java/net/minecraftforge/fml/ServerLifecycleHooks.java new file mode 100644 index 000000000..fd0ef10a4 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/ServerLifecycleHooks.java @@ -0,0 +1,156 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml; + +import net.minecraft.network.EnumConnectionState; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.handshake.client.C00Handshake; +import net.minecraft.network.login.server.SPacketDisconnect; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.text.TextComponentString; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.FMLLog; +import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; +import net.minecraftforge.fml.common.event.FMLServerStartedEvent; +import net.minecraftforge.fml.common.event.FMLServerStartingEvent; +import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; +import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.network.NetworkHooks; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; + +public class ServerLifecycleHooks +{ + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker SERVERHOOKS = MarkerManager.getMarker("SERVERHOOKS"); + private static volatile CountDownLatch exitLatch = null; + private static MinecraftServer currentServer; + + public static boolean handleServerAboutToStart(final MinecraftServer server) + { + currentServer = server; + return !MinecraftForge.EVENT_BUS.post(new FMLServerAboutToStartEvent(server)); + } + + public static boolean handleServerStarting(final MinecraftServer server) + { + return !MinecraftForge.EVENT_BUS.post(new FMLServerStartingEvent(server)); + } + + public static void handleServerStarted() + { + MinecraftForge.EVENT_BUS.post(new FMLServerStartedEvent()); + allowLogins.set(true); + } + + public static void handleServerStopping() + { + allowLogins.set(false); + MinecraftForge.EVENT_BUS.post(new FMLServerStoppingEvent()); + } + + public static void expectServerStopped() + { + exitLatch = new CountDownLatch(1); + } + + public static void handleServerStopped(final MinecraftServer server) + { + MinecraftForge.EVENT_BUS.post(new FMLServerStoppedEvent()); + currentServer = null; + CountDownLatch latch = exitLatch; + + if (latch != null) + { + latch.countDown(); + exitLatch = null; + } + } + + public static MinecraftServer getCurrentServer() + { + return currentServer; + } + private static AtomicBoolean allowLogins = new AtomicBoolean(false); + + public static boolean handleServerLogin(final C00Handshake packet, final NetworkManager manager) { + if (!allowLogins.get()) + { + TextComponentString text = new TextComponentString("Server is still starting! Please wait before reconnecting."); + LOGGER.info(SERVERHOOKS,"Disconnecting Player (server is still starting): {}", text.getUnformattedText()); + manager.sendPacket(new SPacketDisconnect(text)); + manager.closeChannel(text); + return false; + } + + if (packet.getRequestedState() == EnumConnectionState.LOGIN && !NetworkHooks.accepts(packet)) + { + manager.setConnectionState(EnumConnectionState.LOGIN); + TextComponentString text = new TextComponentString("This server has mods that require Forge to be installed on the client. Contact your server admin for more details."); + List modNames = net.minecraftforge.fml.network.NetworkRegistry.getNonVanillaNetworkMods(); + LOGGER.info(SERVERHOOKS,"Disconnecting vanilla connection attempt. Required mods {}", modNames); + manager.sendPacket(new SPacketDisconnect(text)); + manager.closeChannel(text); + return false; + } + + manager.channel().attr(NetworkRegistry.FML_MARKER).set(packet.getFMLVersion()); + return true; + + } + + public void handleExit(int retVal) + { +/* + CountDownLatch latch = exitLatch; + + if (latch != null) + { + try + { + FMLLog.log.info("Waiting for the server to terminate/save."); + if (!latch.await(10, TimeUnit.SECONDS)) + { + FMLLog.log.warn("The server didn't stop within 10 seconds, exiting anyway."); + } + else + { + FMLLog.log.info("Server terminated."); + } + } + catch (InterruptedException e) + { + FMLLog.log.warn("Interrupted wait, exiting."); + } + } + +*/ + System.exit(retVal); + } + +} diff --git a/src/main/java/net/minecraftforge/fml/SidedExecutor.java b/src/main/java/net/minecraftforge/fml/SidedExecutor.java index 0de311715..c2bbccb6f 100644 --- a/src/main/java/net/minecraftforge/fml/SidedExecutor.java +++ b/src/main/java/net/minecraftforge/fml/SidedExecutor.java @@ -19,7 +19,7 @@ package net.minecraftforge.fml; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.loading.FMLEnvironment; import java.util.concurrent.Callable; @@ -32,13 +32,13 @@ public final class SidedExecutor /** * Run the callable in the supplier only on the specified {@link Side} * - * @param side The side to run on - * @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate side) + * @param dist The dist to run on + * @param toRun A supplier of the callable to run (Supplier wrapper to ensure classloading only on the appropriate dist) * @param The return type from the callable * @return The callable's result */ - public static T runOn(Side side, Supplier> toRun) { - if (side == FMLEnvironment.side) { + public static T runOn(Dist dist, Supplier> toRun) { + if (dist == FMLEnvironment.dist) { try { return toRun.get().call(); @@ -52,11 +52,11 @@ public final class SidedExecutor } public static T runSided(Supplier> clientTarget, Supplier> serverTarget) { - switch (FMLEnvironment.side) + switch (FMLEnvironment.dist) { case CLIENT: return clientTarget.get().get(); - case SERVER: + case DEDICATED_SERVER: return serverTarget.get().get(); default: throw new IllegalArgumentException("UNSIDED?"); diff --git a/src/main/java/net/minecraftforge/fml/SidedProvider.java b/src/main/java/net/minecraftforge/fml/SidedProvider.java index 0952517d9..cab3cb3be 100644 --- a/src/main/java/net/minecraftforge/fml/SidedProvider.java +++ b/src/main/java/net/minecraftforge/fml/SidedProvider.java @@ -21,13 +21,12 @@ package net.minecraftforge.fml; import net.minecraft.client.Minecraft; import net.minecraft.server.dedicated.DedicatedServer; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.client.SplashProgress; import net.minecraftforge.fml.common.event.FMLClientInitEvent; import net.minecraftforge.fml.common.event.FMLServerInitEvent; import net.minecraftforge.fml.loading.FMLEnvironment; -import sun.plugin.security.StripClassFile; import java.util.function.Function; import java.util.function.Supplier; @@ -38,7 +37,8 @@ public enum SidedProvider SIDEDINIT((Function, Function>)c-> mc->new FMLClientInitEvent(c.get(), mc), (Function, Function>)s-> mc->new FMLServerInitEvent(s.get(), mc)), STRIPCHARS((Function, Function>)c-> SplashProgress::stripSpecialChars, - (Function, Function>)s-> str->str); + (Function, Function>)s-> str->str), + STARTUPQUERY(StartupQuery::clientQuery, StartupQuery::dedicatedServerQuery); private static Supplier client; private static Supplier server; @@ -64,10 +64,10 @@ public enum SidedProvider @SuppressWarnings("unchecked") public T get() { - if (FMLEnvironment.side == Side.CLIENT) { + if (FMLEnvironment.dist == Dist.CLIENT) { return (T)this.clientSide.apply(client); } - else if (FMLEnvironment.side == Side.SERVER) { + else if (FMLEnvironment.dist == Dist.DEDICATED_SERVER) { return (T)this.serverSide.apply(server); } else { diff --git a/src/main/java/net/minecraftforge/fml/StartupQuery.java b/src/main/java/net/minecraftforge/fml/StartupQuery.java new file mode 100644 index 000000000..9e84c8e9c --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/StartupQuery.java @@ -0,0 +1,322 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml; + +import java.util.Iterator; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import net.minecraft.client.Minecraft; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.dedicated.DedicatedServer; +import net.minecraft.server.dedicated.PendingCommand; +import net.minecraftforge.fml.client.gui.GuiConfirmation; +import net.minecraftforge.fml.client.gui.GuiNotification; +import net.minecraftforge.fml.common.thread.EffectiveSide; +import net.minecraftforge.fml.loading.FMLEnvironment; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; + +import javax.annotation.Nullable; + +public class StartupQuery { + // internal class/functionality, do not use + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker SQ = MarkerManager.getMarker("STARTUPQUERY"); + + public static boolean confirm(String text) + { + StartupQuery query = new StartupQuery(text, new AtomicBoolean()); + query.execute(); + return query.getResult(); + } + + private InterruptedException exception; + + public static void notify(String text) + { + StartupQuery query = new StartupQuery(text, null); + query.execute(); + } + + public static void abort() + { + MinecraftServer server = ServerLifecycleHooks.getCurrentServer(); + if (server != null) server.initiateShutdown(); + + aborted = true; // to abort loading and go back to the main menu + throw new AbortedException(); // to halt the server + } + + + public static void reset() + { + pending = null; + aborted = false; + } + + public static boolean check() + { + if (pending != null) + { + try + { + try + { + SidedProvider.STARTUPQUERY.>get().accept(pending); + } + catch (RuntimeException e) + { + } + pending.throwException(); + } + catch (InterruptedException e) + { + LOGGER.warn(SQ, "query interrupted"); + abort(); + } + + pending = null; + } + + return !aborted; + } + + private void throwException() throws InterruptedException + { + if (exception != null) throw exception; + } + + private static volatile StartupQuery pending; + private static volatile boolean aborted = false; + + + private StartupQuery(String text, @Nullable AtomicBoolean result) + { + this.text = text; + this.result = result; + } + + @Nullable + public Boolean getResult() + { + return result == null ? null : result.get(); + } + + public void setResult(boolean result) + { + this.result.set(result); + } + + public String getText() + { + return text; + } + + public boolean isSynchronous() + { + return synchronous; + } + + public void finish() + { + signal.countDown(); + } + + private void execute() + { + String prop = System.getProperty("fml.queryResult"); + + if (result != null && prop != null) + { + LOGGER.info(SQ, "Using fml.queryResult {} to answer the following query:\n{}", prop, text); + + if (prop.equalsIgnoreCase("confirm")) + { + setResult(true); + return; + } + else if (prop.equalsIgnoreCase("cancel")) + { + setResult(false); + return; + } + + LOGGER.warn(SQ, "Invalid value for fml.queryResult: {}, expected confirm or cancel", prop); + } + + synchronous = false; + pending = this; // let the other thread start the query + + // from the integrated server thread: the client will eventually check pending and execute the query + // from the client thread: synchronous execution + // dedicated server: command handling in mc is synchronous, execute the server-side query directly + if (FMLEnvironment.dist.isDedicatedServer() || EffectiveSide.get() == LogicalSide.CLIENT) + { + synchronous = true; + check(); + } + + try + { + signal.await(); + reset(); + } + catch (InterruptedException e) + { + LOGGER.warn(SQ, "query interrupted"); + abort(); + } + } + + private String text; + @Nullable + private AtomicBoolean result; + private CountDownLatch signal = new CountDownLatch(1); + private volatile boolean synchronous; + + + /** + * Exception not being caught by the crash report generation logic. + */ + public static class AbortedException extends RuntimeException + { + private static final long serialVersionUID = -5933665223696833921L; + + private AbortedException() + { + super(); + } + } + + + + public static Consumer clientQuery(Supplier clientSupplier) + { + return (query) -> { + Minecraft client = clientSupplier.get(); + if (query.getResult() == null) + { + client.displayGuiScreen(new GuiNotification(query)); + } + else + { + client.displayGuiScreen(new GuiConfirmation(query)); + } + + if (query.isSynchronous()) + { + while (client.currentScreen instanceof GuiNotification) + { + if (Thread.interrupted()) { + query.exception = new InterruptedException(); + throw new RuntimeException(); + } + + client.loadingScreen.displayLoadingString(""); + + try + { + Thread.sleep(50); + } catch (InterruptedException ie) { + query.exception = ie; + } + } + + client.loadingScreen.displayLoadingString(""); // make sure the blank screen is being drawn at the end + } + }; + } + + public static Consumer dedicatedServerQuery(Supplier serverSupplier) + { + return (query) -> { + DedicatedServer server = serverSupplier.get(); + if (query.getResult() == null) + { + LOGGER.warn(SQ, query.getText()); + query.finish(); + } + else + { + String text = query.getText() + + "\n\nRun the command /fml confirm or or /fml cancel to proceed." + + "\nAlternatively start the server with -Dfml.queryResult=confirm or -Dfml.queryResult=cancel to preselect the answer."; + LOGGER.warn(SQ, text); + + if (!query.isSynchronous()) return; // no-op until mc does commands in another thread (if ever) + + boolean done = false; + + while (!done && server.isServerRunning()) + { + if (Thread.interrupted()) + { + query.exception = new InterruptedException(); + throw new RuntimeException(); + } + + DedicatedServer dedServer = (DedicatedServer)server; + + // rudimentary command processing, check for fml confirm/cancel and stop commands + synchronized (dedServer.pendingCommandList) + { + for (Iterator it = dedServer.pendingCommandList.iterator(); it.hasNext(); ) + { + String cmd = it.next().command.trim().toLowerCase(); + + if (cmd.equals("/fml confirm")) + { + LOGGER.info(SQ, "confirmed"); + query.setResult(true); + done = true; + it.remove(); + } + else if (cmd.equals("/fml cancel")) + { + LOGGER.info(SQ, "cancelled"); + query.setResult(false); + done = true; + it.remove(); + } + else if (cmd.equals("/stop")) + { + StartupQuery.abort(); + } + } + } + try + { + Thread.sleep(10L); + } catch (InterruptedException ie) { + query.exception = ie; + } + } + + query.finish(); + } + }; + } + +} diff --git a/src/main/java/net/minecraftforge/fml/WorldPersistenceHooks.java b/src/main/java/net/minecraftforge/fml/WorldPersistenceHooks.java new file mode 100644 index 000000000..7fad4ad2d --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/WorldPersistenceHooks.java @@ -0,0 +1,81 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml; + +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.storage.SaveHandler; +import net.minecraft.world.storage.WorldInfo; +import net.minecraftforge.fml.common.thread.EffectiveSide; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WorldPersistenceHooks +{ + private static List worldPersistenceHooks = new ArrayList<>(); + + public static void addHook(WorldPersistenceHook hook) { + worldPersistenceHooks.add(hook); + } + + public static void handleWorldDataSave(final SaveHandler handler, final WorldInfo worldInfo, final NBTTagCompound tagCompound) + { + worldPersistenceHooks.forEach(wac->tagCompound.setTag(wac.getModId(), wac.getDataForWriting(handler, worldInfo))); + } + + public static void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound) + { + if (EffectiveSide.get() == LogicalSide.SERVER) + { + Map additionalProperties = new HashMap<>(); + worldInfo.setAdditionalProperties(additionalProperties); + worldPersistenceHooks.forEach(wac->wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(wac.getModId()))); + } + } + + public static void confirmBackupLevelDatUse(SaveHandler handler) + { +/* + if (handlerToCheck == null || handlerToCheck.get() != handler) { + // only run if the save has been initially loaded + handlerToCheck = null; + return; + } + + String text = "Forge Mod Loader detected that the backup level.dat is being used.\n\n" + + "This may happen due to a bug or corruption, continuing can damage\n" + + "your world beyond repair or lose data / progress.\n\n" + + "It's recommended to create a world backup before continuing."; + + boolean confirmed = StartupQuery.confirm(text); + if (!confirmed) StartupQuery.abort(); +*/ + } + + public interface WorldPersistenceHook + { + String getModId(); + NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info); + void readData(SaveHandler handler, WorldInfo info, Map propertyMap, NBTTagCompound tag); + } +} diff --git a/src/main/java/net/minecraftforge/fml/client/ClientHooks.java b/src/main/java/net/minecraftforge/fml/client/ClientHooks.java new file mode 100644 index 000000000..437a89e81 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/client/ClientHooks.java @@ -0,0 +1,197 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.client; + +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiWorldSelection; +import net.minecraft.client.gui.ServerListEntryNormal; +import net.minecraft.client.multiplayer.ServerData; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.ServerStatusResponse; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.storage.WorldSummary; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.StartupQuery; +import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; +import net.minecraftforge.registries.GameData; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; + +import javax.annotation.Nullable; +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; + +public class ClientHooks +{ + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS"); + + private static Map extraServerListData; + private static Map serverDataTag; + + public static void setupServerList() + { + extraServerListData = Collections.synchronizedMap(new HashMap<>()); + serverDataTag = Collections.synchronizedMap(new HashMap<>()); + } + + public static void captureAdditionalData(ServerStatusResponse serverstatusresponse, JsonObject jsonobject) + { + if (jsonobject.has("modinfo")) + { + JsonObject fmlData = jsonobject.get("modinfo").getAsJsonObject(); + extraServerListData.put(serverstatusresponse, fmlData); + } + } + public static void bindServerListData(ServerData data, ServerStatusResponse originalResponse) + { + if (extraServerListData.containsKey(originalResponse)) + { + JsonObject jsonData = extraServerListData.get(originalResponse); + String type = jsonData.get("type").getAsString(); + JsonArray modDataArray = jsonData.get("modList").getAsJsonArray(); + boolean moddedClientAllowed = !jsonData.has("clientModsAllowed") || jsonData.get("clientModsAllowed").getAsBoolean(); + ImmutableMap.Builder modListBldr = ImmutableMap.builder(); + for (JsonElement obj : modDataArray) + { + JsonObject modObj = obj.getAsJsonObject(); + modListBldr.put(modObj.get("modid").getAsString(), modObj.get("version").getAsString()); + } + + Map modListMap = modListBldr.build(); + String modRejections = FMLNetworkHandler.checkModList(modListMap, LogicalSide.SERVER); + serverDataTag.put(data, new ExtendedServerListData(type, modRejections == null, modListMap, !moddedClientAllowed)); + } + else + { + String serverDescription = data.serverMOTD; + boolean moddedClientAllowed = true; + if (!Strings.isNullOrEmpty(serverDescription)) + { + moddedClientAllowed = !serverDescription.endsWith(":NOFML§r"); + } + serverDataTag.put(data, new ExtendedServerListData("VANILLA", false, ImmutableMap.of(), !moddedClientAllowed)); + } + startupConnectionData.countDown(); + } + + private static final ResourceLocation iconSheet = new ResourceLocation("fml:textures/gui/icons.png"); + private static final CountDownLatch startupConnectionData = new CountDownLatch(1); + + @Nullable + public static String enhanceServerListEntry(ServerListEntryNormal serverListEntry, ServerData serverEntry, int x, int width, int y, int relativeMouseX, int relativeMouseY) + { + String tooltip; + int idx; + boolean blocked = false; + if (serverDataTag.containsKey(serverEntry)) + { + ExtendedServerListData extendedData = serverDataTag.get(serverEntry); + if ("FML".equals(extendedData.type) && extendedData.isCompatible) + { + idx = 0; + tooltip = String.format("Compatible FML modded server\n%d mods present", extendedData.modData.size()); + } + else if ("FML".equals(extendedData.type) && !extendedData.isCompatible) + { + idx = 16; + tooltip = String.format("Incompatible FML modded server\n%d mods present", extendedData.modData.size()); + } + else if ("BUKKIT".equals(extendedData.type)) + { + idx = 32; + tooltip = String.format("Bukkit modded server"); + } + else if ("VANILLA".equals(extendedData.type)) + { + idx = 48; + tooltip = String.format("Vanilla server"); + } + else + { + idx = 64; + tooltip = String.format("Unknown server data"); + } + blocked = extendedData.isBlocked; + } + else + { + return null; + } + Minecraft.getMinecraft().getTextureManager().bindTexture(iconSheet); + Gui.drawModalRectWithCustomSizedTexture(x + width - 18, y + 10, 0, (float)idx, 16, 16, 256.0f, 256.0f); + if (blocked) + { + Gui.drawModalRectWithCustomSizedTexture(x + width - 18, y + 10, 0, 80, 16, 16, 256.0f, 256.0f); + } + + return relativeMouseX > width - 15 && relativeMouseX < width && relativeMouseY > 10 && relativeMouseY < 26 ? tooltip : null; + } + + public static String fixDescription(String description) + { + return description.endsWith(":NOFML§r") ? description.substring(0, description.length() - 8)+"§r" : description; + } + + static File getSavesDir() + { + return new File(Minecraft.getMinecraft().mcDataDir, "saves"); + } + + public static void tryLoadExistingWorld(GuiWorldSelection selectWorldGUI, WorldSummary comparator) + { + try + { + Minecraft.getMinecraft().launchIntegratedServer(comparator.getFileName(), comparator.getDisplayName(), null); + } + catch (StartupQuery.AbortedException e) + { + // ignore + } + } + + private static NetworkManager getClientToServerNetworkManager() + { + return Minecraft.getMinecraft().getConnection()!=null ? Minecraft.getMinecraft().getConnection().getNetworkManager() : null; + } + + public static void handleClientWorldClosing(WorldClient world) + { + NetworkManager client = getClientToServerNetworkManager(); + // ONLY revert a non-local connection + if (client != null && !client.isLocalChannel()) + { + GameData.revertToFrozen(); + } + } + +} diff --git a/src/main/java/net/minecraftforge/fml/client/ClientModLoader.java b/src/main/java/net/minecraftforge/fml/client/ClientModLoader.java index bb186a92d..09808fe50 100644 --- a/src/main/java/net/minecraftforge/fml/client/ClientModLoader.java +++ b/src/main/java/net/minecraftforge/fml/client/ClientModLoader.java @@ -25,8 +25,8 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourcePack; import net.minecraft.client.resources.data.MetadataSerializer; -import net.minecraftforge.api.Side; -import net.minecraftforge.api.SideOnly; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.SidedProvider; import net.minecraftforge.fml.VersionChecker; import net.minecraftforge.fml.ModLoader; @@ -37,7 +37,7 @@ import org.lwjgl.input.Mouse; import java.io.IOException; import java.util.List; -@SideOnly(Side.CLIENT) +@OnlyIn(Dist.CLIENT) public class ClientModLoader { private static boolean loading; diff --git a/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java b/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java index 0cb8a7ec8..d9ecb3241 100644 --- a/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java +++ b/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java @@ -113,14 +113,12 @@ import net.minecraftforge.fml.common.MetadataCollection; import net.minecraftforge.fml.common.MissingModsException; import net.minecraftforge.fml.common.MultipleModsErrored; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.ModMetadata; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.common.WrongMinecraftVersionException; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; import net.minecraftforge.fml.common.toposort.ModSortingException; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.registries.GameData; import org.lwjgl.input.Mouse; diff --git a/src/main/java/net/minecraftforge/fml/client/gui/CustomModLoadingErrorDisplayException.java b/src/main/java/net/minecraftforge/fml/client/gui/CustomModLoadingErrorDisplayException.java index 820d6f2d6..7889e8f1e 100644 --- a/src/main/java/net/minecraftforge/fml/client/gui/CustomModLoadingErrorDisplayException.java +++ b/src/main/java/net/minecraftforge/fml/client/gui/CustomModLoadingErrorDisplayException.java @@ -21,11 +21,10 @@ package net.minecraftforge.fml.client.gui; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiErrorScreen; -import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.common.EnhancedRuntimeException; import net.minecraftforge.fml.common.IFMLHandledException; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; /** * If a mod throws this exception during loading, it will be called back to render @@ -37,7 +36,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; * @author cpw * */ -@SideOnly(Side.CLIENT) +@OnlyIn(Dist.CLIENT) public abstract class CustomModLoadingErrorDisplayException extends EnhancedRuntimeException implements IFMLHandledException, IDisplayableError { public CustomModLoadingErrorDisplayException() { diff --git a/src/main/java/net/minecraftforge/fml/client/gui/GuiConfirmation.java b/src/main/java/net/minecraftforge/fml/client/gui/GuiConfirmation.java index 196685b49..f30b28046 100644 --- a/src/main/java/net/minecraftforge/fml/client/gui/GuiConfirmation.java +++ b/src/main/java/net/minecraftforge/fml/client/gui/GuiConfirmation.java @@ -23,7 +23,7 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiOptionButton; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; public class GuiConfirmation extends GuiNotification { diff --git a/src/main/java/net/minecraftforge/fml/client/gui/GuiNotification.java b/src/main/java/net/minecraftforge/fml/client/gui/GuiNotification.java index 201ae7643..952154d47 100644 --- a/src/main/java/net/minecraftforge/fml/client/gui/GuiNotification.java +++ b/src/main/java/net/minecraftforge/fml/client/gui/GuiNotification.java @@ -23,7 +23,7 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; public class GuiNotification extends GuiScreen { diff --git a/src/main/java/net/minecraftforge/fml/client/gui/GuiOldSaveLoadConfirm.java b/src/main/java/net/minecraftforge/fml/client/gui/GuiOldSaveLoadConfirm.java index ea45e7ee4..7108ef161 100644 --- a/src/main/java/net/minecraftforge/fml/client/gui/GuiOldSaveLoadConfirm.java +++ b/src/main/java/net/minecraftforge/fml/client/gui/GuiOldSaveLoadConfirm.java @@ -28,7 +28,7 @@ import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.common.ZipperUtil; public class GuiOldSaveLoadConfirm extends GuiYesNo implements GuiYesNoCallback { diff --git a/src/main/java/net/minecraftforge/fml/common/FMLCommonHandler.java b/src/main/java/net/minecraftforge/fml/common/FMLCommonHandler.java index a2fd9abcf..9f07c9203 100644 --- a/src/main/java/net/minecraftforge/fml/common/FMLCommonHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/FMLCommonHandler.java @@ -52,7 +52,10 @@ import net.minecraftforge.client.model.animation.Animation; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.CompoundDataFixer; -import net.minecraftforge.fml.client.BrandingControl; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.StartupQuery; +import net.minecraftforge.fml.WorldPersistenceHooks; +import net.minecraftforge.fml.BrandingControl; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.gameevent.InputEvent; @@ -63,7 +66,6 @@ import net.minecraftforge.fml.common.network.FMLNetworkEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.thread.SidedThreadGroup; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.server.FMLServerHandler; import org.apache.logging.log4j.Logger; @@ -320,7 +322,7 @@ public class FMLCommonHandler { if (mc instanceof InjectedModContainer) { - WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); + WorldPersistenceHooks.WorldPersistenceHook wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); if (wac != null) { NBTTagCompound dataForWriting = wac.getDataForWriting(handler, worldInfo); @@ -332,7 +334,7 @@ public class FMLCommonHandler public void handleWorldDataLoad(SaveHandler handler, WorldInfo worldInfo, NBTTagCompound tagCompound) { - if (getEffectiveSide()!=Side.SERVER) + if (getEffectiveSide()!=LogicalSide.SERVER) { return; } @@ -348,7 +350,7 @@ public class FMLCommonHandler { if (mc instanceof InjectedModContainer) { - WorldAccessContainer wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); + WorldPersistenceHooks.WorldPersistenceHook wac = ((InjectedModContainer)mc).getWrappedWorldAccessContainer(); if (wac != null) { wac.readData(handler, worldInfo, additionalProperties, tagCompound.getCompoundTag(mc.getModId())); @@ -564,7 +566,7 @@ public class FMLCommonHandler if (!shouldAllowPlayerLogins()) { TextComponentString text = new TextComponentString("Server is still starting! Please wait before reconnecting."); - FMLLog.log.info("Disconnecting Player: {}", text.getUnformattedText()); + LOGGER.info("Disconnecting Player: {}", text.getUnformattedText()); manager.sendPacket(new SPacketDisconnect(text)); manager.closeChannel(text); return false; diff --git a/src/main/java/net/minecraftforge/fml/common/FMLContainer.java b/src/main/java/net/minecraftforge/fml/common/FMLContainer.java deleted file mode 100644 index 999cd1727..000000000 --- a/src/main/java/net/minecraftforge/fml/common/FMLContainer.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.io.File; -import java.security.cert.Certificate; -import java.util.Arrays; -import java.util.Map; -import net.minecraft.nbt.NBTBase; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.storage.SaveHandler; -import net.minecraft.world.storage.WorldInfo; -import net.minecraftforge.fml.client.FMLFileResourcePack; -import net.minecraftforge.fml.client.FMLFolderResourcePack; -import net.minecraftforge.fml.common.asm.FMLSanityChecker; -import net.minecraftforge.fml.common.event.FMLConstructionEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.network.NetworkCheckHandler; -import net.minecraftforge.fml.common.network.NetworkRegistry; -import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; -import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.GameData; -import net.minecraftforge.registries.RegistryManager; - -import org.apache.logging.log4j.LogManager; - -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; -import org.apache.logging.log4j.Logger; - -import javax.annotation.Nullable; - -/** - * @author cpw - * - */ -public final class FMLContainer extends DummyModContainer implements WorldAccessContainer -{ - private static final Logger modTrackerLogger = LogManager.getLogger("FML.ModTracker"); - - public FMLContainer() - { - super(new ModMetadata()); - ModMetadata meta = getMetadata(); - meta.modId="FML"; - meta.name="Forge Mod Loader"; - meta.version=Loader.instance().getFMLVersionString(); - meta.credits="Made possible with help from many people"; - meta.authorList=Arrays.asList("cpw", "LexManos", "Player"); - meta.description="The Forge Mod Loader provides the ability for systems to load mods " + - "from the file system. It also provides key capabilities for mods to be able " + - "to cooperate and provide a good modding environment. "; - meta.url="https://github.com/MinecraftForge/FML/wiki"; - meta.screenshots=new String[0]; - meta.logoFile=""; - } - - @Override - public boolean registerBus(EventBus bus, LoadController controller) - { - bus.register(this); - return true; - } - - @Subscribe - public void modConstruction(FMLConstructionEvent evt) - { - NetworkRegistry.INSTANCE.register(this, this.getClass(), null, evt.getASMHarvestedData()); - FMLNetworkHandler.registerChannel(this, evt.getSide()); - } - - @Subscribe - public void modPreinitialization(FMLPreInitializationEvent evt) - { - // Initialize all Forge/Vanilla registries {invoke the static init) - if (ForgeRegistries.ITEMS == null) - throw new RuntimeException("Something horrible went wrong in init, ForgeRegistres didn't create..."); - } - - @NetworkCheckHandler - public boolean checkModLists(Map modList, Side side) - { - return Loader.instance().checkRemoteModList(modList,side); - } - - @Override - public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info) - { - NBTTagCompound fmlData = new NBTTagCompound(); - NBTTagList modList = new NBTTagList(); - for (ModContainer mc : Loader.instance().getActiveModList()) - { - NBTTagCompound mod = new NBTTagCompound(); - mod.setString("ModId", mc.getModId()); - mod.setString("ModVersion", mc.getVersion()); - modList.appendTag(mod); - } - fmlData.setTag("LoadingModList", modList); - - NBTTagCompound registries = new NBTTagCompound(); - fmlData.setTag("Registries", registries); - FMLLog.log.debug("Gathering id map for writing to world save {}", info.getWorldName()); - - for (Map.Entry e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet()) - { - registries.setTag(e.getKey().toString(), e.getValue().write()); - } - return fmlData; - } - - @Override - public void readData(SaveHandler handler, WorldInfo info, Map propertyMap, NBTTagCompound tag) - { - if (tag.hasKey("LoadingModList")) - { - NBTTagList modList = tag.getTagList("LoadingModList", (byte)10); - for (int i = 0; i < modList.tagCount(); i++) - { - NBTTagCompound mod = modList.getCompoundTagAt(i); - String modId = mod.getString("ModId"); - String modVersion = mod.getString("ModVersion"); - ModContainer container = Loader.instance().getIndexedModList().get(modId); - if (container == null) - { - modTrackerLogger.error("This world was saved with mod {} which appears to be missing, things may not work well", modId); - continue; - } - if (!modVersion.equals(container.getVersion())) - { - modTrackerLogger.info("This world was saved with mod {} version {} and it is now at version {}, things may not work well", modId, modVersion, container.getVersion()); - } - } - } - - Multimap failedElements = null; - - if (tag.hasKey("ModItemData") || tag.hasKey("ItemData")) // Pre 1.7 - { - StartupQuery.notify("This save predates 1.7.10, it can no longer be loaded here. Please load in 1.7.10 or 1.8 first"); - StartupQuery.abort(); - } - else if (tag.hasKey("Registries")) // 1.8, genericed out the 'registries' list - { - Map snapshot = Maps.newHashMap(); - NBTTagCompound regs = tag.getCompoundTag("Registries"); - for (String key : regs.getKeySet()) - { - snapshot.put(new ResourceLocation(key), ForgeRegistry.Snapshot.read(regs.getCompoundTag(key))); - } - failedElements = GameData.injectSnapshot(snapshot, true, true); - } - - if (failedElements != null && !failedElements.isEmpty()) - { - StringBuilder buf = new StringBuilder(); - buf.append("Forge Mod Loader could not load this save.\n\n") - .append("There are ").append(failedElements.size()).append(" unassigned registry entries in this save.\n") - .append("You will not be able to load until they are present again.\n\n"); - - failedElements.asMap().forEach((name, entries) -> - { - buf.append("Missing ").append(name).append(":\n"); - entries.forEach(rl -> buf.append(" ").append(rl).append("\n")); - }); - - StartupQuery.notify(buf.toString()); - StartupQuery.abort(); - } - } - - - @Override - @Nullable - public Certificate getSigningCertificate() - { - Certificate[] certificates = getClass().getProtectionDomain().getCodeSource().getCertificates(); - return certificates != null ? certificates[0] : null; - } - - @Override - public File getSource() - { - return FMLSanityChecker.fmlLocation; - } - - @Override - public Class getCustomResourcePackClass() - { - return getSource().isDirectory() ? FMLFolderResourcePack.class : FMLFileResourcePack.class; - } - - @Override - public String getGuiClassName() - { - return "net.minecraftforge.fml.client.FMLConfigGuiFactory"; - } - - @Override - public Object getMod() - { - return this; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/FMLLog.java b/src/main/java/net/minecraftforge/fml/common/FMLLog.java index 4b517ecb0..22e2ac96f 100644 --- a/src/main/java/net/minecraftforge/fml/common/FMLLog.java +++ b/src/main/java/net/minecraftforge/fml/common/FMLLog.java @@ -19,12 +19,15 @@ package net.minecraftforge.fml.common; +import java.util.Locale; + import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.relauncher.FMLRelaunchLog; +import net.minecraftforge.api.distmarker.Dist; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.ThreadContext; /** * FMLs logging class. Internal use only, NOT FOR MOD LOGGING! Mods use your own log, see {@link FMLPreInitializationEvent#getModLog()}. diff --git a/src/main/java/net/minecraftforge/fml/common/IFMLSidedHandler.java b/src/main/java/net/minecraftforge/fml/common/IFMLSidedHandler.java index d464e020b..56a46d8f1 100644 --- a/src/main/java/net/minecraftforge/fml/common/IFMLSidedHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/IFMLSidedHandler.java @@ -30,7 +30,7 @@ import net.minecraft.util.IThreadListener; import net.minecraftforge.common.util.CompoundDataFixer; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.StartupQuery; public interface IFMLSidedHandler { diff --git a/src/main/java/net/minecraftforge/fml/common/ILanguageAdapter.java b/src/main/java/net/minecraftforge/fml/common/ILanguageAdapter.java deleted file mode 100644 index 904ea57bb..000000000 --- a/src/main/java/net/minecraftforge/fml/common/ILanguageAdapter.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import net.minecraftforge.fml.javafmlmod.FMLModContainer; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; - -public interface ILanguageAdapter { - Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception; - boolean supportsStatics(); - void setProxy(Field target, Class proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException; - void setInternalProxies(ModContainer mod, Side side, ClassLoader loader); - - public static class ScalaAdapter implements ILanguageAdapter { - @Override - public Object getNewInstance(FMLModContainer container, Class scalaObjectClass, ClassLoader classLoader, Method factoryMarkedAnnotation) throws Exception - { - Class sObjectClass = Class.forName(scalaObjectClass.getName()+"$",true,classLoader); - return sObjectClass.getField("MODULE$").get(null); - } - - @Override - public boolean supportsStatics() - { - return false; - } - - @Override - public void setProxy(Field target, Class proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException - { - try - { - // Get the actual singleton class. The two variants are from - // whether the @SidedProxy is declared in a the class block - // of the object directly, or in the object block, i.e. - // whether it's: - // class ModName { - // @SidedProxy ... - // } - // object ModName extends ModName {} - // which leads to us getting the outer class, or - // object ModName { - // @SidedProxy ... - // } - // which leads to us getting the inner class. - if (!proxyTarget.getName().endsWith("$")) - { - // Get internal class generated by Scala. - proxyTarget = Class.forName(proxyTarget.getName() + "$", true, proxyTarget.getClassLoader()); - } - } - catch (ClassNotFoundException e) - { - // Not a singleton, look for @Instance field as a fallback. - FMLLog.log.info("An error occurred trying to load a proxy into {}.{}. Did you declare your mod as 'class' instead of 'object'?", proxyTarget.getSimpleName(), target.getName(), e); - return; - } - - // Get the instance via the MODULE$ field which is - // automatically generated by the Scala compiler for - // singletons. - Object targetInstance = proxyTarget.getField("MODULE$").get(null); - - try - { - // Find setter function. We do it this way because we can't - // necessarily use proxyTarget.getMethod(proxy.getClass()), as - // it might be a subclass and not the exact parameter type. - // All fields are private in Scala, wrapped by a getter and - // setter named and _$eq. To those - // familiar with scala.reflect.BeanProperty: these will always - // be there, set and get will always - // only be generated *additionally*. - final String setterName = target.getName() + "_$eq"; - for (Method setter : proxyTarget.getMethods()) - { - Class[] setterParameters = setter.getParameterTypes(); - if (setterName.equals(setter.getName()) && - // Some more validation. - setterParameters.length == 1 && - setterParameters[0].isAssignableFrom(proxy.getClass())) - { - // Here goes nothing... - setter.invoke(targetInstance, proxy); - return; - } - } - } - catch (InvocationTargetException e) - { - FMLLog.log.error("An error occurred trying to load a proxy into {}.{}", target.getName(), e); - throw new LoaderException(e); - } - - // If we come here we could not find a setter for this proxy. - FMLLog.log.fatal("Failed loading proxy into {}.{}, could not find setter function. Did you declare the field with 'val' instead of 'var'?", proxyTarget.getSimpleName(), target.getName()); - throw new LoaderException(String.format("Failed loading proxy into %s.%s, could not find setter function. Did you declare the field with 'val' instead of 'var'?", proxyTarget.getSimpleName(), target.getName())); - } - - @Override - public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader) - { - // For Scala mods, we want to enable authors to write them like so: - // object ModName { - // @SidedProxy(...) - // var proxy: ModProxy = null - // } - // For this to work, we have to search inside the inner class Scala - // generates for singletons, which is in called ModName$. These are - // not automatically handled, because the mod discovery code ignores - // internal classes. - // Note that it is alternatively possible to write this like so: - // class ModName { - // @SidedProxy(...) - // var proxy: ModProxy = null - // } - // object ModName extends ModName { ... } - // which will fall back to the normal injection code which calls - // setProxy in turn. - - // Get the actual mod implementation, which will be the inner class - // if we have a singleton. - Class proxyTarget = mod.getMod().getClass(); - if (proxyTarget.getName().endsWith("$")) - { - // So we have a singleton class, check if there are targets. - for (Field target : proxyTarget.getDeclaredFields()) - { - // This will not turn up anything if the alternative - // approach was taken (manually declaring the class). - // So we don't initialize the field twice. - if (target.getAnnotation(SidedProxy.class) != null) - { - String targetType = side.isClient() ? target.getAnnotation(SidedProxy.class).clientSide() : target.getAnnotation(SidedProxy.class).serverSide(); - try - { - Object proxy = Class.forName(targetType, true, loader).newInstance(); - - if (!target.getType().isAssignableFrom(proxy.getClass())) - { - FMLLog.log.fatal("Attempted to load a proxy type {} into {}.{}, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName()); - throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, proxyTarget.getSimpleName(), target.getName())); - } - - setProxy(target, proxyTarget, proxy); - } - catch (Exception e) { - FMLLog.log.error("An error occurred trying to load a proxy into {}.{}", target.getName(), e); - throw new LoaderException(e); - } - } - } - } - else - { - FMLLog.log.trace("Mod does not appear to be a singleton."); - } - } - } - - public static class JavaAdapter implements ILanguageAdapter { - @Override - public Object getNewInstance(FMLModContainer container, Class objectClass, ClassLoader classLoader, Method factoryMarkedMethod) throws Exception - { - if (factoryMarkedMethod != null) - { - return factoryMarkedMethod.invoke(null); - } - else - { - return objectClass.newInstance(); - } - } - - @Override - public boolean supportsStatics() - { - return true; - } - - @Override - public void setProxy(Field target, Class proxyTarget, Object proxy) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, - SecurityException - { - target.set(null, proxy); - } - - @Override - public void setInternalProxies(ModContainer mod, Side side, ClassLoader loader) - { - // Nothing to do here. - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/LoadController.java b/src/main/java/net/minecraftforge/fml/common/LoadController.java index 689db2647..d5e1c0bcf 100644 --- a/src/main/java/net/minecraftforge/fml/common/LoadController.java +++ b/src/main/java/net/minecraftforge/fml/common/LoadController.java @@ -29,7 +29,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import net.minecraftforge.common.util.TextTable; -import net.minecraftforge.fml.common.LoaderState.ModState; import net.minecraftforge.fml.common.ProgressManager.ProgressBar; import net.minecraftforge.fml.common.event.ModLifecycleEvent; import net.minecraftforge.fml.common.event.FMLLoadEvent; diff --git a/src/main/java/net/minecraftforge/fml/common/Loader.java b/src/main/java/net/minecraftforge/fml/common/Loader.java index 0084e8a01..9e781c496 100644 --- a/src/main/java/net/minecraftforge/fml/common/Loader.java +++ b/src/main/java/net/minecraftforge/fml/common/Loader.java @@ -41,14 +41,9 @@ import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.fml.common.LoaderState.ModState; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.ModContainer.Disableable; import net.minecraftforge.fml.common.ProgressManager.ProgressBar; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ContainerType; -import net.minecraftforge.fml.common.discovery.ModCandidate; -import net.minecraftforge.fml.common.discovery.ModDiscoverer; import net.minecraftforge.fml.common.event.FMLInterModComms; import net.minecraftforge.fml.common.event.FMLLoadEvent; import net.minecraftforge.fml.common.event.FMLModIdMappingEvent; @@ -60,11 +55,8 @@ import net.minecraftforge.fml.common.toposort.ModSortingException.SortingExcepti import net.minecraftforge.fml.common.versioning.ArtifactVersion; import net.minecraftforge.fml.common.versioning.DependencyParser; import net.minecraftforge.fml.common.versioning.VersionParser; -import net.minecraftforge.fml.relauncher.CoreModManager; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.libraries.Artifact; -import net.minecraftforge.fml.relauncher.libraries.LibraryManager; -import net.minecraftforge.fml.relauncher.libraries.Repository; +import net.minecraftforge.fml.relauncher.ModListHelper; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.ObjectHolderRegistry; diff --git a/src/main/java/net/minecraftforge/fml/common/LoaderState.java b/src/main/java/net/minecraftforge/fml/common/LoaderState.java deleted file mode 100644 index d2176a7cc..000000000 --- a/src/main/java/net/minecraftforge/fml/common/LoaderState.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import net.minecraftforge.fml.common.event.FMLConstructionEvent; -import net.minecraftforge.fml.common.event.FMLInitializationEvent; -import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; -import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; -import net.minecraftforge.fml.common.event.FMLServerStartedEvent; -import net.minecraftforge.fml.common.event.FMLServerStartingEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; -import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; -import net.minecraftforge.fml.common.event.FMLStateEvent; - -/** - * The state enum used to help track state progression for the loader - * @author cpw - * - */ -public enum LoaderState -{ - NOINIT("Uninitialized",null), - LOADING("Loading",null), - CONSTRUCTING("Constructing mods",FMLConstructionEvent.class), - PREINITIALIZATION("Pre-initializing mods", FMLPreInitializationEvent.class), - INITIALIZATION("Initializing mods", FMLInitializationEvent.class), - POSTINITIALIZATION("Post-initializing mods", FMLPostInitializationEvent.class), - AVAILABLE("Mod loading complete", FMLLoadCompleteEvent.class), - SERVER_ABOUT_TO_START("Server about to start", FMLServerAboutToStartEvent.class), - SERVER_STARTING("Server starting", FMLServerStartingEvent.class), - SERVER_STARTED("Server started", FMLServerStartedEvent.class), - SERVER_STOPPING("Server stopping", FMLServerStoppingEvent.class), - SERVER_STOPPED("Server stopped", FMLServerStoppedEvent.class), - ERRORED("Mod Loading errored",null); - - - private Class eventClass; - private String name; - - private LoaderState(String name, Class event) - { - this.name = name; - this.eventClass = event; - } - - public LoaderState transition(boolean errored) - { - if (errored) - { - return ERRORED; - } - // stopping -> available - if (this == SERVER_STOPPED) - { - return AVAILABLE; - } - return values()[ordinal() < values().length ? ordinal()+1 : ordinal()]; - } - - public boolean hasEvent() - { - return eventClass != null; - } - - public FMLStateEvent getEvent(Object... eventData) - { - try - { - return eventClass.getConstructor(Object[].class).newInstance((Object)eventData); - } - catch (ReflectiveOperationException e) - { - throw new RuntimeException(e); - } - } - public LoaderState requiredState() - { - if (this == NOINIT) return NOINIT; - return LoaderState.values()[this.ordinal()-1]; - } - - public String getPrettyName() - { - return name; - } - - public enum ModState - { - UNLOADED ("Unloaded", "U"), - LOADED ("Loaded", "L"), - CONSTRUCTED ("Constructed", "C"), - PREINITIALIZED ("Pre-initialized", "H"), - INITIALIZED ("Initialized", "I"), - POSTINITIALIZED("Post-initialized", "J"), - AVAILABLE ("Available", "A"), - DISABLED ("Disabled", "D"), - ERRORED ("Errored", "E"); - - private String label; - private String marker; - - private ModState(String label, String marker) - { - this.label = label; - this.marker = marker; - } - - @Override - public String toString() - { - return this.label; - } - - public String getMarker() - { - return this.marker; - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/Mod.java b/src/main/java/net/minecraftforge/fml/common/Mod.java index db8e6e132..9e44e89a8 100644 --- a/src/main/java/net/minecraftforge/fml/common/Mod.java +++ b/src/main/java/net/minecraftforge/fml/common/Mod.java @@ -24,7 +24,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.event.ModLifecycleEvent; import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; @@ -108,7 +108,7 @@ public @interface Mod @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface EventBusSubscriber { - Side[] value() default { Side.CLIENT, Side.SERVER }; + Dist[] value() default { Dist.CLIENT, Dist.DEDICATED_SERVER }; /** * Optional value, only nessasary if tis annotation is not on the same class that has a @Mod annotation. diff --git a/src/main/java/net/minecraftforge/fml/common/ModClassLoader.java b/src/main/java/net/minecraftforge/fml/common/ModClassLoader.java index cb991aa68..133cfbd19 100644 --- a/src/main/java/net/minecraftforge/fml/common/ModClassLoader.java +++ b/src/main/java/net/minecraftforge/fml/common/ModClassLoader.java @@ -32,10 +32,6 @@ import java.util.Set; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.common.asm.transformers.ModAPITransformer; -import net.minecraftforge.fml.common.discovery.ASMDataTable; - -import org.apache.logging.log4j.Level; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; diff --git a/src/main/java/net/minecraftforge/fml/common/ModContainerFactory.java b/src/main/java/net/minecraftforge/fml/common/ModContainerFactory.java deleted file mode 100644 index a35026fe9..000000000 --- a/src/main/java/net/minecraftforge/fml/common/ModContainerFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.io.File; -import java.lang.reflect.Constructor; -import java.util.Map; - -import net.minecraftforge.fml.common.discovery.ModCandidate; -import net.minecraftforge.fml.common.discovery.asm.ASMModParser; -import net.minecraftforge.fml.javafmlmod.FMLModContainer; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation; - -import org.objectweb.asm.Type; - -import com.google.common.collect.Maps; - -import javax.annotation.Nullable; - -public class ModContainerFactory -{ - public static Map> modTypes = Maps.newHashMap(); - private static ModContainerFactory INSTANCE = new ModContainerFactory(); - - private ModContainerFactory() { - // We always know about Mod type - registerContainerType(Type.getType(Mod.class), FMLModContainer.class); - } - public static ModContainerFactory instance() { - return INSTANCE; - } - - public void registerContainerType(Type type, Class container) - { - try - { - Constructor constructor = container.getConstructor(new Class[] { String.class, ModCandidate.class, Map.class }); - modTypes.put(type, constructor); - } - catch (Exception e) - { - throw new RuntimeException("Critical error : cannot register mod container type " + container.getName() + ", it has an invalid constructor", e); - } - } - - @Nullable - public ModContainer build(ASMModParser modParser, File modSource, ModCandidate container) - { - String className = modParser.getASMType().getClassName(); - for (ModAnnotation ann : modParser.getAnnotations()) - { - if (modTypes.containsKey(ann.getASMType())) - { - FMLLog.log.debug("Identified a mod of type {} ({}) - loading", ann.getASMType(), className); - try { - ModContainer ret = modTypes.get(ann.getASMType()).newInstance(className, container, ann.getValues()); - if (!ret.shouldLoadInEnvironment()) - { - FMLLog.log.debug("Skipping mod {}, container opted to not load.", className); - return null; - } - return ret; - } catch (Exception e) { - FMLLog.log.error("Unable to construct {} container", ann.getASMType().getClassName(), e); - return null; - } - } - } - - return null; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/ModMetadata.java b/src/main/java/net/minecraftforge/fml/common/ModMetadata.java deleted file mode 100644 index 552c01fb6..000000000 --- a/src/main/java/net/minecraftforge/fml/common/ModMetadata.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.util.List; -import java.util.Set; - -import net.minecraftforge.fml.common.versioning.ArtifactVersion; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.gson.annotations.SerializedName; -import net.minecraftforge.fml.ModContainer; - -/** - * @author cpw - * - */ -public class ModMetadata -{ - @SerializedName("modid") - public String modId; - public String name; - public String description = ""; - - public String url = ""; - @Deprecated //Never really used for anything and format is undefined. See updateJSON for replacement. - public String updateUrl = ""; - /** - * URL to update json file. Format is defined here: https://gist.github.com/LexManos/7aacb9aa991330523884 - */ - public String updateJSON = ""; - - public String logoFile = ""; - public String version = ""; - public List authorList = Lists.newArrayList(); - public String credits = ""; - public String parent = ""; - public String[] screenshots; - - // this field is not for use in the json - public transient ModContainer parentMod; - // this field is not for use in the json - public transient List childMods = Lists.newArrayList(); - - public boolean useDependencyInformation; - public Set requiredMods = Sets.newHashSet(); - public List dependencies = Lists.newArrayList(); - public List dependants = Lists.newArrayList(); - // this field is not for use in the json - public transient boolean autogenerated; - - public ModMetadata() - { - } - - public String getChildModCountString() - { - return String.format("%d child mod%s", childMods.size(), childMods.size() != 1 ? "s" : ""); - } - - public String getAuthorList() - { - return Joiner.on(", ").join(authorList); - } - - public String getChildModList() - { - return Joiner.on(", ").join(childMods.stream().map(ModContainer::getName).iterator()); - } - - public String printableSortingRules() - { - return ""; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java b/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java index a39251aa8..9973e95e2 100644 --- a/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java +++ b/src/main/java/net/minecraftforge/fml/common/ObfuscationReflectionHelper.java @@ -21,13 +21,11 @@ package net.minecraftforge.fml.common; import java.util.Arrays; -import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper; +import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToAccessFieldException; import net.minecraftforge.fml.relauncher.ReflectionHelper.UnableToFindFieldException; -import org.apache.logging.log4j.Level; - /** * Some reflection helper code. * diff --git a/src/main/java/net/minecraftforge/fml/common/ProgressManager.java b/src/main/java/net/minecraftforge/fml/common/ProgressManager.java index 2eee4f52a..2137a96b2 100644 --- a/src/main/java/net/minecraftforge/fml/common/ProgressManager.java +++ b/src/main/java/net/minecraftforge/fml/common/ProgressManager.java @@ -26,7 +26,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.stream.Collectors; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.SidedExecutor; import net.minecraftforge.fml.SidedProvider; import net.minecraftforge.fml.client.SplashProgress; @@ -62,7 +62,7 @@ public class ProgressManager { bar.timeEachStep(); } - SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages); + SidedExecutor.runOn(Dist.CLIENT, ()->SplashProgress::processMessages); return bar; } @@ -87,7 +87,7 @@ public class ProgressManager else fmlLog.debug(SPLASH, () -> new MessageFormatMessage("Bar Finished: {0} took {1,number,0.000}ms", bar.getTitle(), (newTime - bar.lastTime) / 1.0e6)); } - SidedExecutor.runOn(Side.CLIENT, ()->SplashProgress::processMessages); + SidedExecutor.runOn(Dist.CLIENT, ()->SplashProgress::processMessages); } /* diff --git a/src/main/java/net/minecraftforge/fml/common/ProxyInjector.java b/src/main/java/net/minecraftforge/fml/common/ProxyInjector.java deleted file mode 100644 index caea6546b..000000000 --- a/src/main/java/net/minecraftforge/fml/common/ProxyInjector.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Set; - -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; - -import com.google.common.base.Strings; -import com.google.common.collect.SetMultimap; - -/** - * @author cpw - * - */ -public class ProxyInjector -{ - public static void inject(ModContainer mod, ASMDataTable data, Side side, ILanguageAdapter languageAdapter) - { - FMLLog.log.debug("Attempting to inject @SidedProxy classes into {}", mod.getModId()); - SetMultimap modData = data.getAnnotationsFor(mod); - Set mods = modData.get(Mod.class.getName()); - Set targets = modData.get(SidedProxy.class.getName()); - ClassLoader mcl = Loader.instance().getModClassLoader(); - - for (ASMData targ : targets) - { - try - { - String amodid = (String)targ.getAnnotationInfo().get("modId"); - if (Strings.isNullOrEmpty(amodid)) - { - amodid = ASMDataTable.getOwnerModID(mods, targ); - if (Strings.isNullOrEmpty(amodid)) - { - FMLLog.bigWarning("Could not determine owning mod for @SidedProxy on {} for mod {}", targ.getClassName(), mod.getModId()); - continue; - } - } - if (!mod.getModId().equals(amodid)) - { - FMLLog.log.debug("Skipping proxy injection for {}.{} since it is not for mod {}", targ.getClassName(), targ.getObjectName(), mod.getModId()); - continue; - } - - Class proxyTarget = Class.forName(targ.getClassName(), true, mcl); - Field target = proxyTarget.getDeclaredField(targ.getObjectName()); - if (target == null) - { - // Impossible? - FMLLog.log.fatal("Attempted to load a proxy type into {}.{} but the field was not found", targ.getClassName(), targ.getObjectName()); - throw new LoaderException(String.format("Attempted to load a proxy type into %s.%s but the field was not found", targ.getClassName(), targ.getObjectName())); - } - target.setAccessible(true); - - SidedProxy annotation = target.getAnnotation(SidedProxy.class); - String targetType = side.isClient() ? annotation.clientSide() : annotation.serverSide(); - if(targetType.equals("")) - { - targetType = targ.getClassName() + (side.isClient() ? "$ClientProxy" : "$ServerProxy"); - } - Object proxy=Class.forName(targetType, true, mcl).newInstance(); - - if (languageAdapter.supportsStatics() && (target.getModifiers() & Modifier.STATIC) == 0 ) - { - FMLLog.log.fatal("Attempted to load a proxy type {} into {}.{}, but the field is not static", targetType, targ.getClassName(), targ.getObjectName()); - throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the field is not static", targetType, targ.getClassName(), targ.getObjectName())); - } - if (!target.getType().isAssignableFrom(proxy.getClass())) - { - FMLLog.log.fatal("Attempted to load a proxy type {} into {}.{}, but the types don't match", targetType, targ.getClassName(), targ.getObjectName()); - throw new LoaderException(String.format("Attempted to load a proxy type %s into %s.%s, but the types don't match", targetType, targ.getClassName(), targ.getObjectName())); - } - languageAdapter.setProxy(target, proxyTarget, proxy); - } - catch (Exception e) - { - FMLLog.log.error("An error occurred trying to load a proxy into {}.{}", targ.getObjectName(), e); - throw new LoaderException(e); - } - } - - // Allow language specific proxy injection. - languageAdapter.setInternalProxies(mod, side, mcl); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/SidedProxy.java b/src/main/java/net/minecraftforge/fml/common/SidedProxy.java deleted file mode 100644 index 9df6369fa..000000000 --- a/src/main/java/net/minecraftforge/fml/common/SidedProxy.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Sided proxies are loaded based on the specific environment they find themselves loaded into. - * They are used to ensure that client-specific code (such as GUIs) is only loaded into the game - * on the client side. - * It is applied to static fields of a class, anywhere in your mod code. FML will scan - * and load any classes with this annotation at mod construction time. - * - *

- * This example will load a CommonProxy on the server side, and a ClientProxy on the client side. - * - *

{@code
- *  public class MySidedProxyHolder {
- *      {@literal @}SidedProxy(modId="MyModId",clientSide="mymod.ClientProxy", serverSide="mymod.CommonProxy")
- *      public static CommonProxy proxy;
- *  }
- *
- *  public class CommonProxy {
- *      // Common or server stuff here that needs to be overridden on the client
- *  }
- *
- *  public class ClientProxy extends CommonProxy {
- *      // Override common stuff with client specific stuff here
- *  }
- * }
- * 
- * @author cpw - * - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface SidedProxy -{ - /** - * The full name of the client side class to load and populate. - * Defaults to the nested class named "ClientProxy" in the current class. - */ - String clientSide() default ""; - - /** - * The full name of the server side class to load and populate. - * Defaults to the nested class named "ServerProxy" in the current class. - */ - String serverSide() default ""; - - /** - * The name of a mod to load this proxy for. This is required if this annotation is not in the class with @Mod annotation. - * Or there is no other way to determine the mod this annotation belongs to. When in doubt, add this value. - */ - String modId() default ""; -} diff --git a/src/main/java/net/minecraftforge/fml/common/StartupQuery.java b/src/main/java/net/minecraftforge/fml/common/StartupQuery.java deleted file mode 100644 index 64dfc42fb..000000000 --- a/src/main/java/net/minecraftforge/fml/common/StartupQuery.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; - -import net.minecraft.server.MinecraftServer; - -import javax.annotation.Nullable; - -public class StartupQuery { - // internal class/functionality, do not use - - public static boolean confirm(String text) - { - StartupQuery query = new StartupQuery(text, new AtomicBoolean()); - query.execute(); - return query.getResult(); - } - - public static void notify(String text) - { - StartupQuery query = new StartupQuery(text, null); - query.execute(); - } - - public static void abort() - { - MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if (server != null) server.initiateShutdown(); - - aborted = true; // to abort loading and go back to the main menu - throw new AbortedException(); // to halt the server - } - - - public static void reset() - { - pending = null; - aborted = false; - } - - public static boolean check() - { - if (pending != null) - { - try - { - FMLCommonHandler.instance().queryUser(pending); - } - catch (InterruptedException e) - { - FMLLog.log.warn("query interrupted"); - abort(); - } - - pending = null; - } - - return !aborted; - } - - private static volatile StartupQuery pending; - private static volatile boolean aborted = false; - - - private StartupQuery(String text, @Nullable AtomicBoolean result) - { - this.text = text; - this.result = result; - } - - @Nullable - public Boolean getResult() - { - return result == null ? null : result.get(); - } - - public void setResult(boolean result) - { - this.result.set(result); - } - - public String getText() - { - return text; - } - - public boolean isSynchronous() - { - return synchronous; - } - - public void finish() - { - signal.countDown(); - } - - private void execute() - { - String prop = System.getProperty("fml.queryResult"); - - if (result != null && prop != null) - { - FMLLog.log.info("Using fml.queryResult {} to answer the following query:\n{}", prop, text); - - if (prop.equalsIgnoreCase("confirm")) - { - setResult(true); - return; - } - else if (prop.equalsIgnoreCase("cancel")) - { - setResult(false); - return; - } - - FMLLog.log.warn("Invalid value for fml.queryResult: {}, expected confirm or cancel", prop); - } - - synchronous = false; - pending = this; // let the other thread start the query - - // from the integrated server thread: the client will eventually check pending and execute the query - // from the client thread: synchronous execution - // dedicated server: command handling in mc is synchronous, execute the server-side query directly - if (FMLCommonHandler.instance().getSide().isServer() || - FMLCommonHandler.instance().getEffectiveSide().isClient()) - { - synchronous = true; - check(); - } - - try - { - signal.await(); - reset(); - } - catch (InterruptedException e) - { - FMLLog.log.warn("query interrupted"); - abort(); - } - } - - private String text; - @Nullable - private AtomicBoolean result; - private CountDownLatch signal = new CountDownLatch(1); - private volatile boolean synchronous; - - - /** - * Exception not being caught by the crash report generation logic. - */ - public static class AbortedException extends RuntimeException - { - private static final long serialVersionUID = -5933665223696833921L; - - private AbortedException() - { - super(); - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/DeobfuscationTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/DeobfuscationTransformer.java similarity index 91% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/DeobfuscationTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/DeobfuscationTransformer.java index 75e48dabe..09f173423 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/DeobfuscationTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/DeobfuscationTransformer.java @@ -17,12 +17,12 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; import net.minecraft.launchwrapper.IClassNameTransformer; import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper; -import net.minecraftforge.fml.common.asm.transformers.deobf.FMLRemappingAdapter; +import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper; +import net.minecraftforge.fml.common.asm.deobf.FMLRemappingAdapter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; @@ -34,7 +34,7 @@ public class DeobfuscationTransformer implements IClassTransformer, IClassNameTr private static final int WRITER_FLAGS = ClassWriter.COMPUTE_MAXS | (RECALC_FRAMES ? ClassWriter.COMPUTE_FRAMES : 0); private static final int READER_FLAGS = RECALC_FRAMES ? ClassReader.SKIP_FRAMES : ClassReader.EXPAND_FRAMES; // COMPUTE_FRAMES causes classes to be loaded, which could cause issues if the classes do not exist. - // However in testing this has not happened. {As we run post SideTransformer} + // However in testing this has not happened. {As we run post RuntimeDistCleaner} // If reported we need to add a custom implementation of ClassWriter.getCommonSuperClass // that does not cause class loading. diff --git a/src/main/java/net/minecraftforge/fml/common/asm/FMLSanityChecker.java b/src/main/java/net/minecraftforge/fml/common/asm/FMLSanityChecker.java index bfb25b55a..7f4fd3afa 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/FMLSanityChecker.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/FMLSanityChecker.java @@ -35,11 +35,9 @@ import org.apache.commons.io.IOUtils; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraftforge.fml.common.CertificateHelper; import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper; +import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper; import net.minecraftforge.fml.common.patcher.ClassPatchManager; -import net.minecraftforge.fml.relauncher.FMLLaunchHandler; -import net.minecraftforge.fml.relauncher.IFMLCallHook; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import com.google.common.io.ByteStreams; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/FieldRedirectTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/FieldRedirectTransformer.java similarity index 98% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/FieldRedirectTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/FieldRedirectTransformer.java index a86a7eadb..93faedb75 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/FieldRedirectTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/FieldRedirectTransformer.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; import java.util.ListIterator; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockSpecialTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/ItemBlockSpecialTransformer.java similarity index 94% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockSpecialTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/ItemBlockSpecialTransformer.java index 20aedb4d3..de9e64a2f 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockSpecialTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/ItemBlockSpecialTransformer.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; public class ItemBlockSpecialTransformer extends FieldRedirectTransformer { diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/ItemBlockTransformer.java similarity index 94% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/ItemBlockTransformer.java index 33eea295c..2581c99d9 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemBlockTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/ItemBlockTransformer.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; public class ItemBlockTransformer extends FieldRedirectTransformer { diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemStackTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/ItemStackTransformer.java similarity index 94% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemStackTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/ItemStackTransformer.java index fe0e2e487..13b384922 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ItemStackTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/ItemStackTransformer.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; public class ItemStackTransformer extends FieldRedirectTransformer { diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/TerminalTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/TerminalTransformer.java similarity index 99% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/TerminalTransformer.java rename to src/main/java/net/minecraftforge/fml/common/asm/TerminalTransformer.java index 7107bf791..54e3df4dc 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/TerminalTransformer.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/TerminalTransformer.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.common.asm; import org.objectweb.asm.*; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLDeobfuscatingRemapper.java b/src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLDeobfuscatingRemapper.java similarity index 99% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLDeobfuscatingRemapper.java rename to src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLDeobfuscatingRemapper.java index 3cb6a89ae..c6dfab834 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLDeobfuscatingRemapper.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLDeobfuscatingRemapper.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers.deobf; +package net.minecraftforge.fml.common.asm.deobf; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLRemappingAdapter.java b/src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLRemappingAdapter.java similarity index 98% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLRemappingAdapter.java rename to src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLRemappingAdapter.java index 64b6debbc..700bc9ebf 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/FMLRemappingAdapter.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/deobf/FMLRemappingAdapter.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers.deobf; +package net.minecraftforge.fml.common.asm.deobf; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/LZMAInputSupplier.java b/src/main/java/net/minecraftforge/fml/common/asm/deobf/LZMAInputSupplier.java similarity index 95% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/LZMAInputSupplier.java rename to src/main/java/net/minecraftforge/fml/common/asm/deobf/LZMAInputSupplier.java index 7dff8db1d..25603f474 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/deobf/LZMAInputSupplier.java +++ b/src/main/java/net/minecraftforge/fml/common/asm/deobf/LZMAInputSupplier.java @@ -17,7 +17,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers.deobf; +package net.minecraftforge.fml.common.asm.deobf; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/AccessTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/transformers/AccessTransformer.java deleted file mode 100644 index eeb1720fb..000000000 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/AccessTransformer.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.asm.transformers; - -import net.minecraftforge.fml.common.FMLLog; -import static org.objectweb.asm.Opcodes.ACC_FINAL; -import static org.objectweb.asm.Opcodes.ACC_PRIVATE; -import static org.objectweb.asm.Opcodes.ACC_PROTECTED; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.apache.commons.io.IOUtils; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.MethodNode; - -import com.google.common.base.Splitter; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.io.CharSource; -import com.google.common.io.LineProcessor; -import com.google.common.io.Resources; - -public class AccessTransformer implements IClassTransformer -{ - private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("fml.debugAccessTransformer", "false")); - class Modifier - { - public String name = ""; - public String desc = ""; - public int oldAccess = 0; - public int newAccess = 0; - public int targetAccess = 0; - public boolean changeFinal = false; - public boolean markFinal = false; - protected boolean modifyClassVisibility; - - private void setTargetAccess(String name) - { - if (name.startsWith("public")) targetAccess = ACC_PUBLIC; - else if (name.startsWith("private")) targetAccess = ACC_PRIVATE; - else if (name.startsWith("protected")) targetAccess = ACC_PROTECTED; - - if (name.endsWith("-f")) - { - changeFinal = true; - markFinal = false; - } - else if (name.endsWith("+f")) - { - changeFinal = true; - markFinal = true; - } - } - } - - private Multimap modifiers = ArrayListMultimap.create(); - - public AccessTransformer() throws IOException - { - this("forge_at.cfg"); - } - protected AccessTransformer(String rulesFile) throws IOException - { - readMapFile(rulesFile); - } - - AccessTransformer(Class dummyClazz) - { - // This is a noop - } - void readMapFile(String rulesFile) throws IOException - { - File file = new File(rulesFile); - URL rulesResource; - if (file.exists()) - { - rulesResource = file.toURI().toURL(); - } - else - { - rulesResource = Resources.getResource(rulesFile); - } - processATFile(Resources.asCharSource(rulesResource, StandardCharsets.UTF_8)); - FMLLog.log.debug("Loaded {} rules from AccessTransformer config file {}", modifiers.size(), rulesFile); - } - protected void processATFile(CharSource rulesResource) throws IOException - { - rulesResource.readLines(new LineProcessor() - { - @Override - public Void getResult() - { - return null; - } - - @Override - public boolean processLine(String input) throws IOException - { - String line = Iterables.getFirst(Splitter.on('#').limit(2).split(input), "").trim(); - if (line.length()==0) - { - return true; - } - List parts = Lists.newArrayList(Splitter.on(" ").trimResults().split(line)); - if (parts.size()>3) - { - throw new RuntimeException("Invalid config file line "+ input); - } - Modifier m = new Modifier(); - m.setTargetAccess(parts.get(0)); - - if (parts.size() == 2) - { - m.modifyClassVisibility = true; - } - else - { - String nameReference = parts.get(2); - int parenIdx = nameReference.indexOf('('); - if (parenIdx>0) - { - m.desc = nameReference.substring(parenIdx); - m.name = nameReference.substring(0,parenIdx); - } - else - { - m.name = nameReference; - } - } - String className = parts.get(1).replace('/', '.'); - modifiers.put(className, m); - if (DEBUG) FMLLog.log.debug("AT RULE: {} {} {} (type {})", toBinary(m.targetAccess), m.name, m.desc, className); - return true; - } - }); - } - - @Override - public byte[] transform(String name, String transformedName, byte[] bytes) - { - if (bytes == null) { return null; } - if (!modifiers.containsKey(transformedName)) { return bytes; } - - if (DEBUG) - { - FMLLog.log.debug("Considering all methods and fields on {} ({})", transformedName, name); - } - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - Collection mods = modifiers.get(transformedName); - for (Modifier m : mods) - { - if (m.modifyClassVisibility) - { - classNode.access = getFixedAccess(classNode.access, m); - if (DEBUG) - { - FMLLog.log.debug("Class: {} {} -> {}", name, toBinary(m.oldAccess), toBinary(m.newAccess)); - } - continue; - } - if (m.desc.isEmpty()) - { - for (FieldNode n : classNode.fields) - { - if (n.name.equals(m.name) || m.name.equals("*")) - { - n.access = getFixedAccess(n.access, m); - if (DEBUG) - { - FMLLog.log.debug("Field: {}.{} {} -> {}", name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)); - } - - if (!m.name.equals("*")) - { - break; - } - } - } - } - else - { - List nowOverrideable = Lists.newArrayList(); - for (MethodNode n : classNode.methods) - { - if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*")) - { - n.access = getFixedAccess(n.access, m); - - // constructors always use INVOKESPECIAL - if (!n.name.equals("")) - { - // if we changed from private to something else we need to replace all INVOKESPECIAL calls to this method with INVOKEVIRTUAL - // so that overridden methods will be called. Only need to scan this class, because obviously the method was private. - boolean wasPrivate = (m.oldAccess & ACC_PRIVATE) == ACC_PRIVATE; - boolean isNowPrivate = (m.newAccess & ACC_PRIVATE) == ACC_PRIVATE; - - if (wasPrivate && !isNowPrivate) - { - nowOverrideable.add(n); - } - - } - - if (DEBUG) - { - FMLLog.log.debug("Method: {}.{}{} {} -> {}", name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)); - } - - if (!m.name.equals("*")) - { - break; - } - } - } - - replaceInvokeSpecial(classNode, nowOverrideable); - } - } - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - return writer.toByteArray(); - } - - private void replaceInvokeSpecial(ClassNode clazz, List toReplace) - { - for (MethodNode method : clazz.methods) - { - for (Iterator it = method.instructions.iterator(); it.hasNext();) - { - AbstractInsnNode insn = it.next(); - if (insn.getOpcode() == INVOKESPECIAL) - { - MethodInsnNode mInsn = (MethodInsnNode) insn; - for (MethodNode n : toReplace) - { - if (n.name.equals(mInsn.name) && n.desc.equals(mInsn.desc)) - { - mInsn.setOpcode(INVOKEVIRTUAL); - break; - } - } - } - } - } - } - - private String toBinary(int num) - { - return String.format("%16s", Integer.toBinaryString(num)).replace(' ', '0'); - } - - private int getFixedAccess(int access, Modifier target) - { - target.oldAccess = access; - int t = target.targetAccess; - int ret = (access & ~7); - - switch (access & 7) - { - case ACC_PRIVATE: - ret |= t; - break; - case 0: // default - ret |= (t != ACC_PRIVATE ? t : 0 /* default */); - break; - case ACC_PROTECTED: - ret |= (t != ACC_PRIVATE && t != 0 /* default */? t : ACC_PROTECTED); - break; - case ACC_PUBLIC: - ret |= (t != ACC_PRIVATE && t != 0 /* default */&& t != ACC_PROTECTED ? t : ACC_PUBLIC); - break; - default: - throw new RuntimeException("The fuck?"); - } - - // Clear the "final" marker on fields only if specified in control field - if (target.changeFinal) - { - if (target.markFinal) - { - ret |= ACC_FINAL; - } - else - { - ret &= ~ACC_FINAL; - } - } - target.newAccess = ret; - return ret; - } - - public static void main(String[] args) - { - if (args.length < 2) - { - System.out.println("Usage: AccessTransformer [MapFile2]... "); - System.exit(1); - } - - boolean hasTransformer = false; - AccessTransformer[] trans = new AccessTransformer[args.length - 1]; - for (int x = 1; x < args.length; x++) - { - try - { - trans[x - 1] = new AccessTransformer(args[x]); - hasTransformer = true; - } - catch (IOException e) - { - System.out.println("Could not read Transformer Map: " + args[x]); - e.printStackTrace(); - } - } - - if (!hasTransformer) - { - System.out.println("Could not find a valid transformer to perform"); - System.exit(1); - } - - File orig = new File(args[0]); - File temp = new File(args[0] + ".ATBack"); - if (!orig.exists() && !temp.exists()) - { - System.out.println("Could not find target jar: " + orig); - System.exit(1); - } - - if (!orig.renameTo(temp)) - { - System.out.println("Could not rename file: " + orig + " -> " + temp); - System.exit(1); - } - - try - { - processJar(temp, orig, trans); - } - catch (IOException e) - { - e.printStackTrace(); - System.exit(1); - } - - if (!temp.delete()) - { - System.out.println("Could not delete temp file: " + temp); - } - } - - private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException - { - ZipInputStream inJar = null; - ZipOutputStream outJar = null; - - try - { - try - { - inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile))); - } - catch (FileNotFoundException e) - { - throw new FileNotFoundException("Could not open input file: " + e.getMessage()); - } - - try - { - outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); - } - catch (FileNotFoundException e) - { - throw new FileNotFoundException("Could not open output file: " + e.getMessage()); - } - - ZipEntry entry; - while ((entry = inJar.getNextEntry()) != null) - { - if (entry.isDirectory()) - { - outJar.putNextEntry(entry); - continue; - } - - byte[] data = new byte[4096]; - ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream(); - - int len; - do - { - len = inJar.read(data); - if (len > 0) - { - entryBuffer.write(data, 0, len); - } - } - while (len != -1); - - byte[] entryData = entryBuffer.toByteArray(); - - String entryName = entry.getName(); - - if (entryName.endsWith(".class") && !entryName.startsWith(".")) - { - ClassNode cls = new ClassNode(); - ClassReader rdr = new ClassReader(entryData); - rdr.accept(cls, 0); - String name = cls.name.replace('/', '.').replace('\\', '.'); - - for (AccessTransformer trans : transformers) - { - entryData = trans.transform(name, name, entryData); - } - } - - ZipEntry newEntry = new ZipEntry(entryName); - outJar.putNextEntry(newEntry); - outJar.write(entryData); - } - } - finally - { - IOUtils.closeQuietly(outJar); - IOUtils.closeQuietly(inJar); - } - } - Multimap getModifiers() - { - return modifiers; - } - boolean isEmpty() - { - return modifiers.isEmpty(); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriberTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriberTransformer.java deleted file mode 100644 index e547c7252..000000000 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriberTransformer.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.asm.transformers; - -import java.lang.reflect.Modifier; -import java.util.List; - -import net.minecraft.launchwrapper.IClassTransformer; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -public class EventSubscriberTransformer implements IClassTransformer -{ - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) - { - if (basicClass == null) return null; - - ClassNode classNode = new ClassNode(); - new ClassReader(basicClass).accept(classNode, 0); - - boolean isSubscriber = false; - - for (MethodNode methodNode : classNode.methods) - { - List anns = methodNode.visibleAnnotations; - - if (anns != null && Iterables.any(anns, SubscribeEventPredicate.INSTANCE)) - { - if (Modifier.isPrivate(methodNode.access)) - { - String msg = "Cannot apply @SubscribeEvent to private method %s/%s%s"; - throw new RuntimeException(String.format(msg, classNode.name, methodNode.name, methodNode.desc)); - } - - methodNode.access = toPublic(methodNode.access); - isSubscriber = true; - } - } - - if (isSubscriber) - { - classNode.access = toPublic(classNode.access); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - return writer.toByteArray(); - } - - return basicClass; - } - - private static int toPublic(int access) - { - return access & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED) | Opcodes.ACC_PUBLIC; - } - - private static class SubscribeEventPredicate implements Predicate - { - static final SubscribeEventPredicate INSTANCE = new SubscribeEventPredicate(); - - @Override - public boolean apply(AnnotationNode input) - { - return input.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/SubscribeEvent;"); - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriptionTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriptionTransformer.java deleted file mode 100644 index f0aac3b74..000000000 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/EventSubscriptionTransformer.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.asm.transformers; - -import static org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; -import static org.objectweb.asm.Opcodes.ACC_PRIVATE; -import static org.objectweb.asm.Opcodes.ACC_PROTECTED; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_STATIC; -import static org.objectweb.asm.Opcodes.ALOAD; -import static org.objectweb.asm.Opcodes.ARETURN; -import static org.objectweb.asm.Opcodes.DUP; -import static org.objectweb.asm.Opcodes.F_SAME; -import static org.objectweb.asm.Opcodes.GETSTATIC; -import static org.objectweb.asm.Opcodes.IFNULL; -import static org.objectweb.asm.Opcodes.INVOKESPECIAL; -import static org.objectweb.asm.Opcodes.NEW; -import static org.objectweb.asm.Opcodes.PUTSTATIC; -import static org.objectweb.asm.Opcodes.RETURN; -import static org.objectweb.asm.Opcodes.IRETURN; -import static org.objectweb.asm.Opcodes.ICONST_1; -import static org.objectweb.asm.Type.VOID_TYPE; -import static org.objectweb.asm.Type.BOOLEAN_TYPE; -import static org.objectweb.asm.Type.getMethodDescriptor; - -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.eventbus.api.Event; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Type; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.FieldInsnNode; -import org.objectweb.asm.tree.FieldNode; -import org.objectweb.asm.tree.FrameNode; -import org.objectweb.asm.tree.InsnNode; -import org.objectweb.asm.tree.JumpInsnNode; -import org.objectweb.asm.tree.LabelNode; -import org.objectweb.asm.tree.MethodInsnNode; -import org.objectweb.asm.tree.MethodNode; -import org.objectweb.asm.tree.TypeInsnNode; -import org.objectweb.asm.tree.VarInsnNode; - -public class EventSubscriptionTransformer implements IClassTransformer -{ - public EventSubscriptionTransformer() - { - } - - @Override - public byte[] transform(String name, String transformedName, byte[] bytes) - { - if (bytes == null || name.equals("net.minecraftforge.fml.common.eventhandler.Event") || name.startsWith("net.minecraft.") || name.indexOf('.') == -1) - { - return bytes; - } - ClassReader cr = new ClassReader(bytes); - ClassNode classNode = new ClassNode(); - cr.accept(classNode, 0); - - try - { - if (buildEvents(classNode)) - { - ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); - classNode.accept(cw); - return cw.toByteArray(); - } - return bytes; - } - catch (ClassNotFoundException ex) - { - // Discard silently- it's just noise - } - catch (Exception e) - { - FMLLog.log.error("Error building events.", e); - } - - return bytes; - } - - private boolean buildEvents(ClassNode classNode) throws Exception - { - // Yes, this recursively loads classes until we get this base class. THIS IS NOT A ISSUE. Coremods should handle re-entry just fine. - // If they do not this a COREMOD issue NOT a Forge/LaunchWrapper issue. - Class parent = this.getClass().getClassLoader().loadClass(classNode.superName.replace('/', '.')); - if (!net.minecraftforge.eventbus.api.Event.class.isAssignableFrom(parent)) - { - return false; - } - - //Class listenerListClazz = Class.forName("net.minecraftforge.fml.common.eventhandler.ListenerList", false, getClass().getClassLoader()); - Type tList = Type.getType("Lnet/minecraftforge/fml/common/eventhandler/ListenerList;"); - - boolean edited = false; - boolean hasSetup = false; - boolean hasGetListenerList = false; - boolean hasDefaultCtr = false; - boolean hasCancelable = false; - boolean hasResult = false; - String voidDesc = Type.getMethodDescriptor(VOID_TYPE); - String boolDesc = Type.getMethodDescriptor(BOOLEAN_TYPE); - String listDesc = tList.getDescriptor(); - String listDescM = Type.getMethodDescriptor(tList); - - for (MethodNode method : classNode.methods) - { - if (method.name.equals("setup") && method.desc.equals(voidDesc) && (method.access & ACC_PROTECTED) == ACC_PROTECTED) hasSetup = true; - if ((method.access & ACC_PUBLIC) == ACC_PUBLIC) - { - if (method.name.equals("getListenerList") && method.desc.equals(listDescM)) hasGetListenerList = true; - if (method.name.equals("isCancelable") && method.desc.equals(boolDesc)) hasCancelable = true; - if (method.name.equals("hasResult") && method.desc.equals(boolDesc)) hasResult = true; - } - if (method.name.equals("") && method.desc.equals(voidDesc)) hasDefaultCtr = true; - } - - if (classNode.visibleAnnotations != null) - { - for (AnnotationNode node : classNode.visibleAnnotations) - { - if (!hasResult && node.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/Event$HasResult;")) - { - /* Add: - * public boolean hasResult() - * { - * return true; - * } - */ - MethodNode method = new MethodNode(ACC_PUBLIC, "hasResult", boolDesc, null, null); - method.instructions.add(new InsnNode(ICONST_1)); - method.instructions.add(new InsnNode(IRETURN)); - classNode.methods.add(method); - edited = true; - } - else if (!hasCancelable && node.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/Cancelable;")) - { - /* Add: - * public boolean isCancelable() - * { - * return true; - * } - */ - MethodNode method = new MethodNode(ACC_PUBLIC, "isCancelable", boolDesc, null, null); - method.instructions.add(new InsnNode(ICONST_1)); - method.instructions.add(new InsnNode(IRETURN)); - classNode.methods.add(method); - edited = true; - } - } - } - - if (hasSetup) - { - if (!hasGetListenerList) - throw new RuntimeException("Event class defines setup() but does not define getListenerList! " + classNode.name); - else - return edited; - } - - Type tSuper = Type.getType(classNode.superName); - - //Add private static ListenerList LISTENER_LIST - classNode.fields.add(new FieldNode(ACC_PRIVATE | ACC_STATIC, "LISTENER_LIST", listDesc, null, null)); - - /*Add: - * public () - * { - * super(); - * } - */ - if (!hasDefaultCtr) - { - MethodNode method = new MethodNode(ACC_PUBLIC, "", voidDesc, null, null); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "", voidDesc, false)); - method.instructions.add(new InsnNode(RETURN)); - classNode.methods.add(method); - } - - /*Add: - * protected void setup() - * { - * super.setup(); - * if (LISTENER_LIST != NULL) - * { - * return; - * } - * LISTENER_LIST = new ListenerList(super.getListenerList()); - * } - */ - MethodNode method = new MethodNode(ACC_PROTECTED, "setup", voidDesc, null, null); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "setup", voidDesc, false)); - method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - LabelNode initListener = new LabelNode(); - method.instructions.add(new JumpInsnNode(IFNULL, initListener)); - method.instructions.add(new InsnNode(RETURN)); - method.instructions.add(initListener); - method.instructions.add(new FrameNode(F_SAME, 0, null, 0, null)); - method.instructions.add(new TypeInsnNode(NEW, tList.getInternalName())); - method.instructions.add(new InsnNode(DUP)); - method.instructions.add(new VarInsnNode(ALOAD, 0)); - method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "getListenerList", listDescM, false)); - method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tList.getInternalName(), "", getMethodDescriptor(VOID_TYPE, tList), false)); - method.instructions.add(new FieldInsnNode(PUTSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - method.instructions.add(new InsnNode(RETURN)); - classNode.methods.add(method); - - /*Add: - * public ListenerList getListenerList() - * { - * return this.LISTENER_LIST; - * } - */ - method = new MethodNode(ACC_PUBLIC, "getListenerList", listDescM, null, null); - method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc)); - method.instructions.add(new InsnNode(ARETURN)); - classNode.methods.add(method); - return true; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAPITransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAPITransformer.java deleted file mode 100644 index 2568c83db..000000000 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAPITransformer.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.asm.transformers; - -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Set; - -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModAPIManager; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.signature.SignatureReader; -import org.objectweb.asm.signature.SignatureWriter; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Sets; - -public class ModAPITransformer implements IClassTransformer { - - private static final boolean logDebugInfo = Boolean.valueOf(System.getProperty("fml.debugAPITransformer", "false")); - private ListMultimap optionals; - - @Override - public byte[] transform(String name, String transformedName, byte[] basicClass) - { - String lookupName = name; - if(name.endsWith("$class")) - { - lookupName = name.substring(0, name.length() - 6); - } - if (optionals == null || !optionals.containsKey(lookupName)) - { - return basicClass; - } - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(basicClass); - classReader.accept(classNode, 0); - - if (logDebugInfo) FMLLog.log.trace("Optional removal - found optionals for class {} - processing", name); - for (ASMData optional : optionals.get(lookupName)) - { - String modId = (String) optional.getAnnotationInfo().get("modid"); - - if (Loader.isModLoaded(modId) || ModAPIManager.INSTANCE.hasAPI(modId)) - { - if (logDebugInfo) FMLLog.log.trace("Optional removal skipped - mod present {}", modId); - continue; - } - if (logDebugInfo) FMLLog.log.trace("Optional on {} triggered - mod missing {}", name, modId); - - if (optional.getAnnotationInfo().containsKey("iface")) - { - Boolean stripRefs = (Boolean)optional.getAnnotationInfo().get("striprefs"); - if (stripRefs == null) stripRefs = Boolean.FALSE; - stripInterface(classNode,(String)optional.getAnnotationInfo().get("iface"), stripRefs); - } - else - { - stripMethod(classNode, optional.getObjectName()); - } - - } - if (logDebugInfo) FMLLog.log.trace("Optional removal - class {} processed", name); - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - return writer.toByteArray(); - } - - private void stripMethod(ClassNode classNode, String methodDescriptor) - { - if(classNode.name.endsWith("$class")) - { - String subName = classNode.name.substring(0, classNode.name.length() - 6); - int pos = methodDescriptor.indexOf('(') + 1; - methodDescriptor = methodDescriptor.substring(0, pos) + 'L' + subName + ';' + methodDescriptor.substring(pos); - } - for (ListIterator iterator = classNode.methods.listIterator(); iterator.hasNext();) - { - MethodNode method = iterator.next(); - if (methodDescriptor.equals(method.name+method.desc)) - { - iterator.remove(); - if (logDebugInfo) FMLLog.log.debug("Optional removal - method {} removed", methodDescriptor); - return; - } - } - if (logDebugInfo) FMLLog.log.debug("Optional removal - method {} NOT removed - not found", methodDescriptor); - } - - private void stripInterface(ClassNode classNode, String interfaceName, boolean stripRefs) - { - final String ifaceName = interfaceName.replace('.', '/'); - boolean found = classNode.interfaces.remove(ifaceName); - if (found && classNode.signature != null) - { - SignatureReader sr = new SignatureReader(classNode.signature); - final RemovingSignatureWriter signatureWriter = new RemovingSignatureWriter(ifaceName); - sr.accept(signatureWriter); - classNode.signature = signatureWriter.toString(); - if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} removed from type signature", interfaceName); - } - if (found && logDebugInfo) FMLLog.log.debug("Optional removal - interface {} removed", interfaceName); - if (!found && logDebugInfo) FMLLog.log.debug("Optional removal - interface {} NOT removed - not found", interfaceName); - - if (found && stripRefs) - { - if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - stripping method signature references", interfaceName); - for (Iterator iterator = classNode.methods.iterator(); iterator.hasNext();) - { - MethodNode node = iterator.next(); - if (node.desc.contains(ifaceName)) - { - if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - stripping method containing reference {}", interfaceName, node.name); - iterator.remove(); - } - } - if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - all method signature references stripped", interfaceName); - } - else if (found) - { - if (logDebugInfo) FMLLog.log.debug("Optional removal - interface {} - NOT stripping method signature references", interfaceName); - } - } - - public void initTable(ASMDataTable dataTable) - { - optionals = ArrayListMultimap.create(); - Set interfaceLists = dataTable.getAll("net.minecraftforge.fml.common.Optional$InterfaceList"); - addData(unpackInterfaces(interfaceLists)); - Set interfaces = dataTable.getAll("net.minecraftforge.fml.common.Optional$Interface"); - addData(interfaces); - Set methods = dataTable.getAll("net.minecraftforge.fml.common.Optional$Method"); - addData(methods); - } - - private Set unpackInterfaces(Set packedInterfaces) - { - Set result = Sets.newHashSet(); - for (ASMData data : packedInterfaces) - { - @SuppressWarnings("unchecked") - List> packedList = (List>) data.getAnnotationInfo().get("value"); - for (Map packed : packedList) - { - ASMData newData = data.copy(packed); - result.add(newData); - } - } - - return result; - } - private void addData(Set interfaces) - { - for (ASMData data : interfaces) - { - optionals.put(data.getClassName(),data); - } - } - - private static class RemovingSignatureWriter extends SignatureWriter - { - private final String ifaceName; - - RemovingSignatureWriter(String ifaceName) - { - this.ifaceName = ifaceName; - } - - @Override - public void visitClassType(String name) - { - if (name.equals(ifaceName)) { - super.visitClassType("java/lang/Object"); - } - else - { - super.visitClassType(name); - } - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAccessTransformer.java b/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAccessTransformer.java deleted file mode 100644 index e443ee659..000000000 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/ModAccessTransformer.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.asm.transformers; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.jar.Attributes; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import net.minecraftforge.fml.common.FMLLog; - -import com.google.common.collect.Maps; -import com.google.common.io.ByteSource; -import com.google.common.io.CharSource; - -public class ModAccessTransformer extends AccessTransformer -{ - public static final Attributes.Name FMLAT = new Attributes.Name("FMLAT"); - private static Map embedded = Maps.newHashMap(); //Needs to be primitive so that both classloaders get the same class. - @SuppressWarnings("unchecked") - public ModAccessTransformer() throws Exception - { - super(ModAccessTransformer.class); - //We are in the new ClassLoader here, so we need to get the static field from the other ClassLoader. - ClassLoader classLoader = this.getClass().getClassLoader().getClass().getClassLoader(); //Bit odd but it gets the class loader that loaded our current class loader yay java! - Class otherClazz = Class.forName(this.getClass().getName(), true, classLoader); - Field otherField = otherClazz.getDeclaredField("embedded"); - otherField.setAccessible(true); - embedded = (Map)otherField.get(null); - - for (Map.Entry e : embedded.entrySet()) - { - int old_count = getModifiers().size(); - processATFile(CharSource.wrap(e.getValue())); - int added = getModifiers().size() - old_count; - if (added > 0) - { - FMLLog.log.debug("Loaded {} rules from AccessTransformer mod jar file {}\n", added, e.getKey()); - } - } - } - - public static void addJar(JarFile jar, String atList) throws IOException - { - for (String at : atList.split(" ")) - { - JarEntry jarEntry = jar.getJarEntry("META-INF/"+at); - if (jarEntry != null) - { - embedded.put(String.format("%s!META-INF/%s", jar.getName(), at), - new JarByteSource(jar,jarEntry).asCharSource(StandardCharsets.UTF_8).read()); - } - } - } - - private static class JarByteSource extends ByteSource - { - private JarFile jar; - private JarEntry entry; - public JarByteSource(JarFile jar, JarEntry entry) - { - this.jar = jar; - this.entry = entry; - } - @Override - public InputStream openStream() throws IOException - { - return jar.getInputStream(entry); - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/ASMDataTable.java b/src/main/java/net/minecraftforge/fml/common/discovery/ASMDataTable.java deleted file mode 100644 index 6b0fe983e..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/ASMDataTable.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Nullable; - -import com.google.common.base.Predicate; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSetMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.common.collect.SetMultimap; - -import net.minecraftforge.fml.ModContainer; - -public class ASMDataTable -{ - public final static class ASMData implements Cloneable - { - private ModCandidate candidate; - private String annotationName; - private String className; - private String objectName; - private int classVersion; - private Map annotationInfo; - public ASMData(ModCandidate candidate, String annotationName, String className, @Nullable String objectName, @Nullable Map info) - { - this.candidate = candidate; - this.annotationName = annotationName; - this.className = className; - this.objectName = objectName; - this.annotationInfo = info; - } - public ModCandidate getCandidate() - { - return candidate; - } - public String getAnnotationName() - { - return annotationName; - } - public String getClassName() - { - return className; - } - public String getObjectName() - { - return objectName; - } - public Map getAnnotationInfo() - { - return annotationInfo; - } - - public ASMData copy(Map newAnnotationInfo) - { - try - { - ASMData clone = (ASMData) this.clone(); - clone.annotationInfo = newAnnotationInfo; - return clone; - } - catch (CloneNotSupportedException e) - { - throw new RuntimeException("Unpossible", e); - } - } - } - - private static class ModContainerPredicate implements Predicate - { - private ModContainer container; - public ModContainerPredicate(ModContainer container) - { - this.container = container; - } - @Override - public boolean apply(ASMData data) - { - return container.getSource().equals(data.candidate.getModContainer()); - } - } - private SetMultimap globalAnnotationData = HashMultimap.create(); - private Map> containerAnnotationData; - - private List containers = Lists.newArrayList(); - private SetMultimap packageMap = HashMultimap.create(); - - public SetMultimap getAnnotationsFor(ModContainer container) - { - if (containerAnnotationData == null) - { - ImmutableMap.Builder> mapBuilder = ImmutableMap.builder(); - for (ModContainer cont : containers) - { - Multimap values = Multimaps.filterValues(globalAnnotationData, new ModContainerPredicate(cont)); - mapBuilder.put(cont, ImmutableSetMultimap.copyOf(values)); - } - containerAnnotationData = mapBuilder.build(); - } - return containerAnnotationData.get(container); - } - - public Set getAll(String annotation) - { - return globalAnnotationData.get(annotation); - } - - public void addASMData(ModCandidate candidate, String annotation, String className, @Nullable String objectName, @Nullable Map annotationInfo) - { - globalAnnotationData.put(annotation, new ASMData(candidate, annotation, className, objectName, annotationInfo)); - } - - public void addContainer(ModContainer container) - { - this.containers.add(container); - } - - public void registerPackage(ModCandidate modCandidate, String pkg) - { - this.packageMap.put(pkg,modCandidate); - } - - public Set getCandidatesFor(String pkg) - { - return this.packageMap.get(pkg); - } - - @Nullable - public static String getOwnerModID(Set mods, ASMData targ) - { - if (mods.size() == 1) { - return (String)mods.iterator().next().getAnnotationInfo().get("modid"); - } else { - for (ASMData m : mods) { - if (targ.getClassName().startsWith(m.getClassName())) { - return (String)m.getAnnotationInfo().get("modid"); - } - } - } - return null; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/ContainerType.java b/src/main/java/net/minecraftforge/fml/common/discovery/ContainerType.java deleted file mode 100644 index 8d2d18948..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/ContainerType.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.util.List; - -import net.minecraftforge.fml.ModContainer; - -public enum ContainerType -{ - JAR(JarDiscoverer.class), - DIR(DirectoryDiscoverer.class); - - private ITypeDiscoverer discoverer; - - private ContainerType(Class discovererClass) - { - try - { - this.discoverer = discovererClass.newInstance(); - } - catch (ReflectiveOperationException e) - { - throw new RuntimeException(e); - } - } - - public List findMods(ModCandidate candidate, ASMDataTable table) - { - return discoverer.discover(candidate, table); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/DirectoryDiscoverer.java b/src/main/java/net/minecraftforge/fml/common/discovery/DirectoryDiscoverer.java deleted file mode 100644 index 62297306b..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/DirectoryDiscoverer.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; - -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.LoaderException; -import net.minecraftforge.fml.common.MetadataCollection; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.ModContainerFactory; -import net.minecraftforge.fml.common.discovery.asm.ASMModParser; - -import org.apache.commons.io.IOUtils; - -import com.google.common.collect.Lists; - -import javax.annotation.Nullable; - -public class DirectoryDiscoverer implements ITypeDiscoverer -{ - private class ClassFilter implements FileFilter - { - @Override - public boolean accept(File file) - { - return (file.isFile() && classFile.matcher(file.getName()).matches()) || file.isDirectory(); - } - } - - private ASMDataTable table; - - @Override - public List discover(ModCandidate candidate, ASMDataTable table) - { - this.table = table; - List found = Lists.newArrayList(); - FMLLog.log.debug("Examining directory {} for potential mods", candidate.getModContainer().getName()); - exploreFileSystem("", candidate.getModContainer(), found, candidate, null); - for (ModContainer mc : found) - { - table.addContainer(mc); - } - return found; - } - - public void exploreFileSystem(String path, File modDir, List harvestedMods, ModCandidate candidate, @Nullable MetadataCollection mc) - { - if (path.length() == 0) - { - File metadata = new File(modDir, "mcmod.info"); - try - { - FileInputStream fis = new FileInputStream(metadata); - try - { - mc = MetadataCollection.from(fis, modDir.getName()); - } - finally - { - IOUtils.closeQuietly(fis); - } - FMLLog.log.debug("Found an mcmod.info file in directory {}", modDir.getName()); - } - catch (Exception e) - { - mc = MetadataCollection.from(null,""); - FMLLog.log.debug("No mcmod.info file found in directory {}", modDir.getName()); - } - } - - File[] content = modDir.listFiles(new ClassFilter()); - - // Always sort our content - Arrays.sort(content); - for (File file : content) - { - if (file.isDirectory()) - { - FMLLog.log.trace("Recursing into package {}", path + file.getName()); - exploreFileSystem(path + file.getName() + "/", file, harvestedMods, candidate, mc); - continue; - } - Matcher match = classFile.matcher(file.getName()); - - if (match.matches()) - { - ASMModParser modParser = null; - FileInputStream fis = null; - try - { - fis = new FileInputStream(file); - modParser = new ASMModParser(fis); - candidate.addClassEntry(path+file.getName()); - } - catch (LoaderException e) - { - FMLLog.log.error("There was a problem reading the file {} - probably this is a corrupt file", file.getPath(), e); - throw e; - } - catch (IOException e) - { - throw new RuntimeException(e); - } - finally - { - IOUtils.closeQuietly(fis); - } - - modParser.validate(); - modParser.sendToTable(table, candidate); - ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate); - if (container!=null) - { - harvestedMods.add(container); - container.bindMetadata(mc); - } - } - - - } - } - -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/JarDiscoverer.java b/src/main/java/net/minecraftforge/fml/common/discovery/JarDiscoverer.java deleted file mode 100644 index e25b15ce5..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/JarDiscoverer.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.util.Collections; -import java.util.List; -import java.util.Map.Entry; -import java.util.jar.JarFile; - -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.LoaderException; -import net.minecraftforge.fml.common.MetadataCollection; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.ModContainerFactory; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; -import net.minecraftforge.fml.common.discovery.asm.ASMModParser; -import net.minecraftforge.fml.common.discovery.json.JsonAnnotationLoader; - -import java.util.regex.Matcher; -import java.util.zip.ZipEntry; - -import org.objectweb.asm.Type; - -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; - -public class JarDiscoverer implements ITypeDiscoverer -{ - private static final boolean ENABLE_JSON_TEST = "true".equals(System.getProperty("fml.enableJsonAnnotations", "false")); - - @Override - public List discover(ModCandidate candidate, ASMDataTable table) - { - List foundMods = Lists.newArrayList(); - FMLLog.log.debug("Examining file {} for potential mods", candidate.getModContainer().getName()); - try (JarFile jar = new JarFile(candidate.getModContainer())) - { - ZipEntry modInfo = jar.getEntry("mcmod.info"); - MetadataCollection mc = null; - if (modInfo != null) - { - FMLLog.log.trace("Located mcmod.info file in file {}", candidate.getModContainer().getName()); - try (InputStream inputStream = jar.getInputStream(modInfo)) - { - mc = MetadataCollection.from(inputStream, candidate.getModContainer().getName()); - } - } - else - { - FMLLog.log.debug("The mod container {} appears to be missing an mcmod.info file", candidate.getModContainer().getName()); - mc = MetadataCollection.from(null, ""); - } - - if (ENABLE_JSON_TEST && jar.getEntry(JsonAnnotationLoader.ANNOTATION_JSON) != null) - findClassesJSON(candidate, table, jar, foundMods, mc); - else - findClassesASM(candidate, table, jar, foundMods, mc); - } - catch (Exception e) - { - FMLLog.log.warn("Zip file {} failed to read properly, it will be ignored", candidate.getModContainer().getName(), e); - } - return foundMods; - } - - private void findClassesASM(ModCandidate candidate, ASMDataTable table, JarFile jar, List foundMods, MetadataCollection mc) throws IOException - { - for (ZipEntry ze : Collections.list(jar.entries())) - { - if (ze.getName()!=null && ze.getName().startsWith("__MACOSX")) - { - continue; - } - Matcher match = classFile.matcher(ze.getName()); - if (match.matches()) - { - ASMModParser modParser; - try - { - try (InputStream inputStream = jar.getInputStream(ze)) - { - modParser = new ASMModParser(inputStream); - } - candidate.addClassEntry(ze.getName()); - } - catch (LoaderException e) - { - FMLLog.log.error("There was a problem reading the entry {} in the jar {} - probably a corrupt zip", candidate.getModContainer().getPath(), e); - jar.close(); - throw e; - } - modParser.validate(); - modParser.sendToTable(table, candidate); - ModContainer container = ModContainerFactory.instance().build(modParser, candidate.getModContainer(), candidate); - if (container!=null) - { - table.addContainer(container); - foundMods.add(container); - container.bindMetadata(mc); - container.setClassVersion(modParser.getClassVersion()); - } - } - } - } - - private void findClassesJSON(ModCandidate candidate, ASMDataTable table, JarFile jar, List foundMods, MetadataCollection mc) throws IOException - { - FMLLog.log.info("Loading jar {} annotation data from json", candidate.getModContainer().getPath()); - ZipEntry json = jar.getEntry(JsonAnnotationLoader.ANNOTATION_JSON); - Multimap annos = JsonAnnotationLoader.loadJson(jar.getInputStream(json), candidate, table); - - for (ZipEntry e : Collections.list(jar.entries())) - { - if (!e.getName().startsWith("__MACOSX") && !e.getName().startsWith("META-INF/") && e.getName().endsWith(".class")) - { - candidate.addClassEntry(e.getName()); - } - } - - for (Entry> entry : ModContainerFactory.modTypes.entrySet()) - { - Type type = entry.getKey(); - Constructor ctr = entry.getValue(); - - for (ASMData data : annos.get(type.getClassName())) - { - FMLLog.log.debug("Identified a mod of type {} ({}) - loading", type.getClassName(), data.getClassName()); - try - { - ModContainer ret = ctr.newInstance(data.getClassName(), candidate, data.getAnnotationInfo()); - if (!ret.shouldLoadInEnvironment()) - FMLLog.log.debug("Skipping mod {}, container opted to not load.", data.getClassName()); - else - { - table.addContainer(ret); - foundMods.add(ret); - ret.bindMetadata(mc); - //ret.setClassVersion(classVersion); // Not really needed anymore as we're forcing J8. Maybe think of reinstating for J9 support? After LaunchWraper re-do. - } - } - catch (Exception e) - { - FMLLog.log.error("Unable to construct {} container", data.getClassName(), e); - } - } - } - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/ModCandidate.java b/src/main/java/net/minecraftforge/fml/common/discovery/ModCandidate.java deleted file mode 100644 index 499bfcf7d..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/ModCandidate.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.io.File; -import java.util.List; -import java.util.Set; - -import net.minecraftforge.fml.ModContainer; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - - -public class ModCandidate -{ - private File classPathRoot; - private File modContainer; - private ContainerType sourceType; - private boolean classpath; - private boolean isMinecraft; - private Set foundClasses = Sets.newHashSet(); - private List mods; - private List packages = Lists.newArrayList(); - private ASMDataTable table; - - public ModCandidate(File classPathRoot, File modContainer, ContainerType sourceType) - { - this(classPathRoot, modContainer, sourceType, false, false); - } - public ModCandidate(File classPathRoot, File modContainer, ContainerType sourceType, boolean isMinecraft, boolean classpath) - { - this.classPathRoot = classPathRoot; - this.modContainer = modContainer; - this.sourceType = sourceType; - this.isMinecraft = isMinecraft; - this.classpath = classpath; - } - - public File getClassPathRoot() - { - return classPathRoot; - } - - public File getModContainer() - { - return modContainer; - } - - public ContainerType getSourceType() - { - return sourceType; - } - public List explore(ASMDataTable table) - { - this.table = table; - this.mods = sourceType.findMods(this, table); - return this.mods; - } - - public void addClassEntry(String name) - { - String className = name.substring(0, name.lastIndexOf('.')); // strip the .class - foundClasses.add(className); - className = className.replace('/','.'); - int pkgIdx = className.lastIndexOf('.'); - if (pkgIdx > -1) - { - String pkg = className.substring(0,pkgIdx); - packages.add(pkg); - this.table.registerPackage(this,pkg); - } - } - - public boolean isClasspath() - { - return classpath; - } - public boolean isMinecraftJar() - { - return isMinecraft; - } - public Set getClassList() - { - return foundClasses; - } - public List getContainedMods() - { - return mods; - } - public List getContainedPackages() - { - return packages; - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/ModDiscoverer.java b/src/main/java/net/minecraftforge/fml/common/discovery/ModDiscoverer.java deleted file mode 100644 index 17b327b7a..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/ModDiscoverer.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery; - -import java.io.File; -import java.util.List; - -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.LoaderException; -import net.minecraftforge.fml.common.ModClassLoader; -import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.CoreModManager; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -public class ModDiscoverer -{ - private List candidates = Lists.newArrayList(); - - private ASMDataTable dataTable = new ASMDataTable(); - - private List nonModLibs = Lists.newArrayList(); - - public void findClasspathMods(ModClassLoader modClassLoader) - { - List knownLibraries = ImmutableList.builder() - // skip default libs - .addAll(modClassLoader.getDefaultLibraries()) - // skip loaded coremods - .addAll(CoreModManager.getIgnoredMods()) - // skip reparse coremods here - .addAll(CoreModManager.getReparseableCoremods()) - .build(); - File[] minecraftSources = modClassLoader.getParentSources(); - if (minecraftSources.length == 1 && minecraftSources[0].isFile()) - { - FMLLog.log.debug("Minecraft is a file at {}, loading", minecraftSources[0].getAbsolutePath()); - addCandidate(new ModCandidate(minecraftSources[0], minecraftSources[0], ContainerType.JAR, true, true)); - } - else - { - int i = 0; - for (File source : minecraftSources) - { - if (source.isFile()) - { - if (knownLibraries.contains(source.getName()) || modClassLoader.isDefaultLibrary(source)) - { - FMLLog.log.trace("Skipping known library file {}", source.getAbsolutePath()); - } - else - { - FMLLog.log.debug("Found a minecraft related file at {}, examining for mod candidates", source.getAbsolutePath()); - addCandidate(new ModCandidate(source, source, ContainerType.JAR, i==0, true)); - } - } - else if (minecraftSources[i].isDirectory()) - { - FMLLog.log.debug("Found a minecraft related directory at {}, examining for mod candidates", source.getAbsolutePath()); - addCandidate(new ModCandidate(source, source, ContainerType.DIR, i==0, true)); - } - i++; - } - } - - } - - public List identifyMods() - { - List modList = Lists.newArrayList(); - - for (ModCandidate candidate : candidates) - { - try - { - List mods = candidate.explore(dataTable); - if (mods.isEmpty() && !candidate.isClasspath()) - { - nonModLibs.add(candidate.getModContainer()); - } - else - { - modList.addAll(mods); - } - } - catch (LoaderException le) - { - FMLLog.log.warn("Identified a problem with the mod candidate {}, ignoring this source", candidate.getModContainer(), le); - } - } - - return modList; - } - - public ASMDataTable getASMTable() - { - return dataTable; - } - - public List getNonModLibs() - { - return nonModLibs; - } - - public void addCandidate(ModCandidate candidate) - { - for (ModCandidate c : candidates) - { - if (c.getModContainer().equals(candidate.getModContainer())) - { - FMLLog.log.trace(" Skipping already in list {}", candidate.getModContainer()); - return; - } - } - candidates.add(candidate); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/asm/ASMModParser.java b/src/main/java/net/minecraftforge/fml/common/discovery/asm/ASMModParser.java deleted file mode 100644 index 68f1ca7e1..000000000 --- a/src/main/java/net/minecraftforge/fml/common/discovery/asm/ASMModParser.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.discovery.asm; - -import java.io.IOException; -import java.io.InputStream; -import java.util.LinkedList; -import java.util.Set; - -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.LoaderException; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ModCandidate; - -import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation; -import net.minecraftforge.fml.loading.moddiscovery.ModClassVisitor; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.Type; - -import com.google.common.base.MoreObjects; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -public class ASMModParser -{ - private Type asmType; - private int classVersion; - private Type asmSuperType; - private LinkedList annotations = Lists.newLinkedList(); - private Set interfaces = Sets.newHashSet(); - - static enum AnnotationType - { - CLASS, FIELD, METHOD, SUBTYPE; - } - - public ASMModParser(InputStream stream) throws IOException - { - try - { - ClassReader reader = new ClassReader(stream); - reader.accept(new ModClassVisitor(this), 0); - } - catch (Exception ex) - { - FMLLog.log.error("Unable to read a class file correctly", ex); - throw new LoaderException(ex); - } - } - - public void beginNewTypeName(String typeQName, int classVersion, String superClassQName, String[] interfaces) - { - this.asmType = Type.getObjectType(typeQName); - this.classVersion = classVersion; - this.asmSuperType = !Strings.isNullOrEmpty(superClassQName) ? Type.getObjectType(superClassQName) : null; - for (String intf : interfaces) - this.interfaces.add(intf); - } - - public void startClassAnnotation(String annotationName) - { - ModAnnotation ann = new ModAnnotation(AnnotationType.CLASS, Type.getType(annotationName), this.asmType.getClassName()); - annotations.addFirst(ann); - } - - public void addAnnotationProperty(String key, Object value) - { - annotations.getFirst().addProperty(key, value); - } - - public void startFieldAnnotation(String fieldName, String annotationName) - { - ModAnnotation ann = new ModAnnotation(AnnotationType.FIELD, Type.getType(annotationName), fieldName); - annotations.addFirst(ann); - } - - @Override - public String toString() - { - return MoreObjects.toStringHelper("ASMAnnotationDiscoverer") - .add("className", asmType.getClassName()) - .add("classVersion", classVersion) - .add("superName", asmSuperType.getClassName()) - .add("annotations", annotations) - .toString(); - } - - public Type getASMType() - { - return asmType; - } - - public int getClassVersion() - { - return classVersion; - } - - public Type getASMSuperType() - { - return asmSuperType; - } - - public LinkedList getAnnotations() - { - return annotations; - } - - public void validate() - { - - } - - public void sendToTable(ASMDataTable table, ModCandidate candidate) - { - for (ModAnnotation ma : annotations) - { - table.addASMData(candidate, ma.asmType.getClassName(), this.asmType.getClassName(), ma.member, ma.values); - } - - for (String intf : interfaces) - { - table.addASMData(candidate, intf, this.asmType.getInternalName(), null, null); - } - } - - public void addAnnotationArray(String name) - { - annotations.getFirst().addArray(name); - } - - public void addAnnotationEnumProperty(String name, String desc, String value) - { - annotations.getFirst().addEnumProperty(name, desc, value); - - } - - public void endArray() - { - annotations.getFirst().endArray(); - - } - - public void addSubAnnotation(String name, String desc) - { - ModAnnotation ma = annotations.getFirst(); - annotations.addFirst(ma.addChildAnnotation(name, desc)); - } - - public void endSubAnnotation() - { - // take the child and stick it at the end - ModAnnotation child = annotations.removeFirst(); - annotations.addLast(child); - } - - public void startMethodAnnotation(String methodName, String methodDescriptor, String annotationName) - { - ModAnnotation ann = new ModAnnotation(AnnotationType.METHOD, Type.getType(annotationName), methodName+methodDescriptor); - annotations.addFirst(ann); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/json/JsonAnnotationLoader.java b/src/main/java/net/minecraftforge/fml/common/discovery/json/JsonAnnotationLoader.java index ea91b628c..da3c1ce0e 100644 --- a/src/main/java/net/minecraftforge/fml/common/discovery/json/JsonAnnotationLoader.java +++ b/src/main/java/net/minecraftforge/fml/common/discovery/json/JsonAnnotationLoader.java @@ -33,9 +33,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; -import net.minecraftforge.fml.common.discovery.ModCandidate; import net.minecraftforge.fml.common.discovery.json.ASMInfo.Annotation; import net.minecraftforge.fml.common.discovery.json.ASMInfo.TargetType; diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLInterModComms.java b/src/main/java/net/minecraftforge/fml/common/event/FMLInterModComms.java index 94d462cc1..47878efdb 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLInterModComms.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLInterModComms.java @@ -28,8 +28,6 @@ import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModThreadContext; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.LoaderState; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.common.Mod.Instance; @@ -379,11 +377,11 @@ public class FMLInterModComms { private static boolean enqueueStartupMessage(String modTarget, IMCMessage message) { - if (ModThreadContext.get().getCurrentContainer() == null) + if (ModThreadContext.get().getActiveContainer() == null) { return false; } - enqueueMessage(ModThreadContext.get().getCurrentContainer(), modTarget, message); + enqueueMessage(ModThreadContext.get().getActiveContainer(), modTarget, message); return ModList.get().isLoaded(modTarget); } diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLPreInitializationEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLPreInitializationEvent.java index 3a4e38a1a..d8d31bfb4 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLPreInitializationEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLPreInitializationEvent.java @@ -20,7 +20,6 @@ package net.minecraftforge.fml.common.event; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.ModMetadata; /** * Called before {@link FMLInitializationEvent} during mod startup. diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLServerAboutToStartEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLServerAboutToStartEvent.java index 65c40209b..5769bca15 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLServerAboutToStartEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLServerAboutToStartEvent.java @@ -20,7 +20,6 @@ package net.minecraftforge.fml.common.event; import net.minecraft.server.MinecraftServer; -import net.minecraftforge.fml.common.LoaderState.ModState; /** * Called before the server begins loading anything. Called after {@link FMLPostInitializationEvent} on the dedicated @@ -32,17 +31,11 @@ import net.minecraftforge.fml.common.LoaderState.ModState; */ public class FMLServerAboutToStartEvent extends FMLStateEvent { - private MinecraftServer server; + private final MinecraftServer server; - public FMLServerAboutToStartEvent(Object... data) + public FMLServerAboutToStartEvent(MinecraftServer server) { - super(data); - this.server = (MinecraftServer) data[0]; - } - @Override - public ModState getModState() - { - return ModState.AVAILABLE; + this.server = (MinecraftServer) server; } public MinecraftServer getServer() diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartedEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartedEvent.java index 2e203a712..ce1a9cbcf 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartedEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartedEvent.java @@ -19,8 +19,6 @@ package net.minecraftforge.fml.common.event; -import net.minecraftforge.fml.common.LoaderState.ModState; - /** * Called after {@link FMLServerStartingEvent} when the server is available and ready to play. * @@ -30,15 +28,7 @@ import net.minecraftforge.fml.common.LoaderState.ModState; public class FMLServerStartedEvent extends FMLStateEvent { - public FMLServerStartedEvent(Object... data) + public FMLServerStartedEvent() { - super(data); } - - @Override - public ModState getModState() - { - return ModState.AVAILABLE; - } - } diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartingEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartingEvent.java index e069ea5fe..f6c101d98 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartingEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStartingEvent.java @@ -22,7 +22,6 @@ package net.minecraftforge.fml.common.event; import net.minecraft.command.CommandHandler; import net.minecraft.command.ICommand; import net.minecraft.server.MinecraftServer; -import net.minecraftforge.fml.common.LoaderState.ModState; /** * Called after {@link FMLServerAboutToStartEvent} and before {@link FMLServerStartedEvent}. @@ -35,17 +34,11 @@ import net.minecraftforge.fml.common.LoaderState.ModState; public class FMLServerStartingEvent extends FMLStateEvent { - private MinecraftServer server; + private final MinecraftServer server; - public FMLServerStartingEvent(Object... data) + public FMLServerStartingEvent(final MinecraftServer server) { - super(data); - this.server = (MinecraftServer) data[0]; - } - @Override - public ModState getModState() - { - return ModState.AVAILABLE; + this.server = (MinecraftServer) server; } public MinecraftServer getServer() diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppedEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppedEvent.java index 48f6fb839..365435ae0 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppedEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppedEvent.java @@ -19,8 +19,6 @@ package net.minecraftforge.fml.common.event; -import net.minecraftforge.fml.common.LoaderState.ModState; - /** * Called after {@link FMLServerStoppingEvent} when the server has completely shut down. * Called immediately before shutting down, on the dedicated server, and before returning @@ -30,15 +28,4 @@ import net.minecraftforge.fml.common.LoaderState.ModState; * @author cpw */ public class FMLServerStoppedEvent extends FMLStateEvent { - - public FMLServerStoppedEvent(Object... data) - { - super(data); - } - @Override - public ModState getModState() - { - return ModState.AVAILABLE; - } - } diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppingEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppingEvent.java index 68fe5eaa4..874e874b4 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppingEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLServerStoppingEvent.java @@ -19,8 +19,6 @@ package net.minecraftforge.fml.common.event; -import net.minecraftforge.fml.common.LoaderState.ModState; - /** * Called when the server begins an orderly shutdown, before {@link FMLServerStoppedEvent}. * @@ -29,16 +27,4 @@ import net.minecraftforge.fml.common.LoaderState.ModState; */ public class FMLServerStoppingEvent extends FMLStateEvent { - - public FMLServerStoppingEvent(Object... data) - { - super(data); - } - - @Override - public ModState getModState() - { - return ModState.AVAILABLE; - } - } diff --git a/src/main/java/net/minecraftforge/fml/common/event/FMLStateEvent.java b/src/main/java/net/minecraftforge/fml/common/event/FMLStateEvent.java index 86a35ac52..42dae9bef 100644 --- a/src/main/java/net/minecraftforge/fml/common/event/FMLStateEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/event/FMLStateEvent.java @@ -20,7 +20,7 @@ package net.minecraftforge.fml.common.event; import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; /** * The parent of all mod-state changing events diff --git a/src/main/java/net/minecraftforge/fml/common/gameevent/TickEvent.java b/src/main/java/net/minecraftforge/fml/common/gameevent/TickEvent.java index a2f4863c2..aadda417e 100644 --- a/src/main/java/net/minecraftforge/fml/common/gameevent/TickEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/gameevent/TickEvent.java @@ -22,8 +22,8 @@ package net.minecraftforge.fml.common.gameevent; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.world.World; -import net.minecraftforge.eventbus.api.Event; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.fml.LogicalSide; public class TickEvent extends net.minecraftforge.eventbus.api.Event { @@ -35,9 +35,9 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event START, END; } public final Type type; - public final Side side; + public final LogicalSide side; public final Phase phase; - public TickEvent(Type type, Side side, Phase phase) + public TickEvent(Type type, LogicalSide side, Phase phase) { this.type = type; this.side = side; @@ -47,20 +47,20 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event public static class ServerTickEvent extends TickEvent { public ServerTickEvent(Phase phase) { - super(Type.SERVER, Side.SERVER, phase); + super(Type.SERVER, LogicalSide.SERVER, phase); } } public static class ClientTickEvent extends TickEvent { public ClientTickEvent(Phase phase) { - super(Type.CLIENT, Side.CLIENT, phase); + super(Type.CLIENT, LogicalSide.CLIENT, phase); } } public static class WorldTickEvent extends TickEvent { public final World world; - public WorldTickEvent(Side side, Phase phase, World world) + public WorldTickEvent(LogicalSide side, Phase phase, World world) { super(Type.WORLD, side, phase); this.world = world; @@ -71,7 +71,7 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event public PlayerTickEvent(Phase phase, EntityPlayer player) { - super(Type.PLAYER, player instanceof EntityPlayerMP ? Side.SERVER : Side.CLIENT, phase); + super(Type.PLAYER, player instanceof EntityPlayerMP ? LogicalSide.SERVER : LogicalSide.CLIENT, phase); this.player = player; } } @@ -80,7 +80,7 @@ public class TickEvent extends net.minecraftforge.eventbus.api.Event public final float renderTickTime; public RenderTickEvent(Phase phase, float renderTickTime) { - super(Type.RENDER, Side.CLIENT, phase); + super(Type.RENDER, LogicalSide.CLIENT, phase); this.renderTickTime = renderTickTime; } } diff --git a/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java b/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java deleted file mode 100644 index ad6e07035..000000000 --- a/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.launcher; - -import java.io.File; -import java.lang.reflect.Method; -import java.util.List; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.relauncher.CoreModManager; -import net.minecraftforge.fml.relauncher.FMLInjectionData; - -public class FMLDeobfTweaker implements ITweaker { - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - // Deobfuscation transformer, always last, and the access transformer tweaker as well - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.DeobfuscationTransformer"); - // Add all the access transformers now as well - for (String transformer : CoreModManager.getAccessTransformers()) - { - classLoader.registerTransformer(transformer); - } - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ModAccessTransformer"); - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemStackTransformer"); - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockTransformer"); - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockSpecialTransformer"); - try - { - FMLLog.log.debug("Validating minecraft"); - Class loaderClazz = Class.forName("net.minecraftforge.fml.common.Loader", true, classLoader); - Method m = loaderClazz.getMethod("injectData", Object[].class); - m.invoke(null, (Object)FMLInjectionData.data()); - m = loaderClazz.getMethod("instance"); - m.invoke(null); - FMLLog.log.debug("Minecraft validated, launching..."); - } - catch (Exception e) - { - // Load in the Loader, make sure he's ready to roll - this will initialize most of the rest of minecraft here - FMLLog.log.fatal("A CRITICAL PROBLEM OCCURRED INITIALIZING MINECRAFT - LIKELY YOU HAVE AN INCORRECT VERSION FOR THIS FML"); - throw new RuntimeException(e); - } - } - - @Override - public String getLaunchTarget() - { - throw new RuntimeException("Invalid for use as a primary tweaker"); - } - - @Override - public String[] getLaunchArguments() - { - return new String[0]; - } - -} diff --git a/src/main/java/net/minecraftforge/fml/common/launcher/FMLInjectionAndSortingTweaker.java b/src/main/java/net/minecraftforge/fml/common/launcher/FMLInjectionAndSortingTweaker.java deleted file mode 100644 index 8bb8cc9b6..000000000 --- a/src/main/java/net/minecraftforge/fml/common/launcher/FMLInjectionAndSortingTweaker.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.launcher; - -import java.io.File; -import java.util.List; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.relauncher.CoreModManager; - -/** - * This class is to manage the injection of coremods as tweakers into the tweak framework. - * It has to inject the coremod tweaks during construction, because that is the only time - * the tweak list is writeable. - * @author cpw - * - */ -public class FMLInjectionAndSortingTweaker implements ITweaker { - private boolean run; - public FMLInjectionAndSortingTweaker() - { - CoreModManager.injectCoreModTweaks(this); - run = false; - } - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - if (!run) - { - // We sort the tweak list here so that it obeys the tweakordering - CoreModManager.sortTweakList(); - @SuppressWarnings("unchecked") - List newTweaks = (List) Launch.blackboard.get("TweakClasses"); - newTweaks.add("net.minecraftforge.fml.common.launcher.TerminalTweaker"); - } - run = true; - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - } - - @Override - public String getLaunchTarget() - { - return ""; - } - - @Override - public String[] getLaunchArguments() - { - return new String[0]; - } - -} diff --git a/src/main/java/net/minecraftforge/fml/common/launcher/FMLServerTweaker.java b/src/main/java/net/minecraftforge/fml/common/launcher/FMLServerTweaker.java deleted file mode 100644 index 5153cb972..000000000 --- a/src/main/java/net/minecraftforge/fml/common/launcher/FMLServerTweaker.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.launcher; - -import java.io.File; -import java.util.List; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; - -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.relauncher.FMLLaunchHandler; - -public class FMLServerTweaker extends FMLTweaker { - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - super.acceptOptions(args, gameDir, assetsDir, profile); - - if (System.getProperty("log4j.configurationFile") == null) - { - System.setProperty("log4j.configurationFile", "log4j2_server.xml"); - ((LoggerContext) LogManager.getContext(false)).reconfigure(); - } - } - - @Override - public String getLaunchTarget() - { - return "net.minecraft.server.MinecraftServer"; - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - // The log4j2 queue is excluded so it is correctly visible from the obfuscated - // and deobfuscated parts of the code. Without, the UI won't show anything - classLoader.addClassLoaderExclusion("com.mojang.util.QueueLogAppender"); - - classLoader.addClassLoaderExclusion("org.jline."); - classLoader.addClassLoaderExclusion("com.sun.jna."); - classLoader.addClassLoaderExclusion("net.minecraftforge.server.terminalconsole."); - - FMLLaunchHandler.configureForServerLaunch(classLoader, this); - FMLLaunchHandler.appendCoreMods(); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java b/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java deleted file mode 100644 index 13f7b11e3..000000000 --- a/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.launcher; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.relauncher.FMLLaunchHandler; -import net.minecraftforge.fml.relauncher.FMLSecurityManager; - -import org.apache.logging.log4j.LogManager; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -public class FMLTweaker implements ITweaker { - private File gameDir; - private Map launchArgs; - private List standaloneArgs; - private static URI jarLocation; - - public FMLTweaker() - { - if (System.getProperty("java.net.preferIPv4Stack") == null) - { - System.setProperty("java.net.preferIPv4Stack", "true"); - } - try - { - System.setSecurityManager(new FMLSecurityManager()); - } - catch (SecurityException se) - { - throw new RuntimeException("FML was unable to install the security manager. The game will not start", se); - } - } - @SuppressWarnings("unchecked") - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - this.gameDir = (gameDir == null ? new File(".") : gameDir); - - this.launchArgs = (Map)Launch.blackboard.get("launchArgs"); - - this.standaloneArgs = Lists.newArrayList(); - if (this.launchArgs == null) - { - this.launchArgs = Maps.newHashMap(); - Launch.blackboard.put("launchArgs", this.launchArgs); - } - - String classifier = null; - - for (String arg : args) - { - if (arg.startsWith("-")) - { - if (classifier != null) - { - classifier = launchArgs.put(classifier, ""); - } - else if (arg.contains("=")) - { - classifier = launchArgs.put(arg.substring(0, arg.indexOf('=')), arg.substring(arg.indexOf('=') + 1)); - } - else - { - classifier = arg; - } - } - else - { - if (classifier != null) - { - classifier = launchArgs.put(classifier, arg); - } - else - { - this.standaloneArgs.add(arg); - } - } - } - - if (!this.launchArgs.containsKey("--version")) - { - launchArgs.put("--version", profile != null ? profile : "UnknownFMLProfile"); - } - - if (!this.launchArgs.containsKey("--gameDir") && gameDir != null) - { - launchArgs.put("--gameDir", gameDir.getAbsolutePath()); - } - - if (!this.launchArgs.containsKey("--assetsDir") && assetsDir != null) - { - launchArgs.put("--assetsDir", assetsDir.getAbsolutePath()); - } - - Yggdrasil.login(launchArgs); - - try - { - jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().toURI(); - } - catch (URISyntaxException e) - { - LogManager.getLogger("FML.TWEAK").error("Missing URI information for FML tweak"); - throw new RuntimeException(e); - } - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - FMLLaunchHandler.configureForClientLaunch(classLoader, this); - FMLLaunchHandler.appendCoreMods(); - } - - @Override - public String getLaunchTarget() - { - return "net.minecraft.client.main.Main"; - } - - @Override - public String[] getLaunchArguments() - { - List args = Lists.newArrayList(); - args.addAll(standaloneArgs); - - for (Entry arg : launchArgs.entrySet()) - { - if ("--modListFile".equals(arg.getKey()) || "--mods".equals(arg.getKey())) - continue; - args.add(arg.getKey()); - args.add(arg.getValue()); - } - - return args.toArray(new String[args.size()]); - } - - public File getGameDir() - { - return gameDir; - } - - public static URI getJarLocation() - { - return jarLocation; - } - - public void injectCascadingTweak(String tweakClassName) - { - @SuppressWarnings("unchecked") - List tweakClasses = (List) Launch.blackboard.get("TweakClasses"); - tweakClasses.add(tweakClassName); - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/launcher/TerminalTweaker.java b/src/main/java/net/minecraftforge/fml/common/launcher/TerminalTweaker.java deleted file mode 100644 index a9858e0af..000000000 --- a/src/main/java/net/minecraftforge/fml/common/launcher/TerminalTweaker.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.common.launcher; - -import java.io.File; -import java.util.List; -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.LaunchClassLoader; - -public final class TerminalTweaker implements ITweaker { - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.TerminalTransformer"); - } - - @Override - public String getLaunchTarget() - { - return null; - } - - @Override - public String[] getLaunchArguments() - { - return new String[0]; - } - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - - } -} diff --git a/src/main/java/net/minecraftforge/fml/common/network/FMLEmbeddedChannel.java b/src/main/java/net/minecraftforge/fml/common/network/FMLEmbeddedChannel.java index 58087648a..f10ae0dfb 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/FMLEmbeddedChannel.java +++ b/src/main/java/net/minecraftforge/fml/common/network/FMLEmbeddedChannel.java @@ -25,14 +25,13 @@ import io.netty.channel.embedded.EmbeddedChannel; import java.util.Map.Entry; import net.minecraft.network.Packet; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.ModThreadContext; -import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.ModContainer; import net.minecraftforge.fml.common.network.FMLOutboundHandler.OutboundTarget; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.javafmlmod.ModLoadingContext; import javax.annotation.Nullable; @@ -44,11 +43,11 @@ import javax.annotation.Nullable; * */ public class FMLEmbeddedChannel extends EmbeddedChannel { - public FMLEmbeddedChannel(String channelName, Side source, ChannelHandler... handlers) + public FMLEmbeddedChannel(String channelName, LogicalSide source, ChannelHandler... handlers) { - this(ModThreadContext.get().getCurrentContainer(), channelName, source, handlers); + this(ModThreadContext.get().getActiveContainer(), channelName, source, handlers); } - public FMLEmbeddedChannel(ModContainer container, String channelName, Side source, ChannelHandler... handlers) + public FMLEmbeddedChannel(ModContainer container, String channelName, LogicalSide source, ChannelHandler... handlers) { super(handlers); this.attr(NetworkRegistry.FML_CHANNEL).set(channelName); diff --git a/src/main/java/net/minecraftforge/fml/common/network/FMLEventChannel.java b/src/main/java/net/minecraftforge/fml/common/network/FMLEventChannel.java index 38ab4f1ee..fad03205f 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/FMLEventChannel.java +++ b/src/main/java/net/minecraftforge/fml/common/network/FMLEventChannel.java @@ -32,7 +32,7 @@ import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import javax.annotation.Nullable; diff --git a/src/main/java/net/minecraftforge/fml/common/network/FMLNetworkEvent.java b/src/main/java/net/minecraftforge/fml/common/network/FMLNetworkEvent.java index 2c4619b48..68b530eb5 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/FMLNetworkEvent.java +++ b/src/main/java/net/minecraftforge/fml/common/network/FMLNetworkEvent.java @@ -29,7 +29,7 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; public class FMLNetworkEvent extends Event { private final T handler; diff --git a/src/main/java/net/minecraftforge/fml/common/network/FMLOutboundHandler.java b/src/main/java/net/minecraftforge/fml/common/network/FMLOutboundHandler.java index 9d8eea16a..1aabe8c95 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/FMLOutboundHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/network/FMLOutboundHandler.java @@ -42,7 +42,7 @@ import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; diff --git a/src/main/java/net/minecraftforge/fml/common/network/NetworkCheckHandler.java b/src/main/java/net/minecraftforge/fml/common/network/NetworkCheckHandler.java index d3770d52a..b753432eb 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/NetworkCheckHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/network/NetworkCheckHandler.java @@ -19,13 +19,13 @@ package net.minecraftforge.fml.common.network; +import net.minecraftforge.api.distmarker.Dist; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import net.minecraftforge.fml.relauncher.Side; - /** * A method annotated with this will be called when a remote network connection is offered. * The method should have two parameters, of types Map and {@link Side}. It should return a boolean diff --git a/src/main/java/net/minecraftforge/fml/common/network/NetworkHandshakeEstablished.java b/src/main/java/net/minecraftforge/fml/common/network/NetworkHandshakeEstablished.java index 2869d6800..f037893d3 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/NetworkHandshakeEstablished.java +++ b/src/main/java/net/minecraftforge/fml/common/network/NetworkHandshakeEstablished.java @@ -21,7 +21,7 @@ package net.minecraftforge.fml.common.network; import net.minecraft.network.INetHandler; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; /** * This message is sent through all channels affected by a currently occurring handshake. It is guaranteed to diff --git a/src/main/java/net/minecraftforge/fml/common/network/NetworkRegistry.java b/src/main/java/net/minecraftforge/fml/common/network/NetworkRegistry.java index 92792f75d..8ca2e760d 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/NetworkRegistry.java +++ b/src/main/java/net/minecraftforge/fml/common/network/NetworkRegistry.java @@ -35,12 +35,11 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; import net.minecraft.network.INetHandler; import net.minecraft.world.World; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.network.FMLOutboundHandler.OutboundTarget; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; import net.minecraftforge.fml.common.network.internal.NetworkModHolder; @@ -55,10 +54,10 @@ import javax.annotation.Nullable; * @author cpw * */ -public enum NetworkRegistry +public class NetworkRegistry { - INSTANCE; - private EnumMap> channels = Maps.newEnumMap(Side.class); + public static final NetworkRegistry INSTANCE = new NetworkRegistry(); + private EnumMap> channels = Maps.newEnumMap(LogicalSide.class); private Map registry = Maps.newHashMap(); private Map serverGuiHandlers = Maps.newHashMap(); private Map clientGuiHandlers = Maps.newHashMap(); @@ -67,10 +66,10 @@ public enum NetworkRegistry * Set in the {@link ChannelHandlerContext} */ public static final AttributeKey FML_CHANNEL = AttributeKey.valueOf("fml:channelName"); - public static final AttributeKey CHANNEL_SOURCE = AttributeKey.valueOf("fml:channelSource"); + public static final AttributeKey CHANNEL_SOURCE = AttributeKey.valueOf("fml:channelSource"); public static final AttributeKey MOD_CONTAINER = AttributeKey.valueOf("fml:modContainer"); public static final AttributeKey NET_HANDLER = AttributeKey.valueOf("fml:netHandler"); - public static final AttributeKey FML_MARKER = AttributeKey.valueOf("fml:hasMarker"); + public static final AttributeKey FML_MARKER = AttributeKey.valueOf("fml:versionMarker"); // Version 1: ServerHello only contains this value as a byte // Version 2: ServerHello additionally contains a 4 byte (int) dimension for the logging in client @@ -78,8 +77,8 @@ public enum NetworkRegistry private NetworkRegistry() { - channels.put(Side.CLIENT, Maps.newConcurrentMap()); - channels.put(Side.SERVER, Maps.newConcurrentMap()); + channels.put(LogicalSide.CLIENT, Maps.newConcurrentMap()); + channels.put(LogicalSide.SERVER, Maps.newConcurrentMap()); } /** @@ -123,8 +122,8 @@ public enum NetworkRegistry *
  • Alternatively, simply use the netty features provided here and implement the full power of the netty stack. * * - * There are two channels created : one for each logical side (considered as the source of an outbound message) - * The returned map will contain a value for each logical side, though both will only be working in the + * There are two channels created : one for each logical Dist (conDistred as the source of an outbound message) + * The returned map will contain a value for each logical Dist, though both will only be working in the * integrated server case. * * The channel expects to read and write using {@link FMLProxyPacket}. All operation is synchronous, as the @@ -133,7 +132,7 @@ public enum NetworkRegistry * The first handler in the pipeline is special and should not be removed or moved from the head - it transforms * packets from the outbound of this pipeline into custom packets, based on the current {@link AttributeKey} value * {@link FMLOutboundHandler#FML_MESSAGETARGET} and {@link FMLOutboundHandler#FML_MESSAGETARGETARGS} set on the channel. - * For the client to server channel (source side : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets, + * For the client to server channel (source Dist : CLIENT) this is fixed as "TOSERVER". For SERVER to CLIENT packets, * several possible values exist. * * Mod Messages should be transformed using a something akin to a {@link MessageToMessageCodec}. FML provides @@ -147,15 +146,15 @@ public enum NetworkRegistry * @param handlers * @return */ - public EnumMap newChannel(String name, ChannelHandler... handlers) + public EnumMap newChannel(String name, ChannelHandler... handlers) { - if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || name.startsWith("FML")) + if (channels.get(LogicalSide.CLIENT).containsKey(name) || channels.get(LogicalSide.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || name.startsWith("FML")) { throw new RuntimeException("That channel is already registered"); } - EnumMap result = Maps.newEnumMap(Side.class); + EnumMap result = Maps.newEnumMap(LogicalSide.class); - for (Side side : Side.values()) + for (LogicalSide side : LogicalSide.values()) { FMLEmbeddedChannel channel = new FMLEmbeddedChannel(name, side, handlers); channels.get(side).put(name,channel); @@ -191,26 +190,26 @@ public enum NetworkRegistry * @param container The container to associate the channel with * @param name The name for the channel * @param handlers Some {@link ChannelHandler} for the channel - * @return an {@link EnumMap} of the pair of channels. keys are {@link Side}. There will always be two entries. + * @return an {@link EnumMap} of the pair of channels. keys are {@link Dist}. There will always be two entries. */ - public EnumMap newChannel(ModContainer container, String name, ChannelHandler... handlers) + public EnumMap newChannel(ModContainer container, String name, ChannelHandler... handlers) { - if (channels.get(Side.CLIENT).containsKey(name) || channels.get(Side.SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || (name.startsWith("FML") && !("FML".equals(container.getModId())))) + if (channels.get(Dist.CLIENT).containsKey(name) || channels.get(Dist.DEDICATED_SERVER).containsKey(name) || name.startsWith("MC|") || name.startsWith("\u0001") || (name.startsWith("FML") && !("FML".equals(container.getModId())))) { throw new RuntimeException("That channel is already registered"); } - EnumMap result = Maps.newEnumMap(Side.class); + EnumMap result = Maps.newEnumMap(LogicalSide.class); - for (Side side : Side.values()) + for (LogicalSide Dist : LogicalSide.values()) { - FMLEmbeddedChannel channel = new FMLEmbeddedChannel(container, name, side, handlers); - channels.get(side).put(name,channel); - result.put(side, channel); + FMLEmbeddedChannel channel = new FMLEmbeddedChannel(container, name, Dist, handlers); + channels.get(Dist).put(name,channel); + result.put(Dist, channel); } return result; } - public FMLEmbeddedChannel getChannel(String name, Side source) + public FMLEmbeddedChannel getChannel(String name, Dist source) { return channels.get(source).get(name); } @@ -241,7 +240,7 @@ public enum NetworkRegistry * @param x X coord * @param y Y coord * @param z Z coord - * @return The server side GUI object (An instance of {@link Container}) + * @return The server Dist GUI object (An instance of {@link Container}) */ @Nullable public Container getRemoteGuiContainer(ModContainer mc, EntityPlayerMP player, int modGuiId, World world, int x, int y, int z) @@ -267,7 +266,7 @@ public enum NetworkRegistry * @param x X coord * @param y Y coord * @param z Z coord - * @return The client side GUI object (An instance of {@link net.minecraft.client.gui.Gui}) + * @return The client Dist GUI object (An instance of {@link net.minecraft.client.gui.Gui}) */ @Nullable public Object getLocalGuiContainer(ModContainer mc, EntityPlayer player, int modGuiId, World world, int x, int y, int z) @@ -277,12 +276,12 @@ public enum NetworkRegistry } /** - * Is there a channel with this name on this side? + * Is there a channel with this name on this Dist? * @param channelName The name - * @param source the side + * @param source the Dist * @return if there's a channel */ - public boolean hasChannel(String channelName, Side source) + public boolean hasChannel(String channelName, Dist source) { return channels.get(source).containsKey(channelName); } @@ -294,20 +293,23 @@ public enum NetworkRegistry * @param remoteVersionRange the acceptable remote range * @param asmHarvestedData internal data */ +/* public void register(ModContainer fmlModContainer, Class clazz, @Nullable String remoteVersionRange, ASMDataTable asmHarvestedData) { NetworkModHolder networkModHolder = new NetworkModHolder(fmlModContainer, clazz, remoteVersionRange, asmHarvestedData); registry.put(fmlModContainer, networkModHolder); networkModHolder.testVanillaAcceptance(); } +*/ - public boolean isVanillaAccepted(Side from) +/* + public boolean isVanillaAccepted(Dist from) { return registry.values().stream() .allMatch(mod -> mod.acceptsVanilla(from)); } - public Collection getRequiredMods(Side from) + public Collection getRequiredMods(Dist from) { return registry.values().stream() .filter(mod -> !mod.acceptsVanilla(from)) @@ -315,6 +317,7 @@ public enum NetworkRegistry .sorted() .collect(Collectors.toList()); } +*/ public Map registry() { @@ -322,21 +325,21 @@ public enum NetworkRegistry } /** - * All the valid channel names for a side - * @param side the side + * All the valid channel names for a Dist + * @param Dist the Dist * @return the set of channel names */ - public Set channelNamesFor(Side side) + public Set channelNamesFor(Dist Dist) { - return channels.get(side).keySet(); + return channels.get(Dist).keySet(); } /** * INTERNAL fire a handshake to all channels * @param networkDispatcher The dispatcher firing - * @param origin which side the dispatcher is on + * @param origin which Dist the dispatcher is on */ - public void fireNetworkHandshake(NetworkDispatcher networkDispatcher, Side origin) + public void fireNetworkHandshake(NetworkDispatcher networkDispatcher, Dist origin) { /* NetworkHandshakeEstablished handshake = new NetworkHandshakeEstablished(networkDispatcher, networkDispatcher.getNetHandler(), origin); diff --git a/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeClientState.java b/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeClientState.java index afc4e1c6d..397d10524 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeClientState.java +++ b/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeClientState.java @@ -31,13 +31,13 @@ import com.google.common.util.concurrent.Futures; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.handshake.FMLHandshakeMessage.ServerHello; import net.minecraftforge.fml.common.network.internal.FMLMessage; import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.GameData; diff --git a/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeServerState.java b/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeServerState.java index cf5487ebb..f8a13cb8d 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeServerState.java +++ b/src/main/java/net/minecraftforge/fml/common/network/handshake/FMLHandshakeServerState.java @@ -33,7 +33,7 @@ import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.internal.FMLMessage; import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.RegistryManager; diff --git a/src/main/java/net/minecraftforge/fml/common/network/handshake/NetworkDispatcher.java b/src/main/java/net/minecraftforge/fml/common/network/handshake/NetworkDispatcher.java index a04a36f09..ff63b8240 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/handshake/NetworkDispatcher.java +++ b/src/main/java/net/minecraftforge/fml/common/network/handshake/NetworkDispatcher.java @@ -65,7 +65,7 @@ import net.minecraftforge.fml.common.network.PacketLoggingHandler; import net.minecraftforge.fml.common.network.internal.FMLMessage; import net.minecraftforge.fml.common.network.internal.FMLNetworkHandler; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.network.ConnectionType; import net.minecraftforge.registries.ForgeRegistry; // TODO build test suites to validate the behaviour of this stuff and make it less annoyingly magical @@ -75,10 +75,6 @@ public class NetworkDispatcher extends SimpleChannelInboundHandler> im OPENING, AWAITING_HANDSHAKE, HANDSHAKING, HANDSHAKECOMPLETE, FINALIZING, CONNECTED } - public static enum ConnectionType { - MODDED, BUKKIT, VANILLA - } - public static NetworkDispatcher get(NetworkManager manager) { return manager.channel().attr(FML_DISPATCHER).get(); diff --git a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLMessage.java b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLMessage.java index 78150dbc5..dc3112afe 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLMessage.java +++ b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLMessage.java @@ -36,7 +36,7 @@ import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.registry.EntityRegistry.EntityRegistration; import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData; import net.minecraftforge.fml.common.registry.IThrowableEntity; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; public abstract class FMLMessage { public static class CompleteHandshake extends FMLMessage { diff --git a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLNetworkHandler.java b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLNetworkHandler.java index 271fbc27a..bb39e6933 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLNetworkHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLNetworkHandler.java @@ -37,9 +37,12 @@ import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.server.management.PlayerList; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.util.FakePlayer; +import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.FMLContainer; +import net.minecraftforge.fml.FMLWorldPersistenceHook; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.ModContainer; @@ -52,8 +55,6 @@ import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; import net.minecraftforge.fml.common.network.internal.FMLMessage.CompleteHandshake; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry.EntityRegistration; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import com.google.gson.JsonArray; import com.google.gson.JsonObject; @@ -147,8 +148,10 @@ public class FMLNetworkHandler * @return null if everything is fine, returns a string error message if there are mod rejections */ @Nullable - public static String checkModList(Map listData, Side side) + public static String checkModList(Map listData, LogicalSide side) { + return null; +/* List> rejects = NetworkRegistry.INSTANCE.registry().entrySet().stream() .map(entry -> Pair.of(entry.getKey(), entry.getValue().checkCompatible(listData, side))) .filter(pair -> pair.getValue() != null) @@ -170,9 +173,10 @@ public class FMLNetworkHandler FMLLog.log.info("Rejecting connection {}: {}", side, rejectString); return String.format("Server Mod rejections:\n%s", rejectString); } +*/ } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) private static void addClientHandlers() { ChannelPipeline pipeline = channelPair.get(Side.CLIENT).pipeline(); @@ -180,7 +184,7 @@ public class FMLNetworkHandler pipeline.addAfter(targetName, "GuiHandler", new OpenGuiHandler()); pipeline.addAfter(targetName, "EntitySpawnHandler", new EntitySpawnHandler()); } - public static void registerChannel(FMLContainer container, Side side) + public static void registerChannel(FMLWorldPersistenceHook container, Side side) { channelPair = NetworkRegistry.INSTANCE.newChannel(container, "FML", new FMLRuntimeCodec(), new HandshakeCompletionHandler()); EmbeddedChannel embeddedChannel = channelPair.get(Side.SERVER); diff --git a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLProxyPacket.java b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLProxyPacket.java index a7bcd7436..90eca160b 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/internal/FMLProxyPacket.java +++ b/src/main/java/net/minecraftforge/fml/common/network/internal/FMLProxyPacket.java @@ -38,7 +38,7 @@ import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.network.FMLNetworkException; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import com.google.common.collect.ConcurrentHashMultiset; import com.google.common.collect.Lists; diff --git a/src/main/java/net/minecraftforge/fml/common/network/internal/NetworkModHolder.java b/src/main/java/net/minecraftforge/fml/common/network/internal/NetworkModHolder.java index 47c1e58d1..c46992691 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/internal/NetworkModHolder.java +++ b/src/main/java/net/minecraftforge/fml/common/network/internal/NetworkModHolder.java @@ -23,11 +23,9 @@ import java.lang.reflect.Method; import java.util.Map; import java.util.Set; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.common.versioning.DefaultArtifactVersion; import net.minecraftforge.fml.common.versioning.InvalidVersionSpecificationException; diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java index f1b7314ea..ab2b4182c 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/IMessageHandler.java @@ -20,9 +20,11 @@ package net.minecraftforge.fml.common.network.simpleimpl; +import net.minecraftforge.api.distmarker.Dist; + /** * A message handler based on {@link IMessage}. Implement and override {@link #onMessage(IMessage, MessageContext)} to - * process your packet. Supply the class to {@link SimpleNetworkWrapper#registerMessage(Class, Class, int, net.minecraftforge.fml.relauncher.Side)} + * process your packet. Supply the class to {@link SimpleNetworkWrapper#registerMessage(Class, Class, int, Side)} * to register both the message type and it's associated handler. * * @author cpw diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/MessageContext.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/MessageContext.java index a2095b415..76fdc8929 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/MessageContext.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/MessageContext.java @@ -22,7 +22,7 @@ package net.minecraftforge.fml.common.network.simpleimpl; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.INetHandler; import net.minecraft.network.NetHandlerPlayServer; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; /** * Context for the {@link IMessageHandler} @@ -38,13 +38,13 @@ public class MessageContext { public final INetHandler netHandler; /** - * The Side this message has been received on + * The Dist this message has been received on */ - public final Side side; + public final Dist side; /** * @param netHandler */ - MessageContext(INetHandler netHandler, Side side) + MessageContext(INetHandler netHandler, Dist side) { this.netHandler = netHandler; this.side = side; diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java index 90e7da9ff..9e45e0368 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleChannelHandlerWrapper.java @@ -19,7 +19,7 @@ package net.minecraftforge.fml.common.network.simpleimpl; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import org.apache.logging.log4j.Level; import net.minecraft.network.INetHandler; @@ -35,14 +35,14 @@ import io.netty.channel.SimpleChannelInboundHandler; public class SimpleChannelHandlerWrapper extends SimpleChannelInboundHandler { private final IMessageHandler messageHandler; - private final Side side; + private final Dist side; - public SimpleChannelHandlerWrapper(Class> handler, Side side, Class requestType) + public SimpleChannelHandlerWrapper(Class> handler, Dist side, Class requestType) { this(SimpleNetworkWrapper.instantiate(handler), side, requestType); } - public SimpleChannelHandlerWrapper(IMessageHandler handler, Side side, Class requestType) + public SimpleChannelHandlerWrapper(IMessageHandler handler, Dist side, Class requestType) { super(requestType); messageHandler = Preconditions.checkNotNull(handler, "IMessageHandler must not be null"); diff --git a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleNetworkWrapper.java b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleNetworkWrapper.java index 95c9a224a..3772a8c2f 100644 --- a/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleNetworkWrapper.java +++ b/src/main/java/net/minecraftforge/fml/common/network/simpleimpl/SimpleNetworkWrapper.java @@ -33,7 +33,8 @@ import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.fml.LogicalSide; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.network.FMLEmbeddedChannel; @@ -50,7 +51,7 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; * Usage is simple:
      *
    • construct, and store, an instance of this class. It will automatically register and configure your underlying netty channel. * - *
    • Then, call {@link #registerMessage(Class, Class, int, Side)} for each message type you want to exchange + *
    • Then, call {@link #registerMessage(Class, Class, int, Dist)} for each message type you want to exchange * providing an {@link IMessageHandler} implementation class as well as an {@link IMessage} implementation class. The side parameter * to that method indicates which side (server or client) the message processing will occur on. The discriminator byte * should be unique for this channelName - it is used to discriminate between different types of message that might @@ -96,9 +97,9 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; * // Code in a {@link FMLPreInitializationEvent} or {@link FMLInitializationEvent} handler * SimpleNetworkWrapper wrapper = NetworkRegistry.newSimpleChannel("MYCHANNEL"); * // Message1 is handled by the Message1Handler class, it has discriminator id 1 and it's on the client - * wrapper.registerMessage(Message1Handler.class, Message1.class, 1, Side.CLIENT); + * wrapper.registerMessage(Message1Handler.class, Message1.class, 1, Dist.CLIENT); * // Message2 is handled by the Message2Handler class, it has discriminator id 2 and it's on the server - * wrapper.registerMessage(Message2Handler.class, Message2.class, 2, Side.SERVER); + * wrapper.registerMessage(Message2Handler.class, Message2.class, 2, Dist.DEDICATED_SERVER); * * * @@ -111,7 +112,7 @@ import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint; * */ public class SimpleNetworkWrapper { - private EnumMap channels; + private EnumMap channels; private SimpleIndexedCodec packetCodec; private static Class defaultChannelPipeline; private static Method generateName; @@ -154,7 +155,7 @@ public class SimpleNetworkWrapper { * @param discriminator a discriminator byte * @param side the side for the handler */ - public void registerMessage(Class> messageHandler, Class requestMessageType, int discriminator, Side side) + public void registerMessage(Class> messageHandler, Class requestMessageType, int discriminator, Dist side) { registerMessage(instantiate(messageHandler), requestMessageType, discriminator, side); } @@ -180,12 +181,12 @@ public class SimpleNetworkWrapper { * @param discriminator a discriminator byte * @param side the side for the handler */ - public void registerMessage(IMessageHandler messageHandler, Class requestMessageType, int discriminator, Side side) + public void registerMessage(IMessageHandler messageHandler, Class requestMessageType, int discriminator, Dist side) { packetCodec.addDiscriminator(discriminator, requestMessageType); FMLEmbeddedChannel channel = channels.get(side); String type = channel.findChannelHandlerNameForType(SimpleIndexedCodec.class); - if (side == Side.SERVER) + if (side == Dist.DEDICATED_SERVER) { addServerHandlerAfter(channel, type, messageHandler, requestMessageType); } @@ -197,17 +198,17 @@ public class SimpleNetworkWrapper { private void addServerHandlerAfter(FMLEmbeddedChannel channel, String type, IMessageHandler messageHandler, Class requestType) { - SimpleChannelHandlerWrapper handler = getHandlerWrapper(messageHandler, Side.SERVER, requestType); + SimpleChannelHandlerWrapper handler = getHandlerWrapper(messageHandler, Dist.DEDICATED_SERVER, requestType); channel.pipeline().addAfter(type, generateName(channel.pipeline(), handler), handler); } private void addClientHandlerAfter(FMLEmbeddedChannel channel, String type, IMessageHandler messageHandler, Class requestType) { - SimpleChannelHandlerWrapper handler = getHandlerWrapper(messageHandler, Side.CLIENT, requestType); + SimpleChannelHandlerWrapper handler = getHandlerWrapper(messageHandler, Dist.CLIENT, requestType); channel.pipeline().addAfter(type, generateName(channel.pipeline(), handler), handler); } - private SimpleChannelHandlerWrapper getHandlerWrapper(IMessageHandler messageHandler, Side side, Class requestType) + private SimpleChannelHandlerWrapper getHandlerWrapper(IMessageHandler messageHandler, Dist side, Class requestType) { return new SimpleChannelHandlerWrapper(messageHandler, side, requestType); } @@ -221,7 +222,7 @@ public class SimpleNetworkWrapper { */ public Packet getPacketFrom(IMessage message) { - return channels.get(Side.SERVER).generatePacketFrom(message); + return channels.get(Dist.DEDICATED_SERVER).generatePacketFrom(message); } /** @@ -232,8 +233,8 @@ public class SimpleNetworkWrapper { */ public void sendToAll(IMessage message) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL); + channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } /** @@ -245,9 +246,9 @@ public class SimpleNetworkWrapper { */ public void sendTo(IMessage message, EntityPlayerMP player) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER); - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player); + channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } /** @@ -259,9 +260,9 @@ public class SimpleNetworkWrapper { */ public void sendToAllAround(IMessage message, NetworkRegistry.TargetPoint point) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT); - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point); - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point); + channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } /** @@ -304,9 +305,9 @@ public class SimpleNetworkWrapper { */ public void sendToDimension(IMessage message, int dimensionId) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION); - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId); - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION); + channels.get(Dist.DEDICATED_SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId); + channels.get(Dist.DEDICATED_SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } /** @@ -317,7 +318,7 @@ public class SimpleNetworkWrapper { */ public void sendToServer(IMessage message) { - channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER); - channels.get(Side.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + channels.get(Dist.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER); + channels.get(Dist.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } } diff --git a/src/main/java/net/minecraftforge/fml/common/patcher/ClassPatchManager.java b/src/main/java/net/minecraftforge/fml/common/patcher/ClassPatchManager.java index 5d8e3d6f4..81c50cea3 100644 --- a/src/main/java/net/minecraftforge/fml/common/patcher/ClassPatchManager.java +++ b/src/main/java/net/minecraftforge/fml/common/patcher/ClassPatchManager.java @@ -35,8 +35,8 @@ import java.util.regex.Pattern; import net.minecraft.launchwrapper.Launch; import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher; import LZMA.LzmaInputStream; diff --git a/src/main/java/net/minecraftforge/fml/common/patcher/GenDiffSet.java b/src/main/java/net/minecraftforge/fml/common/patcher/GenDiffSet.java index ca01d09f8..7d8ebb8d1 100644 --- a/src/main/java/net/minecraftforge/fml/common/patcher/GenDiffSet.java +++ b/src/main/java/net/minecraftforge/fml/common/patcher/GenDiffSet.java @@ -28,11 +28,14 @@ import java.util.Locale; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import net.minecraftforge.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper; +import net.minecraftforge.fml.common.asm.deobf.FMLDeobfuscatingRemapper; import net.minecraftforge.fml.repackage.com.nothome.delta.Delta; +import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; +import java.util.logging.Logger; + import com.google.common.hash.Hashing; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; @@ -53,8 +56,7 @@ public class GenDiffSet { String outputDir = args[3]; //Path to place generated .binpatch String killTarget = args[4]; //"true" if we should destroy the target file if it generated a successful .binpatch - Logger logger = LogManager.getLogger("FML.GENDIFF"); - logger.info("Creating patches at {} for {} from {}", outputDir, sourceJar, targetDir); + LogManager.getLogger("GENDIFF").log(Level.INFO, String.format("Creating patches at %s for %s from %s", outputDir, sourceJar, targetDir)); Delta delta = new Delta(); FMLDeobfuscatingRemapper remapper = FMLDeobfuscatingRemapper.INSTANCE; remapper.setupLoadOnly(deobfData, false); diff --git a/src/main/java/net/minecraftforge/fml/common/registry/ItemStackHolderInjector.java b/src/main/java/net/minecraftforge/fml/common/registry/ItemStackHolderInjector.java index 03caa0cd3..da24e6818 100644 --- a/src/main/java/net/minecraftforge/fml/common/registry/ItemStackHolderInjector.java +++ b/src/main/java/net/minecraftforge/fml/common/registry/ItemStackHolderInjector.java @@ -25,8 +25,6 @@ import java.util.Map; import java.util.Set; import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import com.google.common.collect.Lists; import com.google.common.collect.Maps; diff --git a/src/main/java/net/minecraftforge/fml/common/API.java b/src/main/java/net/minecraftforge/fml/common/thread/EffectiveSide.java similarity index 65% rename from src/main/java/net/minecraftforge/fml/common/API.java rename to src/main/java/net/minecraftforge/fml/common/thread/EffectiveSide.java index f403b0b2f..622f66153 100644 --- a/src/main/java/net/minecraftforge/fml/common/API.java +++ b/src/main/java/net/minecraftforge/fml/common/thread/EffectiveSide.java @@ -1,6 +1,6 @@ /* * Minecraft Forge - * Copyright (c) 2016-2018. + * Copyright (c) 2018. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -17,17 +17,14 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common; +package net.minecraftforge.fml.common.thread; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import net.minecraftforge.fml.LogicalSide; -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.PACKAGE) -public @interface API { - String owner(); - String provides(); - String apiVersion(); +public class EffectiveSide +{ + public static LogicalSide get() { + final ThreadGroup group = Thread.currentThread().getThreadGroup(); + return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : LogicalSide.CLIENT; + } } diff --git a/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroup.java b/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroup.java index 715513473..bdb0b9261 100644 --- a/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroup.java +++ b/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroup.java @@ -19,20 +19,20 @@ package net.minecraftforge.fml.common.thread; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.LogicalSide; import java.util.concurrent.ThreadFactory; import javax.annotation.Nonnull; /** - * A thread group and factory combination which belongs to a {@link Side}. + * A thread group and factory combination which belongs to a {@link LogicalSide}. */ public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory { - private final Side side; + private final LogicalSide side; - SidedThreadGroup(final Side side) + SidedThreadGroup(final LogicalSide side) { super(side.name()); this.side = side; @@ -43,7 +43,7 @@ public final class SidedThreadGroup extends ThreadGroup implements ThreadFactory * * @return the side */ - public Side getSide() + public LogicalSide getSide() { return this.side; } diff --git a/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroups.java b/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroups.java index 4f088f783..dae07381f 100644 --- a/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroups.java +++ b/src/main/java/net/minecraftforge/fml/common/thread/SidedThreadGroups.java @@ -19,12 +19,12 @@ package net.minecraftforge.fml.common.thread; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.LogicalSide; public final class SidedThreadGroups { - public static final SidedThreadGroup CLIENT = new SidedThreadGroup(Side.CLIENT); - public static final SidedThreadGroup SERVER = new SidedThreadGroup(Side.SERVER); + public static final SidedThreadGroup CLIENT = new SidedThreadGroup(LogicalSide.CLIENT); + public static final SidedThreadGroup SERVER = new SidedThreadGroup(LogicalSide.SERVER); private SidedThreadGroups() { } diff --git a/src/main/java/net/minecraftforge/fml/common/versioning/DependencyParser.java b/src/main/java/net/minecraftforge/fml/common/versioning/DependencyParser.java index 9deaf20ad..79fcfb098 100644 --- a/src/main/java/net/minecraftforge/fml/common/versioning/DependencyParser.java +++ b/src/main/java/net/minecraftforge/fml/common/versioning/DependencyParser.java @@ -31,7 +31,9 @@ import com.google.common.collect.ImmutableList; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.LoaderException; import net.minecraftforge.fml.javafmlmod.FMLModContainer; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public final class DependencyParser { @@ -188,15 +190,15 @@ public final class DependencyParser { if (Strings.isNullOrEmpty(depModId)) { - FMLLog.log.error(new DependencyParserException(modId, dep, "The modId is null or empty").getMessage()); + LOGGER.error(new DependencyParserException(modId, dep, "The modId is null or empty").getMessage()); } else if (depModId.length() > 64) { - FMLLog.log.error(new DependencyParserException(modId, dep, String.format("The modId '%s' is longer than the maximum of 64 characters.", depModId)).getMessage()); + LOGGER.error(new DependencyParserException(modId, dep, String.format("The modId '%s' is longer than the maximum of 64 characters.", depModId)).getMessage()); } else if (!depModId.equals(depModId.toLowerCase(Locale.ENGLISH))) { - FMLLog.log.error(new DependencyParserException(modId, dep, String.format("The modId '%s' must be all lowercase.", depModId)).getMessage()); + LOGGER.error(new DependencyParserException(modId, dep, String.format("The modId '%s' must be all lowercase.", depModId)).getMessage()); } } diff --git a/src/main/java/net/minecraftforge/fml/hooks/BasicEventHooks.java b/src/main/java/net/minecraftforge/fml/hooks/BasicEventHooks.java new file mode 100644 index 000000000..a8d38acd5 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/hooks/BasicEventHooks.java @@ -0,0 +1,131 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.hooks; + +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraftforge.client.model.animation.Animation; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.LogicalSide; +import net.minecraftforge.fml.common.gameevent.InputEvent; +import net.minecraftforge.fml.common.gameevent.PlayerEvent; +import net.minecraftforge.fml.common.gameevent.TickEvent; + +public class BasicEventHooks +{ + public static void fireMouseInput() + { + MinecraftForge.EVENT_BUS.post(new InputEvent.MouseInputEvent()); + } + + public static void fireKeyInput() + { + MinecraftForge.EVENT_BUS.post(new InputEvent.KeyInputEvent()); + } + + public static void firePlayerChangedDimensionEvent(EntityPlayer player, int fromDim, int toDim) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerChangedDimensionEvent(player, fromDim, toDim)); + } + + public static void firePlayerLoggedIn(EntityPlayer player) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedInEvent(player)); + } + + public static void firePlayerLoggedOut(EntityPlayer player) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerLoggedOutEvent(player)); + } + + public static void firePlayerRespawnEvent(EntityPlayer player, boolean endConquered) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.PlayerRespawnEvent(player, endConquered)); + } + + public static void firePlayerItemPickupEvent(EntityPlayer player, EntityItem item, ItemStack clone) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemPickupEvent(player, item, clone)); + } + + public static void firePlayerCraftingEvent(EntityPlayer player, ItemStack crafted, IInventory craftMatrix) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemCraftedEvent(player, crafted, craftMatrix)); + } + + public static void firePlayerSmeltedEvent(EntityPlayer player, ItemStack smelted) + { + MinecraftForge.EVENT_BUS.post(new PlayerEvent.ItemSmeltedEvent(player, smelted)); + } + + public static void onRenderTickStart(float timer) + { + Animation.setClientPartialTickTime(timer); + MinecraftForge.EVENT_BUS.post(new TickEvent.RenderTickEvent(TickEvent.Phase.START, timer)); + } + + public static void onRenderTickEnd(float timer) + { + MinecraftForge.EVENT_BUS.post(new TickEvent.RenderTickEvent(TickEvent.Phase.END, timer)); + } + + public static void onPlayerPreTick(EntityPlayer player) + { + MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.START, player)); + } + + public static void onPlayerPostTick(EntityPlayer player) + { + MinecraftForge.EVENT_BUS.post(new TickEvent.PlayerTickEvent(TickEvent.Phase.END, player)); + } + + public static void onPreWorldTick(World world) + { + MinecraftForge.EVENT_BUS.post(new TickEvent.WorldTickEvent(LogicalSide.SERVER, TickEvent.Phase.START, world)); + } + + public static void onPostWorldTick(World world) + { + MinecraftForge.EVENT_BUS.post(new TickEvent.WorldTickEvent(LogicalSide.SERVER, TickEvent.Phase.END, world)); + } + + public static void onPreClientTick() + { + MinecraftForge.EVENT_BUS.post(new TickEvent.ClientTickEvent(TickEvent.Phase.START)); + } + + public static void onPostClientTick() + { + MinecraftForge.EVENT_BUS.post(new TickEvent.ClientTickEvent(TickEvent.Phase.END)); + } + + public static void onPreServerTick() + { + MinecraftForge.EVENT_BUS.post(new TickEvent.ServerTickEvent(TickEvent.Phase.START)); + } + + public static void onPostServerTick() + { + MinecraftForge.EVENT_BUS.post(new TickEvent.ServerTickEvent(TickEvent.Phase.END)); + } +} diff --git a/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java b/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java index 38b789b7d..2763f6d06 100644 --- a/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java +++ b/src/main/java/net/minecraftforge/fml/javafmlmod/FMLJavaModLanguageProvider.java @@ -92,7 +92,7 @@ public class FMLJavaModLanguageProvider implements IModLanguageProvider return scanResult -> { final Map modTargetMap = scanResult.getAnnotations().stream() .filter(ad -> ad.getAnnotationType().equals(MODANNOTATION)) - .peek(ad -> fmlLog.debug(SCAN, "Found @Mod class {} with id {}", ad.getClassType().getClassName(), ad.getAnnotationData().get("modid"))) + .peek(ad -> fmlLog.debug(SCAN, "Found @Mod class {} with id {}", ad.getClassType().getClassName(), ad.getAnnotationData().get("value"))) .map(ad -> new FMLModTarget(ad.getClassType().getClassName(), (String)ad.getAnnotationData().get("value"))) .collect(Collectors.toMap(FMLModTarget::getModId, Function.identity())); scanResult.addLanguageLoader(modTargetMap); diff --git a/src/main/java/net/minecraftforge/fml/javafmlmod/FMLModContainer.java b/src/main/java/net/minecraftforge/fml/javafmlmod/FMLModContainer.java index 28098c574..bf4c1aefc 100644 --- a/src/main/java/net/minecraftforge/fml/javafmlmod/FMLModContainer.java +++ b/src/main/java/net/minecraftforge/fml/javafmlmod/FMLModContainer.java @@ -23,6 +23,7 @@ import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventListener; import net.minecraftforge.fml.LifecycleEventProvider; +import net.minecraftforge.fml.ModThreadContext; import net.minecraftforge.fml.common.event.ModLifecycleEvent; import net.minecraftforge.fml.AutomaticEventSubscriber; import net.minecraftforge.fml.ModLoadingStage; @@ -84,19 +85,21 @@ public class FMLModContainer extends ModContainer private void onEventFailed(IEventBus iEventBus, Event event, IEventListener[] iEventListeners, int i, Throwable throwable) { LOGGER.error(new EventBusErrorMessage(event, i, iEventListeners, throwable)); + modLoadingError.add(throwable); } private void beforeEvent(LifecycleEventProvider.LifecycleEvent lifecycleEvent) { - ModLoadingContext.get().activeContainer = this; + ModLoadingContext.get().setActiveContainer(this); + ModThreadContext.get().setActiveContainer(this); } private void fireEvent(LifecycleEventProvider.LifecycleEvent lifecycleEvent) { final ModLifecycleEvent event = lifecycleEvent.buildModEvent(this); - LOGGER.debug(LOADING, "Firing event {} for modid {}", event, this.getModId()); + LOGGER.debug(LOADING, "Firing event for modid {} : {} @ {}", this.getModId(), event, System.identityHashCode(event.getClass())); try { eventBus.post(event); - LOGGER.debug(LOADING, "Fired event {} for modid {}", event, this.getModId()); + LOGGER.debug(LOADING, "Fired event for modid {} : {}", this.getModId(), event); } catch (Throwable e) { @@ -107,7 +110,8 @@ public class FMLModContainer extends ModContainer } private void afterEvent(LifecycleEventProvider.LifecycleEvent lifecycleEvent) { - ModLoadingContext.get().activeContainer = null; + ModThreadContext.get().setActiveContainer(null); + ModLoadingContext.get().setActiveContainer(null); if (getCurrentState() == ModLoadingStage.ERROR) { LOGGER.error(LOADING,"An error occurred while dispatching event {} to {}", lifecycleEvent.fromStage(), getModId()); } diff --git a/src/main/java/net/minecraftforge/fml/javafmlmod/ModLoadingContext.java b/src/main/java/net/minecraftforge/fml/javafmlmod/ModLoadingContext.java index fc7bd98db..11a3a61a8 100644 --- a/src/main/java/net/minecraftforge/fml/javafmlmod/ModLoadingContext.java +++ b/src/main/java/net/minecraftforge/fml/javafmlmod/ModLoadingContext.java @@ -20,27 +20,34 @@ package net.minecraftforge.fml.javafmlmod; import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.fml.DeferredWorkQueue; import net.minecraftforge.fml.ExtensionPoint; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; import java.util.function.Supplier; public class ModLoadingContext { private static ThreadLocal context = ThreadLocal.withInitial(ModLoadingContext::new); - FMLModContainer activeContainer; + private FMLModContainer activeContainer; public static ModLoadingContext get() { return context.get(); } public void registerExtensionPoint(ExtensionPoint point, Supplier extension) { - activeContainer.registerExtensionPoint(point, extension); + getActiveContainer().registerExtensionPoint(point, extension); } public IEventBus getModEventBus() { - return activeContainer.getEventBus(); + return getActiveContainer().getEventBus(); + } + + public FMLModContainer getActiveContainer() + { + return activeContainer; + } + + public void setActiveContainer(FMLModContainer activeContainer) + { + this.activeContainer = activeContainer; } } diff --git a/src/main/java/net/minecraftforge/fml/language/IModInfo.java b/src/main/java/net/minecraftforge/fml/language/IModInfo.java index 2565a6310..17c2dbe2d 100644 --- a/src/main/java/net/minecraftforge/fml/language/IModInfo.java +++ b/src/main/java/net/minecraftforge/fml/language/IModInfo.java @@ -53,7 +53,7 @@ public interface IModInfo public boolean isCorrectSide() { - return this == BOTH || FMLEnvironment.side.name().equals(this.name()); + return this == BOTH || FMLEnvironment.dist.name().equals(this.name()); } } diff --git a/src/main/java/net/minecraftforge/fml/language/ModFileScanData.java b/src/main/java/net/minecraftforge/fml/language/ModFileScanData.java index b1b457853..b62eb555b 100644 --- a/src/main/java/net/minecraftforge/fml/language/ModFileScanData.java +++ b/src/main/java/net/minecraftforge/fml/language/ModFileScanData.java @@ -33,6 +33,7 @@ public class ModFileScanData private final List annotations = new ArrayList<>(); private final List classes = new ArrayList<>(); private Map modTargets; + private Map functionalScanners; public static Predicate interestingAnnotations() { return t->true; diff --git a/src/main/java/net/minecraftforge/fml/loading/DefaultModInfos.java b/src/main/java/net/minecraftforge/fml/loading/DefaultModInfos.java index 22595d68a..87c8e0bf6 100644 --- a/src/main/java/net/minecraftforge/fml/loading/DefaultModInfos.java +++ b/src/main/java/net/minecraftforge/fml/loading/DefaultModInfos.java @@ -50,7 +50,7 @@ public class DefaultModInfos } public static final IModInfo minecraftModInfo; - private static final IModInfo forgeModInfo; + public static final IModInfo forgeModInfo; // no construction private DefaultModInfos() {} diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLCommonLaunchHandler.java b/src/main/java/net/minecraftforge/fml/loading/FMLCommonLaunchHandler.java index a68350f31..1e2810846 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLCommonLaunchHandler.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLCommonLaunchHandler.java @@ -21,7 +21,7 @@ package net.minecraftforge.fml.loading; import cpw.mods.modlauncher.api.IEnvironment; import cpw.mods.modlauncher.api.ITransformingClassLoader; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; public abstract class FMLCommonLaunchHandler { @@ -30,7 +30,7 @@ public abstract class FMLCommonLaunchHandler // We need to check for deobf and patched jar here and if not, build one. } - public abstract Side getSidedness(); + public abstract Dist getDist(); protected void beforeStart(ITransformingClassLoader launchClassLoader) { diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLDevClientLaunchProvider.java b/src/main/java/net/minecraftforge/fml/loading/FMLDevClientLaunchProvider.java index 4701a9a98..7bb55eab4 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLDevClientLaunchProvider.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLDevClientLaunchProvider.java @@ -22,7 +22,7 @@ package net.minecraftforge.fml.loading; import cpw.mods.modlauncher.api.IEnvironment; import cpw.mods.modlauncher.api.ILaunchHandlerService; import cpw.mods.modlauncher.api.ITransformingClassLoader; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import java.lang.reflect.Field; import java.net.URISyntaxException; @@ -89,8 +89,8 @@ public class FMLDevClientLaunchProvider extends FMLCommonLaunchHandler implement } @Override - public Side getSidedness() + public Dist getDist() { - return Side.CLIENT; + return Dist.CLIENT; } } diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java b/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java index ff82b0547..7c30298ed 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLEnvironment.java @@ -19,10 +19,9 @@ package net.minecraftforge.fml.loading; -import net.minecraftforge.api.Side; -import net.minecraftforge.fml.loading.FMLLoader; +import net.minecraftforge.api.distmarker.Dist; public class FMLEnvironment { - public static final Side side = FMLLoader.getSide(); + public static final Dist dist = FMLLoader.getDist(); } diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLLaunchProvider.java b/src/main/java/net/minecraftforge/fml/loading/FMLLaunchProvider.java index 190c45d72..0b6ebfb47 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLLaunchProvider.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLLaunchProvider.java @@ -21,8 +21,7 @@ package net.minecraftforge.fml.loading; import cpw.mods.modlauncher.api.ILaunchHandlerService; import cpw.mods.modlauncher.api.ITransformingClassLoader; -import net.minecraft.client.main.Main; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import java.nio.file.Path; import java.util.concurrent.Callable; @@ -50,8 +49,8 @@ public class FMLLaunchProvider extends FMLCommonLaunchHandler implements ILaunch } @Override - public Side getSidedness() + public Dist getDist() { - return Side.CLIENT; + return Dist.CLIENT; } } diff --git a/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java b/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java index 4eda8152e..e821ad24d 100644 --- a/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java +++ b/src/main/java/net/minecraftforge/fml/loading/FMLLoader.java @@ -25,7 +25,7 @@ import cpw.mods.modlauncher.api.ITransformationService; import cpw.mods.modlauncher.api.ITransformingClassLoader; import cpw.mods.modlauncher.api.IncompatibleEnvironmentException; import cpw.mods.modlauncher.serviceapi.ILaunchPluginService; -import net.minecraftforge.api.Side; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.fml.loading.moddiscovery.BackgroundScanHandler; import net.minecraftforge.fml.loading.moddiscovery.ModDiscoverer; @@ -53,9 +53,10 @@ public class FMLLoader private static ICoreModProvider coreModProvider; private static ILaunchPluginService eventBus; private static LanguageLoadingProvider languageLoadingProvider; - private static Side side; + private static Dist dist; private static LoadingModList loadingModList; private static ClassLoader launchClassLoader; + private static RuntimeDistCleaner runtimeDistCleaner; static void onInitialLoad(IEnvironment environment, Set otherServices) throws IncompatibleEnvironmentException { @@ -88,6 +89,9 @@ public class FMLLoader throw new IncompatibleEnvironmentException("Incompatible eventbus found "+eventBusPackage.getSpecificationVersion()); } + runtimeDistCleaner = (RuntimeDistCleaner)environment.findLaunchPlugin("runtimedistcleaner").orElseThrow(()->new IncompatibleEnvironmentException("Missing RuntimeDistCleaner, cannot run!")); + fmlLog.debug(CORE, "Found Runtime Dist Cleaner"); + final ArrayList coreModProviders = new ArrayList<>(); ServiceLoader.load(ICoreModProvider.class).forEach(coreModProviders::add); @@ -123,7 +127,8 @@ public class FMLLoader FMLCommonLaunchHandler commonLaunchHandler = (FMLCommonLaunchHandler)launchHandler.get(); commonLaunchHandler.setup(environment); - side = commonLaunchHandler.getSidedness(); + dist = commonLaunchHandler.getDist(); + runtimeDistCleaner.getExtension().accept(dist); } public static void beginModScan() { @@ -166,9 +171,9 @@ public class FMLLoader accessTransformer.addResource(atPath, modName.getFileName()); } - public static Side getSide() + public static Dist getDist() { - return side; + return dist; } public static void beforeStart(ITransformingClassLoader launchClassLoader) diff --git a/src/main/java/net/minecraftforge/fml/common/asm/transformers/SideTransformer.java b/src/main/java/net/minecraftforge/fml/loading/RuntimeDistCleaner.java similarity index 50% rename from src/main/java/net/minecraftforge/fml/common/asm/transformers/SideTransformer.java rename to src/main/java/net/minecraftforge/fml/loading/RuntimeDistCleaner.java index b8483dbb6..a628123f7 100644 --- a/src/main/java/net/minecraftforge/fml/common/asm/transformers/SideTransformer.java +++ b/src/main/java/net/minecraftforge/fml/loading/RuntimeDistCleaner.java @@ -17,19 +17,23 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.asm.transformers; +package net.minecraftforge.fml.loading; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.ListIterator; +import java.util.Objects; +import java.util.function.Consumer; -import net.minecraft.launchwrapper.IClassTransformer; -import net.minecraftforge.fml.relauncher.FMLLaunchHandler; -import net.minecraftforge.fml.relauncher.SideOnly; - -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassWriter; +import com.google.common.collect.Streams; +import cpw.mods.modlauncher.serviceapi.ILaunchPluginService; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; @@ -40,38 +44,40 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; -public class SideTransformer implements IClassTransformer +public class RuntimeDistCleaner implements ILaunchPluginService { - private static String SIDE = FMLLaunchHandler.side().name(); - private static final boolean DEBUG = false; + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker DISTXFORM = MarkerManager.getMarker("DISTXFORM"); + private static String DIST; + private static final String ONLYIN = Type.getDescriptor(OnlyIn.class); @Override - public byte[] transform(String name, String transformedName, byte[] bytes) + public String name() { - if (bytes == null) { return null; } + return "runtimedistcleaner"; + } - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); + @Override + public void addResource(Path resource, String name) + { - if (remove(classNode.visibleAnnotations, SIDE)) + } + + @Override + public ClassNode processClass(ClassNode classNode, Type classType) + { + if (remove(classNode.visibleAnnotations, DIST)) { - if (DEBUG) - { - System.out.println(String.format("Attempted to load class %s for invalid side %s", classNode.name, SIDE)); - } - throw new RuntimeException(String.format("Attempted to load class %s for invalid side %s", classNode.name, SIDE)); + LOGGER.debug(DISTXFORM, "Attempted to load class {} for invalid dist {}", classNode.name, DIST); + throw new RuntimeException("Attempted to load class "+ classNode.name + " for invalid dist "+ DIST); } Iterator fields = classNode.fields.iterator(); while(fields.hasNext()) { FieldNode field = fields.next(); - if (remove(field.visibleAnnotations, SIDE)) + if (remove(field.visibleAnnotations, DIST)) { - if (DEBUG) - { - System.out.println(String.format("Removing Field: %s.%s", classNode.name, field.name)); - } + LOGGER.debug(DISTXFORM,"Removing field: {}.{}", classNode.name, field.name); fields.remove(); } } @@ -81,12 +87,9 @@ public class SideTransformer implements IClassTransformer while(methods.hasNext()) { MethodNode method = methods.next(); - if (remove(method.visibleAnnotations, SIDE)) + if (remove(method.visibleAnnotations, DIST)) { - if (DEBUG) - { - System.out.println(String.format("Removing Method: %s.%s%s", classNode.name, method.name, method.desc)); - } + LOGGER.debug(DISTXFORM,"Removing method: {}.{}{}", classNode.name, method.name, method.desc); methods.remove(); lambdaGatherer.accept(method); } @@ -104,74 +107,53 @@ public class SideTransformer implements IClassTransformer { if (method.name.equals(dynamicLambdaHandle.getName()) && method.desc.equals(dynamicLambdaHandle.getDesc())) { - if (DEBUG) - { - System.out.println(String.format("Removing Method: %s.%s%s", classNode.name, method.name, method.desc)); - } + LOGGER.debug(DISTXFORM,"Removing lambda method: {}.{}{}", classNode.name, method.name, method.desc); methods.remove(); } } } } - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - return writer.toByteArray(); + return classNode; } - private boolean remove(List anns, String side) + private boolean remove(final List anns, final String side) { - if (anns == null) - { - return false; - } - for (AnnotationNode ann : anns) - { - if (ann.desc.equals(Type.getDescriptor(SideOnly.class))) - { - if (ann.values != null) - { - for (int x = 0; x < ann.values.size() - 1; x += 2) - { - Object key = ann.values.get(x); - Object value = ann.values.get(x+1); - if (key instanceof String && key.equals("value")) - { - if (value instanceof String[] ) - { - if (!((String[])value)[1].equals(side)) - { - return true; - } - } - } - } - } - } - } - return false; + return !(anns == null) && anns.stream(). + filter(ann->Objects.equals(ann.desc, ONLYIN)). + anyMatch(ann -> !Objects.equals(((String[])ann.values.get(ann.values.indexOf("value")+1))[1], side)); + } + + @SuppressWarnings("unchecked") + @Override + public Consumer getExtension() + { + return (s)-> { + DIST = s.name(); + LOGGER.debug(DISTXFORM, "Configuring for Dist {}", DIST); + }; + } + + @Override + public boolean handlesClass(Type classType, boolean isEmpty) + { + return !isEmpty; } private static class LambdaGatherer extends MethodVisitor { - private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", + private static final Handle META_FACTORY = new Handle(Opcodes.H_INVOKESTATIC, + "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;", false); - private final List dynamicLambdaHandles = new ArrayList(); + private final List dynamicLambdaHandles = new ArrayList<>(); public LambdaGatherer() { super(Opcodes.ASM5); } public void accept(MethodNode method) { - ListIterator insnNodeIterator = method.instructions.iterator(); - while (insnNodeIterator.hasNext()) - { - AbstractInsnNode insnNode = insnNodeIterator.next(); - if (insnNode.getType() == AbstractInsnNode.INVOKE_DYNAMIC_INSN) - { - insnNode.accept(this); - } - } + Streams.stream(method.instructions.iterator()). + filter(insnNode->insnNode.getType() == AbstractInsnNode.INVOKE_DYNAMIC_INSN). + forEach(insnNode->insnNode.accept(this)); } @Override diff --git a/src/main/java/net/minecraftforge/fml/common/discovery/ITypeDiscoverer.java b/src/main/java/net/minecraftforge/fml/loading/moddiscovery/IScanPlugin.java similarity index 59% rename from src/main/java/net/minecraftforge/fml/common/discovery/ITypeDiscoverer.java rename to src/main/java/net/minecraftforge/fml/loading/moddiscovery/IScanPlugin.java index 54dabdd48..51efce0f4 100644 --- a/src/main/java/net/minecraftforge/fml/common/discovery/ITypeDiscoverer.java +++ b/src/main/java/net/minecraftforge/fml/loading/moddiscovery/IScanPlugin.java @@ -1,6 +1,6 @@ /* * Minecraft Forge - * Copyright (c) 2016-2018. + * Copyright (c) 2018. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -17,17 +17,9 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common.discovery; +package net.minecraftforge.fml.loading.moddiscovery; -import java.util.List; -import java.util.regex.Pattern; - -import net.minecraftforge.fml.ModContainer; - -public interface ITypeDiscoverer +public interface IScanPlugin { - // main class part, followed by an optional $ and an "inner class" part. $ cannot be last, otherwise scala breaks - public static Pattern classFile = Pattern.compile("[^\\s\\$]+(\\$[^\\s]+)?\\.class$"); - - List discover(ModCandidate candidate, ASMDataTable table); + public } diff --git a/src/main/java/net/minecraftforge/fml/network/ConnectionType.java b/src/main/java/net/minecraftforge/fml/network/ConnectionType.java new file mode 100644 index 000000000..e5394af89 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/network/ConnectionType.java @@ -0,0 +1,25 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.network; + +public enum ConnectionType +{ + MODDED, BUKKIT, VANILLA +} diff --git a/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java b/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java new file mode 100644 index 000000000..0d7529da4 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/network/NetworkHooks.java @@ -0,0 +1,59 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.network; + +import net.minecraft.entity.Entity; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.network.Packet; +import net.minecraft.network.handshake.client.C00Handshake; +import net.minecraftforge.fml.common.network.internal.FMLMessage; +import net.minecraftforge.fml.common.registry.EntityRegistry; + +import java.util.Objects; + +public class NetworkHooks +{ + public static final String NETVERSION = "FML1"; + public static final String NOVERSION = "NONE"; + public static String getFMLVersion(final String ip) + { + return ip.contains("\0") ? Objects.equals(ip.split("\0")[1], NETVERSION) ? NETVERSION : ip.split("\0")[1] : NOVERSION; + } + + public static boolean accepts(final C00Handshake packet) + { + return Objects.equals(packet.getFMLVersion(), NETVERSION); + } + + public static ConnectionType getConnectionType(final NetHandlerPlayServer connection) + { + return ConnectionType.MODDED; + } + + public static Packet getEntitySpawningPacket(Entity entity) + { + EntityRegistry.EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entity.getClass(), false); + if (er == null || er.usesVanillaSpawning()) + { + return null; + } + return null; + } +} diff --git a/src/main/java/net/minecraftforge/fml/common/WorldAccessContainer.java b/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java similarity index 68% rename from src/main/java/net/minecraftforge/fml/common/WorldAccessContainer.java rename to src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java index 8b80b4785..a65152d8f 100644 --- a/src/main/java/net/minecraftforge/fml/common/WorldAccessContainer.java +++ b/src/main/java/net/minecraftforge/fml/network/NetworkRegistry.java @@ -17,16 +17,17 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -package net.minecraftforge.fml.common; +package net.minecraftforge.fml.network; -import java.util.Map; +import java.util.Collections; +import java.util.List; -import net.minecraft.nbt.*; -import net.minecraft.world.storage.*; - - -public interface WorldAccessContainer +public class NetworkRegistry { - NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info); - void readData(SaveHandler handler, WorldInfo info, Map propertyMap, NBTTagCompound tag); + public static final NetworkRegistry INSTANCE = new NetworkRegistry(); + + public static List getNonVanillaNetworkMods() + { + return Collections.emptyList(); + } } diff --git a/src/main/java/net/minecraftforge/fml/network/Networking.java b/src/main/java/net/minecraftforge/fml/network/Networking.java new file mode 100644 index 000000000..54d67df37 --- /dev/null +++ b/src/main/java/net/minecraftforge/fml/network/Networking.java @@ -0,0 +1,25 @@ +/* + * Minecraft Forge + * Copyright (c) 2018. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation version 2.1 + * of the License. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +package net.minecraftforge.fml.network; + +public class Networking +{ + public enum Type { SIMPLE, EVENT, NONE } +} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java deleted file mode 100644 index 55110c66e..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ /dev/null @@ -1,688 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.io.Closeable; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.ToIntFunction; -import java.util.jar.Attributes; -import java.util.jar.JarFile; -import java.util.jar.Manifest; - -import net.minecraft.launchwrapper.ITweaker; -import net.minecraft.launchwrapper.Launch; -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.common.CertificateHelper; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.asm.ASMTransformerWrapper; -import net.minecraftforge.fml.common.asm.transformers.ModAccessTransformer; -import net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker; -import net.minecraftforge.fml.common.launcher.FMLTweaker; -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.DependsOn; -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.MCVersion; -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.Name; -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.SortingIndex; -import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions; -import net.minecraftforge.fml.relauncher.libraries.Artifact; -import net.minecraftforge.fml.relauncher.libraries.LibraryManager; -import net.minecraftforge.fml.relauncher.libraries.Repository; - -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.ObjectArrays; -import com.google.common.collect.Sets; -import com.google.common.primitives.Ints; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; - -public class CoreModManager { - private static final Attributes.Name COREMODCONTAINSFMLMOD = new Attributes.Name("FMLCorePluginContainsFMLMod"); - private static final Attributes.Name MODTYPE = new Attributes.Name("ModType"); - private static String[] rootPlugins = { "net.minecraftforge.fml.relauncher.FMLCorePlugin", "net.minecraftforge.classloading.FMLForgePlugin" }; - private static List ignoredModFiles = Lists.newArrayList(); - private static Map> transformers = Maps.newHashMap(); - private static List loadPlugins; - private static boolean deobfuscatedEnvironment; - private static FMLTweaker tweaker; - private static File mcDir; - private static List candidateModFiles = Lists.newArrayList(); - private static List accessTransformers = Lists.newArrayList(); - private static Set rootNames = Sets.newHashSet(); - - static - { - for(String cls : rootPlugins) - { - rootNames.add(cls.substring(cls.lastIndexOf('.') + 1)); - } - } - - private static class FMLPluginWrapper implements ITweaker { - public final String name; - public final IFMLLoadingPlugin coreModInstance; - public final List predepends; - public final File location; - public final int sortIndex; - - public FMLPluginWrapper(String name, IFMLLoadingPlugin coreModInstance, File location, int sortIndex, String... predepends) - { - super(); - this.name = name; - this.coreModInstance = coreModInstance; - this.location = location; - this.sortIndex = sortIndex; - this.predepends = Lists.newArrayList(predepends); - } - - @Override - public String toString() - { - return String.format("%s {%s}", this.name, this.predepends); - } - - @Override - public void acceptOptions(List args, File gameDir, File assetsDir, String profile) - { - // NO OP - } - - @Override - public void injectIntoClassLoader(LaunchClassLoader classLoader) - { - FMLLog.log.debug("Injecting coremod {} \\{{}\\} class transformers", name, coreModInstance.getClass().getName()); - List ts = Lists.newArrayList(); - if (coreModInstance.getASMTransformerClass() != null) for (String transformer : coreModInstance.getASMTransformerClass()) - { - FMLLog.log.trace("Registering transformer {}", transformer); - classLoader.registerTransformer(ASMTransformerWrapper.getTransformerWrapper(classLoader, transformer, name)); - ts.add(transformer); - } - if(!rootNames.contains(name)) - { - String loc; - if(location == null) loc = "unknown"; - else loc = location.getName(); - transformers.put(name + " (" + loc + ")", ts); - } - FMLLog.log.debug("Injection complete"); - - FMLLog.log.debug("Running coremod plugin for {} \\{{}\\}", name, coreModInstance.getClass().getName()); - Map data = new HashMap(); - data.put("mcLocation", mcDir); - data.put("coremodList", loadPlugins); - data.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); - FMLLog.log.debug("Running coremod plugin {}", name); - data.put("coremodLocation", location); - coreModInstance.injectData(data); - String setupClass = coreModInstance.getSetupClass(); - if (setupClass != null) - { - try - { - IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader).newInstance(); - Map callData = new HashMap(); - callData.put("runtimeDeobfuscationEnabled", !deobfuscatedEnvironment); - callData.put("mcLocation", mcDir); - callData.put("classLoader", classLoader); - callData.put("coremodLocation", location); - callData.put("deobfuscationFileName", FMLInjectionData.debfuscationDataName()); - call.injectData(callData); - call.call(); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } - FMLLog.log.debug("Coremod plugin class {} run successfully", coreModInstance.getClass().getSimpleName()); - - String modContainer = coreModInstance.getModContainerClass(); - if (modContainer != null) - { - FMLInjectionData.containers.add(modContainer); - } - } - - @Override - public String getLaunchTarget() - { - return ""; - } - - @Override - public String[] getLaunchArguments() - { - return new String[0]; - } - - } - - public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker) - { - CoreModManager.mcDir = mcDir; - CoreModManager.tweaker = tweaker; - - //TODO: Detect this better? Support install time deobfusication? Decouple deobf from dev? Add dev flag in GradleStart? - try - { - // Are we in a 'decompiled' environment? - byte[] bs = classLoader.getClassBytes("net.minecraft.world.World"); - if (bs != null) - { - FMLLog.log.info("Managed to load a deobfuscated Minecraft name- we are in a deobfuscated environment. Skipping runtime deobfuscation"); - deobfuscatedEnvironment = true; - } - } - catch (IOException e1) - { - // NOOP - } - - if (!deobfuscatedEnvironment) - { - FMLLog.log.debug("Enabling runtime deobfuscation"); - } - else - { - if (System.getProperty("log4j.configurationFile") == null) - { - FMLLog.log.info("Detected deobfuscated environment, loading log configs for colored console logs."); - // use server logging configs in deobfuscated environment so developers get nicely colored console logs - System.setProperty("log4j.configurationFile", "log4j2_server.xml"); - ((LoggerContext) LogManager.getContext(false)).reconfigure(); - } - } - - tweaker.injectCascadingTweak("net.minecraftforge.fml.common.launcher.FMLInjectionAndSortingTweaker"); - try - { - classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.PatchingTransformer"); - } - catch (Exception e) - { - throw new RuntimeException("The patch transformer failed to load! This is critical, loading cannot continue!", e); - } - - loadPlugins = new ArrayList(); - for (String rootPluginName : rootPlugins) - { - loadCoreMod(classLoader, rootPluginName, new File(FMLTweaker.getJarLocation())); - } - - if (loadPlugins.isEmpty()) - { - throw new RuntimeException("A fatal error has occurred - no valid fml load plugin was found - this is a completely corrupt FML installation."); - } - - FMLLog.log.debug("All fundamental core mods are successfully located"); - // Now that we have the root plugins loaded - lets see what else might - // be around - String commandLineCoremods = System.getProperty("fml.coreMods.load", ""); - for (String coreModClassName : commandLineCoremods.split(",")) - { - if (coreModClassName.isEmpty()) - { - continue; - } - FMLLog.log.info("Found a command line coremod : {}", coreModClassName); - loadCoreMod(classLoader, coreModClassName, null); - } - discoverCoreMods(mcDir, classLoader); - - } - - private static void findDerpMods(LaunchClassLoader classLoader, File modDir, File modDirVer) - { - File[] derplist = listFiles(path -> path.getName().endsWith(".jar.zip"), modDir, modDirVer); - if (derplist != null && derplist.length > 0) - { - FMLLog.log.fatal("FML has detected several badly downloaded jar files, which have been named as zip files. You probably need to download them again, or they may not work properly"); - for (File f : derplist) - FMLLog.log.fatal("Problem file : {}", f.getName()); - } - - FileFilter derpdirfilter = pathname -> pathname.isDirectory() && new File(pathname,"META-INF").isDirectory(); - File[] derpdirlist = listFiles(derpdirfilter, modDir, modDirVer); - if (derpdirlist != null && derpdirlist.length > 0) - { - FMLLog.log.fatal("There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL"); - FMLLog.log.fatal("You should place original jars only in the mods directory. NEVER extract them to the mods directory."); - FMLLog.log.fatal("The directories below appear to be extracted jar files. Fix this before you continue."); - - for (File f : derpdirlist) - { - FMLLog.log.fatal("Directory {} contains {}", f.getName(), Arrays.asList(new File(f,"META-INF").list())); - } - - RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue"); - // We're generating a crash report for the launcher to show to the user here - // Does this actually work with the obfed names? - try - { - Class crashreportclass = classLoader.loadClass("b"); - Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re, "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided."); - File crashreportfile = new File(new File(modDir.getParentFile(),"crash-reports"),String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tH.%1$tM.%1$tS.txt",Calendar.getInstance())); - crashreportclass.getMethod("a",File.class).invoke(crashreport, crashreportfile); - FMLLog.log.fatal("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# {}", crashreportfile.getAbsolutePath()); - } catch (Exception e) - { - FMLLog.log.fatal("#@!@# FML has crashed while generating a crash report, please report this. #@!@#", e); - // NOOP - hopefully - } - throw re; - } - } - - private static File[] listFiles(FileFilter filter, File ... dirs) - { - File[] ret = null; - for (File dir : dirs) - { - if (!dir.isDirectory() || !dir.exists()) - continue; - if (ret == null) - ret = dir.listFiles(filter); - else - ret = ObjectArrays.concat(ret, dir.listFiles(filter), File.class); - } - return ret == null ? new File[0] : ret; - } - - private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) - { - - File modsDir = setupCoreModDir(mcDir); - File modsDirVer = new File(modsDir, FMLInjectionData.mccversion); - - findDerpMods(classLoader, modsDir, modsDirVer); - - //By the time we get here, all bundeled jars should be extracted to the proper repos. - //As well as the mods folders being cleaned up {any files that have maven info being moved to maven folder} - - FMLLog.log.debug("Discovering coremods"); - List maven_canidates = LibraryManager.flattenLists(mcDir); - List file_canidates = LibraryManager.gatherLegacyCanidates(mcDir); - - for (Artifact artifact : maven_canidates) - { - artifact = Repository.resolveAll(artifact); - if (artifact != null) - { - File target = artifact.getFile(); - if (!file_canidates.contains(target)) - file_canidates.add(target); - } - } - //Do we want to sort the full list after resolving artifacts? - //TODO: Add dependency gathering? - - for (File coreMod : file_canidates) - { - FMLLog.log.debug("Examining for coremod candidacy {}", coreMod.getName()); - JarFile jar = null; - Attributes mfAttributes; - String fmlCorePlugin; - try - { - File manifest = new File(coreMod.getAbsolutePath() + ".meta"); - - if (LibraryManager.DISABLE_EXTERNAL_MANIFEST || !manifest.exists()) - { - jar = new JarFile(coreMod); - mfAttributes = jar.getManifest() == null ? null : jar.getManifest().getMainAttributes(); - } - else - { - FileInputStream fis = new FileInputStream(manifest); - mfAttributes = new Manifest(fis).getMainAttributes(); - fis.close(); - } - - if (mfAttributes == null) // Not a coremod and no access transformer list - continue; - - String modSide = mfAttributes.getValue(LibraryManager.MODSIDE); - if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide)) - { - FMLLog.log.debug("Mod {} has ModSide meta-inf value {}, and we're {} It will be ignored", coreMod.getName(), modSide, FMLLaunchHandler.side.name()); - ignoredModFiles.add(coreMod.getName()); - continue; - } - - String ats = mfAttributes.getValue(ModAccessTransformer.FMLAT); - if (ats != null && !ats.isEmpty()) - { - if (jar == null) //We could of loaded the external manifest earlier, if so the jar isn't loaded. - jar = new JarFile(coreMod); - ModAccessTransformer.addJar(jar, ats); - } - - String cascadedTweaker = mfAttributes.getValue("TweakClass"); - if (cascadedTweaker != null) - { - FMLLog.log.info("Loading tweaker {} from {}", cascadedTweaker, coreMod.getName()); - Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder"))); - sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder); - handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder); - ignoredModFiles.add(coreMod.getName()); - continue; - } - List modTypes = mfAttributes.containsKey(MODTYPE) ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(",")) : ImmutableList.of("FML"); - - if (!modTypes.contains("FML")) - { - FMLLog.log.debug("Adding {} to the list of things to skip. It is not an FML mod, it has types {}", coreMod.getName(), modTypes); - ignoredModFiles.add(coreMod.getName()); - continue; - } - fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin"); - if (fmlCorePlugin == null) - { - // Not a coremod - FMLLog.log.debug("Not found coremod data in {}", coreMod.getName()); - continue; - } - } - catch (IOException ioe) - { - FMLLog.log.error("Unable to read the jar file {} - ignoring", coreMod.getName(), ioe); - continue; - } - finally - { - closeQuietly(jar); - } - // Support things that are mod jars, but not FML mod jars - try - { - classLoader.addURL(coreMod.toURI().toURL()); - if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) - { - FMLLog.log.trace("Adding {} to the list of known coremods, it will not be examined again", coreMod.getName()); - ignoredModFiles.add(coreMod.getName()); - } - else - { - FMLLog.log.warn("Found FMLCorePluginContainsFMLMod marker in {}. This is not recommended, @Mods should be in a separate jar from the coremod.", - coreMod.getName()); - candidateModFiles.add(coreMod.getName()); - } - } - catch (MalformedURLException e) - { - FMLLog.log.error("Unable to convert file into a URL. weird", e); - continue; - } - loadCoreMod(classLoader, fmlCorePlugin, coreMod); - } - } - - private static Method ADDURL; - - private static void handleCascadingTweak(File coreMod, JarFile jar, String cascadedTweaker, LaunchClassLoader classLoader, Integer sortingOrder) - { - try - { - // Have to manually stuff the tweaker into the parent classloader - if (ADDURL == null) - { - ADDURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - ADDURL.setAccessible(true); - } - ADDURL.invoke(classLoader.getClass().getClassLoader(), coreMod.toURI().toURL()); - classLoader.addURL(coreMod.toURI().toURL()); - CoreModManager.tweaker.injectCascadingTweak(cascadedTweaker); - tweakSorting.put(cascadedTweaker,sortingOrder); - } - catch (Exception e) - { - FMLLog.log.info("There was a problem trying to load the mod dir tweaker {}", coreMod.getAbsolutePath(), e); - } - } - - /** - * @param mcDir - * the minecraft home directory - * @return the coremod directory - */ - private static File setupCoreModDir(File mcDir) - { - File coreModDir = new File(mcDir, "mods"); - try - { - coreModDir = coreModDir.getCanonicalFile(); - } - catch (IOException e) - { - throw new RuntimeException(String.format("Unable to canonicalize the coremod dir at %s", mcDir.getName()), e); - } - if (!coreModDir.exists()) - { - coreModDir.mkdir(); - } - else if (coreModDir.exists() && !coreModDir.isDirectory()) - { - throw new RuntimeException(String.format("Found a coremod file in %s that's not a directory", mcDir.getName())); - } - return coreModDir; - } - - public static List getIgnoredMods() - { - return ignoredModFiles; - } - - public static Map> getTransformers() - { - return transformers; - } - - public static List getReparseableCoremods() - { - return candidateModFiles; - } - - private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) - { - String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1); - try - { - FMLLog.log.debug("Instantiating coremod class {}", coreModName); - classLoader.addTransformerExclusion(coreModClass); - Class coreModClazz = Class.forName(coreModClass, true, classLoader); - Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class); - if (coreModNameAnn != null && !Strings.isNullOrEmpty(coreModNameAnn.value())) - { - coreModName = coreModNameAnn.value(); - FMLLog.log.trace("coremod named {} is loading", coreModName); - } - MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class); - if (!Arrays.asList(rootPlugins).contains(coreModClass) && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value()))) - { - FMLLog.log.warn("The coremod {} does not have a MCVersion annotation, it may cause issues with this version of Minecraft", - coreModClass); - } - else if (requiredMCVersion != null && !FMLInjectionData.mccversion.equals(requiredMCVersion.value())) - { - FMLLog.log.error("The coremod {} is requesting minecraft version {} and minecraft is {}. It will be ignored.", coreModClass, - requiredMCVersion.value(), FMLInjectionData.mccversion); - return null; - } - else if (requiredMCVersion != null) - { - FMLLog.log.debug("The coremod {} requested minecraft version {} and minecraft is {}. It will be loaded.", coreModClass, - requiredMCVersion.value(), FMLInjectionData.mccversion); - } - TransformerExclusions trExclusions = coreModClazz.getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class); - if (trExclusions != null) - { - for (String st : trExclusions.value()) - { - classLoader.addTransformerExclusion(st); - } - } - DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class); - String[] dependencies = new String[0]; - if (deplist != null) - { - dependencies = deplist.value(); - } - SortingIndex index = coreModClazz.getAnnotation(IFMLLoadingPlugin.SortingIndex.class); - int sortIndex = index != null ? index.value() : 0; - - Certificate[] certificates = coreModClazz.getProtectionDomain().getCodeSource().getCertificates(); - ImmutableList certList = CertificateHelper.getFingerprints(certificates); - if (certList.isEmpty()) - { - if (deobfuscatedEnvironment && Arrays.asList(rootPlugins).contains(coreModClass)) //This is probably a forge/mod dev environment - ignore missing forge certificates - { - FMLLog.log.info("Ignoring missing certificate for coremod {} ({}), we are in deobf and it's a forge core plugin", coreModName, coreModClass); - } - else if (deobfuscatedEnvironment && location == null) // This is probably a mod dev workspace - { - FMLLog.log.info("Ignoring missing certificate for coremod {} ({}), as this is probably a dev workspace", coreModName, coreModClass); - } - else // This is a probably a normal minecraft workspace - log at warn - { - FMLLog.log.warn("The coremod {} ({}) is not signed!", coreModName, coreModClass); - } - } - else - { - FMLLog.log.debug("Found signing certificates for coremod {} ({})", coreModName, coreModClass); - for (String cert : certList) - { - FMLLog.log.debug("Found certificate {}", cert); - } - } - - IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance(); - String accessTransformerClass = plugin.getAccessTransformerClass(); - if (accessTransformerClass != null) - { - FMLLog.log.debug("Added access transformer class {} to enqueued access transformers", accessTransformerClass); - accessTransformers.add(accessTransformerClass); - } - FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, sortIndex, dependencies); - loadPlugins.add(wrap); - FMLLog.log.debug("Enqueued coremod {}", coreModName); - return wrap; - } - catch (ClassNotFoundException cnfe) - { - if (!Lists.newArrayList(rootPlugins).contains(coreModClass)) - FMLLog.log.error("Coremod {}: Unable to class load the plugin {}", coreModClass, cnfe); - else - FMLLog.log.debug("Skipping root plugin {}", coreModClass); - } - catch (ClassCastException cce) - { - FMLLog.log.error("Coremod {}: The plugin {} is not an implementor of IFMLLoadingPlugin", coreModClass, cce); - } - catch (InstantiationException ie) - { - FMLLog.log.error("Coremod {}: The plugin class {} was not instantiable", coreModClass, ie); - } - catch (IllegalAccessException iae) - { - FMLLog.log.error("Coremod {}: The plugin class {} was not accessible", coreModClass, iae); - } - return null; - } - - public static void injectTransformers(LaunchClassLoader classLoader) - { - - Launch.blackboard.put("fml.deobfuscatedEnvironment", deobfuscatedEnvironment); - tweaker.injectCascadingTweak("net.minecraftforge.fml.common.launcher.FMLDeobfTweaker"); - tweakSorting.put("net.minecraftforge.fml.common.launcher.FMLDeobfTweaker", 1000); - } - - public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectionAndSortingTweaker) - { - @SuppressWarnings("unchecked") - List tweakers = (List) Launch.blackboard.get("Tweaks"); - // Add the sorting tweaker first- it'll appear twice in the list - tweakers.add(0, fmlInjectionAndSortingTweaker); - for (FMLPluginWrapper wrapper : loadPlugins) - { - tweakers.add(wrapper); - } - } - - private static Map tweakSorting = Maps.newHashMap(); - - public static void sortTweakList() - { - @SuppressWarnings("unchecked") - List tweakers = (List) Launch.blackboard.get("Tweaks"); - // Basically a copy of Collections.sort pre 8u20, optimized as we know we're an array list. - // Thanks unhelpful fixer of http://bugs.java.com/view_bug.do?bug_id=8032636 - ITweaker[] toSort = tweakers.toArray(new ITweaker[tweakers.size()]); - ToIntFunction getOrder = o -> o instanceof FMLInjectionAndSortingTweaker ? Integer.MIN_VALUE : o instanceof FMLPluginWrapper ? ((FMLPluginWrapper)o).sortIndex : tweakSorting.getOrDefault(o.getClass().getName(), 0); - Arrays.sort(toSort, (o1, o2) -> Ints.saturatedCast((long)getOrder.applyAsInt(o1) - (long)getOrder.applyAsInt(o2))); - for (int j = 0; j < toSort.length; j++) { - tweakers.set(j, toSort[j]); - } - } - - public static List getAccessTransformers() - { - return accessTransformers; - } - - public static void onCrash(StringBuilder builder) - { - if(!ignoredModFiles.isEmpty() || !candidateModFiles.isEmpty()) - { - builder.append("\nWARNING: coremods are present:\n"); - for(String coreMod : transformers.keySet()) - { - builder.append(" ").append(coreMod).append('\n'); - } - builder.append("Contact their authors BEFORE contacting forge\n\n"); - } - } - - private static void closeQuietly(Closeable closeable) { - try { - if (closeable != null) - closeable.close(); - } catch (final IOException ioe){} - } - -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/FMLCorePlugin.java b/src/main/java/net/minecraftforge/fml/relauncher/FMLCorePlugin.java deleted file mode 100644 index aea4b6a4c..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/FMLCorePlugin.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.util.Map; - -public class FMLCorePlugin implements IFMLLoadingPlugin -{ - @Override - public String[] getASMTransformerClass() - { - return new String[] { - "net.minecraftforge.fml.common.asm.transformers.SideTransformer", - "net.minecraftforge.fml.common.asm.transformers.EventSubscriptionTransformer", - "net.minecraftforge.fml.common.asm.transformers.EventSubscriberTransformer", - "net.minecraftforge.fml.common.asm.transformers.SoundEngineFixTransformer" - }; - } - - @Override - public String getAccessTransformerClass() - { - return "net.minecraftforge.fml.common.asm.transformers.AccessTransformer"; - } - @Override - public String getModContainerClass() - { - return "net.minecraftforge.fml.common.FMLContainer"; - } - - @Override - public String getSetupClass() - { - return "net.minecraftforge.fml.common.asm.FMLSanityChecker"; - } - - @Override - public void injectData(Map data) - { - // don't care about this data - } -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/FMLInjectionData.java b/src/main/java/net/minecraftforge/fml/relauncher/FMLInjectionData.java deleted file mode 100644 index 81ea3d96f..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/FMLInjectionData.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.common.ForgeVersion; - -public class FMLInjectionData -{ - static File minecraftHome; - static String major; - static String minor; - static String rev; - static String build; - static String mccversion; - static String mcpversion; - - public static final List containers = new ArrayList(); - - static void build(File mcHome, LaunchClassLoader classLoader) - { - minecraftHome = mcHome; - major = String.valueOf(ForgeVersion.majorVersion); - minor = String.valueOf(ForgeVersion.minorVersion); - rev = String.valueOf(ForgeVersion.revisionVersion); - build = String.valueOf(ForgeVersion.buildVersion); - mccversion = ForgeVersion.mcVersion; - mcpversion = ForgeVersion.mcpVersion; - } - - static String debfuscationDataName() - { - return "/deobfuscation_data-"+mccversion+".lzma"; - } - public static Object[] data() - { - return new Object[] { major, minor, rev, build, mccversion, mcpversion, minecraftHome, containers }; - } -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java b/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java deleted file mode 100644 index ea5be70a9..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/FMLLaunchHandler.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.io.File; - -import net.minecraft.launchwrapper.LaunchClassLoader; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.TracingPrintStream; -import net.minecraftforge.fml.common.launcher.FMLTweaker; -import net.minecraftforge.fml.relauncher.libraries.LibraryManager; - -import org.apache.logging.log4j.LogManager; - -public class FMLLaunchHandler -{ - private static FMLLaunchHandler INSTANCE; - static Side side; - private LaunchClassLoader classLoader; - private FMLTweaker tweaker; - private File minecraftHome; - - public static void configureForClientLaunch(LaunchClassLoader loader, FMLTweaker tweaker) - { - instance(loader, tweaker).setupClient(); - } - - public static void configureForServerLaunch(LaunchClassLoader loader, FMLTweaker tweaker) - { - instance(loader, tweaker).setupServer(); - } - - private static FMLLaunchHandler instance(LaunchClassLoader launchLoader, FMLTweaker tweaker) - { - if (INSTANCE == null) - { - INSTANCE = new FMLLaunchHandler(launchLoader, tweaker); - } - return INSTANCE; - - } - - private FMLLaunchHandler(LaunchClassLoader launchLoader, FMLTweaker tweaker) - { - this.classLoader = launchLoader; - this.tweaker = tweaker; - this.minecraftHome = tweaker.getGameDir(); - this.classLoader.addClassLoaderExclusion("net.minecraftforge.fml.relauncher."); - this.classLoader.addClassLoaderExclusion("net.minecraftforge.classloading."); - this.classLoader.addTransformerExclusion("net.minecraftforge.fml.common.asm.transformers."); - this.classLoader.addTransformerExclusion("net.minecraftforge.fml.common.patcher."); - this.classLoader.addTransformerExclusion("net.minecraftforge.fml.repackage."); - this.classLoader.addClassLoaderExclusion("org.apache.commons."); - this.classLoader.addClassLoaderExclusion("org.apache.http."); - this.classLoader.addClassLoaderExclusion("org.apache.maven."); - this.classLoader.addClassLoaderExclusion("com.google.common."); - this.classLoader.addClassLoaderExclusion("org.objectweb.asm."); - this.classLoader.addClassLoaderExclusion("LZMA."); - } - - private void setupClient() - { - side = Side.CLIENT; - setupHome(); - } - - private void setupServer() - { - side = Side.SERVER; - setupHome(); - } - - private void setupHome() - { - FMLInjectionData.build(minecraftHome, classLoader); - redirectStdOutputToLog(); - FMLLog.log.info("Forge Mod Loader version {}.{}.{}.{} for Minecraft {} loading", FMLInjectionData.major, FMLInjectionData.minor, - FMLInjectionData.rev, FMLInjectionData.build, FMLInjectionData.mccversion); - FMLLog.log.info("Java is {}, version {}, running on {}:{}:{}, installed at {}", System.getProperty("java.vm.name"), System.getProperty("java.version"), System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version"), System.getProperty("java.home")); - FMLLog.log.debug("Java classpath at launch is:"); - for (String path : System.getProperty("java.class.path").split(File.pathSeparator)) - FMLLog.log.debug(" {}", path); - FMLLog.log.debug("Java library path at launch is:"); - for (String path : System.getProperty("java.library.path").split(File.pathSeparator)) - FMLLog.log.debug(" {}", path); - - try - { - LibraryManager.setup(minecraftHome); - CoreModManager.handleLaunch(minecraftHome, classLoader, tweaker); - } - catch (Throwable t) - { - throw new RuntimeException("An error occurred trying to configure the Minecraft home at " + minecraftHome.getAbsolutePath() + " for Forge Mod Loader", t); - } - } - - private void redirectStdOutputToLog() - { - FMLLog.log.debug("Injecting tracing printstreams for STDOUT/STDERR."); - System.setOut(new TracingPrintStream(LogManager.getLogger("STDOUT"), System.out)); - System.setErr(new TracingPrintStream(LogManager.getLogger("STDERR"), System.err)); - } - - public static Side side() - { - return side; - } - - - private void injectPostfixTransformers() - { - CoreModManager.injectTransformers(classLoader); - } - - public static void appendCoreMods() - { - INSTANCE.injectPostfixTransformers(); - } - - -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/FMLRelaunchLog.java b/src/main/java/net/minecraftforge/fml/relauncher/FMLRelaunchLog.java deleted file mode 100644 index 523f6fd19..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/FMLRelaunchLog.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * Legacy FML logging class. Mods use {@link FMLPreInitializationEvent#getModLog()} instead, for Forge internal use use FMLLog. - * TODO 1.13 remove this class - */ -@Deprecated -public class FMLRelaunchLog { - - /** - * Our special logger for logging issues to. We copy various assets from the - * Minecraft logger to achieve a similar appearance. - */ - public static final FMLRelaunchLog log = new FMLRelaunchLog(); - - private FMLRelaunchLog() - { - } - - public static void log(String targetLog, Level level, String format, Object... data) - { - LogManager.getLogger(targetLog).log(level, String.format(format, data)); - } - - public static void log(Level level, String format, Object... data) - { - FMLLog.log.log(level, String.format(format, data)); - } - - public static void log(String targetLog, Level level, Throwable ex, String format, Object... data) - { - LogManager.getLogger(targetLog).log(level, String.format(format, data), ex); - } - - public static void log(Level level, Throwable ex, String format, Object... data) - { - FMLLog.log.log(level, String.format(format, data), ex); - } - - public static void severe(String format, Object... data) - { - log(Level.ERROR, format, data); - } - - public static void warning(String format, Object... data) - { - log(Level.WARN, format, data); - } - - public static void info(String format, Object... data) - { - log(Level.INFO, format, data); - } - - public static void fine(String format, Object... data) - { - log(Level.DEBUG, format, data); - } - - public static void finer(String format, Object... data) - { - log(Level.TRACE, format, data); - } - - public Logger getLogger() - { - return FMLLog.log; - } -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/IFMLCallHook.java b/src/main/java/net/minecraftforge/fml/relauncher/IFMLCallHook.java deleted file mode 100644 index 6bbdb7e30..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/IFMLCallHook.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.util.Map; -import java.util.concurrent.Callable; - -/** - * This call hook allows for code to execute at the very early stages of - * minecraft initialization. FML uses it to validate that there is a - * safe environment for further loading of FML. - * - * @author cpw - * - */ -public interface IFMLCallHook extends Callable -{ - /** - * Injected with data from the FML environment: - * "classLoader" : The FML Class Loader - * @param data - */ - void injectData(Map data); -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/Side.java b/src/main/java/net/minecraftforge/fml/relauncher/Side.java deleted file mode 100644 index 7a2d8148c..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/Side.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -public enum Side { - - /** - * The client side. Specifically, an environment where rendering capability exists. - * Usually in the game client. - */ - CLIENT, - /** - * The server side. Specifically, an environment where NO rendering capability exists. - * Usually on the dedicated server. - */ - SERVER; - - /** - * @return If this is the server environment - */ - public boolean isServer() - { - return !isClient(); - } - - /** - * @return if this is the Client environment - */ - public boolean isClient() - { - return this == CLIENT; - } -} diff --git a/src/main/java/net/minecraftforge/fml/relauncher/SideOnly.java b/src/main/java/net/minecraftforge/fml/relauncher/SideOnly.java deleted file mode 100644 index 034e5e215..000000000 --- a/src/main/java/net/minecraftforge/fml/relauncher/SideOnly.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Minecraft Forge - * Copyright (c) 2016-2018. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation version 2.1 - * of the License. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -package net.minecraftforge.fml.relauncher; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import net.minecraftforge.fml.common.SidedProxy; - - -/** - * Marks the associated element as being only available on a certain {@link Side}. This is - * generally meant for internal Forge and FML use only and should only be used on mod classes - * when other more common mechanisms, such as using a {@link SidedProxy} fail to work. - * - * Note, this will only apply to the direct element marked. This code: - * @SideOnly public MyField field = new MyField(); will not work, as the initializer - * is a separate piece of code to the actual field declaration, and will not be able to find - * it's field on the wrong side. - * - * @author cpw - * - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR}) -public @interface SideOnly -{ - Side value(); -} diff --git a/src/main/java/net/minecraftforge/fml/server/FMLServerHandler.java b/src/main/java/net/minecraftforge/fml/server/FMLServerHandler.java index c4c0ceec3..fa5bcdd9e 100644 --- a/src/main/java/net/minecraftforge/fml/server/FMLServerHandler.java +++ b/src/main/java/net/minecraftforge/fml/server/FMLServerHandler.java @@ -43,9 +43,8 @@ import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.IFMLSidedHandler; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.common.network.FMLNetworkEvent; -import net.minecraftforge.fml.relauncher.Side; import com.google.common.collect.ImmutableList; import org.apache.commons.io.IOUtils; @@ -147,7 +146,7 @@ public class FMLServerHandler implements IFMLSidedHandler } /* (non-Javadoc) - * @see net.minecraftforge.fml.common.IFMLSidedHandler#getSide() + * @see net.minecraftforge.fml.common.IFMLSidedHandler#getDist() */ @Override public Side getSide() diff --git a/src/main/java/net/minecraftforge/oredict/RecipeSorter.java b/src/main/java/net/minecraftforge/oredict/RecipeSorter.java index a798f0c28..63bdb1633 100644 --- a/src/main/java/net/minecraftforge/oredict/RecipeSorter.java +++ b/src/main/java/net/minecraftforge/oredict/RecipeSorter.java @@ -260,7 +260,7 @@ public class RecipeSorter implements Comparator private static void bake() { if (!isDirty) return; - FMLLog.log.debug("Forge RecipeSorter Baking:"); + LOG.debug("Forge RecipeSorter Baking:"); DirectedGraph sorter = new DirectedGraph(); sorter.addNode(before); sorter.addNode(after); diff --git a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java index 56829baca..72a006b40 100644 --- a/src/main/java/net/minecraftforge/registries/ForgeRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ForgeRegistry.java @@ -276,7 +276,7 @@ public class ForgeRegistry> implements IForgeRe int add(int id, V value) { - final String owner = ModThreadContext.get().getCurrentContainer().getPrefix(); + final String owner = ModThreadContext.get().getActiveContainer().getPrefix(); return add(id, value, owner); } diff --git a/src/main/java/net/minecraftforge/registries/GameData.java b/src/main/java/net/minecraftforge/registries/GameData.java index f406f01ad..8bb681549 100644 --- a/src/main/java/net/minecraftforge/registries/GameData.java +++ b/src/main/java/net/minecraftforge/registries/GameData.java @@ -49,15 +49,8 @@ import net.minecraft.world.biome.Biome; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.event.RegistryEvent.MissingMappings; -import net.minecraftforge.fml.Logging; import net.minecraftforge.fml.common.EnhancedRuntimeException; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.FMLContainer; -import net.minecraftforge.fml.common.FMLLog; -import net.minecraftforge.fml.common.InjectedModContainer; -import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModContainer; -import net.minecraftforge.fml.common.StartupQuery; +import net.minecraftforge.fml.StartupQuery; import net.minecraftforge.fml.common.ZipperUtil; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.registry.EntityEntryBuilder; @@ -81,10 +74,13 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; +import net.minecraftforge.fml.common.thread.EffectiveSide; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; import static net.minecraftforge.fml.Logging.fmlLog; @@ -118,7 +114,8 @@ public class GameData private static final ResourceLocation BLOCK_TO_ITEM = new ResourceLocation("minecraft:blocktoitemmap"); private static final ResourceLocation BLOCKSTATE_TO_ID = new ResourceLocation("minecraft:blockstatetoid"); - private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Logger LOGGER = LogManager.getLogger("FML"); + private static final Marker GD = MarkerManager.getMarker("GAMEDATA"); private static boolean hasInit = false; private static final boolean DISABLE_VANILLA_REGISTRIES = Boolean.parseBoolean(System.getProperty("forge.disableVanillaGameData", "false")); // Use for unit tests/debugging private static final BiConsumer> LOCK_VANILLA = (name, reg) -> reg.slaves.values().stream().filter(o -> o instanceof ILockableRegistry).forEach(o -> ((ILockableRegistry)o).lock()); @@ -131,7 +128,7 @@ public class GameData { if ( DISABLE_VANILLA_REGISTRIES) { - FMLLog.bigWarning("DISABLING VANILLA REGISTRY CREATION AS PER SYSTEM VARIABLE SETTING! forge.disableVanillaGameData"); + LOGGER.warn(GD, "DISABLING VANILLA REGISTRY CREATION AS PER SYSTEM VARIABLE SETTING! forge.disableVanillaGameData"); return; } if (hasInit) @@ -226,7 +223,7 @@ public class GameData @SuppressWarnings({ "rawtypes", "unchecked" }) public static void freezeData() { - FMLLog.log.debug("Freezing registries"); + LOGGER.debug(GD, "Freezing registries"); for (Map.Entry>> r : RegistryManager.ACTIVE.registries.entrySet()) { final Class clazz = RegistryManager.ACTIVE.getSuperType(r.getKey()); @@ -240,9 +237,9 @@ public class GameData RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.freeze()); // the id mapping is fanilized, no ids actually changed but this is a good place to tell everyone to 'bake' their stuff. - Loader.instance().fireRemapEvent(ImmutableMap.of(), true); + //Loader.instance().fireRemapEvent(ImmutableMap.of(), true); - FMLLog.log.debug("All registries frozen"); + LOGGER.debug(GD, "All registries frozen"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -250,32 +247,31 @@ public class GameData { if (RegistryManager.FROZEN.registries.isEmpty()) { - FMLLog.log.warn("Can't revert to frozen GameData state without freezing first."); + LOGGER.warn(GD, "Can't revert to frozen GameData state without freezing first."); return; } RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates()); - FMLLog.log.debug("Reverting to frozen data state."); + LOGGER.debug(GD, "Reverting to frozen data state."); for (Map.Entry>> r : RegistryManager.ACTIVE.registries.entrySet()) { final Class clazz = RegistryManager.ACTIVE.getSuperType(r.getKey()); loadRegistry(r.getKey(), RegistryManager.FROZEN, RegistryManager.ACTIVE, clazz, true); } // the id mapping has reverted, fire remap events for those that care about id changes - Loader.instance().fireRemapEvent(ImmutableMap.of(), true); + //Loader.instance().fireRemapEvent(ImmutableMap.of(), true); // the id mapping has reverted, ensure we sync up the object holders - ObjectHolderRegistry.INSTANCE.applyObjectHolders(); - FMLLog.log.debug("Frozen state restored."); + LOGGER.debug("Frozen state restored."); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static void revert(RegistryManager state, ResourceLocation registry, boolean lock) { - FMLLog.log.debug("Reverting {} to {}", registry, state.getName()); + LOGGER.debug(GD, "Reverting {} to {}", registry, state.getName()); final Class clazz = RegistryManager.ACTIVE.getSuperType(registry); loadRegistry(registry, state, RegistryManager.ACTIVE, clazz, lock); - FMLLog.log.debug("Reverting complete"); + LOGGER.debug(GD, "Reverting complete"); } //Lets us clear the map so we can rebuild it. @@ -517,7 +513,7 @@ public class GameData @SuppressWarnings({ "unchecked", "rawtypes" }) public static Multimap injectSnapshot(Map snapshot, boolean injectFrozenData, boolean isLocalWorld) { - FMLLog.log.info("Injecting existing registry data into this {} instance", FMLCommonHandler.instance().getEffectiveSide().isServer() ? "server" : "client"); + LOGGER.info(GD, "Injecting existing registry data into this {} instance", EffectiveSide.get()); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.validateContent(name)); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name)); RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates()); @@ -573,7 +569,7 @@ public class GameData // The server believes this is a dummy block identity, but we seem to have one locally. This is likely a conflict // in mod setup - Mark this entry as a dummy int id = reg.getID(dummy); - FMLLog.log.warn("Registry {}: The ID {} @ {} is currently locally mapped - it will be replaced with a dummy for this session", dummy, key, id); + LOGGER.warn(GD, "Registry {}: The ID {} @ {} is currently locally mapped - it will be replaced with a dummy for this session", dummy, key, id); reg.markDummy(dummy, id); } }); @@ -582,7 +578,7 @@ public class GameData int count = missing.values().stream().mapToInt(Map::size).sum(); if (count > 0) { - FMLLog.log.debug("There are {} mappings missing - attempting a mod remap", count); + LOGGER.debug(GD,"There are {} mappings missing - attempting a mod remap", count); Multimap defaulted = ArrayListMultimap.create(); Multimap failed = ArrayListMultimap.create(); @@ -596,8 +592,8 @@ public class GameData List> lst = event.getAllMappings().stream().filter(e -> e.getAction() == MissingMappings.Action.DEFAULT).sorted((a, b) -> a.toString().compareTo(b.toString())).collect(Collectors.toList()); if (!lst.isEmpty()) { - FMLLog.log.error("Unidentified mapping from registry {}", name); - lst.forEach(map -> FMLLog.log.error(" {}: {}", map.key, map.id)); + LOGGER.error(GD,"Unidentified mapping from registry {}", name); + lst.forEach(map -> LOGGER.error(" {}: {}", map.key, map.id)); } event.getAllMappings().stream().filter(e -> e.getAction() == MissingMappings.Action.FAIL).forEach(fail -> failed.put(name, fail.key)); @@ -636,7 +632,7 @@ public class GameData else { for (int x = 0; x < 10; x++) - FMLLog.log.error("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!"); + LOGGER.error(GD, "!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!"); } } catch (IOException e) @@ -649,7 +645,7 @@ public class GameData if (!defaulted.isEmpty()) { if (isLocalWorld) - FMLLog.log.error("There are unidentified mappings in this world - we are going to attempt to process anyway"); + LOGGER.error(GD, "There are unidentified mappings in this world - we are going to attempt to process anyway"); } } @@ -688,10 +684,10 @@ public class GameData RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name)); // Tell mods that the ids have changed - Loader.instance().fireRemapEvent(remaps, false); + //Loader.instance().fireRemapEvent(remaps, false); // The id map changed, ensure we apply object holders - ObjectHolderRegistry.INSTANCE.applyObjectHolders(); + //ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // Return an empty list, because we're good return ArrayListMultimap.create(); @@ -801,8 +797,7 @@ public class GameData } catch (NoSuchFieldException | SecurityException e) { - FMLLog.log.error("Could not get `registryName` field from IForgeRegistryEntry.Impl"); - FMLLog.log.throwing(Level.ERROR, e); + LOGGER.error(GD, "Could not get `registryName` field from IForgeRegistryEntry.Impl", e); throw new RuntimeException(e); } } @@ -812,8 +807,7 @@ public class GameData } catch (IllegalArgumentException | IllegalAccessException e) { - FMLLog.log.error("Could not set `registryName` field in IForgeRegistryEntry.Impl to `{}`", name.toString()); - FMLLog.log.throwing(Level.ERROR, e); + LOGGER.error(GD,"Could not set `registryName` field in IForgeRegistryEntry.Impl to `{}`", name.toString(), e); throw new RuntimeException(e); } diff --git a/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java b/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java index 1da5ccd0d..3104e993d 100644 --- a/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java +++ b/src/main/java/net/minecraftforge/registries/ObjectHolderRegistry.java @@ -28,8 +28,6 @@ import java.util.Set; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; diff --git a/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java b/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java index c8bf3009b..f4cbd8f87 100644 --- a/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java +++ b/src/main/java/net/minecraftforge/server/permission/PermissionAPI.java @@ -24,10 +24,8 @@ import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.LoaderState; import net.minecraftforge.server.permission.context.IContext; import net.minecraftforge.server.permission.context.PlayerContext; -import org.apache.logging.log4j.Level; import javax.annotation.Nullable; diff --git a/src/main/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService b/src/main/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService new file mode 100644 index 000000000..cdcf67fe4 --- /dev/null +++ b/src/main/resources/META-INF/services/cpw.mods.modlauncher.serviceapi.ILaunchPluginService @@ -0,0 +1 @@ +net.minecraftforge.fml.loading.RuntimeDistCleaner \ No newline at end of file diff --git a/src/test/java/net/minecraftforge/debug/block/MaterialFogColorTest.java b/src/test/java/net/minecraftforge/debug/block/MaterialFogColorTest.java index 3fb690925..a429d70e5 100644 --- a/src/test/java/net/minecraftforge/debug/block/MaterialFogColorTest.java +++ b/src/test/java/net/minecraftforge/debug/block/MaterialFogColorTest.java @@ -33,6 +33,7 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; @@ -46,7 +47,6 @@ import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; @EventBusSubscriber @Mod(modid = MaterialFogColorTest.MODID, name = "FogColor inside material debug.", version = "1.0", acceptableRemoteVersions = "*") diff --git a/src/test/java/net/minecraftforge/debug/block/ParticleEffectsTest.java b/src/test/java/net/minecraftforge/debug/block/ParticleEffectsTest.java index 5783f5d32..07b2876d7 100644 --- a/src/test/java/net/minecraftforge/debug/block/ParticleEffectsTest.java +++ b/src/test/java/net/minecraftforge/debug/block/ParticleEffectsTest.java @@ -37,6 +37,8 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.minecraft.world.WorldServer; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; @@ -44,8 +46,6 @@ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import static net.minecraftforge.debug.block.ParticleEffectsTest.MOD_ID; import static net.minecraftforge.debug.block.ParticleEffectsTest.MOD_NAME; @@ -86,7 +86,7 @@ public class ParticleEffectsTest } @Override - @SideOnly (Side.CLIENT) + @OnlyIn(Dist.CLIENT) public boolean addHitEffects(IBlockState state, World world, RayTraceResult target, ParticleManager manager) { world.spawnParticle(EnumParticleTypes.REDSTONE, target.hitVec.x, target.hitVec.y, target.hitVec.z, 0, 1, 0); @@ -94,7 +94,7 @@ public class ParticleEffectsTest } @Override - @SideOnly (Side.CLIENT) + @OnlyIn(Dist.CLIENT) public boolean addDestroyEffects(World world, BlockPos pos, ParticleManager manager) { world.spawnParticle(EnumParticleTypes.REDSTONE, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 0, 0, 1); diff --git a/src/test/java/net/minecraftforge/debug/block/PathNodeTypeTest.java b/src/test/java/net/minecraftforge/debug/block/PathNodeTypeTest.java index 2730ec76a..c3efc49a5 100644 --- a/src/test/java/net/minecraftforge/debug/block/PathNodeTypeTest.java +++ b/src/test/java/net/minecraftforge/debug/block/PathNodeTypeTest.java @@ -27,12 +27,11 @@ import net.minecraft.item.Item; import net.minecraft.pathfinding.PathNodeType; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; import java.util.Collections; diff --git a/src/test/java/net/minecraftforge/debug/block/SlipperinessTest.java b/src/test/java/net/minecraftforge/debug/block/SlipperinessTest.java index 7a58329e8..5d50ef90d 100644 --- a/src/test/java/net/minecraftforge/debug/block/SlipperinessTest.java +++ b/src/test/java/net/minecraftforge/debug/block/SlipperinessTest.java @@ -30,13 +30,13 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; import java.util.Collections; diff --git a/src/test/java/net/minecraftforge/debug/block/StickyBlockTest.java b/src/test/java/net/minecraftforge/debug/block/StickyBlockTest.java index d140b5481..a757fd4e3 100644 --- a/src/test/java/net/minecraftforge/debug/block/StickyBlockTest.java +++ b/src/test/java/net/minecraftforge/debug/block/StickyBlockTest.java @@ -32,16 +32,15 @@ import net.minecraft.item.ItemMultiTexture; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraft.util.NonNullList; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; @Mod(modid = StickyBlockTest.MODID, name = "ForgeDebugCustomSlimeBlock", version = StickyBlockTest.VERSION, acceptableRemoteVersions = "*") public class StickyBlockTest @@ -86,7 +85,7 @@ public class StickyBlockTest } @Override - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public void getSubBlocks(CreativeTabs creativeTabs, NonNullList list) { for (int i = 0; i < BlockType.values.length; ++i) diff --git a/src/test/java/net/minecraftforge/debug/client/SearchableCreativeTabTest.java b/src/test/java/net/minecraftforge/debug/client/SearchableCreativeTabTest.java index f7717fc61..ddbc965f3 100644 --- a/src/test/java/net/minecraftforge/debug/client/SearchableCreativeTabTest.java +++ b/src/test/java/net/minecraftforge/debug/client/SearchableCreativeTabTest.java @@ -24,9 +24,9 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; @Mod(modid = SearchableCreativeTabTest.MODID, name = "Debug Search Tab", version = "1.0", acceptableRemoteVersions = "*") public class SearchableCreativeTabTest @@ -36,7 +36,7 @@ public class SearchableCreativeTabTest public static final CreativeTabs SEARCH_TAB = !ENABLED ? null : new CreativeTabs(1, "searchtab") { - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public ItemStack getTabIconItem() { return new ItemStack(Items.TOTEM_OF_UNDYING); @@ -49,7 +49,7 @@ public class SearchableCreativeTabTest } @Override - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public void displayAllRelevantItems(NonNullList items) { super.displayAllRelevantItems(items); diff --git a/src/test/java/net/minecraftforge/debug/client/gui/ContainerDrawForegroundEventTest.java b/src/test/java/net/minecraftforge/debug/client/gui/ContainerDrawForegroundEventTest.java index 5e47379fe..f71c3ef55 100644 --- a/src/test/java/net/minecraftforge/debug/client/gui/ContainerDrawForegroundEventTest.java +++ b/src/test/java/net/minecraftforge/debug/client/gui/ContainerDrawForegroundEventTest.java @@ -22,13 +22,13 @@ package net.minecraftforge.debug.client.gui; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.GuiContainerEvent; import net.minecraftforge.fml.client.config.GuiUtils; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; @EventBusSubscriber(Side.CLIENT) @Mod (modid = "guicontainereventtest", name = "GuiContainer Event Tests!", version = "1.0", acceptableRemoteVersions = "*") diff --git a/src/test/java/net/minecraftforge/debug/client/model/AnimatedModelTest.java b/src/test/java/net/minecraftforge/debug/client/model/AnimatedModelTest.java index 67b928da1..cf33bccee 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/AnimatedModelTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/AnimatedModelTest.java @@ -45,6 +45,7 @@ import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.ModelLoaderRegistry; @@ -69,14 +70,12 @@ import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; -import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; import org.apache.logging.log4j.Logger; import javax.annotation.Nonnull; @@ -104,7 +103,6 @@ public class AnimatedModelTest @Instance(MODID) public static AnimatedModelTest instance; - @SidedProxy public static CommonProxy proxy; private static Logger logger; diff --git a/src/test/java/net/minecraftforge/debug/client/model/BlockstateRetextureTest.java b/src/test/java/net/minecraftforge/debug/client/model/BlockstateRetextureTest.java index 5a1547775..fd229e042 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/BlockstateRetextureTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/BlockstateRetextureTest.java @@ -29,12 +29,11 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = BlockstateRetextureTest.MODID, name = "BlockstateRetextureTest", version = BlockstateRetextureTest.VERSION, acceptableRemoteVersions = "*", clientSideOnly = true) public class BlockstateRetextureTest diff --git a/src/test/java/net/minecraftforge/debug/client/model/ForgeBlockStatesLoaderTest.java b/src/test/java/net/minecraftforge/debug/client/model/ForgeBlockStatesLoaderTest.java index ea970cd52..086bac2f7 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/ForgeBlockStatesLoaderTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/ForgeBlockStatesLoaderTest.java @@ -29,13 +29,13 @@ import net.minecraft.client.renderer.block.statemap.StateMap; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemMultiTexture; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; import java.util.Map; import java.util.Map.Entry; diff --git a/src/test/java/net/minecraftforge/debug/client/model/ItemModelGenerationTest.java b/src/test/java/net/minecraftforge/debug/client/model/ItemModelGenerationTest.java index 8137b8f6d..9cd5bedda 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/ItemModelGenerationTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/ItemModelGenerationTest.java @@ -22,13 +22,13 @@ package net.minecraftforge.debug.client.model; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; @Mod.EventBusSubscriber @Mod(modid = ItemModelGenerationTest.MOD_ID, name = "Item model generation test", version = "1.0", acceptableRemoteVersions = "*") diff --git a/src/test/java/net/minecraftforge/debug/client/model/ModelBakeEventTest.java b/src/test/java/net/minecraftforge/debug/client/model/ModelBakeEventTest.java index 76cbfa3c9..593122b27 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/ModelBakeEventTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/ModelBakeEventTest.java @@ -62,7 +62,7 @@ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import javax.annotation.Nullable; import java.util.ArrayList; diff --git a/src/test/java/net/minecraftforge/debug/client/model/ModelFluidTest.java b/src/test/java/net/minecraftforge/debug/client/model/ModelFluidTest.java index 06c738608..9a7d5d7b0 100644 --- a/src/test/java/net/minecraftforge/debug/client/model/ModelFluidTest.java +++ b/src/test/java/net/minecraftforge/debug/client/model/ModelFluidTest.java @@ -29,6 +29,7 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.ForgeVersion; @@ -39,7 +40,6 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = ModelFluidTest.MODID, name = "ForgeDebugModelFluid", version = ModelFluidTest.VERSION, acceptableRemoteVersions = "*") public class ModelFluidTest diff --git a/src/test/java/net/minecraftforge/debug/client/rendering/FastTESRTransparentTest.java b/src/test/java/net/minecraftforge/debug/client/rendering/FastTESRTransparentTest.java index 3eb4b89d8..574fc5de7 100644 --- a/src/test/java/net/minecraftforge/debug/client/rendering/FastTESRTransparentTest.java +++ b/src/test/java/net/minecraftforge/debug/client/rendering/FastTESRTransparentTest.java @@ -56,9 +56,8 @@ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; @Mod(modid = FastTESRTransparentTest.MODID, name = "TransparentFastTESRTest", version = "1.0", acceptableRemoteVersions = "*") public class FastTESRTransparentTest diff --git a/src/test/java/net/minecraftforge/debug/client/rendering/ItemTESRTest.java b/src/test/java/net/minecraftforge/debug/client/rendering/ItemTESRTest.java index 7ddeb66c2..9afd88cb5 100644 --- a/src/test/java/net/minecraftforge/debug/client/rendering/ItemTESRTest.java +++ b/src/test/java/net/minecraftforge/debug/client/rendering/ItemTESRTest.java @@ -32,6 +32,7 @@ import net.minecraft.item.ItemBlock; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.ModelRegistryEvent; @@ -43,7 +44,6 @@ import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; import static org.lwjgl.opengl.GL11.*; diff --git a/src/test/java/net/minecraftforge/debug/client/rendering/VertexBufferNormalTest.java b/src/test/java/net/minecraftforge/debug/client/rendering/VertexBufferNormalTest.java index ae1f0f550..9a7d98c6e 100644 --- a/src/test/java/net/minecraftforge/debug/client/rendering/VertexBufferNormalTest.java +++ b/src/test/java/net/minecraftforge/debug/client/rendering/VertexBufferNormalTest.java @@ -32,7 +32,6 @@ import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; -import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.registry.EntityRegistry; @@ -42,7 +41,6 @@ public class VertexBufferNormalTest @Instance("wrnormal") public static VertexBufferNormalTest instance; - @SidedProxy public static ServerProxy proxy; @EventHandler diff --git a/src/test/java/net/minecraftforge/debug/entity/player/ReachDistanceAttributeTest.java b/src/test/java/net/minecraftforge/debug/entity/player/ReachDistanceAttributeTest.java index 73583ee2a..3005b834f 100644 --- a/src/test/java/net/minecraftforge/debug/entity/player/ReachDistanceAttributeTest.java +++ b/src/test/java/net/minecraftforge/debug/entity/player/ReachDistanceAttributeTest.java @@ -27,12 +27,12 @@ import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = ReachDistanceAttributeTest.MODID, name = ReachDistanceAttributeTest.MODID, version = "1.0", acceptableRemoteVersions = "*") @Mod.EventBusSubscriber diff --git a/src/test/java/net/minecraftforge/debug/fluid/DynBucketTest.java b/src/test/java/net/minecraftforge/debug/fluid/DynBucketTest.java index c20563647..42e871840 100644 --- a/src/test/java/net/minecraftforge/debug/fluid/DynBucketTest.java +++ b/src/test/java/net/minecraftforge/debug/fluid/DynBucketTest.java @@ -48,6 +48,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.ForgeVersion; @@ -76,7 +77,6 @@ import net.minecraftforge.eventbus.api.Event.Result; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import net.minecraftforge.items.wrapper.CombinedInvWrapper; diff --git a/src/test/java/net/minecraftforge/debug/fluid/FluidPlacementTest.java b/src/test/java/net/minecraftforge/debug/fluid/FluidPlacementTest.java index 4ac8dac8d..cacab1544 100644 --- a/src/test/java/net/minecraftforge/debug/fluid/FluidPlacementTest.java +++ b/src/test/java/net/minecraftforge/debug/fluid/FluidPlacementTest.java @@ -37,6 +37,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.MinecraftForge; @@ -53,8 +54,7 @@ import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStack; import net.minecraftforge.fluids.capability.wrappers.FluidBucketWrapper; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -271,7 +271,7 @@ public class FluidPlacementTest } @Override - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public void addInformation(ItemStack stack, @Nullable World playerIn, List tooltip, ITooltipFlag advanced) { FluidStack fluid = getFluid(stack); diff --git a/src/test/java/net/minecraftforge/debug/gameplay/InputUpdateEventTest.java b/src/test/java/net/minecraftforge/debug/gameplay/InputUpdateEventTest.java index 77bc1485d..5d4d0d3c7 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/InputUpdateEventTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/InputUpdateEventTest.java @@ -25,10 +25,9 @@ import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextComponentString; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.InputUpdateEvent; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = InputUpdateEventTest.MODID, name = "InputUpdateTest", version = "1.0", acceptableRemoteVersions = "*") public class InputUpdateEventTest diff --git a/src/test/java/net/minecraftforge/debug/gameplay/PotionRegistryTest.java b/src/test/java/net/minecraftforge/debug/gameplay/PotionRegistryTest.java index 8fb1bf568..a4bec4cc8 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/PotionRegistryTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/PotionRegistryTest.java @@ -57,7 +57,7 @@ public class PotionRegistryTest taken.add(ra); // a new potion with a random id so that forge has to remap it - //new PotionForge(ra, new ResourceLocation(ForgeModContainer.MOD_ID, "realRandomPotion"), false, 0x0000ff); + //new PotionForge(ra, new ResourceLocation(ForgeMod.MOD_ID, "realRandomPotion"), false, 0x0000ff); for (int i = 0; i < 20; i++) { @@ -68,7 +68,7 @@ public class PotionRegistryTest taken.add(r); // this potions will most likely not have the same IDs between server and client. // The forge handshake on connect should fix this. - //new PotionForge(new ResourceLocation(ForgeModContainer.MOD_ID, "randomPotion" + r), false, 0xff00ff); + //new PotionForge(new ResourceLocation(ForgeMod.MOD_ID, "randomPotion" + r), false, 0xff00ff); } } diff --git a/src/test/java/net/minecraftforge/debug/gameplay/RecipeMatchingTest.java b/src/test/java/net/minecraftforge/debug/gameplay/RecipeMatchingTest.java index 9c70378bc..203a10766 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/RecipeMatchingTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/RecipeMatchingTest.java @@ -29,16 +29,14 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.ShapedRecipes; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.FMLLaunchHandler; -import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.oredict.ShapedOreRecipe; @Mod(modid = RecipeMatchingTest.MODID, name = "Recipe test mod", version = "1.0", acceptableRemoteVersions = "*") @@ -46,7 +44,6 @@ public class RecipeMatchingTest { public static final String MODID = "recipetest"; private static final boolean ENABLED = true; - @SidedProxy public static CommonProxy proxy = null; diff --git a/src/test/java/net/minecraftforge/debug/gameplay/advancement/AdvancementCriterionTest.java b/src/test/java/net/minecraftforge/debug/gameplay/advancement/AdvancementCriterionTest.java index 05d4ed681..418f303d8 100644 --- a/src/test/java/net/minecraftforge/debug/gameplay/advancement/AdvancementCriterionTest.java +++ b/src/test/java/net/minecraftforge/debug/gameplay/advancement/AdvancementCriterionTest.java @@ -23,11 +23,11 @@ import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.advancements.critereon.PositionTrigger; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(name = "advancementcriteriontest", modid = "advancementcriteriontest", version = "1.0", acceptableRemoteVersions = "*") @Mod.EventBusSubscriber diff --git a/src/test/java/net/minecraftforge/debug/item/CanApplyAtEnchantingTableTest.java b/src/test/java/net/minecraftforge/debug/item/CanApplyAtEnchantingTableTest.java index 2d3116f84..da5bc2827 100644 --- a/src/test/java/net/minecraftforge/debug/item/CanApplyAtEnchantingTableTest.java +++ b/src/test/java/net/minecraftforge/debug/item/CanApplyAtEnchantingTableTest.java @@ -24,11 +24,11 @@ import net.minecraft.enchantment.Enchantment; import net.minecraft.init.Enchantments; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = CanApplyAtEnchantingTableTest.MODID, name = "CanApplyAtEnchantingTableTest", version = "0.0.0", acceptableRemoteVersions = "*") public class CanApplyAtEnchantingTableTest diff --git a/src/test/java/net/minecraftforge/debug/item/HorseArmorTest.java b/src/test/java/net/minecraftforge/debug/item/HorseArmorTest.java index fac0bd12b..ebad66877 100644 --- a/src/test/java/net/minecraftforge/debug/item/HorseArmorTest.java +++ b/src/test/java/net/minecraftforge/debug/item/HorseArmorTest.java @@ -27,6 +27,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.util.EnumHelper; @@ -34,9 +35,7 @@ import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; @EventBusSubscriber @Mod(modid = HorseArmorTest.MODID, name = "HorseArmorTest", version = "1.0", acceptableRemoteVersions = "*") diff --git a/src/test/java/net/minecraftforge/debug/item/IsBookEnchantableTest.java b/src/test/java/net/minecraftforge/debug/item/IsBookEnchantableTest.java index 831e882da..db70557fd 100644 --- a/src/test/java/net/minecraftforge/debug/item/IsBookEnchantableTest.java +++ b/src/test/java/net/minecraftforge/debug/item/IsBookEnchantableTest.java @@ -24,11 +24,10 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.Enchantment; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = IsBookEnchantableTest.MOD_ID, name = "Test for isBookEnchantable", version = "1.0", acceptableRemoteVersions = "*") @Mod.EventBusSubscriber diff --git a/src/test/java/net/minecraftforge/debug/item/MapDataTest.java b/src/test/java/net/minecraftforge/debug/item/MapDataTest.java index d545cf36d..e4917969e 100644 --- a/src/test/java/net/minecraftforge/debug/item/MapDataTest.java +++ b/src/test/java/net/minecraftforge/debug/item/MapDataTest.java @@ -40,6 +40,8 @@ import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.MinecraftForge; @@ -52,8 +54,6 @@ import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.io.IOException; @@ -141,7 +141,7 @@ public class MapDataTest // copy of super with own map prefix and type @Nullable - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) public static CustomMapData loadMapData(int mapId, World worldIn) { String s = PREFIX + "_" + mapId; diff --git a/src/test/java/net/minecraftforge/debug/item/OnItemUseFirstTest.java b/src/test/java/net/minecraftforge/debug/item/OnItemUseFirstTest.java index 1b0c3e6f2..08914b91c 100644 --- a/src/test/java/net/minecraftforge/debug/item/OnItemUseFirstTest.java +++ b/src/test/java/net/minecraftforge/debug/item/OnItemUseFirstTest.java @@ -31,7 +31,6 @@ import net.minecraft.world.World; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.eventbus.api.SubscribeEvent; import javax.annotation.Nonnull; @@ -42,7 +41,6 @@ public class OnItemUseFirstTest { public static final boolean ENABLE = true; public static final String MODID = "onitemusefirsttest"; - @SidedProxy public static CommonProxy proxy = null; public static abstract class CommonProxy diff --git a/src/test/java/net/minecraftforge/debug/item/PotionCurabilityTest.java b/src/test/java/net/minecraftforge/debug/item/PotionCurabilityTest.java index 8fb1335f8..e829fce04 100644 --- a/src/test/java/net/minecraftforge/debug/item/PotionCurabilityTest.java +++ b/src/test/java/net/minecraftforge/debug/item/PotionCurabilityTest.java @@ -28,12 +28,12 @@ import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionType; import net.minecraft.world.World; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; import java.util.ArrayList; import java.util.Collections; diff --git a/src/test/java/net/minecraftforge/debug/item/ShieldTest.java b/src/test/java/net/minecraftforge/debug/item/ShieldTest.java index c0662475f..90e9ecd5d 100644 --- a/src/test/java/net/minecraftforge/debug/item/ShieldTest.java +++ b/src/test/java/net/minecraftforge/debug/item/ShieldTest.java @@ -30,6 +30,7 @@ import net.minecraft.item.ItemShield; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.util.text.translation.I18n; +import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; @@ -37,8 +38,7 @@ import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.api.distmarker.Dist; @ObjectHolder("shield_test") @EventBusSubscriber @@ -95,7 +95,7 @@ public class ShieldTest event.getRegistry().register(new ItemHeavyDiamondSword().setUnlocalizedName("heavy_diamond_sword").setRegistryName("heavy_diamond_sword")); } - @SideOnly(Side.CLIENT) + @OnlyIn(Dist.CLIENT) @SubscribeEvent public static void registerModels(ModelRegistryEvent event) { diff --git a/src/test/java/net/minecraftforge/debug/network/BigNetworkMessageTest.java b/src/test/java/net/minecraftforge/debug/network/BigNetworkMessageTest.java index 3b2f053e4..40722ada4 100644 --- a/src/test/java/net/minecraftforge/debug/network/BigNetworkMessageTest.java +++ b/src/test/java/net/minecraftforge/debug/network/BigNetworkMessageTest.java @@ -21,6 +21,7 @@ package net.minecraftforge.debug.network; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -28,7 +29,6 @@ import net.minecraftforge.fml.common.gameevent.PlayerEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = BigNetworkMessageTest.MOD_ID, name = "Big network message test mod", version = "1.0", acceptableRemoteVersions = "*") @Mod.EventBusSubscriber diff --git a/src/test/java/net/minecraftforge/debug/util/ModNameTooltip.java b/src/test/java/net/minecraftforge/debug/util/ModNameTooltip.java index edbe97225..f1facb522 100644 --- a/src/test/java/net/minecraftforge/debug/util/ModNameTooltip.java +++ b/src/test/java/net/minecraftforge/debug/util/ModNameTooltip.java @@ -25,11 +25,11 @@ import java.util.List; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.ModContainer; -import net.minecraftforge.fml.relauncher.Side; @Mod(modid = "forgemodnametooltip", name = "ForgeModNameTooltip", version = "1.0", clientSideOnly = true) @Mod.EventBusSubscriber(Side.CLIENT) diff --git a/src/test/java/net/minecraftforge/debug/world/TileEntityLoadingTest.java b/src/test/java/net/minecraftforge/debug/world/TileEntityLoadingTest.java index 6ab7661a7..50bbd7997 100644 --- a/src/test/java/net/minecraftforge/debug/world/TileEntityLoadingTest.java +++ b/src/test/java/net/minecraftforge/debug/world/TileEntityLoadingTest.java @@ -34,10 +34,9 @@ import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import org.apache.logging.log4j.Logger; diff --git a/src/test/java/net/minecraftforge/fml/common/registry/BlockStateMappingsTest.java b/src/test/java/net/minecraftforge/fml/common/registry/BlockStateMappingsTest.java index dc53ff243..e9c45a342 100644 --- a/src/test/java/net/minecraftforge/fml/common/registry/BlockStateMappingsTest.java +++ b/src/test/java/net/minecraftforge/fml/common/registry/BlockStateMappingsTest.java @@ -25,7 +25,6 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Bootstrap; import net.minecraftforge.fml.common.DummyModContainer; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.registries.GameData; import org.junit.BeforeClass; diff --git a/src/test/java/net/minecraftforge/fml/common/registry/DummyBlockReplacementTest.java b/src/test/java/net/minecraftforge/fml/common/registry/DummyBlockReplacementTest.java index bfe68dccc..2b3ffff46 100644 --- a/src/test/java/net/minecraftforge/fml/common/registry/DummyBlockReplacementTest.java +++ b/src/test/java/net/minecraftforge/fml/common/registry/DummyBlockReplacementTest.java @@ -26,7 +26,6 @@ import net.minecraft.init.Bootstrap; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.DummyModContainer; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.ObjectHolderRegistry; diff --git a/src/test/java/net/minecraftforge/fml/common/registry/ItemBlockSubstitutionRemoveRestoreTest.java b/src/test/java/net/minecraftforge/fml/common/registry/ItemBlockSubstitutionRemoveRestoreTest.java index 6b960ca86..33e9b77ce 100644 --- a/src/test/java/net/minecraftforge/fml/common/registry/ItemBlockSubstitutionRemoveRestoreTest.java +++ b/src/test/java/net/minecraftforge/fml/common/registry/ItemBlockSubstitutionRemoveRestoreTest.java @@ -19,7 +19,6 @@ package net.minecraftforge.fml.common.registry; -import net.minecraft.block.Block; import net.minecraft.block.BlockDirt; import net.minecraft.init.Blocks; import net.minecraft.init.Bootstrap; @@ -30,7 +29,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.DummyModContainer; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.ObjectHolderRegistry; @@ -45,8 +43,6 @@ import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import java.util.Map; - /** * Substitution test harness - tests that substitutions behave correctly */ diff --git a/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionInjectionTest.java b/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionInjectionTest.java index a9f87993b..8966f9304 100644 --- a/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionInjectionTest.java +++ b/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionInjectionTest.java @@ -29,7 +29,6 @@ import net.minecraft.stats.StatList; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.DummyModContainer; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.registries.ForgeRegistry; import net.minecraftforge.registries.GameData; import net.minecraftforge.registries.ObjectHolderRegistry; diff --git a/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionRemoveRestoreTest.java b/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionRemoveRestoreTest.java index db3580df8..f13e3be66 100644 --- a/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionRemoveRestoreTest.java +++ b/src/test/java/net/minecraftforge/fml/common/registry/SubstitutionRemoveRestoreTest.java @@ -21,18 +21,10 @@ package net.minecraftforge.fml.common.registry; import net.minecraft.block.Block; import net.minecraft.block.BlockDirt; -import net.minecraft.init.Blocks; import net.minecraft.init.Bootstrap; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.DummyModContainer; import net.minecraftforge.fml.common.Loader; -import net.minecraftforge.fml.common.ModMetadata; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.GameData; -import net.minecraftforge.registries.ObjectHolderRegistry; -import net.minecraftforge.registries.RegistryManager; import org.junit.BeforeClass; import org.junit.Test; @@ -41,8 +33,6 @@ import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import java.util.Map; - /** * Substitution test harness - tests that substitutions behave correctly */ diff --git a/src/test/java/net/minecraftforge/fml/test/DependencyParserTest.java b/src/test/java/net/minecraftforge/fml/test/DependencyParserTest.java index 120536f60..af33edaea 100644 --- a/src/test/java/net/minecraftforge/fml/test/DependencyParserTest.java +++ b/src/test/java/net/minecraftforge/fml/test/DependencyParserTest.java @@ -27,7 +27,7 @@ import java.util.List; import com.google.common.collect.ImmutableList; import net.minecraftforge.fml.common.versioning.DependencyParser; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import com.google.common.base.Functions; import com.google.common.collect.Collections2; diff --git a/src/test/java/net/minecraftforge/fml/test/ForgeNetworkTestMod.java b/src/test/java/net/minecraftforge/fml/test/ForgeNetworkTestMod.java index a773f5757..424f64bae 100644 --- a/src/test/java/net/minecraftforge/fml/test/ForgeNetworkTestMod.java +++ b/src/test/java/net/minecraftforge/fml/test/ForgeNetworkTestMod.java @@ -27,13 +27,12 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.common.network.FMLEventChannel; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import org.apache.logging.log4j.Logger; +import net.minecraftforge.api.distmarker.Dist; @Mod(modid = ForgeNetworkTestMod.MOD_ID, name = ForgeNetworkTestMod.MOD_ID, version = "1.0", acceptableRemoteVersions = "*") public class ForgeNetworkTestMod diff --git a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetTester.java b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetTester.java index 58009f5b3..aa748b75c 100644 --- a/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetTester.java +++ b/src/test/java/net/minecraftforge/fml/test/simplenet/SimpleNetTester.java @@ -21,7 +21,7 @@ package net.minecraftforge.fml.test.simplenet; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; -import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.api.distmarker.Dist; import org.junit.Test; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/net/minecraftforge/test/TestAnnotationParser.java b/src/test/java/net/minecraftforge/test/TestAnnotationParser.java index 157a11aee..8595ad213 100644 --- a/src/test/java/net/minecraftforge/test/TestAnnotationParser.java +++ b/src/test/java/net/minecraftforge/test/TestAnnotationParser.java @@ -33,10 +33,6 @@ import java.util.zip.ZipFile; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.discovery.ContainerType; -import net.minecraftforge.fml.common.discovery.ModCandidate; -import net.minecraftforge.fml.common.discovery.asm.ASMModParser; import net.minecraftforge.fml.common.discovery.json.JsonAnnotationLoader; import org.junit.jupiter.api.Test;