Initial port to 1.18

Co-authored-by: David Quintana <[email protected]>
Co-authored-by: SizableShrimp <[email protected]>
This commit is contained in:
committed 2021-11-30 17:42:18 +00:00
1 parent be0a6819ac
commit 40a174310d
538 files changed
+3322 -9030

No files matched your search

@@ -0,0 +1,229 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* 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.client.loading;
import static net.minecraftforge.fml.Logging.CORE;
import static net.minecraftforge.fml.Logging.LOADING;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.function.Consumer;
import net.minecraft.server.packs.repository.RepositorySource;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.world.level.DataPackConfig;
import net.minecraftforge.event.AddPackFindersEvent;
import net.minecraftforge.fml.*;
import net.minecraftforge.internal.BrandingControl;
import net.minecraftforge.logging.CrashReportExtender;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.resource.PathResourcePack;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.ClientPackSource;
import net.minecraft.util.profiling.ProfilerFiller;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.metadata.pack.PackMetadataSection;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.common.ForgeConfig;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.client.gui.LoadingErrorScreen;
import net.minecraftforge.resource.DelegatingResourcePack;
import net.minecraftforge.resource.ResourcePackLoader;
import net.minecraftforge.server.LanguageHook;
import net.minecraftforge.forgespi.language.IModInfo;
@OnlyIn(Dist.CLIENT)
public class ClientModLoader
{
private static final Logger LOGGER = LogManager.getLogger();
private static boolean loading;
private static Minecraft mc;
private static boolean loadingComplete;
private static LoadingFailedException error;
private static EarlyLoaderGUI earlyLoaderGUI;
private static class SpacedRunnable implements Runnable {
static final long NANO_SLEEP_TIME = TimeUnit.MILLISECONDS.toNanos(50);
private final Runnable wrapped;
private long lastRun;
private SpacedRunnable(final Runnable wrapped) {
this.wrapped = wrapped;
this.lastRun = System.nanoTime() - NANO_SLEEP_TIME;
}
@Override
public void run() {
if (System.nanoTime() - this.lastRun > NANO_SLEEP_TIME) {
wrapped.run();
this.lastRun = System.nanoTime();
}
}
}
public static void begin(final Minecraft minecraft, final PackRepository defaultResourcePacks, final ReloadableResourceManager mcResourceManager, ClientPackSource metadataSerializer)
{
// force log4j to shutdown logging in a shutdown hook. This is because we disable default shutdown hook so the server properly logs it's shutdown
Runtime.getRuntime().addShutdownHook(new Thread(LogManager::shutdown));
loading = true;
ClientModLoader.mc = minecraft;
LogicalSidedProvider.setClient(()->minecraft);
LanguageHook.loadForgeAndMCLangs();
earlyLoaderGUI = new EarlyLoaderGUI(minecraft);
createRunnableWithCatch(()->ModLoader.get().gatherAndInitializeMods(ModWorkManager.syncExecutor(), ModWorkManager.parallelExecutor(), new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
if (error == null) {
ResourcePackLoader.loadResourcePacks(defaultResourcePacks, ClientModLoader::buildPackFinder);
ModLoader.get().postEvent(new AddPackFindersEvent(PackType.CLIENT_RESOURCES, defaultResourcePacks::addPackFinder));
DataPackConfig.DEFAULT.addModPacks(ResourcePackLoader.getPackNames());
mcResourceManager.registerReloadListener(ClientModLoader::onResourceReload);
mcResourceManager.registerReloadListener(BrandingControl.resourceManagerReloadListener());
ModelLoaderRegistry.init();
}
}
private static CompletableFuture<Void> onResourceReload(final PreparableReloadListener.PreparationBarrier stage, final ResourceManager resourceManager, final ProfilerFiller prepareProfiler, final ProfilerFiller executeProfiler, final Executor asyncExecutor, final Executor syncExecutor) {
return CompletableFuture.runAsync(createRunnableWithCatch(() -> startModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor)), ModWorkManager.parallelExecutor())
.thenCompose(stage::wait)
.thenRunAsync(() -> finishModLoading(ModWorkManager.wrappedExecutor(syncExecutor), asyncExecutor), ModWorkManager.parallelExecutor());
}
private static Runnable createRunnableWithCatch(Runnable r) {
return ()-> {
if (loadingComplete) return;
try {
r.run();
} catch (LoadingFailedException e) {
if (error == null) error = e;
}
};
}
private static void startModLoading(ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor) {
earlyLoaderGUI.handleElsewhere();
createRunnableWithCatch(() -> ModLoader.get().loadMods(syncExecutor, parallelExecutor, new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
}
private static void finishModLoading(ModWorkManager.DrivenExecutor syncExecutor, Executor parallelExecutor)
{
createRunnableWithCatch(() -> ModLoader.get().finishMods(syncExecutor, parallelExecutor, new SpacedRunnable(earlyLoaderGUI::renderTick))).run();
loading = false;
loadingComplete = true;
// reload game settings on main thread
syncExecutor.execute(()->mc.options.load());
}
public static VersionChecker.Status checkForUpdates()
{
boolean anyOutdated = ModList.get().getMods().stream()
.map(VersionChecker::getResult)
.map(result -> result.status())
.anyMatch(status -> status == VersionChecker.Status.OUTDATED || status == VersionChecker.Status.BETA_OUTDATED);
return anyOutdated ? VersionChecker.Status.OUTDATED : null;
}
public static boolean completeModLoading()
{
RenderSystem.disableTexture();
RenderSystem.enableTexture();
List<ModLoadingWarning> warnings = ModLoader.get().getWarnings();
boolean showWarnings = true;
try {
showWarnings = ForgeConfig.CLIENT.showLoadWarnings.get();
} catch (NullPointerException e) {
// We're in an early error state, config is not available. Assume true.
}
if (!showWarnings) {
//User disabled warning screen, as least log them
if (!warnings.isEmpty()) {
LOGGER.warn(LOADING, "Mods loaded with {} warning(s)", warnings.size());
warnings.forEach(warning -> LOGGER.warn(LOADING, warning.formatToString()));
}
warnings = Collections.emptyList(); //Clear warnings, as the user does not want to see them
}
File dumpedLocation = null;
if (error == null) {
// We can finally start the forge eventbus up
MinecraftForge.EVENT_BUS.start();
} else {
// Double check we have the langs loaded for forge
LanguageHook.loadForgeAndMCLangs();
dumpedLocation = CrashReportExtender.dumpModLoadingCrashReport(LOGGER, error, mc.gameDirectory);
}
if (error != null || !warnings.isEmpty()) {
mc.setScreen(new LoadingErrorScreen(error, warnings, dumpedLocation));
return true;
} else {
return false;
}
}
public static void renderProgressText() {
earlyLoaderGUI.renderFromGUI();
}
public static boolean isLoading()
{
return loading;
}
private static RepositorySource buildPackFinder(Map<IModFile, ? extends PathResourcePack> modResourcePacks) {
return (packList, factory) -> clientPackFinder(modResourcePacks, packList, factory);
}
private static void clientPackFinder(Map<IModFile, ? extends PathResourcePack> modResourcePacks, Consumer<Pack> consumer, Pack.PackConstructor factory) {
List<PathResourcePack> hiddenPacks = new ArrayList<>();
for (Entry<IModFile, ? extends PathResourcePack> e : modResourcePacks.entrySet())
{
IModInfo mod = e.getKey().getModInfos().get(0);
final String name = "mod:" + mod.getModId();
final Pack packInfo = Pack.create(name, false, e::getValue, factory, Pack.Position.BOTTOM, PackSource.DEFAULT);
if (packInfo == null) {
// Vanilla only logs an error, instead of propagating, so handle null and warn that something went wrong
ModLoader.get().addWarning(new ModLoadingWarning(mod, ModLoadingStage.ERROR, "fml.modloading.brokenresources", e.getKey()));
continue;
}
LOGGER.debug(CORE, "Generating PackInfo named {} for mod file {}", name, e.getKey().getFilePath());
if (mod.getOwningFile().showAsResourcePack()) {
consumer.accept(packInfo);
} else {
hiddenPacks.add(e.getValue());
}
}
final Pack packInfo = Pack.create("mod_resources", true, () -> new DelegatingResourcePack("mod_resources", "Mod Resources",
new PackMetadataSection(new TranslatableComponent("fml.resources.modresources", hiddenPacks.size()), PackType.CLIENT_RESOURCES.getVersion(SharedConstants.getCurrentVersion())),
hiddenPacks), factory, Pack.Position.BOTTOM, PackSource.DEFAULT);
consumer.accept(packInfo);
}
}
@@ -0,0 +1,156 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* 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.client.loading;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.platform.Window;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Mth;
import net.minecraftforge.fml.StartupMessageManager;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import org.lwjgl.stb.STBEasyFont;
import org.lwjgl.system.MemoryUtil;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.nio.ByteBuffer;
public class EarlyLoaderGUI {
private final Minecraft minecraft;
private final Window window;
private boolean handledElsewhere;
public EarlyLoaderGUI(final Minecraft minecraft) {
this.minecraft = minecraft;
this.window = minecraft.getWindow();
}
@SuppressWarnings("deprecation")
private void setupMatrix() {
RenderSystem.clear(256, Minecraft.ON_OSX);
GL11.glMatrixMode(5889);
GL11.glLoadIdentity();
GL11.glOrtho(0.0D, window.getWidth() / window.getGuiScale(), window.getHeight() / window.getGuiScale(), 0.0D, 1000.0D, 3000.0D);
GL11.glMatrixMode(5888);
GL11.glLoadIdentity();
GL11.glTranslatef(0.0F, 0.0F, -2000.0F);
}
public void handleElsewhere() {
this.handledElsewhere = true;
}
void renderFromGUI() {
renderMessages();
}
@SuppressWarnings("deprecation")
void renderTick() {
if (handledElsewhere) return;
// int guiScale = window.calculateScale(0, false);
// window.setGuiScale(guiScale);
//
// RenderSystem.clearColor(1.0f, 1.0f, 1.0f, 1.0f);
// RenderSystem.clear(GL11.GL_COLOR_BUFFER_BIT, Minecraft.ON_OSX);
// GL11.glPushMatrix();
// setupMatrix();
// renderBackground();
// renderMessages();
// window.updateDisplay();
// GL11.glPopMatrix();
}
private void renderBackground() {
GL11.glBegin(GL11.GL_QUADS);
boolean isDarkBackground = minecraft.options.darkMojangStudiosBackground;
GL11.glColor4f(isDarkBackground ? 0 : (239F / 255F), isDarkBackground ? 0 : (50F / 255F), isDarkBackground ? 0 : (61F / 255F), 1); //Color from LoadingOverlay
GL11.glVertex3f(0, 0, -10);
GL11.glVertex3f(0, window.getGuiScaledHeight(), -10);
GL11.glVertex3f(window.getGuiScaledWidth(), window.getGuiScaledHeight(), -10);
GL11.glVertex3f(window.getGuiScaledWidth(), 0, -10);
GL11.glEnd();
}
private void renderMessages() {
// List<Pair<Integer, StartupMessageManager.Message>> messages = StartupMessageManager.getMessages();
// for (int i = 0; i < messages.size(); i++) {
// boolean nofade = i == 0;
// final Pair<Integer, StartupMessageManager.Message> pair = messages.get(i);
// final float fade = MathHelper.clamp((4000.0f - (float) pair.getLeft() - ( i - 4 ) * 1000.0f) / 5000.0f, 0.0f, 1.0f);
// if (fade <0.01f && !nofade) continue;
// StartupMessageManager.Message msg = pair.getRight();
// renderMessage(msg.getText(), msg.getTypeColour(), ((window.getGuiScaledHeight() - 15) / 10) - i + 1, nofade ? 1.0f : fade);
// }
// List<Pair<Integer, StartupMessageManager.Message>> messages = StartupMessageManager.getMessages();
// for (int i = 0; i < messages.size(); i++) {
// boolean nofade = i == 0;
// final Pair<Integer, StartupMessageManager.Message> pair = messages.get(i);
// final float fade = Mth.clamp((4000.0f - (float) pair.getLeft() - ( i - 4 ) * 1000.0f) / 5000.0f, 0.0f, 1.0f);
// if (fade <0.01f && !nofade) continue;
// StartupMessageManager.Message msg = pair.getRight();
// renderMessage(msg.getText(), msg.getTypeColour(), ((window.getGuiScaledHeight() - 15) / 10) - i + 1, nofade ? 1.0f : fade);
// }
// renderMemoryInfo();
}
private static final float[] memorycolour = new float[] { 0.0f, 0.0f, 0.0f};
private void renderMemoryInfo() {
final MemoryUsage heapusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
final MemoryUsage offheapusage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
final float pctmemory = (float) heapusage.getUsed() / heapusage.getMax();
String memory = String.format("Memory Heap: %d / %d MB (%.1f%%) OffHeap: %d MB", heapusage.getUsed() >> 20, heapusage.getMax() >> 20, pctmemory * 100.0, offheapusage.getUsed() >> 20);
final int i = Mth.hsvToRgb((1.0f - (float)Math.pow(pctmemory, 1.5f)) / 3f, 1.0f, 0.5f);
memorycolour[2] = ((i) & 0xFF) / 255.0f;
memorycolour[1] = ((i >> 8 ) & 0xFF) / 255.0f;
memorycolour[0] = ((i >> 16 ) & 0xFF) / 255.0f;
renderMessage(memory, memorycolour, 1, 1.0f);
}
@SuppressWarnings("deprecation")
void renderMessage(final String message, final float[] colour, int line, float alpha) {
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
// ByteBuffer charBuffer = MemoryUtil.memAlloc(message.length() * 270);
// int quads = STBEasyFont.stb_easy_font_print(0, 0, message, null, charBuffer);
// GL14.glVertexPointer(2, GL11.GL_FLOAT, 16, charBuffer);
//
// RenderSystem.enableBlend();
// RenderSystem.disableTexture();
// // STBEasyFont's quads are in reverse order or what OGGL expects, so it gets culled for facing the wrong way.
// // So Disable culling https://github.com/MinecraftForge/MinecraftForge/pull/6824
// RenderSystem.disableCull();
// GL14.glBlendColor(0,0,0, alpha);
// RenderSystem.blendFunc(GlStateManager.SourceFactor.CONSTANT_ALPHA, GlStateManager.DestFactor.ONE_MINUS_CONSTANT_ALPHA);
// GL11.glColor3f(colour[0],colour[1],colour[2]);
// GL11.glPushMatrix();
// GL11.glTranslatef(10, line * 10, 0);
// GL11.glScalef(1, 1, 0);
// GL11.glDrawArrays(GL11.GL_QUADS, 0, quads * 4);
// GL11.glPopMatrix();
//
// RenderSystem.enableCull();
// GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
// MemoryUtil.memFree(charBuffer);
}
}
@@ -0,0 +1,30 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2021.
*
* 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.client.loading;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
public final class NoVizFallback {
public static LongSupplier fallback(IntSupplier width, IntSupplier height, Supplier<String> title, LongSupplier monitor) {
return ()->org.lwjgl.glfw.GLFW.glfwCreateWindow(width.getAsInt(), height.getAsInt(), title.get(), monitor.getAsLong(), 0L);
}
}