From b7542ae0b1237be539d547bfbefe66ba800f1d8f Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:05:58 -0400 Subject: [PATCH 01/27] Pre splash phases --- .../splash/pre/PreSplashManager.java | 12 +++++++ .../cleanroom/splash/pre/PreSplashPhase.java | 32 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java new file mode 100644 index 000000000..53b0bdec8 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -0,0 +1,12 @@ +package com.cleanroommc.cleanroom.splash.pre; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public final class PreSplashManager { + + private PreSplashManager() { + } + + public static final Logger LOGGER = LogManager.getLogger("Pre Splash"); +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java new file mode 100644 index 000000000..af2da0b89 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java @@ -0,0 +1,32 @@ +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.discovery.CleanroomModDiscoverer; +import net.minecraft.client.Minecraft; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.fml.common.launcher.FMLTweaker; +import net.minecraftforge.fml.relauncher.CoreModManager; + +import java.io.File; + +public enum PreSplashPhase { + + /** + * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) + */ + FML_SETUP, + + /** + * @see CleanroomModDiscoverer#discover() + */ + INITIAL_MOD_SCAN, + + /** + * @see CoreModManager#handleLaunch(File, LaunchClassLoader, FMLTweaker) + */ + CORE_MOD_LAUNCH, + + /** + * @see Minecraft#init() + */ + MINECRAFT_INIT +} From 710d813707d1645407ec237c05c806c534155aa6 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:56:06 -0500 Subject: [PATCH 02/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index 9d446db2d..ee2630b29 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 9d446db2deaa505d5dd66b488a1af8c385ff27de +Subproject commit ee2630b29dd17e26db4c454345436cbc27b7e90b From ca5eaf9bd422af72e6697bc06b673a931e6901c0 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:29:12 -0500 Subject: [PATCH 03/27] feat: add patches to notify the current phase --- .../splash/pre/PreSplashManager.java | 13 +++ .../cleanroom/splash/pre/PreSplashPhase.java | 7 +- .../splash/pre/PreSplashScreenContainer.java | 4 + .../cleanroom/splash/pre/package-info.java | 4 + .../discovery/CleanroomModDiscoverer.java | 4 + .../fml/common/launcher/FMLTweaker.java | 4 + .../fml/relauncher/CoreModManager.java | 8 +- .../net/minecraft/client/Minecraft.java.patch | 96 ++++++++++--------- 8 files changed, 89 insertions(+), 51 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java index 53b0bdec8..afd7125f3 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -1,12 +1,25 @@ package com.cleanroommc.cleanroom.splash.pre; +import com.google.common.base.Preconditions; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; +/** + * This is not a client-side only class, but it's only intended to work for client-side bootstrapping. + */ public final class PreSplashManager { private PreSplashManager() { } + public static final PreSplashManager INSTANCE = new PreSplashManager(); + public static final Logger LOGGER = LogManager.getLogger("Pre Splash"); + + @ApiStatus.Internal + public void notifyPhase(PreSplashPhase phase) { + Preconditions.checkNotNull(phase); + + } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java index af2da0b89..a16bfde22 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java @@ -7,6 +7,7 @@ import net.minecraftforge.fml.relauncher.CoreModManager; import java.io.File; +import java.util.Map; public enum PreSplashPhase { @@ -16,7 +17,7 @@ public enum PreSplashPhase { FML_SETUP, /** - * @see CleanroomModDiscoverer#discover() + * @see CleanroomModDiscoverer#discover(Map) */ INITIAL_MOD_SCAN, @@ -28,5 +29,7 @@ public enum PreSplashPhase { /** * @see Minecraft#init() */ - MINECRAFT_INIT + MINECRAFT_INIT, + + RIGHT_BEFORE_SPLASH } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java new file mode 100644 index 000000000..70233068d --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -0,0 +1,4 @@ +package com.cleanroommc.cleanroom.splash.pre; + +public class PreSplashScreenContainer { +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java new file mode 100644 index 000000000..6598df2f1 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java @@ -0,0 +1,4 @@ +@NullMarked +package com.cleanroommc.cleanroom.splash.pre; + +import org.jspecify.annotations.NullMarked; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java index 662fd4c1c..09915c98b 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java @@ -12,6 +12,8 @@ import com.cleanroommc.cleanmix.CleanMixModContainer; import com.cleanroommc.cleanmix.MixinConfiguration; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.cleanroommc.common.CleanroomContainer; import com.cleanroommc.common.CleanroomEnvironment; import com.cleanroommc.common.ConfigAnytimeContainer; @@ -585,6 +587,8 @@ private void discoverFileDirectorMods(File gameDir, LaunchClassLoader classLoade } private void discover(Map files) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.INITIAL_MOD_SCAN); + CleanroomLog.get().info("Discovering mods"); long startTime = System.nanoTime(); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java index faf27b031..209cef0ce 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java @@ -19,6 +19,8 @@ package net.minecraftforge.fml.common.launcher; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.cleanroommc.common.CleanroomEnvironment; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -144,6 +146,8 @@ else if (arg.contains("=")) @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.FML_SETUP); + FMLLaunchHandler.configureForClientLaunch(classLoader, this); FMLLaunchHandler.appendCoreMods(); } diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java index 04b9a3a47..60f8b4af1 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java @@ -20,6 +20,8 @@ package net.minecraftforge.fml.relauncher; import com.cleanroommc.cleanmix.CleanMixHooks; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.google.common.base.Strings; import com.google.common.collect.*; import com.google.common.primitives.Ints; @@ -174,6 +176,8 @@ public String[] getLaunchArguments() public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); + CoreModManager.mcDir = mcDir; CoreModManager.tweaker = tweaker; @@ -222,7 +226,7 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw { for (String path : System.getProperty("crl.dev.extrapath").split(File.pathSeparator)) { - try + try { Launch.classLoader.addURL(new File(path).getAbsoluteFile().toURI().toURL()); FMLLog.log.debug("Adding extra path {} to class path", path); @@ -290,7 +294,7 @@ public static boolean isCoreModLoaded(String coreModClass) private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) { - if (loadedPlugins.contains(coreModClass)) + if (loadedPlugins.contains(coreModClass)) { return null; } diff --git a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch index fd5afa422..3f4463212 100644 --- a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch +++ b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch @@ -67,15 +67,16 @@ this.isDemo = gameConfig.gameInfo.isDemo; this.displayWidth = gameConfig.displayInfo.width > 0 ? gameConfig.displayInfo.width : 1; this.displayHeight = gameConfig.displayInfo.height > 0 ? gameConfig.displayInfo.height : 1; -@@ -447,6 +436,7 @@ +@@ -447,6 +436,8 @@ /** Starts the game: initializes the canvas, the title, the settings, etcetera. */ private void init() throws IOException, LWJGLException { ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyPhase(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT); + com.cleanroommc.client.sdl.SDL.ensureVideo(); this.gameSettings = new GameSettings(this, this.gameDir); this.creativeSettings = new CreativeSettings(this, this.gameDir); this.defaultResourcePacks.add(this.defaultResourcePack); -@@ -455,8 +445,9 @@ +@@ -455,8 +446,9 @@ this.displayWidth = this.gameSettings.overrideWidth; this.displayHeight = this.gameSettings.overrideHeight; } @@ -87,7 +88,7 @@ this.setWindowIcon(); this.setInitialDisplayMode(); this.createDisplay(); -@@ -468,12 +459,13 @@ +@@ -468,12 +460,14 @@ this.fileResourcepacks, new File(this.gameDir, "server-resource-packs"), this.defaultResourcePack, this.metadataSerializer, this.gameSettings ); this.resourceManager = new SimpleReloadableResourceManager(this.metadataSerializer); @@ -95,6 +96,7 @@ this.languageManager = new LanguageManager(this.metadataSerializer, this.gameSettings.language); this.resourceManager.registerReloadListener(this.languageManager); - this.refreshResources(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyPhase(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.RIGHT_BEFORE_SPLASH); + net.minecraftforge.fml.client.FMLClientHandler.instance().beginMinecraftLoading(this, this.defaultResourcePacks, this.resourceManager, this.metadataSerializer); this.renderEngine = new TextureManager(this.resourceManager); this.resourceManager.registerReloadListener(this.renderEngine); @@ -103,7 +105,7 @@ this.skinManager = new SkinManager(this.renderEngine, new File(this.fileAssets, "skins"), this.sessionService); this.saveLoader = new AnvilSaveConverter(new File(this.gameDir, "saves"), this.dataFixer); this.soundHandler = new SoundHandler(this.resourceManager, this.gameSettings); -@@ -491,6 +483,8 @@ +@@ -491,6 +485,8 @@ this.resourceManager.registerReloadListener(new GrassColorReloadListener()); this.resourceManager.registerReloadListener(new FoliageColorReloadListener()); this.mouseHelper = new MouseHelper(); @@ -112,7 +114,7 @@ this.checkGLError("Pre startup"); GlStateManager.enableTexture2D(); GlStateManager.shadeModel(7425); -@@ -504,19 +498,24 @@ +@@ -504,19 +500,24 @@ GlStateManager.loadIdentity(); GlStateManager.matrixMode(5888); this.checkGLError("Startup"); @@ -137,14 +139,14 @@ this.entityRenderer = new EntityRenderer(this, this.resourceManager); this.resourceManager.registerReloadListener(this.entityRenderer); this.blockRenderDispatcher = new BlockRendererDispatcher(this.modelManager.getBlockModelShapes(), this.blockColors); -@@ -527,18 +526,26 @@ +@@ -527,18 +528,26 @@ this.resourceManager.registerReloadListener(this.searchTreeManager); GlStateManager.viewport(0, 0, this.displayWidth, this.displayHeight); this.effectRenderer = new ParticleManager(this.world, this.renderEngine); + net.minecraftforge.fml.client.SplashProgress.resume(); + net.minecraftforge.fml.common.ProgressManager.pop(bar); + net.minecraftforge.fml.client.FMLClientHandler.instance().finishMinecraftLoading(); -+ if (!net.minecraftforge.fml.client.FMLClientHandler.instance().hasError()) com.cleanroommc.kirino.ImmediateClientServices.refreshMcFontIfNeeded(); ++ com.cleanroommc.kirino.ImmediateClientServices.refreshMcFontIfNeeded(); + net.minecraftforge.client.ForgeHooksClient.clearTaskbarProgress(); this.checkGLError("Post startup"); - this.ingameGUI = new GuiIngame(this); @@ -167,7 +169,7 @@ if (this.gameSettings.fullScreen && !this.fullscreen) { this.toggleFullscreen(); } -@@ -599,34 +606,22 @@ +@@ -599,34 +608,22 @@ private void createDisplay() throws LWJGLException { Display.setResizable(true); @@ -213,7 +215,7 @@ } } -@@ -640,7 +635,7 @@ +@@ -640,7 +637,7 @@ inputstream = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_16x16.png")); inputstream1 = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_32x32.png")); if (inputstream != null && inputstream1 != null) { @@ -222,7 +224,7 @@ } } catch (IOException ioexception) { LOGGER.error("Couldn't set icon", ioexception); -@@ -679,6 +674,7 @@ +@@ -679,6 +676,7 @@ } private void startTimerHackThread() { @@ -230,7 +232,7 @@ Thread thread = new Thread("Timer hack thread") { @Override public void run() { -@@ -691,6 +687,7 @@ +@@ -691,6 +689,7 @@ } }; thread.setDaemon(true); @@ -238,7 +240,7 @@ thread.start(); } -@@ -704,22 +701,26 @@ +@@ -704,22 +703,26 @@ File file1 = new File(getMinecraft().gameDir, "crash-reports"); File file2 = new File(file1, "crash-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + "-client.txt"); Bootstrap.printToSYSOUT(crashReportIn.getCompleteReport()); @@ -268,7 +270,7 @@ public void refreshResources() { List list = Lists.newArrayList(this.defaultResourcePacks); if (this.integratedServer != null) { -@@ -902,16 +903,22 @@ +@@ -902,16 +905,22 @@ * @param guiScreenIn The {@link GuiScreen} to display. If it is {@code null}, any open GUI will be closed. */ public void displayGuiScreen(@Nullable GuiScreen guiScreenIn) { @@ -295,7 +297,7 @@ if (guiScreenIn instanceof GuiMainMenu || guiScreenIn instanceof GuiMultiplayer) { this.gameSettings.showDebugInfo = false; this.ingameGUI.getChatGUI().clearChatMessages(true); -@@ -962,7 +969,8 @@ +@@ -962,7 +971,8 @@ this.soundHandler.unloadSounds(); } finally { @@ -305,7 +307,7 @@ if (!this.hasCrashed) { System.exit(0); } -@@ -980,6 +988,8 @@ +@@ -980,6 +990,8 @@ } this.timer.updateTimer(); @@ -314,7 +316,7 @@ this.profiler.startSection("scheduledExecutables"); synchronized (this.scheduledTasks) { while (!this.scheduledTasks.isEmpty()) { -@@ -999,7 +1009,7 @@ +@@ -999,7 +1011,7 @@ long i1 = System.nanoTime() - l; this.checkGLError("Pre render"); this.profiler.endStartSection("sound"); @@ -323,7 +325,7 @@ this.profiler.endSection(); this.profiler.startSection("render"); GlStateManager.pushMatrix(); -@@ -1009,11 +1019,13 @@ +@@ -1009,11 +1021,13 @@ GlStateManager.enableTexture2D(); this.profiler.endSection(); if (!this.skipRenderWorld) { @@ -337,7 +339,7 @@ } this.profiler.endSection(); -@@ -1096,7 +1108,7 @@ +@@ -1096,7 +1110,7 @@ } protected void checkWindowResize() { @@ -346,7 +348,7 @@ int i = this.displayWidth; int j = this.displayHeight; this.displayWidth = Display.getWidth(); -@@ -1308,9 +1320,9 @@ +@@ -1308,9 +1322,9 @@ if (this.leftClickCounter <= 0 && !this.player.isHandActive()) { if (leftClick && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -359,7 +361,7 @@ this.player.swingArm(EnumHand.MAIN_HAND); } } else { -@@ -1333,7 +1345,8 @@ +@@ -1333,7 +1347,8 @@ break; case BLOCK: BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -369,7 +371,7 @@ this.playerController.clickBlock(blockpos, this.objectMouseOver.sideHit); break; } -@@ -1343,6 +1356,7 @@ +@@ -1343,6 +1358,7 @@ } this.player.resetCooldown(); @@ -377,7 +379,7 @@ } this.player.swingArm(EnumHand.MAIN_HAND); -@@ -1399,6 +1413,7 @@ +@@ -1399,6 +1415,7 @@ } } @@ -385,7 +387,7 @@ if (!itemstack.isEmpty() && this.playerController.processRightClick(this.player, this.world, enumhand) == EnumActionResult.SUCCESS) { this.entityRenderer.itemRenderer.resetEquippedProgress(enumhand); -@@ -1414,7 +1429,12 @@ +@@ -1414,7 +1431,12 @@ try { this.fullscreen = !this.fullscreen; this.gameSettings.fullScreen = this.fullscreen; @@ -399,7 +401,7 @@ this.updateDisplayMode(); this.displayWidth = Display.getDisplayMode().getWidth(); this.displayHeight = Display.getDisplayMode().getHeight(); -@@ -1444,7 +1464,17 @@ +@@ -1444,7 +1466,17 @@ this.updateFramebufferSize(); } @@ -418,7 +420,7 @@ Display.setVSyncEnabled(this.gameSettings.enableVsync); this.updateDisplay(); } catch (Exception exception) { -@@ -1483,6 +1513,8 @@ +@@ -1483,6 +1515,8 @@ this.rightClickDelayTimer--; } @@ -427,7 +429,7 @@ this.profiler.startSection("gui"); if (!this.isGamePaused) { this.ingameGUI.updateTick(); -@@ -1632,6 +1664,7 @@ +@@ -1632,6 +1666,7 @@ } this.profiler.endSection(); @@ -435,7 +437,7 @@ this.systemTime = getSystemTime(); } -@@ -1705,6 +1738,7 @@ +@@ -1705,6 +1740,7 @@ } } } @@ -443,7 +445,7 @@ } this.processKeyBinds(); -@@ -1896,6 +1930,8 @@ +@@ -1896,6 +1932,8 @@ private void runTickMouse() throws IOException { while (Mouse.next()) { @@ -452,7 +454,7 @@ int i = Mouse.getEventButton(); KeyBinding.setKeyBindState(i - 100, Mouse.getEventButtonState()); if (Mouse.getEventButtonState()) { -@@ -1931,6 +1967,7 @@ +@@ -1931,6 +1969,7 @@ this.currentScreen.handleMouseInput(); } } @@ -460,7 +462,7 @@ } } -@@ -1949,6 +1986,7 @@ +@@ -1949,6 +1988,7 @@ /** Arguments: World foldername, World ingame name, WorldSettings */ public void launchIntegratedServer(String folderName, String worldName, @Nullable WorldSettings worldSettingsIn) { @@ -468,7 +470,7 @@ this.loadWorld(null); System.gc(); ISaveHandler isavehandler = this.saveLoader.getSaveLoader(folderName, false); -@@ -1990,6 +2028,11 @@ +@@ -1990,6 +2030,11 @@ this.loadingScreen.displaySavingString(I18n.format("menu.loadingLevel")); while (!this.integratedServer.serverIsInRunLoop()) { @@ -480,7 +482,7 @@ String s = this.integratedServer.getUserMessage(); if (s != null) { this.loadingScreen.displayLoadingString(I18n.format(s)); -@@ -2007,8 +2050,13 @@ +@@ -2007,8 +2052,13 @@ SocketAddress socketaddress = this.integratedServer.getNetworkSystem().addLocalEndpoint(); NetworkManager networkmanager = NetworkManager.provideLocalClient(socketaddress); networkmanager.setNetHandler(new NetHandlerLoginClient(networkmanager, this, null)); @@ -496,7 +498,7 @@ this.networkManager = networkmanager; } -@@ -2019,6 +2067,8 @@ +@@ -2019,6 +2069,8 @@ /** par2Str is displayed on the loading screen to the user unloads the current world first */ public void loadWorld(@Nullable WorldClient worldClientIn, String loadingMessage) { @@ -505,7 +507,7 @@ if (worldClientIn == null) { NetHandlerPlayClient nethandlerplayclient = this.getConnection(); if (nethandlerplayclient != null) { -@@ -2027,6 +2077,14 @@ +@@ -2027,6 +2079,14 @@ if (this.integratedServer != null && this.integratedServer.isAnvilFileSet()) { this.integratedServer.initiateShutdown(); @@ -520,7 +522,7 @@ } this.integratedServer = null; -@@ -2047,6 +2105,7 @@ +@@ -2047,6 +2107,7 @@ this.ingameGUI.resetPlayersOverlayFooterHeader(); this.setServerData(null); this.integratedServerIsRunning = false; @@ -528,7 +530,7 @@ } this.soundHandler.stopSounds(); -@@ -2060,6 +2119,8 @@ +@@ -2060,6 +2121,8 @@ } TileEntityRendererDispatcher.instance.setWorld(worldClientIn); @@ -537,7 +539,7 @@ if (worldClientIn != null) { if (!this.integratedServerIsRunning) { AuthenticationService authenticationservice = new YggdrasilAuthenticationService(this.proxy, UUID.randomUUID().toString()); -@@ -2112,6 +2173,7 @@ +@@ -2112,6 +2175,7 @@ this.player == null ? new RecipeBook() : this.player.getRecipeBook() ); this.player.getDataManager().setEntryValues(entityplayersp.getDataManager().getAll()); @@ -545,7 +547,7 @@ this.player.dimension = dimension; this.renderViewEntity = this.player; this.player.preparePlayerToSpawn(); -@@ -2153,110 +2215,8 @@ +@@ -2153,110 +2217,8 @@ /** Called when user clicked he's mouse middle button (pick block) */ private void middleClickMouse() { if (this.objectMouseOver != null && this.objectMouseOver.typeOfHit != RayTraceResult.Type.MISS) { @@ -658,7 +660,7 @@ } } -@@ -2288,12 +2248,16 @@ +@@ -2288,12 +2250,16 @@ }); theCrash.getCategory().addDetail("LWJGL", new ICrashReportDetail() { public String call() throws Exception { @@ -677,7 +679,7 @@ } }); theCrash.getCategory().addDetail("GL Caps", new ICrashReportDetail() { -@@ -2372,6 +2336,7 @@ +@@ -2372,6 +2338,7 @@ return instance; } @@ -685,7 +687,7 @@ public ListenableFuture scheduleResourcesRefresh() { return this.addScheduledTask(new Runnable() { @Override -@@ -2536,15 +2501,8 @@ +@@ -2536,15 +2503,8 @@ /** Used in the usage snooper. */ public static int getGLMaximumTextureSize() { @@ -703,7 +705,7 @@ } /** Returns whether snooping is enabled or not. */ -@@ -2658,6 +2616,9 @@ +@@ -2658,6 +2618,9 @@ } if (this.player != null) { @@ -713,7 +715,7 @@ if (this.player.world.provider instanceof WorldProviderHell) { return MusicTicker.MusicType.NETHER; } else if (this.player.world.provider instanceof WorldProviderEnd) { -@@ -2677,9 +2638,9 @@ +@@ -2677,9 +2640,9 @@ if (i != 0 && !Keyboard.isRepeatEvent()) { if (!(this.currentScreen instanceof GuiControls) || ((GuiControls)this.currentScreen).time <= getSystemTime() - 20L) { if (Keyboard.getEventKeyState()) { @@ -725,7 +727,7 @@ this.ingameGUI .getChatGUI() .printChatMessage(ScreenShotHelper.saveScreenshot(this.gameDir, this.displayWidth, this.displayHeight, this.framebuffer)); -@@ -2691,7 +2652,7 @@ +@@ -2691,7 +2654,7 @@ ((ScreenChatOptions)this.currentScreen).updateNarratorButton(); } } @@ -734,7 +736,7 @@ } } } -@@ -2720,7 +2681,7 @@ +@@ -2720,7 +2683,7 @@ try { return Futures.immediateFuture(callableToSchedule.call()); } catch (Exception exception) { @@ -743,7 +745,7 @@ } } else { ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callableToSchedule); -@@ -2798,11 +2759,24 @@ +@@ -2798,11 +2761,24 @@ return this.timer.elapsedPartialTicks; } @@ -769,7 +771,7 @@ public boolean isReducedDebug() { return this.player != null && this.player.hasReducedDebug() || this.gameSettings.reducedDebugInfo; } -@@ -2814,4 +2788,8 @@ +@@ -2814,4 +2790,8 @@ public Tutorial getTutorial() { return this.tutorial; } From 0bb5819cf9290cc3d5c148e9e4e8bd9c55d31045 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:41:38 -0500 Subject: [PATCH 04/27] chore: fix patches; add back `hasError` check before `refreshMcFontIfNeeded` --- .../minecraft/patches/net/minecraft/client/Minecraft.java.patch | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch index 3f4463212..6d370d26a 100644 --- a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch +++ b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch @@ -146,7 +146,7 @@ + net.minecraftforge.fml.client.SplashProgress.resume(); + net.minecraftforge.fml.common.ProgressManager.pop(bar); + net.minecraftforge.fml.client.FMLClientHandler.instance().finishMinecraftLoading(); -+ com.cleanroommc.kirino.ImmediateClientServices.refreshMcFontIfNeeded(); ++ if (!net.minecraftforge.fml.client.FMLClientHandler.instance().hasError()) com.cleanroommc.kirino.ImmediateClientServices.refreshMcFontIfNeeded(); + net.minecraftforge.client.ForgeHooksClient.clearTaskbarProgress(); this.checkGLError("Post startup"); - this.ingameGUI = new GuiIngame(this); From dd3c30eaa68bc95d7a8a2027847f958ea9cd05ba Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:19:22 -0500 Subject: [PATCH 05/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index ee2630b29..dfea9d6e0 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit ee2630b29dd17e26db4c454345436cbc27b7e90b +Subproject commit dfea9d6e00f2ea41bb914e0db56f835d2f05f836 From e7779cdfe0c4d4610e9238361f7e1aab4feded49 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:16:28 -0500 Subject: [PATCH 06/27] feat: dedicated rendering thread, sdl window, gl context. isolate class loading --- .../splash/pre/PreSplashClassLoader.java | 62 ++ .../splash/pre/PreSplashFontResources.java | 45 ++ .../splash/pre/PreSplashManager.java | 42 +- .../cleanroom/splash/pre/PreSplashPhase.java | 17 +- .../splash/pre/PreSplashPhaseFSM.java | 52 ++ .../splash/pre/PreSplashScreenContainer.java | 546 +++++++++++++++++- .../cleanroom/splash/pre/package-info.java | 10 + .../discovery/CleanroomModDiscoverer.java | 6 +- .../fml/client/FMLClientHandler.java | 3 + .../fml/common/launcher/FMLTweaker.java | 3 + .../fml/relauncher/CoreModManager.java | 12 +- 11 files changed, 782 insertions(+), 16 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java new file mode 100644 index 000000000..974dd15e0 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Motivation is to keep pre splash's untransformed LWJGL3 classes out of the game's loader. + */ +final class PreSplashClassLoader extends ClassLoader { + + PreSplashClassLoader(ClassLoader parent) { + super(parent); + } + + private static boolean isIsolated(String name) { + return name.startsWith("org.lwjgl.") + || name.startsWith("com.cleanroommc.kirino.") + || name.startsWith("com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer$") + || name.equals("com.cleanroommc.cleanroom.splash.pre.PreSplashFontResources"); + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (!isIsolated(name)) { + return super.loadClass(name, resolve); + } + + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name); + + if (loaded == null) { + String resource = name.replace('.', '/') + ".class"; + try (InputStream input = getParent().getResourceAsStream(resource)) { + if (input == null) { + throw new ClassNotFoundException(name); + } + + byte[] bytes = input.readAllBytes(); + loaded = defineClass(name, bytes, 0, bytes.length); + } catch (IOException e) { + throw new ClassNotFoundException(name, e); + } + } + + if (resolve) { + resolveClass(loaded); + } + + return loaded; + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java new file mode 100644 index 000000000..3d329b272 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.kirino.ui.font.McTtfFontManager; +import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; + +import com.google.common.base.Preconditions; +import org.jspecify.annotations.Nullable; + +import net.minecraft.client.resources.DefaultResourcePack; +import net.minecraft.client.resources.ResourceIndex; +import net.minecraft.client.resources.ResourceIndexFolder; + +import java.io.File; + +/** + *

Note: Loaded only by the screen thread.

+ */ +final class PreSplashFontResources { + + private PreSplashFontResources() { + } + + static McTtfFontManager create(File assetsDirectory, @Nullable String assetIndex, FreeTypeManager freeType) { + Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkNotNull(freeType); + + ResourceIndex index = assetIndex == null + ? new ResourceIndexFolder(assetsDirectory) + : new ResourceIndex(assetsDirectory, assetIndex); + + McTtfFontManager fonts = new McTtfFontManager(new DefaultResourcePack(index), freeType); + fonts.loggerName = "pre_splash"; + return fonts; + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java index afd7125f3..0aaf159b2 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -1,25 +1,53 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + package com.cleanroommc.cleanroom.splash.pre; import com.google.common.base.Preconditions; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; /** * This is not a client-side only class, but it's only intended to work for client-side bootstrapping. */ public final class PreSplashManager { - private PreSplashManager() { - } - public static final PreSplashManager INSTANCE = new PreSplashManager(); - public static final Logger LOGGER = LogManager.getLogger("Pre Splash"); + private final PreSplashPhaseFSM fsm = new PreSplashPhaseFSM(); + private volatile @Nullable PreSplashPhase currentPhase = null; + private PreSplashManager() { + } + + /** + * Thread-safe. + * + * @param phase The next observed phase + */ @ApiStatus.Internal - public void notifyPhase(PreSplashPhase phase) { + public synchronized void notifyPhase(PreSplashPhase phase) { Preconditions.checkNotNull(phase); + Preconditions.checkState(phase == fsm.getState(), + "Expected pre splash phase: %s; Observed: %s", fsm.getState(), phase); + fsm.next(); + currentPhase = phase; + } + + /** + * Thread-safe. Only intended to be read by {@link PreSplashScreenContainer}. + * The screen starts after the first phase has been published. + */ + @ApiStatus.Internal + PreSplashPhase readPhase() { + return Preconditions.checkNotNull(currentPhase); } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java index a16bfde22..15494cd3a 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhase.java @@ -1,13 +1,23 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + package com.cleanroommc.cleanroom.splash.pre; import com.cleanroommc.discovery.CleanroomModDiscoverer; + import net.minecraft.client.Minecraft; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraftforge.fml.common.launcher.FMLTweaker; import net.minecraftforge.fml.relauncher.CoreModManager; import java.io.File; -import java.util.Map; public enum PreSplashPhase { @@ -17,7 +27,7 @@ public enum PreSplashPhase { FML_SETUP, /** - * @see CleanroomModDiscoverer#discover(Map) + * @see CleanroomModDiscoverer#CleanroomModDiscoverer() */ INITIAL_MOD_SCAN, @@ -31,5 +41,8 @@ public enum PreSplashPhase { */ MINECRAFT_INIT, + /** + * @see Minecraft#init() + */ RIGHT_BEFORE_SPLASH } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java new file mode 100644 index 000000000..4a5604c71 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPhaseFSM.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.cleanroommc.kirino.schemata.fsm.FiniteStateMachine; + +import com.google.common.base.Preconditions; + +final class PreSplashPhaseFSM { + + private final FiniteStateMachine fsm; + + private boolean finished = false; + + PreSplashPhaseFSM() { + fsm = FiniteStateMachine.BuilderImpl + .enumIntStateMachine(PreSplashPhase.class, 0, 0) + .initialState(PreSplashPhase.FML_SETUP) + .addTransition(PreSplashPhase.FML_SETUP, 0, PreSplashPhase.INITIAL_MOD_SCAN) + .addTransition(PreSplashPhase.INITIAL_MOD_SCAN, 0, PreSplashPhase.CORE_MOD_LAUNCH) + .addTransition(PreSplashPhase.CORE_MOD_LAUNCH, 0, PreSplashPhase.MINECRAFT_INIT) + .addTransition(PreSplashPhase.MINECRAFT_INIT, 0, PreSplashPhase.RIGHT_BEFORE_SPLASH) + .error((state, input) -> { + throw new RuntimeException(String.format( + "An error occurred inside PreSplashPhaseFSM. The input=%d leads to a non-existent route. Current state=%s.", input, state)); + }) + .validate() + .build(); + } + + public PreSplashPhase getState() { + return fsm.state(); + } + + public void next() { + Preconditions.checkState(!finished); + + if (fsm.state() == PreSplashPhase.RIGHT_BEFORE_SPLASH) { + finished = true; + } else { + fsm.accept(0); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 70233068d..ff7d80160 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -1,4 +1,548 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + package com.cleanroommc.cleanroom.splash.pre; -public class PreSplashScreenContainer { +import com.cleanroommc.anone.reveal.ReflectiveInvocation; +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.GLResourceManager; +import com.cleanroommc.kirino.gl.buffer.view.VBOView; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; +import com.cleanroommc.kirino.gl.vao.attribute.Stride; +import com.cleanroommc.kirino.ui.font.McTtfFontManager; +import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; +import com.cleanroommc.kirino.ui.simpletext.ST_Config; +import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; +import com.cleanroommc.kirino.ui.simpletext.SimpleTextRuntime; +import com.cleanroommc.kirino.ui.simpletext.atlas.Tex2DArrayGlyphAtlas; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextProducer; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; +import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; +import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; +import com.cleanroommc.mcttf.glyph.GlyphBuilder; + +import com.google.common.base.Preconditions; +import net.minecraft.client.Minecraft; +import net.minecraft.client.resources.IReloadableResourceManager; +import net.minecraft.client.resources.data.MetadataSerializer; +import net.minecraft.launchwrapper.LaunchClassLoader; +import net.minecraftforge.fml.common.launcher.FMLTweaker; +import net.minecraftforge.fml.client.FMLClientHandler; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; +import org.jspecify.annotations.Nullable; + +import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL11; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.sdl.SDLEvents; +import org.lwjgl.sdl.SDLHints; +import org.lwjgl.sdl.SDLInit; +import org.lwjgl.sdl.SDLVideo; +import org.lwjgl.sdl.SDL_Event; +import org.lwjgl.sdl.SDL_EventFilter; +import org.lwjgl.sdl.SDL_Rect; +import org.lwjgl.system.Configuration; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.ThreadLocalUtil; +import org.lwjgl.util.freetype.FreeType; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.IntBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** + * It owns the temporary window, isolated class loading, GL context, and all rendering resources. + */ +public final class PreSplashScreenContainer { + + private static @Nullable PreSplashScreenContainer instance; + + public static final Logger LOGGER = LogManager.getLogger("Pre Splash Screen"); + + private static final int WIDTH = 720; + private static final int HEIGHT = 360; + private static final float SCREEN_PERCENTAGE = 0.35f; + private static final float UI_SCALE = 1.15f; + + private static final int INITIAL_WAIT_SECOND = 10; + + private final Thread gameThread; + private final Thread thread; + private final Thread shutdownHook; + + private final CountDownLatch nativeReady = new CountDownLatch(1); + private final CountDownLatch firstFrameReady = new CountDownLatch(1); + + private final File assetsDirectory; + private final @Nullable String assetIndex; + + private volatile boolean running = true; + + /** + * Must be called on the game thread. + * + * @see #start(File, String) + */ + private PreSplashScreenContainer(File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(assetsDirectory); + + gameThread = Thread.currentThread(); + this.assetsDirectory = assetsDirectory; + this.assetIndex = assetIndex; + thread = new Thread(this::run, "Pre Splash Renderer"); + thread.setDaemon(true); + shutdownHook = new Thread(this::stopAndWait, "Pre Splash Shutdown"); + } + + /** + * Called only from the client tweaker, right after publishing {@link PreSplashPhase#FML_SETUP}. + * + * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) + */ + @ApiStatus.Internal + public static synchronized void start(File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkState(instance == null, "Pre splash has already started."); + + PreSplashScreenContainer screen = new PreSplashScreenContainer(assetsDirectory, assetIndex); + instance = screen; + + Runtime.getRuntime().addShutdownHook(screen.shutdownHook); + screen.thread.start(); // this::run + + // wait for native initialization + boolean interrupted = false; + while (true) { + try { + screen.nativeReady.await(); + screen.firstFrameReady.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (screen.running) { + try { + TimeUnit.SECONDS.sleep(INITIAL_WAIT_SECOND); + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + /** + * Called only from the client handler, right after publishing {@link PreSplashPhase#RIGHT_BEFORE_SPLASH}. + * + * @see FMLClientHandler#beginMinecraftLoading(Minecraft, List, IReloadableResourceManager, MetadataSerializer) + */ + @ApiStatus.Internal + public static synchronized void finish() { + if (instance == null) { + return; + } + + instance.stopAndWait(); + } + + private void stopAndWait() { + running = false; + LockSupport.unpark(thread); + + boolean interrupted = false; + while (thread.isAlive()) { + try { + thread.join(); + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + private void run() { + Thread renderThread = Thread.currentThread(); + ClassLoader previousContextLoader = renderThread.getContextClassLoader(); + + try { + ClassLoader loader = new PreSplashClassLoader(PreSplashScreenContainer.class.getClassLoader()); + renderThread.setContextClassLoader(loader); + + Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$Renderer", true, loader); + Runnable render = (Runnable) renderer.getConstructor( + File.class, + String.class, + BooleanSupplier.class, + Supplier.class, + Runnable.class, + Runnable.class, + Runnable.class).newInstance( + assetsDirectory, + assetIndex, + (BooleanSupplier) () -> running && gameThread.isAlive(), + (Supplier) PreSplashManager.INSTANCE::readPhase, + (Runnable) () -> running = false, + (Runnable) nativeReady::countDown, + (Runnable) firstFrameReady::countDown); + + // ENTRYPOINT + render.run(); + + } catch (Throwable failure) { + LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); + } finally { + running = false; + nativeReady.countDown(); + firstFrameReady.countDown(); + renderThread.setContextClassLoader(previousContextLoader); + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException ignored) { + // if shutdown has already begun + } + } + } + + /** + * Defined only by {@link PreSplashClassLoader}. + * + * @see PreSplashScreenContainer#run() + */ + @ApiStatus.Internal + public static final class Renderer implements Runnable { + + private final File assetsDirectory; + private final @Nullable String assetIndex; + private final BooleanSupplier running; + private final Supplier phase; + private final Runnable stop; + private final Runnable nativeReady; + private final Runnable firstFrameReady; + + @ReflectiveInvocation + public Renderer( + File assetsDirectory, + @Nullable String assetIndex, + BooleanSupplier running, + Supplier phase, + Runnable stop, + Runnable nativeReady, + Runnable firstFrameReady) { + + Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkNotNull(running); + Preconditions.checkNotNull(phase); + Preconditions.checkNotNull(stop); + Preconditions.checkNotNull(nativeReady); + Preconditions.checkNotNull(firstFrameReady); + + this.assetsDirectory = assetsDirectory; + this.assetIndex = assetIndex; + this.running = running; + this.phase = phase; + this.stop = stop; + this.nativeReady = nativeReady; + this.firstFrameReady = firstFrameReady; + } + + private static void checkSDL(boolean success, String operation) { + Preconditions.checkState(success, "%s: %s", operation, SDLError.SDL_GetError()); + } + + /** + * @see PreSplashScreenContainer#run() + */ + @Override + public void run() { + long window = 0; + long context = 0; + boolean videoInitialized = false; + SDL_EventFilter watch = null; + String originalLibraryPath = System.getProperty("org.lwjgl.librarypath"); + boolean initialized = false; + + try { + // configure this loader's (PreSplashClassLoader) LWJGL copy + Configuration.LIBRARY_PATH.set(null); + Configuration.SHARED_LIBRARY_EXTRACT_PATH.set(null); + Configuration.SHARED_LIBRARY_EXTRACT_DIRECTORY.set("cleanroom-pre-splash"); + Configuration.SHARED_LIBRARY_EXTRACT_FORCE.set(true); + + // prefer native Wayland over XWayland + if (System.getenv("WAYLAND_DISPLAY") != null && System.getenv("SDL_VIDEODRIVER") == null) { + if (!SDLHints.SDL_SetHintWithPriority(SDLHints.SDL_HINT_VIDEO_DRIVER, "wayland,x11", SDLHints.SDL_HINT_DEFAULT)) { + LOGGER.debug("Could not apply pre splash video driver preference; keeping the configured driver."); + } + } + + checkSDL(SDLInit.SDL_InitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS), "SDL_InitSubSystem"); + + videoInitialized = true; + + SDLVideo.SDL_GL_ResetAttributes(); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MAJOR_VERSION, 4), "GL major version"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MINOR_VERSION, 6), "GL minor version"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_PROFILE_MASK, SDLVideo.SDL_GL_CONTEXT_PROFILE_CORE), "GL profile"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_DOUBLEBUFFER, 1), "GL double buffering"); + + int display = SDLVideo.SDL_GetPrimaryDisplay(); + Preconditions.checkState(display != 0, "SDL_GetPrimaryDisplay: %s", SDLError.SDL_GetError()); + + // must not be SDL.window() which belongs to Minecraft + try (MemoryStack stack = MemoryStack.stackPush()) { + SDL_Rect bounds = SDL_Rect.malloc(stack); + checkSDL(SDLVideo.SDL_GetDisplayBounds(display, bounds), "SDL_GetDisplayBounds"); + + float scale = Math.min((float) bounds.w() / WIDTH, (float) bounds.h() / HEIGHT) * SCREEN_PERCENTAGE; + int windowWidth = Math.max(1, Math.round(WIDTH * scale)); + int windowHeight = Math.max(1, Math.round(HEIGHT * scale)); + + window = SDLVideo.SDL_CreateWindow("Cleanroom Pre Splash", windowWidth, windowHeight, + SDLVideo.SDL_WINDOW_OPENGL + | SDLVideo.SDL_WINDOW_HIGH_PIXEL_DENSITY + | SDLVideo.SDL_WINDOW_HIDDEN + | SDLVideo.SDL_WINDOW_NOT_FOCUSABLE + | SDLVideo.SDL_WINDOW_ALWAYS_ON_TOP); + + Preconditions.checkState(window != 0, "SDL_CreateWindow: %s", SDLError.SDL_GetError()); + + // fixed size window + checkSDL(SDLVideo.SDL_SetWindowMinimumSize(window, windowWidth, windowHeight), "SDL_SetWindowMinimumSize"); + checkSDL(SDLVideo.SDL_SetWindowMaximumSize(window, windowWidth, windowHeight), "SDL_SetWindowMaximumSize"); + } + + // Wayland does not support explicit positioning + String videoDriver = SDLVideo.SDL_GetCurrentVideoDriver(); + Preconditions.checkState(videoDriver != null, "SDL video driver is not initialized."); + if (!"wayland".equals(videoDriver)) { + int centered = SDLVideo.SDL_WINDOWPOS_CENTERED_DISPLAY(display); + if (!SDLVideo.SDL_SetWindowPosition(window, centered, centered)) { + LOGGER.debug("Could not center pre splash window: {}", SDLError.SDL_GetError()); + } + } + + context = SDLVideo.SDL_GL_CreateContext(window); + Preconditions.checkState(context != 0, "SDL_GL_CreateContext: %s", SDLError.SDL_GetError()); + checkSDL(SDLVideo.SDL_GL_MakeCurrent(window, context), "SDL_GL_MakeCurrent"); + // todo: implement multi gl backend + Preconditions.checkState(GL.createCapabilities().OpenGL46, "Pre splash requires OpenGL 4.6."); + + // release LWJGL's global table so the game's LWJGL can initialize + ThreadLocalUtil.setFunctionMissingAddresses(0); + + if (!SDLVideo.SDL_GL_SetSwapInterval(0)) { + LOGGER.debug("Could not disable pre splash VSync: {}", SDLError.SDL_GetError()); + } + + SDLVideo.SDL_GL_ResetAttributes(); + + int windowId = SDLVideo.SDL_GetWindowID(window); + checkSDL(windowId != 0, "SDL_GetWindowID"); + + watch = SDL_EventFilter.create((_, address) -> { + // borrowed. must not close + SDL_Event event = SDL_Event.create(address); + if (event.type() == SDLEvents.SDL_EVENT_QUIT + || (event.type() == SDLEvents.SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window().windowID() == windowId)) { + stop.run(); + } + return true; + }); + checkSDL(SDLEvents.SDL_AddEventWatch(watch, 0), "SDL_AddEventWatch"); + + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } + + initialized = true; + nativeReady.run(); + + // ACTUAL RENDERING ENTRYPOINT + try (GLResourceManager.ResourceScope ignored = GLResourceManager.openScope()) { + if (running.getAsBoolean()) { + render(window); + } + } + + } catch (Throwable failure) { + LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); + } finally { + stop.run(); + try { + if (watch != null) { + SDLEvents.SDL_RemoveEventWatch(watch, 0); + watch.free(); + } + GL.setCapabilities(null); + if (context != 0) { + if (!SDLVideo.SDL_GL_MakeCurrent(window, 0)) { + LOGGER.warn("Could not detach pre splash GL context: {}", SDLError.SDL_GetError()); + } + if (!SDLVideo.SDL_GL_DestroyContext(context)) { + LOGGER.warn("Could not destroy pre splash GL context: {}", SDLError.SDL_GetError()); + } + } + GL.destroy(); + if (window != 0) { + SDLVideo.SDL_DestroyWindow(window); + } + if (videoInitialized) { + if (!initialized) { + SDLVideo.SDL_GL_ResetAttributes(); + } + SDLInit.SDL_QuitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS); + } + } finally { + if (!initialized) { + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } + } + nativeReady.run(); + firstFrameReady.run(); + } + } + } + + private void render(long window) throws Exception { + var constructor = FreeTypeManager.class.getDeclaredConstructor(); + constructor.setAccessible(true); + FreeTypeManager freeType = constructor.newInstance(); + freeType.loggerName = "pre_splash"; + freeType.init(); + try { + McTtfFontManager fonts = PreSplashFontResources.create(assetsDirectory, assetIndex, freeType); + try { + var face = fonts.loadDefaultFace(48); + Preconditions.checkState(face != null, "Could not prepare the default Minecraft font."); + ImmediateShaderAccess shaders = new ImmediateShaderAccess(rl -> { + String path = "/assets/" + rl.getNamespace() + "/" + rl.getPath(); + try (InputStream input = PreSplashScreenContainer.class.getResourceAsStream(path)) { + Preconditions.checkNotNull(input, "Missing pre splash shader: %s", path); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Could not load pre splash shader " + path, e); + } + }); + AttributeLayout layout = new AttributeLayout(); + layout.push(new Stride(0)); + VAO dummyVao = new VAO(layout, null, (VBOView[]) null); + ST_Config config = new ST_Config( + ST_FontBackendType.FREE_TYPE, 48, 16, 12, + FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); + float uiWidth = WIDTH / UI_SCALE; + float uiHeight = HEIGHT / UI_SCALE; + try (SimpleGuiRuntime gui = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + SimpleTextRuntime text = new SimpleTextRuntime( + (_, _) -> new FreeTypeFontHandle(face), + runtime -> { + DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); + renderer.loggerName = "pre_splash"; + return renderer; + }, + runtime -> new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS), + shaders, new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), + new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), config, null)) { + + drawLoop(window, text, gui); + } + } finally { + fonts.destroy(); + } + } finally { + freeType.destroy(); + } + } + + private void drawLoop(long window, SimpleTextRuntime text, SimpleGuiRuntime gui) { + checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); + long started = System.nanoTime(); + boolean firstFrame = true; + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + try (MemoryStack stack = MemoryStack.stackPush()) { + IntBuffer width = stack.mallocInt(1); + IntBuffer height = stack.mallocInt(1); + while (running.getAsBoolean()) { + long frameStart = System.nanoTime(); + PreSplashPhase currentPhase = phase.get(); + if (currentPhase == PreSplashPhase.RIGHT_BEFORE_SPLASH) { + break; + } + SDLEvents.SDL_PumpEvents(); + checkSDL(SDLVideo.SDL_GetWindowSizeInPixels(window, width, height), "SDL_GetWindowSizeInPixels"); + if (width.get(0) <= 0 || height.get(0) <= 0) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); + continue; + } + + float scale = Math.min((float) width.get(0) / WIDTH, (float) height.get(0) / HEIGHT); + int viewportWidth = Math.round(WIDTH * scale); + int viewportHeight = Math.round(HEIGHT * scale); + GL11.glViewport((width.get(0) - viewportWidth) / 2, (height.get(0) - viewportHeight) / 2, viewportWidth, viewportHeight); + + GL11.glClearColor(0.055f, 0.065f, 0.085f, 1); + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + String label = switch (currentPhase) { + case FML_SETUP -> "Preparing Forge Mod Loader"; + case INITIAL_MOD_SCAN -> "Discovering mods"; + case CORE_MOD_LAUNCH -> "Loading core mods"; + case MINECRAFT_INIT -> "Initializing Minecraft"; + case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; + }; + int stage = currentPhase.ordinal() + 1; + int stages = PreSplashPhase.RIGHT_BEFORE_SPLASH.ordinal(); + gui.begin().append(stream -> { + stream.rect(48, 264, 544, 4, 0xFF30384A); + stream.rect(48, 264, 544f * stage / stages, 4, 0xFF88B8F8); + }).endDraw(); + text.begin() + .append("Cleanroom", 48, 106, 32, 0xFFF1F4FA) + .append(label, 48, 190, 16, 0xFFB9C7DB) + .append("Stage " + stage + " / " + stages + " | " + TimeUnit.NANOSECONDS.toSeconds(frameStart - started) + "s", 48, 286, 16, 0xFF8998AE) + .endDraw(); + checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); + if (firstFrame) { + firstFrame = false; + firstFrameReady.run(); + } + long remaining = TimeUnit.SECONDS.toNanos(1) / 30 - (System.nanoTime() - frameStart); + if (remaining > 0) { + LockSupport.parkNanos(remaining); + } + } + } + } + } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java index 6598df2f1..b62fbed75 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/package-info.java @@ -1,3 +1,13 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + @NullMarked package com.cleanroommc.cleanroom.splash.pre; diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java index 09915c98b..aeb3a3499 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java @@ -162,6 +162,10 @@ public final class CleanroomModDiscoverer extends ModDiscoverer { private File fileDirector; private CleanroomModDiscoverer() { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.INITIAL_MOD_SCAN); + } + Map files = new LinkedHashMap<>(); for (File candidate : LibraryManager.getCandidates()) { files.putIfAbsent(normalize(candidate), false); @@ -587,8 +591,6 @@ private void discoverFileDirectorMods(File gameDir, LaunchClassLoader classLoade } private void discover(Map files) { - PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.INITIAL_MOD_SCAN); - CleanroomLog.get().info("Discovering mods"); long startTime = System.nanoTime(); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java b/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java index fb57c59d7..0ea650af1 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/client/FMLClientHandler.java @@ -35,6 +35,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Predicate; +import com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer; import com.cleanroommc.client.modlist.ModListConfig; import com.cleanroommc.client.modlist.screen.ModListScreen; import com.cleanroommc.common.PatchModPresentChecker; @@ -218,6 +219,8 @@ public class FMLClientHandler implements IFMLSidedHandler */ public void beginMinecraftLoading(Minecraft minecraft, List resourcePackList, IReloadableResourceManager resourceManager, MetadataSerializer metaSerializer) { + PreSplashScreenContainer.finish(); + detectOptifine(); SplashProgress.start(); client = minecraft; diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java index 209cef0ce..a7199e041 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java @@ -21,6 +21,7 @@ import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; +import com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer; import com.cleanroommc.common.CleanroomEnvironment; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -147,6 +148,8 @@ else if (arg.contains("=")) public void injectIntoClassLoader(LaunchClassLoader classLoader) { PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.FML_SETUP); + String assets = launchArgs.get("--assetsDir"); + PreSplashScreenContainer.start(assets == null ? new File(gameDir, "assets") : new File(assets), launchArgs.get("--assetIndex")); FMLLaunchHandler.configureForClientLaunch(classLoader, this); FMLLaunchHandler.appendCoreMods(); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java index 60f8b4af1..028c9f166 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java @@ -176,8 +176,6 @@ public String[] getLaunchArguments() public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTweaker tweaker) { - PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); - CoreModManager.mcDir = mcDir; CoreModManager.tweaker = tweaker; @@ -248,10 +246,16 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw FMLLog.log.info("Found a command line coremod : {}", coreModClassName); loadCoreMod(classLoader, coreModClassName, null); } + CleanroomModDiscoverer discoverer = CleanroomModDiscoverer.instance(); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); + } + // Coremods - CleanroomModDiscoverer.instance().discoverCoreMods(mcDir, classLoader, tweaker); + discoverer.discoverCoreMods(mcDir, classLoader, tweaker); // Mixin Mods - CleanroomModDiscoverer.instance().discoverMixinMods(); + discoverer.discoverMixinMods(); } // Some mods call this reflectively From 3a4c871227b332b3955cbda9b502e1a065780c54 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:24:59 -0500 Subject: [PATCH 07/27] fix: revert some unnecessary CoreModManager patches --- .../net/minecraftforge/fml/relauncher/CoreModManager.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java index 028c9f166..6757ffd94 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java @@ -246,16 +246,15 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw FMLLog.log.info("Found a command line coremod : {}", coreModClassName); loadCoreMod(classLoader, coreModClassName, null); } - CleanroomModDiscoverer discoverer = CleanroomModDiscoverer.instance(); if (CleanroomEnvironment.side().isClient()) { PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); } // Coremods - discoverer.discoverCoreMods(mcDir, classLoader, tweaker); + CleanroomModDiscoverer.instance().discoverCoreMods(mcDir, classLoader, tweaker); // Mixin Mods - discoverer.discoverMixinMods(); + CleanroomModDiscoverer.instance().discoverMixinMods(); } // Some mods call this reflectively From cb078e0b18c57763c8d898d1426ef8814bb6a92f Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:18:12 -0500 Subject: [PATCH 08/27] feat: dual backend, sdl & swing --- .../splash/pre/PreSplashClassLoader.java | 4 +- .../splash/pre/PreSplashFontResources.java | 45 - .../splash/pre/PreSplashManager.java | 32 +- .../splash/pre/PreSplashPresentation.java | 51 ++ .../splash/pre/PreSplashScreenContainer.java | 813 +++++++++++++----- .../cleanroom/splash/pre/PreSplashState.java | 14 + .../splash/pre/renderer/PreSplashLayout.java | 23 + .../pre/renderer/SdlSplashRenderer.java | 179 ++++ .../pre/renderer/SwingSplashRenderer.java | 77 ++ .../splash/pre/renderer/package-info.java | 14 + 10 files changed, 1010 insertions(+), 242 deletions(-) delete mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java index 974dd15e0..faba82cef 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java @@ -15,6 +15,8 @@ /** * Motivation is to keep pre splash's untransformed LWJGL3 classes out of the game's loader. + * + *

Note: Only applied to {@link PreSplashScreenContainer.SdlRenderer}.

*/ final class PreSplashClassLoader extends ClassLoader { @@ -26,7 +28,7 @@ private static boolean isIsolated(String name) { return name.startsWith("org.lwjgl.") || name.startsWith("com.cleanroommc.kirino.") || name.startsWith("com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer$") - || name.equals("com.cleanroommc.cleanroom.splash.pre.PreSplashFontResources"); + || name.startsWith("com.cleanroommc.cleanroom.splash.pre.renderer."); } @Override diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java deleted file mode 100644 index 3d329b272..000000000 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashFontResources.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2026 CleanroomMC contributors - * - * This file is licensed under the CleanroomMC License Version 1.0. - * See the applicable LICENSE file in this directory or a parent directory - * for the full licence terms. - * - * This is visible-source software and is not open-source software. - */ - -package com.cleanroommc.cleanroom.splash.pre; - -import com.cleanroommc.kirino.ui.font.McTtfFontManager; -import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; - -import com.google.common.base.Preconditions; -import org.jspecify.annotations.Nullable; - -import net.minecraft.client.resources.DefaultResourcePack; -import net.minecraft.client.resources.ResourceIndex; -import net.minecraft.client.resources.ResourceIndexFolder; - -import java.io.File; - -/** - *

Note: Loaded only by the screen thread.

- */ -final class PreSplashFontResources { - - private PreSplashFontResources() { - } - - static McTtfFontManager create(File assetsDirectory, @Nullable String assetIndex, FreeTypeManager freeType) { - Preconditions.checkNotNull(assetsDirectory); - Preconditions.checkNotNull(freeType); - - ResourceIndex index = assetIndex == null - ? new ResourceIndexFolder(assetsDirectory) - : new ResourceIndex(assetsDirectory, assetIndex); - - McTtfFontManager fonts = new McTtfFontManager(new DefaultResourcePack(index), freeType); - fonts.loggerName = "pre_splash"; - return fonts; - } -} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java index 0aaf159b2..3c2798d38 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -14,6 +14,9 @@ import org.jetbrains.annotations.ApiStatus; import org.jspecify.annotations.Nullable; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + /** * This is not a client-side only class, but it's only intended to work for client-side bootstrapping. */ @@ -22,6 +25,7 @@ public final class PreSplashManager { public static final PreSplashManager INSTANCE = new PreSplashManager(); private final PreSplashPhaseFSM fsm = new PreSplashPhaseFSM(); + private final Queue states = new ConcurrentLinkedQueue<>(); private volatile @Nullable PreSplashPhase currentPhase = null; private PreSplashManager() { @@ -39,15 +43,39 @@ public synchronized void notifyPhase(PreSplashPhase phase) { "Expected pre splash phase: %s; Observed: %s", fsm.getState(), phase); fsm.next(); + String message = switch (phase) { + case FML_SETUP -> "Preparing Forge Mod Loader"; + case INITIAL_MOD_SCAN -> "Discovering mods"; + case CORE_MOD_LAUNCH -> "Loading core mods"; + case MINECRAFT_INIT -> "Initializing Minecraft"; + case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; + }; + + states.add(new PreSplashState("Cleanroom", message, "")); currentPhase = phase; } /** - * Thread-safe. Only intended to be read by {@link PreSplashScreenContainer}. - * The screen starts after the first phase has been published. + * Thread-safe. Only intended to be read by after the first phase has been published. */ @ApiStatus.Internal PreSplashPhase readPhase() { return Preconditions.checkNotNull(currentPhase); } + + /** + * Thread-safe. + */ + @Nullable + PreSplashState peek() { + return states.peek(); + } + + /** + * Thread-safe. + */ + @Nullable + PreSplashState poll() { + return states.poll(); + } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java new file mode 100644 index 000000000..9057b104b --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashPresentation.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +import com.google.common.base.Preconditions; +import org.jspecify.annotations.Nullable; + +public final class PreSplashPresentation { + + private final PreSplashManager manager; + private PreSplashState current; + + public PreSplashPresentation(PreSplashManager manager) { + this.manager = manager; + current = Preconditions.checkNotNull(manager.peek(), + "The initial pre splash frame must be published."); + } + + public boolean isFinished() { + return manager.readPhase() == PreSplashPhase.RIGHT_BEFORE_SPLASH; + } + + @Nullable + public PreSplashState peek() { + return manager.peek(); + } + + @Nullable + public PreSplashState poll() { + PreSplashState next = manager.poll(); + if (next != null) { + current = next; + } + return next; + } + + public PreSplashState nextFrame() { + if (peek() != null) { + poll(); + } + return current; + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index ff7d80160..2c50fec7f 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -11,25 +11,14 @@ package com.cleanroommc.cleanroom.splash.pre; import com.cleanroommc.anone.reveal.ReflectiveInvocation; -import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; -import com.cleanroommc.kirino.gl.GLResourceManager; -import com.cleanroommc.kirino.gl.buffer.view.VBOView; -import com.cleanroommc.kirino.gl.vao.VAO; -import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; -import com.cleanroommc.kirino.gl.vao.attribute.Stride; -import com.cleanroommc.kirino.ui.font.McTtfFontManager; -import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; -import com.cleanroommc.kirino.ui.simpletext.ST_Config; -import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; -import com.cleanroommc.kirino.ui.simpletext.SimpleTextRuntime; -import com.cleanroommc.kirino.ui.simpletext.atlas.Tex2DArrayGlyphAtlas; -import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextProducer; -import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; -import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; -import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; -import com.cleanroommc.mcttf.glyph.GlyphBuilder; +import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLayout; +import com.cleanroommc.cleanroom.splash.pre.renderer.SdlSplashRenderer; +import com.cleanroommc.cleanroom.splash.pre.renderer.SwingSplashRenderer; import com.google.common.base.Preconditions; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.data.MetadataSerializer; @@ -42,7 +31,6 @@ import org.jspecify.annotations.Nullable; import org.lwjgl.opengl.GL; -import org.lwjgl.opengl.GL11; import org.lwjgl.sdl.SDLError; import org.lwjgl.sdl.SDLEvents; import org.lwjgl.sdl.SDLHints; @@ -54,22 +42,43 @@ import org.lwjgl.system.Configuration; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.ThreadLocalUtil; -import org.lwjgl.util.freetype.FreeType; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.Timer; +import javax.swing.WindowConstants; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import java.awt.Window; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.IntBuffer; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; +import java.util.function.BiConsumer; import java.util.function.BooleanSupplier; import java.util.function.Supplier; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; /** - * It owns the temporary window, isolated class loading, GL context, and all rendering resources. + * It owns the renderer lifecycle, SDL worker thread OR Swing process. */ public final class PreSplashScreenContainer { @@ -77,16 +86,14 @@ public final class PreSplashScreenContainer { public static final Logger LOGGER = LogManager.getLogger("Pre Splash Screen"); - private static final int WIDTH = 720; - private static final int HEIGHT = 360; - private static final float SCREEN_PERCENTAGE = 0.35f; - private static final float UI_SCALE = 1.15f; - private static final int INITIAL_WAIT_SECOND = 10; + private static final int THREAD_START_TIMEOUT_SECOND = 30; + private static final int THREAD_STOP_TIMEOUT_SECOND = 10; private final Thread gameThread; private final Thread thread; private final Thread shutdownHook; + private final PreSplashPresentation presentation; private final CountDownLatch nativeReady = new CountDownLatch(1); private final CountDownLatch firstFrameReady = new CountDownLatch(1); @@ -105,6 +112,7 @@ private PreSplashScreenContainer(File assetsDirectory, @Nullable String assetInd Preconditions.checkNotNull(assetsDirectory); gameThread = Thread.currentThread(); + presentation = new PreSplashPresentation(PreSplashManager.INSTANCE); this.assetsDirectory = assetsDirectory; this.assetIndex = assetIndex; thread = new Thread(this::run, "Pre Splash Renderer"); @@ -128,12 +136,16 @@ public static synchronized void start(File assetsDirectory, @Nullable String ass Runtime.getRuntime().addShutdownHook(screen.shutdownHook); screen.thread.start(); // this::run - // wait for native initialization + // wait for renderer initialization and its first frame + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_START_TIMEOUT_SECOND); boolean interrupted = false; while (true) { try { - screen.nativeReady.await(); - screen.firstFrameReady.await(); + if (!screen.nativeReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS) + || !screen.firstFrameReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { + LOGGER.warn("Pre splash renderer did not become ready within {} seconds.", THREAD_START_TIMEOUT_SECOND); + screen.stopAndWait(); + } break; } catch (InterruptedException e) { interrupted = true; @@ -171,10 +183,16 @@ private void stopAndWait() { running = false; LockSupport.unpark(thread); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); boolean interrupted = false; while (thread.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + LOGGER.warn("Pre splash renderer did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); + break; + } try { - thread.join(); + TimeUnit.NANOSECONDS.timedJoin(thread, remaining); } catch (InterruptedException e) { interrupted = true; } @@ -186,14 +204,42 @@ private void stopAndWait() { } private void run() { + try { + boolean mac = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("mac"); + if (mac || !runSdl()) { + if (isRunning()) { + runSwing(); + } + } + } catch (Throwable failure) { + LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); + } finally { + running = false; + nativeReady.countDown(); + firstFrameReady.countDown(); + try { + Runtime.getRuntime().removeShutdownHook(shutdownHook); + } catch (IllegalStateException ignored) { + // if shutdown has already begun + } + } + } + + private boolean isRunning() { + return running && gameThread.isAlive() && !presentation.isFinished(); + } + + // + private boolean runSdl() { Thread renderThread = Thread.currentThread(); ClassLoader previousContextLoader = renderThread.getContextClassLoader(); + boolean[] unavailable = { false }; try { ClassLoader loader = new PreSplashClassLoader(PreSplashScreenContainer.class.getClassLoader()); renderThread.setContextClassLoader(loader); - Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$Renderer", true, loader); + Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$SdlRenderer", true, loader); Runnable render = (Runnable) renderer.getConstructor( File.class, String.class, @@ -201,92 +247,135 @@ private void run() { Supplier.class, Runnable.class, Runnable.class, + Runnable.class, Runnable.class).newInstance( assetsDirectory, assetIndex, - (BooleanSupplier) () -> running && gameThread.isAlive(), - (Supplier) PreSplashManager.INSTANCE::readPhase, + (BooleanSupplier) this::isRunning, + (Supplier) presentation::nextFrame, (Runnable) () -> running = false, (Runnable) nativeReady::countDown, - (Runnable) firstFrameReady::countDown); + (Runnable) firstFrameReady::countDown, + (Runnable) () -> unavailable[0] = true); - // ENTRYPOINT + // SDL ENTRYPOINT render.run(); } catch (Throwable failure) { - LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); + LOGGER.warn("SDL pre splash unavailable. Falling back to Swing.", failure); + return false; } finally { - running = false; - nativeReady.countDown(); - firstFrameReady.countDown(); renderThread.setContextClassLoader(previousContextLoader); - try { - Runtime.getRuntime().removeShutdownHook(shutdownHook); - } catch (IllegalStateException ignored) { - // if shutdown has already begun - } } + + return !unavailable[0]; + } + + private void runSwing() throws IOException, InterruptedException { + // SWING ENTRYPOINT + new SwingRenderer( + this::isRunning, + presentation::nextFrame, + nativeReady::countDown, + firstFrameReady::countDown).run(); } + // + // /** - * Defined only by {@link PreSplashClassLoader}. - * - * @see PreSplashScreenContainer#run() + * @see PreSplashScreenContainer#runSdl() */ @ApiStatus.Internal - public static final class Renderer implements Runnable { + public static final class SdlRenderer implements Runnable { private final File assetsDirectory; private final @Nullable String assetIndex; private final BooleanSupplier running; - private final Supplier phase; + private final Supplier state; private final Runnable stop; private final Runnable nativeReady; private final Runnable firstFrameReady; + private final Runnable unavailable; @ReflectiveInvocation - public Renderer( + public SdlRenderer( File assetsDirectory, @Nullable String assetIndex, BooleanSupplier running, - Supplier phase, + Supplier state, Runnable stop, Runnable nativeReady, - Runnable firstFrameReady) { + Runnable firstFrameReady, + Runnable unavailable) { Preconditions.checkNotNull(assetsDirectory); Preconditions.checkNotNull(running); - Preconditions.checkNotNull(phase); + Preconditions.checkNotNull(state); Preconditions.checkNotNull(stop); Preconditions.checkNotNull(nativeReady); Preconditions.checkNotNull(firstFrameReady); + Preconditions.checkNotNull(unavailable); this.assetsDirectory = assetsDirectory; this.assetIndex = assetIndex; this.running = running; - this.phase = phase; + this.state = state; this.stop = stop; this.nativeReady = nativeReady; this.firstFrameReady = firstFrameReady; + this.unavailable = unavailable; } - private static void checkSDL(boolean success, String operation) { - Preconditions.checkState(success, "%s: %s", operation, SDLError.SDL_GetError()); - } - - /** - * @see PreSplashScreenContainer#run() - */ @Override public void run() { - long window = 0; - long context = 0; - boolean videoInitialized = false; - SDL_EventFilter watch = null; - String originalLibraryPath = System.getProperty("org.lwjgl.librarypath"); - boolean initialized = false; + try (Window window = Window.open(stop)) { + nativeReady.run(); + if (running.getAsBoolean()) { + try (SdlSplashRenderer renderer = new SdlSplashRenderer(assetsDirectory, assetIndex)) { + window.runLoop(running, (width, height) -> { + renderer.update(state.get()); + renderer.render(width, height); + }, firstFrameReady); + } + } + } catch (Throwable failure) { + LOGGER.warn("SDL pre splash unavailable. Falling back to Swing.", failure); + unavailable.run(); + } + } - try { + static final class Window implements AutoCloseable { + + private static final int TARGET_FRAME_RATE = 60; + + private final @Nullable String originalLibraryPath = System.getProperty("org.lwjgl.librarypath"); + private long window; + private long context; + private boolean videoInitialized; + private boolean initialized; + private boolean glInitialized; + private @Nullable SDL_EventFilter watch; + + static Window open(Runnable stop) { + Window window = new Window(); + try { + window.initialize(stop); + return window; + } catch (RuntimeException | Error failure) { + try { + window.close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static void checkSDL(boolean success, String operation) { + Preconditions.checkState(success, "%s: %s", operation, SDLError.SDL_GetError()); + } + + private void initialize(Runnable stop) { // configure this loader's (PreSplashClassLoader) LWJGL copy Configuration.LIBRARY_PATH.set(null); Configuration.SHARED_LIBRARY_EXTRACT_PATH.set(null); @@ -303,6 +392,8 @@ public void run() { checkSDL(SDLInit.SDL_InitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS), "SDL_InitSubSystem"); videoInitialized = true; + // on non-Apple platforms, the video initializing thread is SDL's main thread + Preconditions.checkState(SDLInit.SDL_IsMainThread(), "Pre splash must run on its SDL video thread."); SDLVideo.SDL_GL_ResetAttributes(); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MAJOR_VERSION, 4), "GL major version"); @@ -313,19 +404,19 @@ public void run() { int display = SDLVideo.SDL_GetPrimaryDisplay(); Preconditions.checkState(display != 0, "SDL_GetPrimaryDisplay: %s", SDLError.SDL_GetError()); - // must not be SDL.window() which belongs to Minecraft try (MemoryStack stack = MemoryStack.stackPush()) { SDL_Rect bounds = SDL_Rect.malloc(stack); checkSDL(SDLVideo.SDL_GetDisplayBounds(display, bounds), "SDL_GetDisplayBounds"); - float scale = Math.min((float) bounds.w() / WIDTH, (float) bounds.h() / HEIGHT) * SCREEN_PERCENTAGE; - int windowWidth = Math.max(1, Math.round(WIDTH * scale)); - int windowHeight = Math.max(1, Math.round(HEIGHT * scale)); + float scale = Math.min((float) bounds.w() / PreSplashLayout.WIDTH, (float) bounds.h() / PreSplashLayout.HEIGHT) * PreSplashLayout.SCREEN_PERCENTAGE; + int windowWidth = Math.max(1, Math.round(PreSplashLayout.WIDTH * scale)); + int windowHeight = Math.max(1, Math.round(PreSplashLayout.HEIGHT * scale)); window = SDLVideo.SDL_CreateWindow("Cleanroom Pre Splash", windowWidth, windowHeight, SDLVideo.SDL_WINDOW_OPENGL | SDLVideo.SDL_WINDOW_HIGH_PIXEL_DENSITY | SDLVideo.SDL_WINDOW_HIDDEN + | SDLVideo.SDL_WINDOW_UTILITY | SDLVideo.SDL_WINDOW_NOT_FOCUSABLE | SDLVideo.SDL_WINDOW_ALWAYS_ON_TOP); @@ -349,11 +440,16 @@ public void run() { context = SDLVideo.SDL_GL_CreateContext(window); Preconditions.checkState(context != 0, "SDL_GL_CreateContext: %s", SDLError.SDL_GetError()); checkSDL(SDLVideo.SDL_GL_MakeCurrent(window, context), "SDL_GL_MakeCurrent"); - // todo: implement multi gl backend - Preconditions.checkState(GL.createCapabilities().OpenGL46, "Pre splash requires OpenGL 4.6."); + + // triggers class initializing + GL.getFunctionProvider(); + + glInitialized = true; + boolean gl46 = GL.createCapabilities().OpenGL46; // release LWJGL's global table so the game's LWJGL can initialize ThreadLocalUtil.setFunctionMissingAddresses(0); + Preconditions.checkState(gl46, "Pre splash requires OpenGL 4.6."); if (!SDLVideo.SDL_GL_SetSwapInterval(0)) { LOGGER.debug("Could not disable pre splash VSync: {}", SDLError.SDL_GetError()); @@ -382,25 +478,50 @@ public void run() { } initialized = true; - nativeReady.run(); + } + + void runLoop(BooleanSupplier running, BiConsumer draw, Runnable firstFrameReady) { + checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); + boolean firstFrame = true; + try (MemoryStack stack = MemoryStack.stackPush()) { + IntBuffer width = stack.mallocInt(1); + IntBuffer height = stack.mallocInt(1); + while (running.getAsBoolean()) { + long frameStart = System.nanoTime(); + SDLEvents.SDL_PumpEvents(); + checkSDL(SDLVideo.SDL_GetWindowSizeInPixels(window, width, height), "SDL_GetWindowSizeInPixels"); + if (width.get(0) <= 0 || height.get(0) <= 0) { + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); + continue; + } - // ACTUAL RENDERING ENTRYPOINT - try (GLResourceManager.ResourceScope ignored = GLResourceManager.openScope()) { - if (running.getAsBoolean()) { - render(window); + draw.accept(width.get(0), height.get(0)); + checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); + if (firstFrame) { + firstFrame = false; + firstFrameReady.run(); + } + long remaining = TimeUnit.SECONDS.toNanos(1) / TARGET_FRAME_RATE - (System.nanoTime() - frameStart); + if (remaining > 0) { + LockSupport.parkNanos(remaining); + } } } + } - } catch (Throwable failure) { - LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); - } finally { - stop.run(); + @Override + public void close() { try { if (watch != null) { SDLEvents.SDL_RemoveEventWatch(watch, 0); watch.free(); } - GL.setCapabilities(null); + if (glInitialized) { + GL.setCapabilities(null); + if (!initialized) { + ThreadLocalUtil.setFunctionMissingAddresses(0); + } + } if (context != 0) { if (!SDLVideo.SDL_GL_MakeCurrent(window, 0)) { LOGGER.warn("Could not detach pre splash GL context: {}", SDLError.SDL_GetError()); @@ -409,140 +530,444 @@ public void run() { LOGGER.warn("Could not destroy pre splash GL context: {}", SDLError.SDL_GetError()); } } - GL.destroy(); - if (window != 0) { - SDLVideo.SDL_DestroyWindow(window); + } finally { + try { + if (glInitialized) { + GL.destroy(); + } + } finally { + try { + if (window != 0) { + SDLVideo.SDL_DestroyWindow(window); + } + } finally { + try { + if (videoInitialized) { + if (!initialized) { + SDLVideo.SDL_GL_ResetAttributes(); + } + SDLInit.SDL_QuitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS); + } + } finally { + if (!initialized) { + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } + } + } + } } - if (videoInitialized) { - if (!initialized) { - SDLVideo.SDL_GL_ResetAttributes(); + } + } + } + } + + /** + * @see PreSplashScreenContainer#runSwing() + */ + @ApiStatus.Internal + public static final class SwingRenderer { + + private static final int HELPER_START_TIMEOUT_SECOND = 15; + private static final int HELPER_STOP_TIMEOUT_SECOND = 2; + + private final BooleanSupplier running; + private final Supplier state; + private final Runnable nativeReady; + private final Runnable firstFrameReady; + + private SwingRenderer(BooleanSupplier running, Supplier state, Runnable nativeReady, Runnable firstFrameReady) { + this.running = running; + this.state = state; + this.nativeReady = nativeReady; + this.firstFrameReady = firstFrameReady; + } + + private void run() throws IOException { + new HelperProcess(running, state, nativeReady, firstFrameReady).run(); + } + + static final class Protocol { + + private static final int STATE = 1; + private static final int CLOSE = 2; + private static final int READY = 3; + + private Protocol() { + } + + static void writeState(DataOutputStream output, PreSplashState state) throws IOException { + output.writeByte(STATE); + output.writeUTF(state.title()); + output.writeUTF(state.message()); + output.writeUTF(state.details()); + output.flush(); + } + + @Nullable + static PreSplashState readState(DataInputStream input) throws IOException { + int command; + try { + command = input.readUnsignedByte(); + } catch (IOException ignored) { + return null; + } + if (command == CLOSE) { + return null; + } + if (command != STATE) { + throw new IOException("Invalid pre splash command: " + command); + } + return new PreSplashState(input.readUTF(), input.readUTF(), input.readUTF()); + } + + static void close(DataOutputStream output) throws IOException { + output.writeByte(CLOSE); + output.flush(); + } + + static void ready(DataOutputStream output) throws IOException { + output.writeByte(READY); + output.flush(); + } + + static void readReady(DataInputStream input) throws IOException { + if (input.readUnsignedByte() != READY) { + throw new IOException("Invalid pre splash readiness reply."); + } + } + } + + private record HelperProcess(BooleanSupplier running, Supplier state, Runnable nativeReady, Runnable firstFrameReady) { + + private static void writeHelperClass(JarOutputStream output, Class type, Set entries) throws IOException { + String resource = type.getName().replace('.', '/') + ".class"; + if (!entries.add(resource)) { + return; + } + + try (InputStream input = PreSplashScreenContainer.class.getResourceAsStream("/" + resource)) { + Preconditions.checkNotNull(input, "Missing Swing pre splash class: %s", type.getName()); + output.putNextEntry(new JarEntry(resource)); + input.transferTo(output); + output.closeEntry(); + } + + for (Class nested : type.getDeclaredClasses()) { + writeHelperClass(output, nested, entries); + } + } + + private void run() throws IOException { + String renderer = SwingRenderer.class.getName() + "$Helper"; + String windowTitle = "Cleanroom Pre Splash [" + UUID.randomUUID() + "]"; + Path helperJar = Files.createTempFile("cleanroom-pre-splash-", ".jar"); + Process helper = null; + + try { + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(helperJar))) { + Set entries = new HashSet<>(); + for (Class type : List.of(Protocol.class, Helper.class, PreSplashState.class, SwingSplashRenderer.class, PreSplashLayout.class)) { + writeHelperClass(output, type, entries); + } + } + + boolean windows = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows"); + Path java = Path.of(System.getProperty("java.home"), "bin", windows ? "java.exe" : "java"); + + ProcessBuilder builder = new ProcessBuilder( + java.toString(), + "-Dapple.awt.UIElement=true", + "-cp", helperJar.toString(), + renderer, + Long.toString(ProcessHandle.current().pid()), + windowTitle); + + builder.environment().remove("JDK_JAVA_OPTIONS"); + builder.environment().remove("JAVA_TOOL_OPTIONS"); + builder.environment().remove("_JAVA_OPTIONS"); + builder.redirectError(ProcessBuilder.Redirect.INHERIT); + + helper = builder.start(); + + try (DataOutputStream commands = new DataOutputStream(new BufferedOutputStream(helper.getOutputStream())); + DataInputStream replies = new DataInputStream(helper.getInputStream())) { + + PreSplashState previous = null; + boolean ready = false; + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(HELPER_START_TIMEOUT_SECOND); + + while (running.getAsBoolean()) { + PreSplashState current = state.get(); + if (!helper.isAlive()) { + LOGGER.warn("Swing pre splash helper exited with code {}.", helper.exitValue()); + break; + } + + if (current != previous) { + Protocol.writeState(commands, current); + previous = current; + } + + while (replies.available() > 0) { + Protocol.readReady(replies); + if (!ready) { + centerWindowOnNiri(windowTitle); + ready = true; + nativeReady.run(); + firstFrameReady.run(); + } + } + + if (!ready && System.nanoTime() >= deadline) { + LOGGER.warn("Swing pre splash helper did not become ready in time."); + break; + } + + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50)); + } + + if (helper.isAlive()) { + Protocol.close(commands); } - SDLInit.SDL_QuitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS); } } finally { - if (!initialized) { - if (originalLibraryPath == null) { - System.clearProperty("org.lwjgl.librarypath"); - } else { - System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + try { + if (helper != null) { + stopHelper(helper); } + } finally { + Files.deleteIfExists(helperJar); } - nativeReady.run(); - firstFrameReady.run(); } } - } - private void render(long window) throws Exception { - var constructor = FreeTypeManager.class.getDeclaredConstructor(); - constructor.setAccessible(true); - FreeTypeManager freeType = constructor.newInstance(); - freeType.loggerName = "pre_splash"; - freeType.init(); - try { - McTtfFontManager fonts = PreSplashFontResources.create(assetsDirectory, assetIndex, freeType); + private static void stopHelper(Process helper) { + boolean interrupted = false; try { - var face = fonts.loadDefaultFace(48); - Preconditions.checkState(face != null, "Could not prepare the default Minecraft font."); - ImmediateShaderAccess shaders = new ImmediateShaderAccess(rl -> { - String path = "/assets/" + rl.getNamespace() + "/" + rl.getPath(); - try (InputStream input = PreSplashScreenContainer.class.getResourceAsStream(path)) { - Preconditions.checkNotNull(input, "Missing pre splash shader: %s", path); - return new String(input.readAllBytes(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new IllegalStateException("Could not load pre splash shader " + path, e); + if (!helper.waitFor(HELPER_STOP_TIMEOUT_SECOND, TimeUnit.SECONDS)) { + helper.destroy(); + helper.waitFor(HELPER_STOP_TIMEOUT_SECOND, TimeUnit.SECONDS); + } + } catch (InterruptedException ignored) { + interrupted = true; + } finally { + if (helper.isAlive()) { + helper.destroyForcibly(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(HELPER_STOP_TIMEOUT_SECOND); + while (helper.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + break; + } + try { + helper.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException ignored) { + interrupted = true; + } } - }); - AttributeLayout layout = new AttributeLayout(); - layout.push(new Stride(0)); - VAO dummyVao = new VAO(layout, null, (VBOView[]) null); - ST_Config config = new ST_Config( - ST_FontBackendType.FREE_TYPE, 48, 16, 12, - FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); - float uiWidth = WIDTH / UI_SCALE; - float uiHeight = HEIGHT / UI_SCALE; - try (SimpleGuiRuntime gui = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); - SimpleTextRuntime text = new SimpleTextRuntime( - (_, _) -> new FreeTypeFontHandle(face), - runtime -> { - DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); - renderer.loggerName = "pre_splash"; - return renderer; - }, - runtime -> new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS), - shaders, new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), - new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), config, null)) { - - drawLoop(window, text, gui); } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + // + private static @Nullable JsonElement niriMessage(String... arguments) { + List command = new ArrayList<>(List.of("niri", "msg", "--json")); + command.addAll(List.of(arguments)); + + Process message = null; + try { + message = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + if (message.waitFor(1, TimeUnit.SECONDS) && message.exitValue() == 0) { + try (InputStream input = message.getInputStream()) { + return JsonParser.parseString(new String(input.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } catch (IOException | RuntimeException failure) { + LOGGER.debug("Could not communicate with niri for pre splash positioning.", failure); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); } finally { - fonts.destroy(); + if (message != null && message.isAlive()) { + message.destroyForcibly(); + } } - } finally { - freeType.destroy(); + return null; } - } - private void drawLoop(long window, SimpleTextRuntime text, SimpleGuiRuntime gui) { - checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); - long started = System.nanoTime(); - boolean firstFrame = true; - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - try (MemoryStack stack = MemoryStack.stackPush()) { - IntBuffer width = stack.mallocInt(1); - IntBuffer height = stack.mallocInt(1); - while (running.getAsBoolean()) { - long frameStart = System.nanoTime(); - PreSplashPhase currentPhase = phase.get(); - if (currentPhase == PreSplashPhase.RIGHT_BEFORE_SPLASH) { - break; + private static void centerWindowOnNiri(String windowTitle) { + if (System.getenv("NIRI_SOCKET") == null) { + return; + } + + try { + JsonElement windows = niriMessage("windows"); + if (windows == null) { + return; + } + + JsonObject splash = null; + for (JsonElement element : windows.getAsJsonArray()) { + JsonObject window = element.getAsJsonObject(); + JsonElement title = window.get("title"); + if (title != null + && title.isJsonPrimitive() + && windowTitle.equals(title.getAsString()) + && window.get("is_floating").getAsBoolean()) { + if (splash != null) { + return; + } + + splash = window; + } } - SDLEvents.SDL_PumpEvents(); - checkSDL(SDLVideo.SDL_GetWindowSizeInPixels(window, width, height), "SDL_GetWindowSizeInPixels"); - if (width.get(0) <= 0 || height.get(0) <= 0) { - LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100)); - continue; + + if (splash == null) { + return; } - float scale = Math.min((float) width.get(0) / WIDTH, (float) height.get(0) / HEIGHT); - int viewportWidth = Math.round(WIDTH * scale); - int viewportHeight = Math.round(HEIGHT * scale); - GL11.glViewport((width.get(0) - viewportWidth) / 2, (height.get(0) - viewportHeight) / 2, viewportWidth, viewportHeight); - - GL11.glClearColor(0.055f, 0.065f, 0.085f, 1); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); - String label = switch (currentPhase) { - case FML_SETUP -> "Preparing Forge Mod Loader"; - case INITIAL_MOD_SCAN -> "Discovering mods"; - case CORE_MOD_LAUNCH -> "Loading core mods"; - case MINECRAFT_INIT -> "Initializing Minecraft"; - case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; - }; - int stage = currentPhase.ordinal() + 1; - int stages = PreSplashPhase.RIGHT_BEFORE_SPLASH.ordinal(); - gui.begin().append(stream -> { - stream.rect(48, 264, 544, 4, 0xFF30384A); - stream.rect(48, 264, 544f * stage / stages, 4, 0xFF88B8F8); - }).endDraw(); - text.begin() - .append("Cleanroom", 48, 106, 32, 0xFFF1F4FA) - .append(label, 48, 190, 16, 0xFFB9C7DB) - .append("Stage " + stage + " / " + stages + " | " + TimeUnit.NANOSECONDS.toSeconds(frameStart - started) + "s", 48, 286, 16, 0xFF8998AE) - .endDraw(); - checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); - if (firstFrame) { - firstFrame = false; - firstFrameReady.run(); + JsonElement workspaces = niriMessage("workspaces"); + JsonElement outputs = niriMessage("outputs"); + if (workspaces == null || outputs == null) { + return; } - long remaining = TimeUnit.SECONDS.toNanos(1) / 30 - (System.nanoTime() - frameStart); - if (remaining > 0) { - LockSupport.parkNanos(remaining); + + for (JsonElement element : workspaces.getAsJsonArray()) { + JsonObject workspace = element.getAsJsonObject(); + if (!workspace.get("id").equals(splash.get("workspace_id")) || workspace.get("output").isJsonNull()) { + continue; + } + + JsonObject output = outputs.getAsJsonObject().getAsJsonObject(workspace.get("output").getAsString()); + JsonObject logical = output.getAsJsonObject("logical"); + JsonObject layout = splash.getAsJsonObject("layout"); + var size = layout.getAsJsonArray("tile_size"); + var position = layout.getAsJsonArray("tile_pos_in_workspace_view"); + double x = (logical.get("width").getAsDouble() - size.get(0).getAsDouble()) / 2; + double y = (logical.get("height").getAsDouble() - size.get(1).getAsDouble()) / 2; + + niriMessage( + "action", + "move-floating-window", + "--id", splash.get("id").getAsString(), + "--x=" + String.format(Locale.ROOT, "%+.3f", x - position.get(0).getAsDouble()), + "--y=" + String.format(Locale.ROOT, "%+.3f", y - position.get(1).getAsDouble())); + + return; } + } catch (RuntimeException failure) { + LOGGER.debug("Could not center Swing pre splash through niri.", failure); + } + } + // + } + + /** + * This is the entry point in the helper JVM. + */ + public static final class Helper { + + private static final int TARGET_FRAME_RATE = 60; + + private final SwingSplashRenderer renderer = new SwingSplashRenderer(Helper::notifyReady); + + private @Nullable JDialog window; + private @Nullable Timer timer; + + public static void main(String[] args) { + try { + ProcessHandle parent = ProcessHandle.of(Long.parseLong(args[0])).orElse(null); + if (parent == null) { + return; + } + + parent.onExit().thenRun(() -> System.exit(0)); + + try (DataInputStream commands = new DataInputStream(new BufferedInputStream(System.in))) { + PreSplashState initial = Protocol.readState(commands); + if (initial == null) { + return; + } + + Helper[] screen = new Helper[1]; + SwingUtilities.invokeAndWait(() -> { + Helper helper = new Helper(); + screen[0] = helper; + helper.renderer.update(initial); + helper.open(args[1]); + }); + + Helper helper = screen[0]; + + PreSplashState state; + while ((state = Protocol.readState(commands)) != null) { + PreSplashState update = state; + SwingUtilities.invokeLater(() -> helper.renderer.update(update)); + } + + SwingUtilities.invokeLater(helper::close); + } + } catch (Throwable failure) { + failure.printStackTrace(System.err); + System.exit(1); + } + } + + private void open(String windowTitle) { + var configuration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); + Rectangle bounds = configuration.getBounds(); + float scale = Math.min((float) bounds.width / PreSplashLayout.WIDTH, (float) bounds.height / PreSplashLayout.HEIGHT) * PreSplashLayout.SCREEN_PERCENTAGE; + int width = Math.max(1, Math.round(PreSplashLayout.WIDTH * scale)); + int height = Math.max(1, Math.round(PreSplashLayout.HEIGHT * scale)); + + window = new JDialog((Frame) null, windowTitle, false, configuration); + window.setType(Window.Type.UTILITY); + window.setUndecorated(true); + window.setResizable(false); + window.setFocusableWindowState(false); + window.setAutoRequestFocus(false); + window.setAlwaysOnTop(true); + window.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + window.setContentPane(renderer); + window.setSize(width, height); + window.setLocation(bounds.x + (bounds.width - width) / 2, bounds.y + (bounds.height - height) / 2); + window.setVisible(true); + + timer = new Timer(1000 / TARGET_FRAME_RATE, _ -> { + if (!window.isDisplayable()) { + close(); + return; + } + renderer.repaint(); + }); + + timer.start(); + } + + private static void notifyReady() { + try { + Protocol.ready(new DataOutputStream(System.out)); + } catch (IOException failure) { + failure.printStackTrace(System.err); + System.exit(1); + } + } + + private void close() { + if (timer != null) { + timer.stop(); + } + if (window != null) { + window.dispose(); } + System.exit(0); } } } + // } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java new file mode 100644 index 000000000..9b0873476 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashState.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre; + +public record PreSplashState(String title, String message, String details) { +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java new file mode 100644 index 000000000..6b29932d7 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +public final class PreSplashLayout { + + public static final int WIDTH = 720; + public static final int HEIGHT = 360; + public static final float SCREEN_PERCENTAGE = 0.35f; + public static final float UI_SCALE = 1.15f; + public static final int BACKGROUND = 0xFF0E1116; + + private PreSplashLayout() { + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java new file mode 100644 index 000000000..db22481d7 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.cleanroom.splash.pre.PreSplashState; +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.GLResourceManager; +import com.cleanroommc.kirino.gl.buffer.view.VBOView; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; +import com.cleanroommc.kirino.gl.vao.attribute.Stride; +import com.cleanroommc.kirino.ui.font.McTtfFontManager; +import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; +import com.cleanroommc.kirino.ui.simpletext.ST_Config; +import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; +import com.cleanroommc.kirino.ui.simpletext.SimpleTextRuntime; +import com.cleanroommc.kirino.ui.simpletext.atlas.Tex2DArrayGlyphAtlas; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextProducer; +import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; +import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; +import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; +import com.cleanroommc.mcttf.glyph.GlyphBuilder; + +import com.google.common.base.Preconditions; +import org.jspecify.annotations.Nullable; + +import net.minecraft.client.resources.DefaultResourcePack; +import net.minecraft.client.resources.ResourceIndex; +import net.minecraft.client.resources.ResourceIndexFolder; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.util.freetype.FreeType; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public final class SdlSplashRenderer implements AutoCloseable { + + private final GLResourceManager.ResourceScope scope; + + private final FreeTypeManager freeType; + private final McTtfFontManager fonts; + private final SimpleTextRuntime text; + private final SimpleGuiRuntime gui; + + private @Nullable PreSplashState state; + + public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex) throws Exception { + Preconditions.checkNotNull(assetsDirectory); + + scope = GLResourceManager.openScope(); + + try { + var constructor = FreeTypeManager.class.getDeclaredConstructor(); + constructor.setAccessible(true); + FreeTypeManager freeType = constructor.newInstance(); + freeType.loggerName = "pre_splash"; + freeType.init(); + this.freeType = freeType; + + Preconditions.checkNotNull(assetsDirectory); + ResourceIndex index = assetIndex == null + ? new ResourceIndexFolder(assetsDirectory) + : new ResourceIndex(assetsDirectory, assetIndex); + fonts = new McTtfFontManager(new DefaultResourcePack(index), freeType); + fonts.loggerName = "pre_splash"; + var face = fonts.loadDefaultFace(48); + Preconditions.checkState(face != null, "Could not prepare the default Minecraft font."); + + ImmediateShaderAccess shaders = new ImmediateShaderAccess(rl -> { + String path = "/assets/" + rl.getNamespace() + "/" + rl.getPath(); + try (InputStream input = SdlSplashRenderer.class.getResourceAsStream(path)) { + Preconditions.checkNotNull(input, "Missing pre splash shader: %s", path); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Could not load pre splash shader " + path, e); + } + }); + + ST_Config config = new ST_Config( + ST_FontBackendType.FREE_TYPE, + 48, + 16, + 12, + FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); + + AttributeLayout layout = new AttributeLayout(); + layout.push(new Stride(0)); + VAO dummyVao = new VAO(layout, null, (VBOView @Nullable []) null); + + float uiWidth = PreSplashLayout.WIDTH / PreSplashLayout.UI_SCALE; + float uiHeight = PreSplashLayout.HEIGHT / PreSplashLayout.UI_SCALE; + gui = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + text = new SimpleTextRuntime( + (_, _) -> new FreeTypeFontHandle(face), + runtime -> { + DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); + renderer.loggerName = "pre_splash"; + return renderer; + }, + runtime -> new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS), + shaders, + new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), + new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), config, null); + + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } catch (Exception | Error failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + public void update(PreSplashState state) { + if (this.state == state) { + return; + } + + this.state = state; + } + + public void render(int width, int height) { + if (state == null) { + return; + } + + float scale = Math.min((float) width / PreSplashLayout.WIDTH, (float) height / PreSplashLayout.HEIGHT); + int viewportWidth = Math.round(PreSplashLayout.WIDTH * scale); + int viewportHeight = Math.round(PreSplashLayout.HEIGHT * scale); + GL11.glViewport((width - viewportWidth) / 2, (height - viewportHeight) / 2, viewportWidth, viewportHeight); + + int background = PreSplashLayout.BACKGROUND; + GL11.glClearColor(((background >> 16) & 255) / 255f, ((background >> 8) & 255) / 255f, (background & 255) / 255f, 1); + GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + + text.begin(); + text.append(state.title(), 48, 106, 32, 0xFFF1F4FA); + text.append(state.message(), 48, 190, 16, 0xFFB9C7DB); + text.append(state.details(), 48, 286, 16, 0xFF8998AE); + text.endDraw(); + } + + @Override + public void close() throws Exception { + try { + text.close(); + } finally { + try { + gui.close(); + } finally { + try { + fonts.destroy(); + } finally { + try { + freeType.destroy(); + } finally { + scope.close(); + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java new file mode 100644 index 000000000..7aabc3a8d --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.cleanroom.splash.pre.PreSplashState; + +import org.jspecify.annotations.Nullable; + +import javax.swing.JPanel; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; + +public final class SwingSplashRenderer extends JPanel { + + private final Runnable firstFrameReady; + + private @Nullable PreSplashState state; + private boolean firstFrame = true; + + public SwingSplashRenderer(Runnable firstFrameReady) { + this.firstFrameReady = firstFrameReady; + } + + public void update(PreSplashState state) { + if (this.state == state) { + return; + } + + this.state = state; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + if (state == null) { + return; + } + + Graphics2D draw = (Graphics2D) graphics.create(); + try { + draw.setColor(new Color(PreSplashLayout.BACKGROUND, true)); + draw.fillRect(0, 0, getWidth(), getHeight()); + double scale = Math.min((double) getWidth() / PreSplashLayout.WIDTH, (double) getHeight() / PreSplashLayout.HEIGHT); + draw.translate((getWidth() - PreSplashLayout.WIDTH * scale) / 2, (getHeight() - PreSplashLayout.HEIGHT * scale) / 2); + draw.scale(scale * PreSplashLayout.UI_SCALE, scale * PreSplashLayout.UI_SCALE); + draw.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + draw.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + drawText(draw, state.title(), 48, 106, 32, 0xFFF1F4FA); + drawText(draw, state.message(), 48, 190, 16, 0xFFB9C7DB); + drawText(draw, state.details(), 48, 286, 16, 0xFF8998AE); + } finally { + draw.dispose(); + } + + if (firstFrame) { + firstFrame = false; + firstFrameReady.run(); + } + } + + private static void drawText(Graphics2D draw, String value, float x, float y, float size, int color) { + draw.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 1).deriveFont(size)); + draw.setColor(new Color(color, true)); + draw.drawString(value, x, y); + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java new file mode 100644 index 000000000..579d326e4 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/package-info.java @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +@NullMarked +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import org.jspecify.annotations.NullMarked; From 6b0b75979dfdb07a58bf908dac74665fa5e8d6da Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:56:52 -0500 Subject: [PATCH 09/27] feat: now the renderer decides when to release game thread pause --- .../splash/pre/PreSplashScreenContainer.java | 116 ++++++++---------- .../pre/renderer/SdlSplashRenderer.java | 12 +- .../pre/renderer/SwingSplashRenderer.java | 14 +-- 3 files changed, 69 insertions(+), 73 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 2c50fec7f..089c73409 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -78,7 +78,7 @@ import java.util.jar.JarOutputStream; /** - * It owns the renderer lifecycle, SDL worker thread OR Swing process. + * It owns the renderer lifecycle, SDL window OR Swing process. */ public final class PreSplashScreenContainer { @@ -86,7 +86,6 @@ public final class PreSplashScreenContainer { public static final Logger LOGGER = LogManager.getLogger("Pre Splash Screen"); - private static final int INITIAL_WAIT_SECOND = 10; private static final int THREAD_START_TIMEOUT_SECOND = 30; private static final int THREAD_STOP_TIMEOUT_SECOND = 10; @@ -95,8 +94,7 @@ public final class PreSplashScreenContainer { private final Thread shutdownHook; private final PreSplashPresentation presentation; - private final CountDownLatch nativeReady = new CountDownLatch(1); - private final CountDownLatch firstFrameReady = new CountDownLatch(1); + private final CountDownLatch startupReady = new CountDownLatch(1); private final File assetsDirectory; private final @Nullable String assetIndex; @@ -126,23 +124,25 @@ private PreSplashScreenContainer(File assetsDirectory, @Nullable String assetInd * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) */ @ApiStatus.Internal - public static synchronized void start(File assetsDirectory, @Nullable String assetIndex) { + public static void start(File assetsDirectory, @Nullable String assetIndex) { Preconditions.checkNotNull(assetsDirectory); - Preconditions.checkState(instance == null, "Pre splash has already started."); - PreSplashScreenContainer screen = new PreSplashScreenContainer(assetsDirectory, assetIndex); - instance = screen; + PreSplashScreenContainer screen; + synchronized (PreSplashScreenContainer.class) { + Preconditions.checkState(instance == null, "Pre splash has already started."); + screen = new PreSplashScreenContainer(assetsDirectory, assetIndex); + instance = screen; - Runtime.getRuntime().addShutdownHook(screen.shutdownHook); - screen.thread.start(); // this::run + Runtime.getRuntime().addShutdownHook(screen.shutdownHook); + screen.thread.start(); // this::run + } - // wait for renderer initialization and its first frame + // wait until the renderer releases game startup long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_START_TIMEOUT_SECOND); boolean interrupted = false; while (true) { try { - if (!screen.nativeReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS) - || !screen.firstFrameReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { + if (!screen.startupReady.await(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { LOGGER.warn("Pre splash renderer did not become ready within {} seconds.", THREAD_START_TIMEOUT_SECOND); screen.stopAndWait(); } @@ -152,14 +152,6 @@ public static synchronized void start(File assetsDirectory, @Nullable String ass } } - if (screen.running) { - try { - TimeUnit.SECONDS.sleep(INITIAL_WAIT_SECOND); - } catch (InterruptedException e) { - interrupted = true; - } - } - if (interrupted) { Thread.currentThread().interrupt(); } @@ -171,12 +163,17 @@ public static synchronized void start(File assetsDirectory, @Nullable String ass * @see FMLClientHandler#beginMinecraftLoading(Minecraft, List, IReloadableResourceManager, MetadataSerializer) */ @ApiStatus.Internal - public static synchronized void finish() { - if (instance == null) { - return; + public static void finish() { + PreSplashScreenContainer screen; + synchronized (PreSplashScreenContainer.class) { + if (instance == null) { + return; + } + + screen = instance; } - instance.stopAndWait(); + screen.stopAndWait(); } private void stopAndWait() { @@ -198,13 +195,23 @@ private void stopAndWait() { } } + // only if the renderer has not signaled yet + startupReady.countDown(); + if (interrupted) { Thread.currentThread().interrupt(); } } + private boolean isRunning() { + return running && gameThread.isAlive() && !presentation.isFinished(); + } + private void run() { try { + if (!isRunning()) { + return; + } boolean mac = System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("mac"); if (mac || !runSdl()) { if (isRunning()) { @@ -215,8 +222,7 @@ private void run() { LOGGER.warn("Pre splash unavailable. Continue normal startup.", failure); } finally { running = false; - nativeReady.countDown(); - firstFrameReady.countDown(); + startupReady.countDown(); try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException ignored) { @@ -225,10 +231,6 @@ private void run() { } } - private boolean isRunning() { - return running && gameThread.isAlive() && !presentation.isFinished(); - } - // private boolean runSdl() { Thread renderThread = Thread.currentThread(); @@ -247,15 +249,13 @@ private boolean runSdl() { Supplier.class, Runnable.class, Runnable.class, - Runnable.class, Runnable.class).newInstance( assetsDirectory, assetIndex, (BooleanSupplier) this::isRunning, (Supplier) presentation::nextFrame, (Runnable) () -> running = false, - (Runnable) nativeReady::countDown, - (Runnable) firstFrameReady::countDown, + (Runnable) startupReady::countDown, (Runnable) () -> unavailable[0] = true); // SDL ENTRYPOINT @@ -271,13 +271,12 @@ private boolean runSdl() { return !unavailable[0]; } - private void runSwing() throws IOException, InterruptedException { + private void runSwing() throws IOException { // SWING ENTRYPOINT new SwingRenderer( this::isRunning, presentation::nextFrame, - nativeReady::countDown, - firstFrameReady::countDown).run(); + startupReady::countDown).run(); } // @@ -293,8 +292,7 @@ public static final class SdlRenderer implements Runnable { private final BooleanSupplier running; private final Supplier state; private final Runnable stop; - private final Runnable nativeReady; - private final Runnable firstFrameReady; + private final Runnable startupReady; private final Runnable unavailable; @ReflectiveInvocation @@ -304,16 +302,14 @@ public SdlRenderer( BooleanSupplier running, Supplier state, Runnable stop, - Runnable nativeReady, - Runnable firstFrameReady, + Runnable startupReady, Runnable unavailable) { Preconditions.checkNotNull(assetsDirectory); Preconditions.checkNotNull(running); Preconditions.checkNotNull(state); Preconditions.checkNotNull(stop); - Preconditions.checkNotNull(nativeReady); - Preconditions.checkNotNull(firstFrameReady); + Preconditions.checkNotNull(startupReady); Preconditions.checkNotNull(unavailable); this.assetsDirectory = assetsDirectory; @@ -321,21 +317,19 @@ public SdlRenderer( this.running = running; this.state = state; this.stop = stop; - this.nativeReady = nativeReady; - this.firstFrameReady = firstFrameReady; + this.startupReady = startupReady; this.unavailable = unavailable; } @Override public void run() { try (Window window = Window.open(stop)) { - nativeReady.run(); if (running.getAsBoolean()) { - try (SdlSplashRenderer renderer = new SdlSplashRenderer(assetsDirectory, assetIndex)) { + try (SdlSplashRenderer renderer = new SdlSplashRenderer(assetsDirectory, assetIndex, startupReady)) { window.runLoop(running, (width, height) -> { renderer.update(state.get()); renderer.render(width, height); - }, firstFrameReady); + }); } } } catch (Throwable failure) { @@ -480,9 +474,8 @@ private void initialize(Runnable stop) { initialized = true; } - void runLoop(BooleanSupplier running, BiConsumer draw, Runnable firstFrameReady) { + void runLoop(BooleanSupplier running, BiConsumer draw) { checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); - boolean firstFrame = true; try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer width = stack.mallocInt(1); IntBuffer height = stack.mallocInt(1); @@ -497,10 +490,6 @@ void runLoop(BooleanSupplier running, BiConsumer draw, Runnabl draw.accept(width.get(0), height.get(0)); checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); - if (firstFrame) { - firstFrame = false; - firstFrameReady.run(); - } long remaining = TimeUnit.SECONDS.toNanos(1) / TARGET_FRAME_RATE - (System.nanoTime() - frameStart); if (remaining > 0) { LockSupport.parkNanos(remaining); @@ -575,18 +564,16 @@ public static final class SwingRenderer { private final BooleanSupplier running; private final Supplier state; - private final Runnable nativeReady; - private final Runnable firstFrameReady; + private final Runnable startupReady; - private SwingRenderer(BooleanSupplier running, Supplier state, Runnable nativeReady, Runnable firstFrameReady) { + private SwingRenderer(BooleanSupplier running, Supplier state, Runnable startupReady) { this.running = running; this.state = state; - this.nativeReady = nativeReady; - this.firstFrameReady = firstFrameReady; + this.startupReady = startupReady; } private void run() throws IOException { - new HelperProcess(running, state, nativeReady, firstFrameReady).run(); + new HelperProcess(running, state, startupReady).run(); } static final class Protocol { @@ -640,7 +627,7 @@ static void readReady(DataInputStream input) throws IOException { } } - private record HelperProcess(BooleanSupplier running, Supplier state, Runnable nativeReady, Runnable firstFrameReady) { + private record HelperProcess(BooleanSupplier running, Supplier state, Runnable startupReady) { private static void writeHelperClass(JarOutputStream output, Class type, Set entries) throws IOException { String resource = type.getName().replace('.', '/') + ".class"; @@ -716,8 +703,7 @@ private void run() throws IOException { if (!ready) { centerWindowOnNiri(windowTitle); ready = true; - nativeReady.run(); - firstFrameReady.run(); + startupReady.run(); } } @@ -874,7 +860,7 @@ public static final class Helper { private static final int TARGET_FRAME_RATE = 60; - private final SwingSplashRenderer renderer = new SwingSplashRenderer(Helper::notifyReady); + private final SwingSplashRenderer renderer = new SwingSplashRenderer(Helper::signalStartupReady); private @Nullable JDialog window; private @Nullable Timer timer; @@ -949,7 +935,7 @@ private void open(String windowTitle) { timer.start(); } - private static void notifyReady() { + private static void signalStartupReady() { try { Protocol.ready(new DataOutputStream(System.out)); } catch (IOException failure) { diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index db22481d7..ab840dc80 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -52,11 +52,16 @@ public final class SdlSplashRenderer implements AutoCloseable { private final McTtfFontManager fonts; private final SimpleTextRuntime text; private final SimpleGuiRuntime gui; + private final Runnable startupReady; private @Nullable PreSplashState state; + private boolean startupSignaled; - public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex) throws Exception { + public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { Preconditions.checkNotNull(assetsDirectory); + Preconditions.checkNotNull(startupReady); + + this.startupReady = startupReady; scope = GLResourceManager.openScope(); @@ -154,6 +159,11 @@ public void render(int width, int height) { text.append(state.message(), 48, 190, 16, 0xFFB9C7DB); text.append(state.details(), 48, 286, 16, 0xFF8998AE); text.endDraw(); + + if (!startupSignaled) { + startupSignaled = true; + startupReady.run(); + } } @Override diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java index 7aabc3a8d..747c3df58 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java @@ -23,13 +23,13 @@ public final class SwingSplashRenderer extends JPanel { - private final Runnable firstFrameReady; + private final Runnable startupReady; private @Nullable PreSplashState state; - private boolean firstFrame = true; + private boolean startupSignaled; - public SwingSplashRenderer(Runnable firstFrameReady) { - this.firstFrameReady = firstFrameReady; + public SwingSplashRenderer(Runnable startupReady) { + this.startupReady = startupReady; } public void update(PreSplashState state) { @@ -63,9 +63,9 @@ protected void paintComponent(Graphics graphics) { draw.dispose(); } - if (firstFrame) { - firstFrame = false; - firstFrameReady.run(); + if (!startupSignaled) { + startupSignaled = true; + startupReady.run(); } } From cc41fe7185988889aa2191d965fd5bfafe1ccb2d Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sat, 7 Nov 2026 17:45:54 -0500 Subject: [PATCH 10/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index dfea9d6e0..0629f45f7 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit dfea9d6e00f2ea41bb914e0db56f835d2f05f836 +Subproject commit 0629f45f70b3b6a9fac9688894246b8f9c2b295e From c34c1fc031195cacf7674ac734fa4fcecd2d17aa Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sun, 8 Nov 2026 00:36:43 -0500 Subject: [PATCH 11/27] feat: early mc font loading for SdlSplashRenderer + logger for both SwingSplashRenderer & SdlSplashRenderer --- .../splash/pre/PreSplashScreenContainer.java | 124 ++++++- .../splash/pre/renderer/PreSplashLogger.java | 103 ++++++ .../pre/renderer/SdlSplashRenderer.java | 326 +++++++++++++++--- .../pre/renderer/SwingSplashRenderer.java | 4 + 4 files changed, 491 insertions(+), 66 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 089c73409..260c6d05f 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -12,6 +12,7 @@ import com.cleanroommc.anone.reveal.ReflectiveInvocation; import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLayout; +import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger; import com.cleanroommc.cleanroom.splash.pre.renderer.SdlSplashRenderer; import com.cleanroommc.cleanroom.splash.pre.renderer.SwingSplashRenderer; @@ -58,6 +59,8 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; import java.nio.IntBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -86,7 +89,7 @@ public final class PreSplashScreenContainer { public static final Logger LOGGER = LogManager.getLogger("Pre Splash Screen"); - private static final int THREAD_START_TIMEOUT_SECOND = 30; + private static final int THREAD_START_TIMEOUT_SECOND = 45; private static final int THREAD_STOP_TIMEOUT_SECOND = 10; private final Thread gameThread; @@ -179,6 +182,9 @@ public static void finish() { private void stopAndWait() { running = false; LockSupport.unpark(thread); + if (Thread.currentThread() == thread) { + return; + } long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); boolean interrupted = false; @@ -209,6 +215,7 @@ private boolean isRunning() { private void run() { try { + LOGGER.info("Starting pre splash screen."); if (!isRunning()) { return; } @@ -228,6 +235,7 @@ private void run() { } catch (IllegalStateException ignored) { // if shutdown has already begun } + LOGGER.info("Pre splash screen stopped."); } } @@ -559,7 +567,6 @@ public void close() { @ApiStatus.Internal public static final class SwingRenderer { - private static final int HELPER_START_TIMEOUT_SECOND = 15; private static final int HELPER_STOP_TIMEOUT_SECOND = 2; private final BooleanSupplier running; @@ -581,6 +588,8 @@ static final class Protocol { private static final int STATE = 1; private static final int CLOSE = 2; private static final int READY = 3; + private static final int LOG = 4; + private static final int MAX_LOG_BYTES = 1024 * 1024; private Protocol() { } @@ -616,13 +625,80 @@ static void close(DataOutputStream output) throws IOException { } static void ready(DataOutputStream output) throws IOException { - output.writeByte(READY); - output.flush(); + synchronized (output) { + output.writeByte(READY); + output.flush(); + } + } + + static void log(DataOutputStream output, PreSplashLogger.Level level, String message, @Nullable Throwable failure) throws IOException { + if (failure != null) { + StringWriter stack = new StringWriter(); + failure.printStackTrace(new PrintWriter(stack)); + message += "\n" + stack; + } + + byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + if (bytes.length > MAX_LOG_BYTES) { + throw new IOException("Pre splash log message is too large."); + } + + synchronized (output) { + output.writeByte(LOG); + output.writeByte(level.ordinal()); + output.writeInt(bytes.length); + output.write(bytes); + output.flush(); + } } - static void readReady(DataInputStream input) throws IOException { - if (input.readUnsignedByte() != READY) { - throw new IOException("Invalid pre splash readiness reply."); + private static final class ReplyReader { + + private final DataInputStream input; + private byte @Nullable [] bytes; + private int level; + private int offset; + + private ReplyReader(DataInputStream input) { + this.input = input; + } + + private int poll() throws IOException { + if (bytes == null) { + if (input.available() == 0) { + return 0; + } + input.mark(6); + int reply = input.readUnsignedByte(); + if (reply == READY) { + return READY; + } + if (reply != LOG) { + throw new IOException("Invalid pre splash reply: " + reply); + } + if (input.available() < 5) { + input.reset(); + return 0; + } + level = input.readUnsignedByte(); + int length = input.readInt(); + if (level >= PreSplashLogger.Level.values().length || length < 0 || length > MAX_LOG_BYTES) { + throw new IOException("Invalid pre splash log message."); + } + bytes = new byte[length]; + offset = 0; + } + + int available = Math.min(input.available(), bytes.length - offset); + input.readFully(bytes, offset, available); + offset += available; + if (offset < bytes.length) { + return 0; + } + + PreSplashLogger.LOGGER.log(PreSplashLogger.Level.values()[level], new String(bytes, StandardCharsets.UTF_8)); + bytes = null; + return LOG; } } } @@ -656,7 +732,7 @@ private void run() throws IOException { try { try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(helperJar))) { Set entries = new HashSet<>(); - for (Class type : List.of(Protocol.class, Helper.class, PreSplashState.class, SwingSplashRenderer.class, PreSplashLayout.class)) { + for (Class type : List.of(Protocol.class, Helper.class, PreSplashState.class, SwingSplashRenderer.class, PreSplashLayout.class, PreSplashLogger.class)) { writeHelperClass(output, type, entries); } } @@ -680,11 +756,11 @@ private void run() throws IOException { helper = builder.start(); try (DataOutputStream commands = new DataOutputStream(new BufferedOutputStream(helper.getOutputStream())); - DataInputStream replies = new DataInputStream(helper.getInputStream())) { + DataInputStream replies = new DataInputStream(new BufferedInputStream(helper.getInputStream()))) { PreSplashState previous = null; boolean ready = false; - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(HELPER_START_TIMEOUT_SECOND); + Protocol.ReplyReader reader = new Protocol.ReplyReader(replies); while (running.getAsBoolean()) { PreSplashState current = state.get(); @@ -698,20 +774,15 @@ private void run() throws IOException { previous = current; } - while (replies.available() > 0) { - Protocol.readReady(replies); - if (!ready) { + int reply; + while ((reply = reader.poll()) != 0) { + if (reply == Protocol.READY && !ready) { centerWindowOnNiri(windowTitle); ready = true; startupReady.run(); } } - if (!ready && System.nanoTime() >= deadline) { - LOGGER.warn("Swing pre splash helper did not become ready in time."); - break; - } - LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50)); } @@ -860,6 +931,8 @@ public static final class Helper { private static final int TARGET_FRAME_RATE = 60; + private static final DataOutputStream REPLIES = new DataOutputStream(System.out); + private final SwingSplashRenderer renderer = new SwingSplashRenderer(Helper::signalStartupReady); private @Nullable JDialog window; @@ -867,6 +940,7 @@ public static final class Helper { public static void main(String[] args) { try { + PreSplashLogger.setSink(Helper::log); ProcessHandle parent = ProcessHandle.of(Long.parseLong(args[0])).orElse(null); if (parent == null) { return; @@ -937,13 +1011,25 @@ private void open(String windowTitle) { private static void signalStartupReady() { try { - Protocol.ready(new DataOutputStream(System.out)); + Protocol.ready(REPLIES); } catch (IOException failure) { failure.printStackTrace(System.err); System.exit(1); } } + private static void log(PreSplashLogger.Level level, String message, @Nullable Throwable failure) { + try { + Protocol.log(REPLIES, level, message, failure); + } catch (IOException error) { + System.err.println("[" + level + "] [Pre Splash Renderer]: " + message); + if (failure != null) { + failure.printStackTrace(System.err); + } + error.printStackTrace(System.err); + } + } + private void close() { if (timer != null) { timer.stop(); diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java new file mode 100644 index 000000000..33e518577 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLogger.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jspecify.annotations.Nullable; + +import java.util.Objects; + +public final class PreSplashLogger { + + public enum Level { + TRACE, + DEBUG, + INFO, + WARN, + ERROR + } + + @FunctionalInterface + public interface Sink { + + void log(Level level, String message, @Nullable Throwable failure); + } + + private static final class Log4j { + + private static final Logger LOGGER = LogManager.getLogger("Pre Splash Renderer"); + + private static void log(Level level, String message, @Nullable Throwable failure) { + LOGGER.log(org.apache.logging.log4j.Level.valueOf(level.name()), message, failure); + } + } + + public static final PreSplashLogger LOGGER = new PreSplashLogger(); + + private static volatile @Nullable Sink sink; + + private PreSplashLogger() { + } + + public static void setSink(Sink sink) { + PreSplashLogger.sink = Objects.requireNonNull(sink); + } + + public void trace(String message, Object... arguments) { + log(Level.TRACE, message, arguments); + } + + public void debug(String message, Object... arguments) { + log(Level.DEBUG, message, arguments); + } + + public void info(String message, Object... arguments) { + log(Level.INFO, message, arguments); + } + + public void warn(String message, Object... arguments) { + log(Level.WARN, message, arguments); + } + + public void error(String message, Object... arguments) { + log(Level.ERROR, message, arguments); + } + + /** + * Supports {} placeholders and an optional Throwable. + */ + public void log(Level level, String message, Object... arguments) { + Throwable failure = arguments.length > 0 && arguments[arguments.length - 1] instanceof Throwable cause ? cause : null; + int count = arguments.length - (failure == null ? 0 : 1); + + if (count > 0) { + StringBuilder formatted = new StringBuilder(); + int offset = 0; + for (int i = 0; i < count; i++) { + int placeholder = message.indexOf("{}", offset); + if (placeholder < 0) { + break; + } + formatted.append(message, offset, placeholder).append(arguments[i]); + offset = placeholder + 2; + } + message = formatted.append(message, offset, message.length()).toString(); + } + + Sink sink = PreSplashLogger.sink; + if (sink == null) { + Log4j.log(level, message, failure); + } else { + sink.log(level, message, failure); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index ab840dc80..d83d5e344 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -17,7 +17,7 @@ import com.cleanroommc.kirino.gl.vao.VAO; import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; import com.cleanroommc.kirino.gl.vao.attribute.Stride; -import com.cleanroommc.kirino.ui.font.McTtfFontManager; +import com.cleanroommc.kirino.ui.font.McTtfFontData; import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; import com.cleanroommc.kirino.ui.simpletext.ST_Config; import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; @@ -30,101 +30,308 @@ import com.cleanroommc.mcttf.glyph.GlyphBuilder; import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; import org.jspecify.annotations.Nullable; import net.minecraft.client.resources.DefaultResourcePack; import net.minecraft.client.resources.ResourceIndex; import net.minecraft.client.resources.ResourceIndexFolder; +import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.util.freetype.FT_Face; import org.lwjgl.util.freetype.FreeType; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; public final class SdlSplashRenderer implements AutoCloseable { - private final GLResourceManager.ResourceScope scope; + /** + * FreeType & GL agnostic async font loader. + */ + private static final class FontLoader implements AutoCloseable { - private final FreeTypeManager freeType; - private final McTtfFontManager fonts; - private final SimpleTextRuntime text; - private final SimpleGuiRuntime gui; - private final Runnable startupReady; + private static final int LOAD_TIMEOUT_SECOND = 30; + private static final int THREAD_STOP_TIMEOUT_SECOND = 2; + + private final Thread thread; + private final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(LOAD_TIMEOUT_SECOND); + private byte @Nullable [] data; + private boolean finished; + private boolean closed; + + private FontLoader(File assetsDirectory, @Nullable String assetIndex) { + thread = new Thread(() -> load(assetsDirectory, assetIndex), "Pre Splash Font Loader"); + thread.setDaemon(true); + } + + private synchronized boolean isFinished() { + if (!finished && deadline - System.nanoTime() <= 0) { + LOGGER.warn("Pre splash Minecraft font loading timed out after {} seconds.", LOAD_TIMEOUT_SECOND); + cancel(); + } + + return finished; + } + + @SuppressWarnings("DataFlowIssue") + private synchronized byte @Nullable [] take() { + byte[] data = this.data; + this.data = null; + return data; + } + + @SuppressWarnings("DataFlowIssue") + private void load(File assetsDirectory, @Nullable String assetIndex) { + StopWatch stopWatch = StopWatch.createStarted(); + byte[] data = null; + + try { + synchronized (this) { + if (closed || isFinished()) { + return; + } + } + + ResourceIndex index = assetIndex == null + ? new ResourceIndexFolder(assetsDirectory) + : new ResourceIndex(assetsDirectory, assetIndex); + + synchronized (this) { + if (closed || isFinished()) { + return; + } + } + + data = McTtfFontData.loadDefault(new DefaultResourcePack(index), "pre_splash"); + } catch (Throwable failure) { + LOGGER.warn("Could not prepare the pre splash Minecraft font.", failure); + } finally { + stopWatch.stop(); + synchronized (this) { + if (!closed && !isFinished()) { + this.data = data; + if (data != null) { + LOGGER.info("Pre splash Minecraft font loaded in {} ms.", stopWatch.getTime(TimeUnit.MILLISECONDS)); + } + } + finished = true; + } + } + } + + private void cancel() { + synchronized (this) { + closed = true; + finished = true; + data = null; + } + + thread.interrupt(); + } + @Override + public void close() { + cancel(); + if (Thread.currentThread() == thread) { + return; + } + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); + boolean interrupted = false; + while (thread.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + LOGGER.warn("Pre splash font loader did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); + break; + } + try { + TimeUnit.NANOSECONDS.timedJoin(thread, remaining); + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + private static final ResourceLocation FALLBACK_FONT = new ResourceLocation("kirino:fonts/jetbrains/jetbrains_mono_nl_regular.ttf"); + private static final long ENTRY_ANIMATION_MILLIS = 1000; + + private final StopWatch entryAnimationStopWatch = new StopWatch(); + + private final GLResourceManager.ResourceScope scope; + private final FontLoader fontLoader; + private final ImmediateShaderAccess shaders; + private final VAO dummyVao; + private final Runnable startupReady; + private final @Nullable SimpleGuiRuntime gui; + private final @Nullable FreeTypeManager freeType; + private @Nullable ByteBuffer mcFontData; + private @Nullable SimpleTextRuntime text; private @Nullable PreSplashState state; + private boolean fontResolved; private boolean startupSignaled; public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { + LOGGER.info("Pre Splash Screen Backend: SDL + GL46"); + Preconditions.checkNotNull(assetsDirectory); Preconditions.checkNotNull(startupReady); this.startupReady = startupReady; + fontLoader = new FontLoader(assetsDirectory, assetIndex); scope = GLResourceManager.openScope(); try { - var constructor = FreeTypeManager.class.getDeclaredConstructor(); - constructor.setAccessible(true); - FreeTypeManager freeType = constructor.newInstance(); - freeType.loggerName = "pre_splash"; - freeType.init(); - this.freeType = freeType; - - Preconditions.checkNotNull(assetsDirectory); - ResourceIndex index = assetIndex == null - ? new ResourceIndexFolder(assetsDirectory) - : new ResourceIndex(assetsDirectory, assetIndex); - fonts = new McTtfFontManager(new DefaultResourcePack(index), freeType); - fonts.loggerName = "pre_splash"; - var face = fonts.loadDefaultFace(48); - Preconditions.checkState(face != null, "Could not prepare the default Minecraft font."); + fontLoader.thread.start(); - ImmediateShaderAccess shaders = new ImmediateShaderAccess(rl -> { + shaders = new ImmediateShaderAccess(rl -> { String path = "/assets/" + rl.getNamespace() + "/" + rl.getPath(); try (InputStream input = SdlSplashRenderer.class.getResourceAsStream(path)) { Preconditions.checkNotNull(input, "Missing pre splash shader: %s", path); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("Could not load pre splash shader " + path, e); } }); - ST_Config config = new ST_Config( - ST_FontBackendType.FREE_TYPE, - 48, - 16, - 12, - FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); - AttributeLayout layout = new AttributeLayout(); layout.push(new Stride(0)); - VAO dummyVao = new VAO(layout, null, (VBOView @Nullable []) null); + dummyVao = new VAO(layout, null, (VBOView @Nullable []) null); float uiWidth = PreSplashLayout.WIDTH / PreSplashLayout.UI_SCALE; float uiHeight = PreSplashLayout.HEIGHT / PreSplashLayout.UI_SCALE; gui = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); - text = new SimpleTextRuntime( + + var constructor = FreeTypeManager.class.getDeclaredConstructor(); + constructor.setAccessible(true); + FreeTypeManager freeType = constructor.newInstance(); + freeType.loggerName = "pre_splash"; + freeType.init(); + this.freeType = freeType; + text = createText(freeType.load(FALLBACK_FONT, 0, 48), false); + + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + @SuppressWarnings("DataFlowIssue") + private void resolveFont() { + if (fontResolved || !fontLoader.isFinished()) { + return; + } + + fontResolved = true; + byte[] bytes = fontLoader.take(); + if (bytes == null) { + LOGGER.warn("Could not load the pre splash Minecraft font."); + return; + } + + Preconditions.checkNotNull(freeType); + + ByteBuffer data = null; + SimpleTextRuntime replacement; + try { + data = MemoryUtil.memAlloc(bytes.length); + data.put(bytes).flip(); + replacement = createText(freeType.load(data, 0, 48), true); + } catch (Throwable failure) { + if (data != null) { + try { + freeType.unload(data); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } finally { + MemoryUtil.memFree(data); + } + } + LOGGER.warn("Could not initialize pre splash Minecraft text.", failure); + return; + } + + SimpleTextRuntime previous = text; + text = replacement; + mcFontData = data; + + try { + if (previous != null) { + previous.close(); + } + } catch (Throwable failure) { + LOGGER.warn("Could not dispose the previous pre splash text runtime.", failure); + } finally { + freeType.unload(FALLBACK_FONT); + } + } + + private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { + ST_Config config = new ST_Config( + ST_FontBackendType.FREE_TYPE, + 48, + 16, + 12, + FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); + + float uiWidth = PreSplashLayout.WIDTH / PreSplashLayout.UI_SCALE; + float uiHeight = PreSplashLayout.HEIGHT / PreSplashLayout.UI_SCALE; + SimpleGuiRuntime underline = null; + SimpleGuiRuntime strikethrough = null; + + try { + underline = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + strikethrough = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + return new SimpleTextRuntime( (_, _) -> new FreeTypeFontHandle(face), runtime -> { DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); renderer.loggerName = "pre_splash"; return renderer; }, - runtime -> new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS), + runtime -> minecraftFont + ? new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS) + : new DefaultTextProducer(runtime, config.pixelSize()), shaders, - new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), - new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight), config, null); - - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - } catch (Exception | Error failure) { + underline, + strikethrough, + config, + null); + } catch (Throwable failure) { try { - close(); + if (strikethrough != null) { + strikethrough.close(); + } + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + try { + if (underline != null) { + underline.close(); + } } catch (Throwable cleanup) { failure.addSuppressed(cleanup); } @@ -154,13 +361,29 @@ public void render(int width, int height) { GL11.glClearColor(((background >> 16) & 255) / 255f, ((background >> 8) & 255) / 255f, (background & 255) / 255f, 1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + if (entryAnimationStopWatch.isStarted() && entryAnimationStopWatch.getTime(TimeUnit.MILLISECONDS) >= ENTRY_ANIMATION_MILLIS) { + resolveFont(); + } + + SimpleTextRuntime text = Preconditions.checkNotNull(this.text); text.begin(); text.append(state.title(), 48, 106, 32, 0xFFF1F4FA); text.append(state.message(), 48, 190, 16, 0xFFB9C7DB); text.append(state.details(), 48, 286, 16, 0xFF8998AE); text.endDraw(); - if (!startupSignaled) { + if (!entryAnimationStopWatch.isStarted()) { + entryAnimationStopWatch.start(); + } + + if (!fontResolved) { + double seconds = entryAnimationStopWatch.getTime(TimeUnit.MILLISECONDS) / 1000.0; + float x = 48 + (float) (0.5 - Math.cos(seconds * Math.PI) * 0.5) * 208; + SimpleGuiRuntime gui = Preconditions.checkNotNull(this.gui); + gui.begin().append(stream -> stream.rect(x, 232, 40, 6, 0xFF8998AE)).endDraw(); + } + + if (fontResolved && !startupSignaled) { startupSignaled = true; startupReady.run(); } @@ -168,17 +391,26 @@ public void render(int width, int height) { @Override public void close() throws Exception { + fontLoader.close(); try { - text.close(); + if (text != null) { + text.close(); + } } finally { try { - gui.close(); + if (gui != null) { + gui.close(); + } } finally { try { - fonts.destroy(); + if (freeType != null) { + freeType.destroy(); + } } finally { try { - freeType.destroy(); + if (mcFontData != null) { + MemoryUtil.memFree(mcFontData); + } } finally { scope.close(); } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java index 747c3df58..f680abcce 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java @@ -21,6 +21,8 @@ import java.awt.Graphics2D; import java.awt.RenderingHints; +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + public final class SwingSplashRenderer extends JPanel { private final Runnable startupReady; @@ -29,6 +31,8 @@ public final class SwingSplashRenderer extends JPanel { private boolean startupSignaled; public SwingSplashRenderer(Runnable startupReady) { + LOGGER.info("Pre Splash Screen Backend: Swing"); + this.startupReady = startupReady; } From 11ec54a86afdbeb63ca557b017075498abd52a00 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sun, 8 Nov 2026 01:51:17 -0500 Subject: [PATCH 12/27] fix: swing renderer not consuming some logs before quit --- .../splash/pre/PreSplashScreenContainer.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 260c6d05f..e70157bd2 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -764,18 +764,15 @@ private void run() throws IOException { while (running.getAsBoolean()) { PreSplashState current = state.get(); - if (!helper.isAlive()) { - LOGGER.warn("Swing pre splash helper exited with code {}.", helper.exitValue()); - break; - } + boolean alive = helper.isAlive(); - if (current != previous) { + if (alive && current != previous) { Protocol.writeState(commands, current); previous = current; } int reply; - while ((reply = reader.poll()) != 0) { + while (running.getAsBoolean() && (reply = reader.poll()) != 0) { if (reply == Protocol.READY && !ready) { centerWindowOnNiri(windowTitle); ready = true; @@ -783,6 +780,11 @@ private void run() throws IOException { } } + if (!alive) { + LOGGER.warn("Swing pre splash helper exited with code {}.", helper.exitValue()); + break; + } + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(50)); } From eb40d67079687aa11d7286882c588fa13465dc55 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:46:59 -0500 Subject: [PATCH 13/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index 0629f45f7..c5a476064 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 0629f45f70b3b6a9fac9688894246b8f9c2b295e +Subproject commit c5a4760646638e682021a2c727d10e7434476fc4 From 0f27eb9f6bcf4a9f0fabf860805793b40c61a365 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Sun, 8 Nov 2026 23:28:15 -0500 Subject: [PATCH 14/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index c5a476064..91ac13e82 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit c5a4760646638e682021a2c727d10e7434476fc4 +Subproject commit 91ac13e82f05f1085653287f64349993b6a79fdb From c5d76f80ce080284b9febe8c0bb5fdfdedd7b1c4 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:31:25 -0500 Subject: [PATCH 15/27] refactor(sdl renderer): remove Minecraft dependency --- .../splash/pre/PreSplashClassLoader.java | 3 +- .../pre/renderer/SdlSplashRenderer.java | 105 +++++++++++++++--- module/kirino | 2 +- 3 files changed, 90 insertions(+), 20 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java index faba82cef..5c4670825 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java @@ -14,7 +14,7 @@ import java.io.InputStream; /** - * Motivation is to keep pre splash's untransformed LWJGL3 classes out of the game's loader. + * Motivation is to keep pre splash's untransformed classes out of the game's loader. * *

Note: Only applied to {@link PreSplashScreenContainer.SdlRenderer}.

*/ @@ -27,6 +27,7 @@ final class PreSplashClassLoader extends ClassLoader { private static boolean isIsolated(String name) { return name.startsWith("org.lwjgl.") || name.startsWith("com.cleanroommc.kirino.") + || name.startsWith("com.cleanroommc.mcttf.") || name.startsWith("com.cleanroommc.cleanroom.splash.pre.PreSplashScreenContainer$") || name.startsWith("com.cleanroommc.cleanroom.splash.pre.renderer."); } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index d83d5e344..2e376c9ea 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -27,28 +27,34 @@ import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.cleanroommc.mcttf.extract.AssetSource; import com.cleanroommc.mcttf.glyph.GlyphBuilder; import com.google.common.base.Preconditions; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import org.apache.commons.lang3.time.StopWatch; import org.jspecify.annotations.Nullable; -import net.minecraft.client.resources.DefaultResourcePack; -import net.minecraft.client.resources.ResourceIndex; -import net.minecraft.client.resources.ResourceIndexFolder; -import net.minecraft.util.ResourceLocation; - import org.lwjgl.opengl.GL11; import org.lwjgl.system.MemoryUtil; import org.lwjgl.util.freetype.FT_Face; import org.lwjgl.util.freetype.FreeType; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; @@ -59,6 +65,73 @@ public final class SdlSplashRenderer implements AutoCloseable { */ private static final class FontLoader implements AutoCloseable { + private static final class Assets implements AssetSource { + + private static final Pattern HASH = Pattern.compile("[0-9a-f]{40}"); + + private final Path directory; + private final @Nullable Map index; + + private Assets(Path directory, @Nullable String assetIndex) { + this.directory = directory; + if (assetIndex == null) { + index = null; + return; + } + + index = new HashMap<>(); + Path file = directory.resolve("indexes").resolve(assetIndex + ".json"); + try (var reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + JsonObject objects = JsonParser.parseReader(reader).getAsJsonObject().getAsJsonObject("objects"); + if (objects != null) { + for (var entry : objects.entrySet()) { + String hash = entry.getValue().getAsJsonObject().get("hash").getAsString(); + if (!HASH.matcher(hash).matches()) { + throw new IOException("Invalid asset hash: " + hash); + } + + index.put(entry.getKey(), directory.resolve("objects").resolve(hash.substring(0, 2)).resolve(hash)); + } + } + } catch (Throwable failure) { + index.clear(); + LOGGER.warn("Could not read pre splash asset index {}.", file, failure); + } + } + + @Nullable + private Path find(String path) { + Preconditions.checkArgument(path.startsWith("assets/"), "Invalid asset path: %s", path); + + String name = path.substring("assets/".length()); + Path file = index == null ? directory.resolve(name) : index.get(name); + return file != null && Files.isRegularFile(file) ? file : null; + } + + @Override + public boolean exists(String path) { + return find(path) != null || SdlSplashRenderer.class.getResource("/" + path) != null; + } + + @Override + public InputStream open(String path) throws IOException { + Path file = find(path); + if (file != null) { + return Files.newInputStream(file); + } + InputStream input = SdlSplashRenderer.class.getResourceAsStream("/" + path); + if (input == null) { + throw new FileNotFoundException(path); + } + return input; + } + + @Override + public void close() { + // NO OP + } + } + private static final int LOAD_TIMEOUT_SECOND = 30; private static final int THREAD_STOP_TIMEOUT_SECOND = 2; @@ -101,17 +174,16 @@ private void load(File assetsDirectory, @Nullable String assetIndex) { } } - ResourceIndex index = assetIndex == null - ? new ResourceIndexFolder(assetsDirectory) - : new ResourceIndex(assetsDirectory, assetIndex); + Assets source = new Assets(assetsDirectory.toPath(), assetIndex); synchronized (this) { if (closed || isFinished()) { + source.close(); return; } } - data = McTtfFontData.loadDefault(new DefaultResourcePack(index), "pre_splash"); + data = McTtfFontData.loadDefault(source, "pre_splash"); } catch (Throwable failure) { LOGGER.warn("Could not prepare the pre splash Minecraft font.", failure); } finally { @@ -178,6 +250,7 @@ public void close() { private final Runnable startupReady; private final @Nullable SimpleGuiRuntime gui; private final @Nullable FreeTypeManager freeType; + private @Nullable ByteBuffer mcFontData; private @Nullable SimpleTextRuntime text; private @Nullable PreSplashState state; @@ -198,14 +271,11 @@ public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runn try { fontLoader.thread.start(); - shaders = new ImmediateShaderAccess(rl -> { - String path = "/assets/" + rl.getNamespace() + "/" + rl.getPath(); - try (InputStream input = SdlSplashRenderer.class.getResourceAsStream(path)) { - Preconditions.checkNotNull(input, "Missing pre splash shader: %s", path); - + shaders = ImmediateShaderAccess.fromSourceLoader(rl -> { + try (InputStream input = MinecraftResourceUtils.getEarlyInputStream(rl)) { return new String(input.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { - throw new IllegalStateException("Could not load pre splash shader " + path, e); + throw new IllegalStateException("Could not load pre splash shader " + rl, e); } }); @@ -306,7 +376,7 @@ private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { underline = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); strikethrough = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); return new SimpleTextRuntime( - (_, _) -> new FreeTypeFontHandle(face), + _ -> new FreeTypeFontHandle(face), runtime -> { DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); renderer.loggerName = "pre_splash"; @@ -318,8 +388,7 @@ private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { shaders, underline, strikethrough, - config, - null); + config); } catch (Throwable failure) { try { if (strikethrough != null) { diff --git a/module/kirino b/module/kirino index 91ac13e82..37b9abbf3 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 91ac13e82f05f1085653287f64349993b6a79fdb +Subproject commit 37b9abbf3d589ebbe2e342a4d6bad3c9f8baa136 From b3a80f4ce500277b6064e31e067ce00e49952355 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:16:10 -0500 Subject: [PATCH 16/27] feat(sdl renderer): intro UI & animation --- .../splash/pre/renderer/AsyncFontLoader.java | 203 +++++++ .../pre/renderer/LogoAnimationDrawer.java | 176 ++++++ .../splash/pre/renderer/PreSplashLayout.java | 1 - .../pre/renderer/SdlSplashRenderer.java | 540 ++++++++++-------- .../pre/renderer/SwingSplashRenderer.java | 2 +- .../cleanroom/shaders/logo_animation.frag | 168 ++++++ .../cleanroom/shaders/logo_animation.vert | 10 + 7 files changed, 852 insertions(+), 248 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java create mode 100644 module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag create mode 100644 module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java new file mode 100644 index 000000000..6d277cc49 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/AsyncFontLoader.java @@ -0,0 +1,203 @@ +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.ui.font.McTtfFontData; +import com.cleanroommc.mcttf.extract.AssetSource; +import com.google.common.base.Preconditions; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +/** + * FreeType & GL agnostic async Minecraft font loader. + * + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class AsyncFontLoader implements AutoCloseable { + + private static final class Assets implements AssetSource { + + private static final Pattern HASH = Pattern.compile("[0-9a-f]{40}"); + + private final Path directory; + private final @Nullable Map index; + + private Assets(Path directory, @Nullable String assetIndex) { + this.directory = directory; + if (assetIndex == null) { + index = null; + return; + } + + index = new HashMap<>(); + Path file = directory.resolve("indexes").resolve(assetIndex + ".json"); + try (var reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + JsonObject objects = JsonParser.parseReader(reader).getAsJsonObject().getAsJsonObject("objects"); + if (objects != null) { + for (var entry : objects.entrySet()) { + String hash = entry.getValue().getAsJsonObject().get("hash").getAsString(); + if (!HASH.matcher(hash).matches()) { + throw new IOException("Invalid asset hash: " + hash); + } + + index.put(entry.getKey(), directory.resolve("objects").resolve(hash.substring(0, 2)).resolve(hash)); + } + } + } catch (Throwable failure) { + index.clear(); + LOGGER.warn("Could not read pre splash asset index {}.", file, failure); + } + } + + @Nullable + private Path find(String path) { + Preconditions.checkArgument(path.startsWith("assets/"), "Invalid asset path: %s", path); + + String name = path.substring("assets/".length()); + Path file = index == null ? directory.resolve(name) : index.get(name); + return file != null && Files.isRegularFile(file) ? file : null; + } + + @Override + public boolean exists(String path) { + return find(path) != null || SdlSplashRenderer.class.getResource("/" + path) != null; + } + + @Override + public InputStream open(String path) throws IOException { + Path file = find(path); + if (file != null) { + return Files.newInputStream(file); + } + InputStream input = SdlSplashRenderer.class.getResourceAsStream("/" + path); + if (input == null) { + throw new FileNotFoundException(path); + } + return input; + } + + @Override + public void close() { + // NO OP + } + } + + private static final int LOAD_TIMEOUT_SECOND = 30; + private static final int THREAD_STOP_TIMEOUT_SECOND = 2; + + final Thread thread; + private final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(LOAD_TIMEOUT_SECOND); + private byte @Nullable [] data; + private boolean finished; + private boolean closed; + + AsyncFontLoader(File assetsDirectory, @Nullable String assetIndex) { + thread = new Thread(() -> load(assetsDirectory, assetIndex), "Pre Splash Font Loader"); + thread.setDaemon(true); + } + + synchronized boolean isFinished() { + if (!finished && deadline - System.nanoTime() <= 0) { + LOGGER.warn("Pre splash Minecraft font loading timed out after {} seconds.", LOAD_TIMEOUT_SECOND); + cancel(); + } + + return finished; + } + + @SuppressWarnings("DataFlowIssue") + synchronized byte @Nullable [] take() { + byte[] data = this.data; + this.data = null; + return data; + } + + @SuppressWarnings("DataFlowIssue") + private void load(File assetsDirectory, @Nullable String assetIndex) { + StopWatch stopWatch = StopWatch.createStarted(); + byte[] data = null; + + try { + synchronized (this) { + if (closed || isFinished()) { + return; + } + } + + Assets source = new Assets(assetsDirectory.toPath(), assetIndex); + + synchronized (this) { + if (closed || isFinished()) { + source.close(); + return; + } + } + + data = McTtfFontData.loadDefault(source, "pre_splash"); + } catch (Throwable failure) { + LOGGER.warn("Could not prepare the pre splash Minecraft font.", failure); + } finally { + stopWatch.stop(); + synchronized (this) { + if (!closed && !isFinished()) { + this.data = data; + if (data != null) { + LOGGER.info("Pre splash Minecraft font loaded in {} ms.", stopWatch.getTime(TimeUnit.MILLISECONDS)); + } + } + finished = true; + } + } + } + + private void cancel() { + synchronized (this) { + closed = true; + finished = true; + data = null; + } + + thread.interrupt(); + } + + @Override + public void close() { + cancel(); + if (Thread.currentThread() == thread) { + return; + } + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); + boolean interrupted = false; + while (thread.isAlive()) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + LOGGER.warn("Pre splash font loader did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); + break; + } + try { + TimeUnit.NANOSECONDS.timedJoin(thread, remaining); + } catch (InterruptedException e) { + interrupted = true; + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java new file mode 100644 index 000000000..8a7ccc0ec --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.shader.Shader; +import com.cleanroommc.kirino.gl.shader.ShaderProgram; +import com.cleanroommc.kirino.gl.texture.GLTexture; +import com.cleanroommc.kirino.gl.texture.accessor.Texture2DAccessor; +import com.cleanroommc.kirino.gl.texture.meta.FilterMode; +import com.cleanroommc.kirino.gl.texture.meta.WrapMode; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL45; +import org.lwjgl.stb.STBImage; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.concurrent.TimeUnit; + +/** + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class LogoAnimationDrawer implements AutoCloseable { + + private static final ResourceLocation VERTEX_SHADER = new ResourceLocation("cleanroom:shaders/logo_animation.vert"); + private static final ResourceLocation FRAGMENT_SHADER = new ResourceLocation("cleanroom:shaders/logo_animation.frag"); + private static final ResourceLocation LOGO = new ResourceLocation("cleanroom:icon.png"); + + private final StopWatch stopWatch = new StopWatch(); + private final VAO dummyVao; + private final @Nullable Shader vertexShader; + private final @Nullable Shader fragmentShader; + private final @Nullable ShaderProgram program; + private final @Nullable Texture2DAccessor logo; + + public LogoAnimationDrawer(ImmediateShaderAccess shaders, VAO dummyVao) throws IOException { + Preconditions.checkNotNull(shaders); + Preconditions.checkNotNull(dummyVao); + + this.dummyVao = dummyVao; + + try { + vertexShader = shaders.makeShader(VERTEX_SHADER); + fragmentShader = shaders.makeShader(FRAGMENT_SHADER); + shaders.submitToGL(vertexShader, fragmentShader); + program = shaders.makeProgram(vertexShader, fragmentShader); + + int resolutionLocation = program.uniformLocation("resolution"); + int progressLocation = program.uniformLocation("progress"); + int textureLocation = program.uniformLocation("logoTexture"); + int backgroundLocation = program.uniformLocation("background"); + Preconditions.checkState(resolutionLocation >= 0 && progressLocation >= 0 && textureLocation >= 0 && backgroundLocation >= 0, + "Missing logo animation uniforms."); + + program.uniform1i("logoTexture", 0); + program.uniform3f("background", + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f); + + logo = loadLogo(); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static Texture2DAccessor loadLogo() throws IOException { + byte[] bytes; + try (var input = MinecraftResourceUtils.getEarlyInputStream(LOGO)) { + bytes = input.readAllBytes(); + } + + ByteBuffer encoded = MemoryUtil.memAlloc(bytes.length); + ByteBuffer pixels = null; + GLTexture texture = null; + try (MemoryStack stack = MemoryStack.stackPush()) { + encoded.put(bytes).flip(); + var width = stack.mallocInt(1); + var height = stack.mallocInt(1); + var channels = stack.mallocInt(1); + pixels = STBImage.stbi_load_from_memory(encoded, width, height, channels, STBImage.STBI_rgb_alpha); + if (pixels == null) { + throw new IOException("Could not decode pre splash logo: " + STBImage.stbi_failure_reason()); + } + + texture = GLTexture.newDsaTex2D(width.get(0), height.get(0)); + Texture2DAccessor accessor = new Texture2DAccessor(true, texture); + accessor.highlevel().alloc(false, pixels); + accessor.setCommonParams(FilterMode.LINEAR, FilterMode.LINEAR, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return accessor; + } catch (Throwable failure) { + if (texture != null) { + try { + texture.disposeManually(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + if (pixels != null) { + STBImage.stbi_image_free(pixels); + } + MemoryUtil.memFree(encoded); + } + } + + public void render(int width, int height) { + Preconditions.checkNotNull(program); + Preconditions.checkNotNull(logo); + + float progress = Math.min(1f, stopWatch.getTime(TimeUnit.MILLISECONDS) / (float) SdlSplashRenderer.LOGO_ANIM_DURATION_MILLIS); + + program.uniform2f("resolution", width, height); + program.uniform1f("progress", progress); + logo.bindUnit(0); + dummyVao.bind(); + + program.use(); + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + program.use0(); + + VAO.bind(0); + GL45.glBindTextureUnit(0, 0); + + if (!stopWatch.isStarted()) { + stopWatch.start(); + } + } + + @Override + public void close() { + try { + if (logo != null) { + logo.texture.disposeManually(); + } + } finally { + try { + if (program != null) { + program.disposeManually(); + } + } finally { + try { + if (fragmentShader != null && fragmentShader.getShaderID() != 0) { + fragmentShader.disposeManually(); + } + } finally { + if (vertexShader != null && vertexShader.getShaderID() != 0) { + vertexShader.disposeManually(); + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java index 6b29932d7..c49f05bd1 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java @@ -15,7 +15,6 @@ public final class PreSplashLayout { public static final int WIDTH = 720; public static final int HEIGHT = 360; public static final float SCREEN_PERCENTAGE = 0.35f; - public static final float UI_SCALE = 1.15f; public static final int BACKGROUND = 0xFF0E1116; private PreSplashLayout() { diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index 2e376c9ea..cc2735262 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -17,7 +17,6 @@ import com.cleanroommc.kirino.gl.vao.VAO; import com.cleanroommc.kirino.gl.vao.attribute.AttributeLayout; import com.cleanroommc.kirino.gl.vao.attribute.Stride; -import com.cleanroommc.kirino.ui.font.McTtfFontData; import com.cleanroommc.kirino.ui.simplegui.SimpleGuiRuntime; import com.cleanroommc.kirino.ui.simpletext.ST_Config; import com.cleanroommc.kirino.ui.simpletext.ST_FontBackendType; @@ -27,14 +26,12 @@ import com.cleanroommc.kirino.ui.simpletext.backend.DefaultTextRenderer; import com.cleanroommc.kirino.ui.simpletext.backend.FreeTypeFontHandle; import com.cleanroommc.kirino.ui.simpletext.backend.freetype.FreeTypeManager; +import com.cleanroommc.kirino.ui.simpletext.text.StyledText; import com.cleanroommc.kirino.utils.MinecraftResourceUtils; import com.cleanroommc.kirino.utils.ResourceLocation; -import com.cleanroommc.mcttf.extract.AssetSource; import com.cleanroommc.mcttf.glyph.GlyphBuilder; import com.google.common.base.Preconditions; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import org.apache.commons.lang3.time.StopWatch; import org.jspecify.annotations.Nullable; @@ -44,217 +41,74 @@ import org.lwjgl.util.freetype.FreeType; import java.io.File; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; public final class SdlSplashRenderer implements AutoCloseable { - /** - * FreeType & GL agnostic async font loader. - */ - private static final class FontLoader implements AutoCloseable { - - private static final class Assets implements AssetSource { - - private static final Pattern HASH = Pattern.compile("[0-9a-f]{40}"); - - private final Path directory; - private final @Nullable Map index; - - private Assets(Path directory, @Nullable String assetIndex) { - this.directory = directory; - if (assetIndex == null) { - index = null; - return; - } - - index = new HashMap<>(); - Path file = directory.resolve("indexes").resolve(assetIndex + ".json"); - try (var reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { - JsonObject objects = JsonParser.parseReader(reader).getAsJsonObject().getAsJsonObject("objects"); - if (objects != null) { - for (var entry : objects.entrySet()) { - String hash = entry.getValue().getAsJsonObject().get("hash").getAsString(); - if (!HASH.matcher(hash).matches()) { - throw new IOException("Invalid asset hash: " + hash); - } - - index.put(entry.getKey(), directory.resolve("objects").resolve(hash.substring(0, 2)).resolve(hash)); - } - } - } catch (Throwable failure) { - index.clear(); - LOGGER.warn("Could not read pre splash asset index {}.", file, failure); - } - } - - @Nullable - private Path find(String path) { - Preconditions.checkArgument(path.startsWith("assets/"), "Invalid asset path: %s", path); - - String name = path.substring("assets/".length()); - Path file = index == null ? directory.resolve(name) : index.get(name); - return file != null && Files.isRegularFile(file) ? file : null; - } - - @Override - public boolean exists(String path) { - return find(path) != null || SdlSplashRenderer.class.getResource("/" + path) != null; - } - - @Override - public InputStream open(String path) throws IOException { - Path file = find(path); - if (file != null) { - return Files.newInputStream(file); - } - InputStream input = SdlSplashRenderer.class.getResourceAsStream("/" + path); - if (input == null) { - throw new FileNotFoundException(path); - } - return input; - } - - @Override - public void close() { - // NO OP - } - } - - private static final int LOAD_TIMEOUT_SECOND = 30; - private static final int THREAD_STOP_TIMEOUT_SECOND = 2; - - private final Thread thread; - private final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(LOAD_TIMEOUT_SECOND); - private byte @Nullable [] data; - private boolean finished; - private boolean closed; - - private FontLoader(File assetsDirectory, @Nullable String assetIndex) { - thread = new Thread(() -> load(assetsDirectory, assetIndex), "Pre Splash Font Loader"); - thread.setDaemon(true); - } - - private synchronized boolean isFinished() { - if (!finished && deadline - System.nanoTime() <= 0) { - LOGGER.warn("Pre splash Minecraft font loading timed out after {} seconds.", LOAD_TIMEOUT_SECOND); - cancel(); - } - - return finished; - } - - @SuppressWarnings("DataFlowIssue") - private synchronized byte @Nullable [] take() { - byte[] data = this.data; - this.data = null; - return data; - } - - @SuppressWarnings("DataFlowIssue") - private void load(File assetsDirectory, @Nullable String assetIndex) { - StopWatch stopWatch = StopWatch.createStarted(); - byte[] data = null; - - try { - synchronized (this) { - if (closed || isFinished()) { - return; - } - } - - Assets source = new Assets(assetsDirectory.toPath(), assetIndex); - - synchronized (this) { - if (closed || isFinished()) { - source.close(); - return; - } - } - - data = McTtfFontData.loadDefault(source, "pre_splash"); - } catch (Throwable failure) { - LOGGER.warn("Could not prepare the pre splash Minecraft font.", failure); - } finally { - stopWatch.stop(); - synchronized (this) { - if (!closed && !isFinished()) { - this.data = data; - if (data != null) { - LOGGER.info("Pre splash Minecraft font loaded in {} ms.", stopWatch.getTime(TimeUnit.MILLISECONDS)); - } - } - finished = true; - } - } - } - - private void cancel() { - synchronized (this) { - closed = true; - finished = true; - data = null; - } - - thread.interrupt(); - } - - @Override - public void close() { - cancel(); - if (Thread.currentThread() == thread) { - return; - } - - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(THREAD_STOP_TIMEOUT_SECOND); - boolean interrupted = false; - while (thread.isAlive()) { - long remaining = deadline - System.nanoTime(); - if (remaining <= 0) { - LOGGER.warn("Pre splash font loader did not stop within {} seconds.", THREAD_STOP_TIMEOUT_SECOND); - break; - } - try { - TimeUnit.NANOSECONDS.timedJoin(thread, remaining); - } catch (InterruptedException e) { - interrupted = true; - } - } - - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - private static final ResourceLocation FALLBACK_FONT = new ResourceLocation("kirino:fonts/jetbrains/jetbrains_mono_nl_regular.ttf"); - private static final long ENTRY_ANIMATION_MILLIS = 1000; + private static final String ENGLISH_CHARACTERS = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - private final StopWatch entryAnimationStopWatch = new StopWatch(); + private static final long EARLY_TITLE_INOUT_ANIM_MILLIS = 200; + private static final long EARLY_TITLE_HOLD_MILLIS = 650; + private static final long INTRO_FADE_OUT_ANIM_MILLIS = 200; + private static final long POST_INTRO_MASK_FADE_OUT_MILLIS = 150; + private static final long MAX_TRANSITION_FRAME_MILLIS = 33; + private static final long LOADING_BAR_CYCLE_MILLIS = 1400; + private static final long LOADING_BAR_FADE_OUT_MILLIS = 200; + static final long LOGO_ANIM_DURATION_MILLIS = 1200; + + private final Runnable startupReady; private final GLResourceManager.ResourceScope scope; - private final FontLoader fontLoader; + private final AsyncFontLoader fontLoader; private final ImmediateShaderAccess shaders; private final VAO dummyVao; - private final Runnable startupReady; private final @Nullable SimpleGuiRuntime gui; + private final @Nullable LogoAnimationDrawer logoAnimation; private final @Nullable FreeTypeManager freeType; + private final StopWatch mainStopWatch = new StopWatch(); + private final StopWatch earlyTitleStopWatch = new StopWatch(); + private final StopWatch titleHoldStopWatch = new StopWatch(); + private final StopWatch loadingBarFadeOutStopWatch = new StopWatch(); + private final StopWatch introFadeOutStopWatch = new StopWatch(); + private final StopWatch postIntroMaskStopWatch = new StopWatch(); + private long introFadeOutFrameMillis; + private long introFadeOutElapsedMillis; + private long postIntroMaskFrameMillis; + private long postIntroMaskElapsedMillis; + private @Nullable ByteBuffer mcFontData; - private @Nullable SimpleTextRuntime text; private @Nullable PreSplashState state; + private @Nullable SimpleTextRuntime text; + private @Nullable SimpleTextRuntime introText; + + private enum IntroStage { + LOGO, + TITLE_WARMUP, + TITLE_FADE_IN, + TITLE_HOLD, + FONT_LOADING, + BAR_FADE_OUT, + ENGLISH_WARMUP, + FADE_OUT, + FINISHED + } + + // states private boolean fontResolved; + private boolean fontResolveFailed = true; + private boolean earlyTitleFallback; + private boolean fontLoadingAtEntry; + private boolean englishWarmedUp; + private IntroStage introStage = IntroStage.LOGO; + private boolean startupSignaled; public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { @@ -265,7 +119,7 @@ public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runn this.startupReady = startupReady; - fontLoader = new FontLoader(assetsDirectory, assetIndex); + fontLoader = new AsyncFontLoader(assetsDirectory, assetIndex); scope = GLResourceManager.openScope(); try { @@ -283,9 +137,9 @@ public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runn layout.push(new Stride(0)); dummyVao = new VAO(layout, null, (VBOView @Nullable []) null); - float uiWidth = PreSplashLayout.WIDTH / PreSplashLayout.UI_SCALE; - float uiHeight = PreSplashLayout.HEIGHT / PreSplashLayout.UI_SCALE; - gui = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + gui = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + + logoAnimation = new LogoAnimationDrawer(shaders, dummyVao); var constructor = FreeTypeManager.class.getDeclaredConstructor(); constructor.setAccessible(true); @@ -309,17 +163,25 @@ public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runn } } + /** + * Loads Minecraft font into {@link #text}. + * + * @return Whether Minecraft font is ready + */ @SuppressWarnings("DataFlowIssue") - private void resolveFont() { - if (fontResolved || !fontLoader.isFinished()) { - return; + private boolean resolveFont() { + if (fontResolved) { + return !fontResolveFailed; + } + if (!fontLoader.isFinished()) { + return false; } fontResolved = true; byte[] bytes = fontLoader.take(); if (bytes == null) { LOGGER.warn("Could not load the pre splash Minecraft font."); - return; + return false; } Preconditions.checkNotNull(freeType); @@ -341,22 +203,25 @@ private void resolveFont() { } } LOGGER.warn("Could not initialize pre splash Minecraft text.", failure); - return; + return false; } - SimpleTextRuntime previous = text; + SimpleTextRuntime previous = Preconditions.checkNotNull(text); text = replacement; mcFontData = data; + fontResolveFailed = false; - try { - if (previous != null) { + if (previous != introText) { + try { previous.close(); + } catch (Throwable failure) { + LOGGER.warn("Could not dispose the previous pre splash text runtime.", failure); + } finally { + freeType.unload(FALLBACK_FONT); } - } catch (Throwable failure) { - LOGGER.warn("Could not dispose the previous pre splash text runtime.", failure); - } finally { - freeType.unload(FALLBACK_FONT); } + + return true; } private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { @@ -367,24 +232,27 @@ private SimpleTextRuntime createText(FT_Face face, boolean minecraftFont) { 12, FreeType.FT_LOAD_RENDER | FreeType.FT_LOAD_NO_HINTING); - float uiWidth = PreSplashLayout.WIDTH / PreSplashLayout.UI_SCALE; - float uiHeight = PreSplashLayout.HEIGHT / PreSplashLayout.UI_SCALE; SimpleGuiRuntime underline = null; SimpleGuiRuntime strikethrough = null; try { - underline = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); - strikethrough = new SimpleGuiRuntime(shaders, dummyVao, uiWidth, uiHeight); + underline = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + strikethrough = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); return new SimpleTextRuntime( _ -> new FreeTypeFontHandle(face), runtime -> { - DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, uiWidth, uiHeight); + DefaultTextRenderer renderer = new DefaultTextRenderer(runtime, new Tex2DArrayGlyphAtlas(1024, 1024), shaders, 256, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); renderer.loggerName = "pre_splash"; return renderer; }, - runtime -> minecraftFont - ? new DefaultTextProducer(runtime, config.pixelSize(), GlyphBuilder.LINE_HEIGHT_PIXELS) - : new DefaultTextProducer(runtime, config.pixelSize()), + runtime -> { + int layoutPixelSize = config.pixelSize(); + if (!minecraftFont) { + int capHeight = runtime.getGlyphMetrics(runtime.getFont().getGlyphIndex('A')).getGlyphHeight(); + layoutPixelSize = Math.round(capHeight * GlyphBuilder.LINE_HEIGHT_PIXELS / (float) GlyphBuilder.MC_LINE_TOP_PIXELS); + } + return new DefaultTextProducer(runtime, layoutPixelSize, GlyphBuilder.LINE_HEIGHT_PIXELS); + }, shaders, underline, strikethrough, @@ -416,6 +284,11 @@ public void update(PreSplashState state) { this.state = state; } + private static float easeInOut(float t) { + t = Math.clamp(t, 0f, 1f); + return t * t * (3f - 2f * t); + } + public void render(int width, int height) { if (state == null) { return; @@ -426,62 +299,237 @@ public void render(int width, int height) { int viewportHeight = Math.round(PreSplashLayout.HEIGHT * scale); GL11.glViewport((width - viewportWidth) / 2, (height - viewportHeight) / 2, viewportWidth, viewportHeight); - int background = PreSplashLayout.BACKGROUND; - GL11.glClearColor(((background >> 16) & 255) / 255f, ((background >> 8) & 255) / 255f, (background & 255) / 255f, 1); + GL11.glClearColor( + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f, + 1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); - if (entryAnimationStopWatch.isStarted() && entryAnimationStopWatch.getTime(TimeUnit.MILLISECONDS) >= ENTRY_ANIMATION_MILLIS) { - resolveFont(); + Preconditions.checkNotNull(logoAnimation); + Preconditions.checkNotNull(text); + Preconditions.checkNotNull(gui); + + // + if (!mainStopWatch.isStarted()) { + mainStopWatch.start(); + } + + if (introStage == IntroStage.LOGO && mainStopWatch.getTime(TimeUnit.MILLISECONDS) >= LOGO_ANIM_DURATION_MILLIS) { + fontLoadingAtEntry = !fontLoader.isFinished(); + earlyTitleFallback = fontLoadingAtEntry || !resolveFont(); + introText = text; + introStage = IntroStage.TITLE_WARMUP; } - SimpleTextRuntime text = Preconditions.checkNotNull(this.text); - text.begin(); - text.append(state.title(), 48, 106, 32, 0xFFF1F4FA); - text.append(state.message(), 48, 190, 16, 0xFFB9C7DB); - text.append(state.details(), 48, 286, 16, 0xFF8998AE); - text.endDraw(); + if (introStage == IntroStage.TITLE_HOLD) { + if (!titleHoldStopWatch.isStarted()) { + titleHoldStopWatch.start(); + } + if (!englishWarmedUp) { + introStage = IntroStage.ENGLISH_WARMUP; + } else if (titleHoldStopWatch.getTime(TimeUnit.MILLISECONDS) >= EARLY_TITLE_HOLD_MILLIS) { + introStage = IntroStage.FADE_OUT; + introFadeOutStopWatch.start(); + } + } - if (!entryAnimationStopWatch.isStarted()) { - entryAnimationStopWatch.start(); + if (introStage == IntroStage.FONT_LOADING && fontLoader.isFinished()) { + introStage = IntroStage.BAR_FADE_OUT; + loadingBarFadeOutStopWatch.start(); } - if (!fontResolved) { - double seconds = entryAnimationStopWatch.getTime(TimeUnit.MILLISECONDS) / 1000.0; - float x = 48 + (float) (0.5 - Math.cos(seconds * Math.PI) * 0.5) * 208; - SimpleGuiRuntime gui = Preconditions.checkNotNull(this.gui); - gui.begin().append(stream -> stream.rect(x, 232, 40, 6, 0xFF8998AE)).endDraw(); + if (introStage == IntroStage.ENGLISH_WARMUP) { + if (fontLoadingAtEntry) { + resolveFont(); + } + + text.begin(); + text.append(ENGLISH_CHARACTERS, 0, 0, 40, 0x00FFFFFF); + text.endDraw(); + GL11.glFinish(); + englishWarmedUp = true; + + if (fontLoadingAtEntry || titleHoldStopWatch.getTime(TimeUnit.MILLISECONDS) >= EARLY_TITLE_HOLD_MILLIS) { + introStage = IntroStage.FADE_OUT; + introFadeOutStopWatch.start(); + } else { + introStage = IntroStage.TITLE_HOLD; + } } - if (fontResolved && !startupSignaled) { - startupSignaled = true; - startupReady.run(); + if (introStage != IntroStage.FINISHED) { + logoAnimation.render(viewportWidth, viewportHeight); + } + + if (introStage != IntroStage.LOGO && introStage != IntroStage.FINISHED) { + Preconditions.checkNotNull(introText); + + float progress = switch (introStage) { + case TITLE_WARMUP -> 0; + case TITLE_FADE_IN -> easeInOut(earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS) / (float) EARLY_TITLE_INOUT_ANIM_MILLIS); + default -> 1; + }; + + String title = fontLoadingAtEntry ? "Warming Up" : "Cleanroom"; + int titleFontSize = earlyTitleFallback ? 30 : 40; + var lineInfo = introText.simulate(title, 0, 0, titleFontSize); + + introText.begin(); + introText.appendStyled( + new StyledText(String.format("§c=rgba(255;255;255;%d)[%s]§", (int) (progress * 255), title)), + 4 + (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, + PreSplashLayout.HEIGHT * 0.74f, + titleFontSize); + introText.endDraw(); + + boolean showLoadingBar = fontLoadingAtEntry && (introStage == IntroStage.TITLE_WARMUP + || introStage == IntroStage.TITLE_FADE_IN + || introStage == IntroStage.FONT_LOADING + || introStage == IntroStage.BAR_FADE_OUT); + + float barFadeOut = easeInOut(loadingBarFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS) / (float) LOADING_BAR_FADE_OUT_MILLIS); + float barProgress = progress * (1f - barFadeOut); + long titleTime = earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS); + long fadeOutTime = introFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS); + introFadeOutElapsedMillis += Math.min(fadeOutTime - introFadeOutFrameMillis, MAX_TRANSITION_FRAME_MILLIS); + introFadeOutFrameMillis = fadeOutTime; + float fadeOut = easeInOut(introFadeOutElapsedMillis / (float) INTRO_FADE_OUT_ANIM_MILLIS); + + gui.begin(); + gui.append(stream -> { + if (showLoadingBar) { + float barHeight = 5; + float barWidth = 180; + float segmentWidth = 50; + float barX = (PreSplashLayout.WIDTH - barWidth) / 2f; + float barY = PreSplashLayout.HEIGHT * 0.83f; + float cycle = (titleTime % LOADING_BAR_CYCLE_MILLIS) / (float) LOADING_BAR_CYCLE_MILLIS; + float position = easeInOut(1f - Math.abs(cycle * 2f - 1f)); + stream.rectEx(barX, barY, barWidth, barHeight, (int) (barProgress * 40) << 24 | 0xFFFFFF) + .radius(barHeight / 2f, 1) + .emit(); + stream.rectEx(barX + position * (barWidth - segmentWidth), barY, segmentWidth, barHeight, (int) (barProgress * 255) << 24 | 0xB9C7DB) + .radius(barHeight / 2f, 1) + .emit(); + } + + stream.rect( + 0, + 0, + PreSplashLayout.WIDTH, + PreSplashLayout.HEIGHT, + (int) (fadeOut * 255) << 24 | (PreSplashLayout.BACKGROUND & 0xFFFFFF)); + }); + gui.endDraw(); + + if (introStage == IntroStage.TITLE_WARMUP) { + GL11.glFinish(); + introStage = IntroStage.TITLE_FADE_IN; + earlyTitleStopWatch.start(); + } else if (introStage == IntroStage.TITLE_FADE_IN && progress >= 1) { + introStage = fontLoadingAtEntry ? IntroStage.FONT_LOADING : IntroStage.TITLE_HOLD; + } else if (introStage == IntroStage.BAR_FADE_OUT && barFadeOut >= 1) { + introStage = IntroStage.ENGLISH_WARMUP; + } + + if (introStage == IntroStage.FADE_OUT && !startupSignaled) { + startupSignaled = true; + startupReady.run(); + } + if (introStage == IntroStage.FADE_OUT && fadeOut >= 1) { + introStage = IntroStage.FINISHED; + } + } + // + + if (introStage == IntroStage.FINISHED) { + text.begin(); + text.append(state.title(), 48, 106, 40, 0xFFF1F4FA); + text.append(state.message(), 48, 190, 30, 0xFFB9C7DB); + text.append(state.details(), 48, 286, 30, 0xFF8998AE); + text.endDraw(); + + long maskTime = postIntroMaskStopWatch.getTime(TimeUnit.MILLISECONDS); + boolean maskFinished = postIntroMaskElapsedMillis >= POST_INTRO_MASK_FADE_OUT_MILLIS; + if (!maskFinished) { + postIntroMaskElapsedMillis += Math.min(maskTime - postIntroMaskFrameMillis, MAX_TRANSITION_FRAME_MILLIS); + postIntroMaskFrameMillis = maskTime; + float opacity = 1f - easeInOut(postIntroMaskElapsedMillis / (float) POST_INTRO_MASK_FADE_OUT_MILLIS); + + gui.begin(); + gui.append(stream -> stream.rect( + 0, + 0, + PreSplashLayout.WIDTH, + PreSplashLayout.HEIGHT, + (int) (opacity * 255) << 24 | (PreSplashLayout.BACKGROUND & 0xFFFFFF))); + gui.endDraw(); + + if (!postIntroMaskStopWatch.isStarted()) { + postIntroMaskStopWatch.start(); + } + } + + if (maskFinished && introText != null) { + SimpleTextRuntime previous = introText; + introText = null; + if (previous != text) { + Preconditions.checkNotNull(freeType); + + try { + previous.close(); + } catch (Throwable failure) { + LOGGER.warn("Could not dispose the pre splash intro text runtime.", failure); + } finally { + freeType.unload(FALLBACK_FONT); + } + } + } } } @Override public void close() throws Exception { + if (mainStopWatch.isStarted()) { + mainStopWatch.stop(); + LOGGER.info("Pre splash renderer finished in {}ms.", mainStopWatch.getTime(TimeUnit.MILLISECONDS)); + } + fontLoader.close(); try { - if (text != null) { - text.close(); + try { + if (introText != null && introText != text) { + introText.close(); + } + } finally { + if (text != null) { + text.close(); + } } } finally { try { - if (gui != null) { - gui.close(); + if (logoAnimation != null) { + logoAnimation.close(); } } finally { try { - if (freeType != null) { - freeType.destroy(); + if (gui != null) { + gui.close(); } } finally { try { - if (mcFontData != null) { - MemoryUtil.memFree(mcFontData); + if (freeType != null) { + freeType.destroy(); } } finally { - scope.close(); + try { + if (mcFontData != null) { + MemoryUtil.memFree(mcFontData); + } + } finally { + scope.close(); + } } } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java index f680abcce..18683a955 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SwingSplashRenderer.java @@ -57,7 +57,7 @@ protected void paintComponent(Graphics graphics) { draw.fillRect(0, 0, getWidth(), getHeight()); double scale = Math.min((double) getWidth() / PreSplashLayout.WIDTH, (double) getHeight() / PreSplashLayout.HEIGHT); draw.translate((getWidth() - PreSplashLayout.WIDTH * scale) / 2, (getHeight() - PreSplashLayout.HEIGHT * scale) / 2); - draw.scale(scale * PreSplashLayout.UI_SCALE, scale * PreSplashLayout.UI_SCALE); + draw.scale(scale, scale); draw.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); draw.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawText(draw, state.title(), 48, 106, 32, 0xFFF1F4FA); diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag new file mode 100644 index 000000000..085878f20 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.frag @@ -0,0 +1,168 @@ +#version 460 core + +uniform vec2 resolution; +uniform float progress; +uniform sampler2D logoTexture; +uniform vec3 background; + +in vec2 ViewportUV; +out vec4 Color; + +const vec2 LOGO_CENTER = vec2(0.5, 0.548); +const float FACE_DURATION = 0.607; +const float SETTLE_START = 0.836; +const float SETTLE_END = 1.0; +const float GLOW_FADE_START = 0.541; +const float GLOW_FADE_END = SETTLE_END; + +vec2 faceE1(int face) +{ + if (face == 0) return vec2(0.437, 0.226); + if (face == 1) return vec2(-0.437, 0.226); + return vec2(0.0, -0.548); +} + +vec2 faceE2(int face) +{ + if (face == 0) return vec2(-0.437, 0.226); + if (face == 1) return vec2(0.0, -0.548); + return vec2(0.437, 0.226); +} + +vec2 faceLocalUV(vec2 logoUV, int face) +{ + vec2 a = faceE1(face); + vec2 b = faceE2(face); + vec2 p = logoUV - LOGO_CENTER; + float det = a.x * b.y - a.y * b.x; + return vec2((p.x * b.y - p.y * b.x), (a.x * p.y - a.y * p.x)) / det; +} + +float faceCoverage(vec2 logoUV, int face) +{ + vec2 q = faceLocalUV(logoUV, face); + vec2 w = max(fwidth(q), vec2(0.001)); + vec2 lo = smoothstep(-w, w, q); + vec2 hi = vec2(1.0) - smoothstep(vec2(1.0) - w, vec2(1.0) + w, q); + return clamp(lo.x * lo.y * hi.x * hi.y, 0.0, 1.0); +} + +vec4 sampleLogo(vec2 uv) +{ + if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec4(0.0); + return texture(logoTexture, vec2(uv.x, 1.0 - uv.y)); +} + +vec2 rotate2D(vec2 p, float angle) +{ + float c = cos(angle), s = sin(angle); + return mat2(c, s, -s, c) * p; +} + +float ease(float x) +{ + x = clamp(x, 0.0, 1.0); + return x * x * (3.0 - 2.0 * x); +} + +float easeOut(float x) +{ + x = clamp(x, 0.0, 1.0); + return 1.0 - pow(1.0 - x, 3.0); +} + +vec2 entryOffset(int face) +{ + if (face == 0) return vec2(0.0, 0.105); + if (face == 1) return vec2(-0.115, -0.05); + return vec2(0.115, -0.05); +} + +float entryAngle(int face) +{ + if (face == 0) return -0.18; + if (face == 1) return -0.22; + return 0.22; +} + +float startProgress(int face) +{ + if (face == 0) return 0.033; + if (face == 1) return 0.115; + return 0.197; +} + +vec4 animateFace(vec2 screenLogoUV, int face, float t) +{ + float prog = clamp((t - startProgress(face)) / FACE_DURATION, 0.0, 1.0); + float approach = easeOut(clamp(prog * 1.16, 0.0, 1.0)); + + vec2 translation = entryOffset(face) * (1.0 - approach); + float rotation = entryAngle(face) * (1.0 - approach); + vec2 canonicalUV = rotate2D(screenLogoUV - LOGO_CENTER - translation, -rotation) + LOGO_CENTER; + + vec4 texel = sampleLogo(canonicalUV); + float region = faceCoverage(canonicalUV, face); + vec2 local = faceLocalUV(canonicalUV, face); + + float path = clamp(0.5 * local.x + 0.5 * local.y, 0.0, 1.0); + if (face == 1) path = clamp(1.0 - (0.6 * local.x + 0.4 * local.y), 0.0, 1.0); + if (face == 2) path = clamp(0.35 * local.x + 0.65 * local.y, 0.0, 1.0); + float front = ease(clamp((prog * 1.15 - path + 0.05) / 0.12, 0.0, 1.0)); + + float inside = min(min(local.x, local.y), min(1.0 - local.x, 1.0 - local.y)); + float edgeBand = 1.0 - smoothstep(0.045, 0.1, inside); + float fillIn = ease(clamp((prog - 0.37) / 0.52, 0.0, 1.0)); + float visibility = region * texel.a * max(edgeBand * front, fillIn); + + float light = (1.0 - fillIn) * edgeBand * front * 0.74; + vec3 rgb = mix(texel.rgb, vec3(0.96, 0.97, 1.0), light); + return vec4(rgb * visibility, visibility); +} + +float faceGlow(vec2 screenLogoUV, int face, float t) +{ + float prog = clamp((t - startProgress(face)) / FACE_DURATION, 0.0, 1.0); + if (prog <= 0.001) return 0.0; + float approach = easeOut(clamp(prog * 1.16, 0.0, 1.0)); + vec2 q = rotate2D(screenLogoUV - LOGO_CENTER - entryOffset(face) * (1.0 - approach), -entryAngle(face) * (1.0 - approach)) + LOGO_CENTER; + vec2 v = faceLocalUV(q, face); + float edge = min(min(v.x, v.y), min(1.0 - v.x, 1.0 - v.y)); + float front = clamp(prog * 1.5, 0.0, 1.0); + return (0.12 * exp(-18.0 * abs(edge)) + 0.06 * exp(-7.0 * abs(edge))) * front; +} + +void main() +{ + float scale = resolution.y * 0.4; + vec2 logoUV = (ViewportUV - 0.5) * resolution / scale + 0.5; + float t = clamp(progress, 0.0, 1.0); + + vec4 texel = sampleLogo(logoUV); + vec4 original = vec4(texel.rgb * texel.a, texel.a); + + vec4 logo = original; + float glow = 0.0; + + if (t < SETTLE_END) + { + vec4 assembled = vec4(0.0); + for (int i = 0; i < 3; ++i) + { + vec4 piece = animateFace(logoUV, i, t); + assembled.rgb += (1.0 - assembled.a) * piece.rgb; + assembled.a += (1.0 - assembled.a) * piece.a; + glow += faceGlow(logoUV, i, t); + } + + float settle = ease((t - SETTLE_START) / (SETTLE_END - SETTLE_START)); + logo = mix(assembled, original, settle); + + float glowStrength = 1.0 - ease((t - GLOW_FADE_START) / (GLOW_FADE_END - GLOW_FADE_START)); + glow *= glowStrength; + } + + vec3 rgb = background * (1.0 - logo.a) + logo.rgb; + rgb += glow * vec3(0.57, 0.74, 1.0); + Color = vec4(rgb, 1.0); +} diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert new file mode 100644 index 000000000..d0ba5f721 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/logo_animation.vert @@ -0,0 +1,10 @@ +#version 460 core + +out vec2 ViewportUV; + +void main() +{ + vec2 position = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); + ViewportUV = position; + gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0); +} From 0cccc368b77d33ec4d6b5592f0e4604260569109 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:25:00 -0500 Subject: [PATCH 17/27] feat(sdl renderer): intro title typing effect --- .../pre/renderer/SdlSplashRenderer.java | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index cc2735262..b856afff8 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -54,8 +54,10 @@ public final class SdlSplashRenderer implements AutoCloseable { private static final ResourceLocation FALLBACK_FONT = new ResourceLocation("kirino:fonts/jetbrains/jetbrains_mono_nl_regular.ttf"); private static final String ENGLISH_CHARACTERS = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - private static final long EARLY_TITLE_INOUT_ANIM_MILLIS = 200; - private static final long EARLY_TITLE_HOLD_MILLIS = 650; + private static final long EARLY_TITLE_IN_ANIM_MILLIS = 200; // for "Warming Up" + private static final long EARLY_TITLE_CHAR_TYPE_MILLIS = 40; // for "Cleanroom" + private static final long EARLY_TITLE_CHAR_FADE_IN_MILLIS = 180; // for "Cleanroom" + private static final long EARLY_TITLE_HOLD_MILLIS = 650; // // for "Cleanroom" private static final long INTRO_FADE_OUT_ANIM_MILLIS = 200; private static final long POST_INTRO_MASK_FADE_OUT_MILLIS = 150; private static final long MAX_TRANSITION_FRAME_MILLIS = 33; @@ -365,19 +367,34 @@ public void render(int width, int height) { if (introStage != IntroStage.LOGO && introStage != IntroStage.FINISHED) { Preconditions.checkNotNull(introText); + long titleTime = earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS); + String title = fontLoadingAtEntry ? "Warming Up" : "Cleanroom"; + long titleFadeDuration = fontLoadingAtEntry + ? EARLY_TITLE_IN_ANIM_MILLIS + : EARLY_TITLE_CHAR_FADE_IN_MILLIS + (title.length() - 1) * EARLY_TITLE_CHAR_TYPE_MILLIS; float progress = switch (introStage) { case TITLE_WARMUP -> 0; - case TITLE_FADE_IN -> easeInOut(earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS) / (float) EARLY_TITLE_INOUT_ANIM_MILLIS); + case TITLE_FADE_IN -> easeInOut(titleTime / (float) titleFadeDuration); default -> 1; }; - String title = fontLoadingAtEntry ? "Warming Up" : "Cleanroom"; int titleFontSize = earlyTitleFallback ? 30 : 40; var lineInfo = introText.simulate(title, 0, 0, titleFontSize); + String styledTitle; + if (!fontLoadingAtEntry && introStage == IntroStage.TITLE_FADE_IN) { + StringBuilder characters = new StringBuilder(); + for (int i = 0; i < title.length(); i++) { + float characterProgress = easeInOut((titleTime - i * EARLY_TITLE_CHAR_TYPE_MILLIS) / (float) EARLY_TITLE_CHAR_FADE_IN_MILLIS); + characters.append("§c=rgba(255;255;255;").append((int) (characterProgress * 255)).append(")[").append(title.charAt(i)).append("]§"); + } + styledTitle = characters.toString(); + } else { + styledTitle = String.format("§c=rgba(255;255;255;%d)[%s]§", (int) (progress * 255), title); + } introText.begin(); introText.appendStyled( - new StyledText(String.format("§c=rgba(255;255;255;%d)[%s]§", (int) (progress * 255), title)), + new StyledText(styledTitle), 4 + (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, PreSplashLayout.HEIGHT * 0.74f, titleFontSize); @@ -390,7 +407,6 @@ public void render(int width, int height) { float barFadeOut = easeInOut(loadingBarFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS) / (float) LOADING_BAR_FADE_OUT_MILLIS); float barProgress = progress * (1f - barFadeOut); - long titleTime = earlyTitleStopWatch.getTime(TimeUnit.MILLISECONDS); long fadeOutTime = introFadeOutStopWatch.getTime(TimeUnit.MILLISECONDS); introFadeOutElapsedMillis += Math.min(fadeOutTime - introFadeOutFrameMillis, MAX_TRANSITION_FRAME_MILLIS); introFadeOutFrameMillis = fadeOutTime; From cd9fb2786ee4667987c5eca87dcb9d238bd38cbf Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:42:21 -0500 Subject: [PATCH 18/27] feat(sdl renderer): loading UI --- .../splash/pre/PreSplashManager.java | 2 +- .../splash/pre/PreSplashScreenContainer.java | 20 +- .../splash/pre/renderer/IconDrawer.java | 193 ++++++++++++++++++ .../pre/renderer/LogoAnimationDrawer.java | 12 +- .../pre/renderer/SdlSplashRenderer.java | 87 +++++--- .../assets/cleanroom/shaders/icon.frag | 60 ++++++ .../assets/cleanroom/shaders/icon.vert | 10 + .../fml/common/launcher/FMLTweaker.java | 2 +- 8 files changed, 349 insertions(+), 37 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java create mode 100644 module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag create mode 100644 module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java index 3c2798d38..b2510174d 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -51,7 +51,7 @@ public synchronized void notifyPhase(PreSplashPhase phase) { case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; }; - states.add(new PreSplashState("Cleanroom", message, "")); + states.add(new PreSplashState("Cleanroom", message, "1")); currentPhase = phase; } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index e70157bd2..d20566d72 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -99,6 +99,7 @@ public final class PreSplashScreenContainer { private final CountDownLatch startupReady = new CountDownLatch(1); + private final Path gameDirectory; private final File assetsDirectory; private final @Nullable String assetIndex; @@ -107,13 +108,15 @@ public final class PreSplashScreenContainer { /** * Must be called on the game thread. * - * @see #start(File, String) + * @see #start(Path, File, String) */ - private PreSplashScreenContainer(File assetsDirectory, @Nullable String assetIndex) { + private PreSplashScreenContainer(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(gameDirectory); Preconditions.checkNotNull(assetsDirectory); gameThread = Thread.currentThread(); presentation = new PreSplashPresentation(PreSplashManager.INSTANCE); + this.gameDirectory = gameDirectory; this.assetsDirectory = assetsDirectory; this.assetIndex = assetIndex; thread = new Thread(this::run, "Pre Splash Renderer"); @@ -127,13 +130,14 @@ private PreSplashScreenContainer(File assetsDirectory, @Nullable String assetInd * @see FMLTweaker#injectIntoClassLoader(LaunchClassLoader) */ @ApiStatus.Internal - public static void start(File assetsDirectory, @Nullable String assetIndex) { + public static void start(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex) { + Preconditions.checkNotNull(gameDirectory); Preconditions.checkNotNull(assetsDirectory); PreSplashScreenContainer screen; synchronized (PreSplashScreenContainer.class) { Preconditions.checkState(instance == null, "Pre splash has already started."); - screen = new PreSplashScreenContainer(assetsDirectory, assetIndex); + screen = new PreSplashScreenContainer(gameDirectory, assetsDirectory, assetIndex); instance = screen; Runtime.getRuntime().addShutdownHook(screen.shutdownHook); @@ -251,6 +255,7 @@ private boolean runSdl() { Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$SdlRenderer", true, loader); Runnable render = (Runnable) renderer.getConstructor( + Path.class, File.class, String.class, BooleanSupplier.class, @@ -258,6 +263,7 @@ private boolean runSdl() { Runnable.class, Runnable.class, Runnable.class).newInstance( + gameDirectory, assetsDirectory, assetIndex, (BooleanSupplier) this::isRunning, @@ -295,6 +301,7 @@ private void runSwing() throws IOException { @ApiStatus.Internal public static final class SdlRenderer implements Runnable { + private final Path gameDirectory; private final File assetsDirectory; private final @Nullable String assetIndex; private final BooleanSupplier running; @@ -305,6 +312,7 @@ public static final class SdlRenderer implements Runnable { @ReflectiveInvocation public SdlRenderer( + Path gameDirectory, File assetsDirectory, @Nullable String assetIndex, BooleanSupplier running, @@ -313,6 +321,7 @@ public SdlRenderer( Runnable startupReady, Runnable unavailable) { + Preconditions.checkNotNull(gameDirectory); Preconditions.checkNotNull(assetsDirectory); Preconditions.checkNotNull(running); Preconditions.checkNotNull(state); @@ -320,6 +329,7 @@ public SdlRenderer( Preconditions.checkNotNull(startupReady); Preconditions.checkNotNull(unavailable); + this.gameDirectory = gameDirectory; this.assetsDirectory = assetsDirectory; this.assetIndex = assetIndex; this.running = running; @@ -333,7 +343,7 @@ public SdlRenderer( public void run() { try (Window window = Window.open(stop)) { if (running.getAsBoolean()) { - try (SdlSplashRenderer renderer = new SdlSplashRenderer(assetsDirectory, assetIndex, startupReady)) { + try (SdlSplashRenderer renderer = new SdlSplashRenderer(gameDirectory, assetsDirectory, assetIndex, startupReady)) { window.runLoop(running, (width, height) -> { renderer.update(state.get()); renderer.render(width, height); diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java new file mode 100644 index 000000000..1ec75d0c0 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.cleanroommc.kirino.engine.render.core.shader.ImmediateShaderAccess; +import com.cleanroommc.kirino.gl.shader.Shader; +import com.cleanroommc.kirino.gl.shader.ShaderProgram; +import com.cleanroommc.kirino.gl.texture.GLTexture; +import com.cleanroommc.kirino.gl.texture.accessor.Texture2DAccessor; +import com.cleanroommc.kirino.gl.texture.meta.FilterMode; +import com.cleanroommc.kirino.gl.texture.meta.WrapMode; +import com.cleanroommc.kirino.gl.vao.VAO; +import com.cleanroommc.kirino.utils.MinecraftResourceUtils; +import com.cleanroommc.kirino.utils.ResourceLocation; +import com.google.common.base.Preconditions; +import org.apache.commons.lang3.time.StopWatch; +import org.jspecify.annotations.Nullable; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL45; +import org.lwjgl.stb.STBImage; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; + +/** + *

Note: Only used by {@link SdlSplashRenderer}.

+ */ +final class IconDrawer implements AutoCloseable { + + private static final ResourceLocation VERTEX_SHADER = new ResourceLocation("cleanroom:shaders/icon.vert"); + private static final ResourceLocation FRAGMENT_SHADER = new ResourceLocation("cleanroom:shaders/icon.frag"); + private static final ResourceLocation LOGO = new ResourceLocation("cleanroom:icon.png"); + + private final StopWatch stopWatch = new StopWatch(); + private final VAO dummyVao; // borrowed + private final @Nullable Shader vertexShader; + private final @Nullable Shader fragmentShader; + private final @Nullable ShaderProgram program; + private final @Nullable Texture2DAccessor icon; + + IconDrawer(ImmediateShaderAccess shaders, VAO dummyVao, Path gameDirectory) throws IOException { + Preconditions.checkNotNull(shaders); + Preconditions.checkNotNull(gameDirectory); + Preconditions.checkNotNull(dummyVao); + + this.dummyVao = dummyVao; + + try { + vertexShader = shaders.makeShader(VERTEX_SHADER); + fragmentShader = shaders.makeShader(FRAGMENT_SHADER); + shaders.submitToGL(vertexShader, fragmentShader); + program = shaders.makeProgram(vertexShader, fragmentShader); + + for (String uniform : List.of("resolution", "progress", "logoTexture", "logoCenter", "logoScale", "background")) { + Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); + } + + program.uniform1i("logoTexture", 0); + program.uniform2f("resolution", PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); + program.uniform3f("background", + ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, + ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, + (PreSplashLayout.BACKGROUND & 255) / 255f); + + icon = loadIcon(gameDirectory); + } catch (Throwable failure) { + try { + close(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private static Texture2DAccessor loadIcon(Path gameDirectory) throws IOException { + Path customIcon = gameDirectory.resolve("config").resolve("cleanroom_pre_splash_icon.png"); + + if (Files.isRegularFile(customIcon)) { + try { + return loadIcon(Files.readAllBytes(customIcon)); + } catch (IOException failure) { + LOGGER.warn("Could not load custom pre splash icon {}.", customIcon, failure); + } + } + + try (var input = MinecraftResourceUtils.getEarlyInputStream(LOGO)) { + return loadIcon(input.readAllBytes()); + } + } + + private static Texture2DAccessor loadIcon(byte[] bytes) throws IOException { + ByteBuffer encoded = MemoryUtil.memAlloc(bytes.length); + ByteBuffer pixels = null; + GLTexture texture = null; + try (MemoryStack stack = MemoryStack.stackPush()) { + encoded.put(bytes).flip(); + var width = stack.mallocInt(1); + var height = stack.mallocInt(1); + var channels = stack.mallocInt(1); + pixels = STBImage.stbi_load_from_memory(encoded, width, height, channels, STBImage.STBI_rgb_alpha); + if (pixels == null) { + throw new IOException("Could not decode pre splash icon: " + STBImage.stbi_failure_reason()); + } + + texture = GLTexture.newDsaTex2D(width.get(0), height.get(0)); + Texture2DAccessor accessor = new Texture2DAccessor(true, texture); + accessor.highlevel().alloc(false, pixels); + accessor.setCommonParams(FilterMode.LINEAR, FilterMode.LINEAR, WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + return accessor; + } catch (Throwable failure) { + if (texture != null) { + try { + texture.disposeManually(); + } catch (Throwable cleanup) { + failure.addSuppressed(cleanup); + } + } + throw failure; + } finally { + if (pixels != null) { + STBImage.stbi_image_free(pixels); + } + MemoryUtil.memFree(encoded); + } + } + + void render(float x, float y, float width, float height) { + Preconditions.checkNotNull(program); + Preconditions.checkNotNull(icon); + Preconditions.checkArgument(width > 0 && height > 0); + + float progress = Math.min(1f, stopWatch.getTime(TimeUnit.MILLISECONDS) / (float) SdlSplashRenderer.ICON_ANIM_DURATION_MILLIS); + + program.uniform2f("logoCenter", (x + width / 2f) / PreSplashLayout.WIDTH, 1f - (y + height / 2f) / PreSplashLayout.HEIGHT); + program.uniform2f("logoScale", width / PreSplashLayout.WIDTH, height / PreSplashLayout.HEIGHT); + program.uniform1f("progress", progress); + icon.bindUnit(0); + dummyVao.bind(); + + program.use(); + GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 3); + program.use0(); + + VAO.bind(0); + GL45.glBindTextureUnit(0, 0); + + if (!stopWatch.isStarted()) { + stopWatch.start(); + } + } + + @Override + public void close() { + try { + if (icon != null) { + icon.texture.disposeManually(); + } + } finally { + try { + if (program != null) { + program.disposeManually(); + } + } finally { + try { + if (fragmentShader != null && fragmentShader.getShaderID() != 0) { + fragmentShader.disposeManually(); + } + } finally { + if (vertexShader != null && vertexShader.getShaderID() != 0) { + vertexShader.disposeManually(); + } + } + } + } + } +} diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java index 8a7ccc0ec..8b4568219 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java @@ -31,6 +31,7 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.util.List; import java.util.concurrent.TimeUnit; /** @@ -43,7 +44,7 @@ final class LogoAnimationDrawer implements AutoCloseable { private static final ResourceLocation LOGO = new ResourceLocation("cleanroom:icon.png"); private final StopWatch stopWatch = new StopWatch(); - private final VAO dummyVao; + private final VAO dummyVao; // borrowed private final @Nullable Shader vertexShader; private final @Nullable Shader fragmentShader; private final @Nullable ShaderProgram program; @@ -61,12 +62,9 @@ public LogoAnimationDrawer(ImmediateShaderAccess shaders, VAO dummyVao) throws I shaders.submitToGL(vertexShader, fragmentShader); program = shaders.makeProgram(vertexShader, fragmentShader); - int resolutionLocation = program.uniformLocation("resolution"); - int progressLocation = program.uniformLocation("progress"); - int textureLocation = program.uniformLocation("logoTexture"); - int backgroundLocation = program.uniformLocation("background"); - Preconditions.checkState(resolutionLocation >= 0 && progressLocation >= 0 && textureLocation >= 0 && backgroundLocation >= 0, - "Missing logo animation uniforms."); + for (String uniform : List.of("resolution", "progress", "logoTexture", "background")) { + Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); + } program.uniform1i("logoTexture", 0); program.uniform3f("background", diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index b856afff8..ffe3cbe07 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -45,6 +45,7 @@ import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.concurrent.TimeUnit; import static com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger.LOGGER; @@ -57,13 +58,15 @@ public final class SdlSplashRenderer implements AutoCloseable { private static final long EARLY_TITLE_IN_ANIM_MILLIS = 200; // for "Warming Up" private static final long EARLY_TITLE_CHAR_TYPE_MILLIS = 40; // for "Cleanroom" private static final long EARLY_TITLE_CHAR_FADE_IN_MILLIS = 180; // for "Cleanroom" - private static final long EARLY_TITLE_HOLD_MILLIS = 650; // // for "Cleanroom" + private static final long EARLY_TITLE_HOLD_MILLIS = 650; // for "Cleanroom" private static final long INTRO_FADE_OUT_ANIM_MILLIS = 200; private static final long POST_INTRO_MASK_FADE_OUT_MILLIS = 150; + private static final long POST_INTRO_LOADING_BAR_CYCLE_MILLIS = 1600; private static final long MAX_TRANSITION_FRAME_MILLIS = 33; private static final long LOADING_BAR_CYCLE_MILLIS = 1400; private static final long LOADING_BAR_FADE_OUT_MILLIS = 200; static final long LOGO_ANIM_DURATION_MILLIS = 1200; + static final long ICON_ANIM_DURATION_MILLIS = 480; private final Runnable startupReady; @@ -73,6 +76,7 @@ public final class SdlSplashRenderer implements AutoCloseable { private final VAO dummyVao; private final @Nullable SimpleGuiRuntime gui; private final @Nullable LogoAnimationDrawer logoAnimation; + private final @Nullable IconDrawer icon; private final @Nullable FreeTypeManager freeType; private final StopWatch mainStopWatch = new StopWatch(); @@ -113,9 +117,10 @@ private enum IntroStage { private boolean startupSignaled; - public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { + public SdlSplashRenderer(Path gameDirectory, File assetsDirectory, @Nullable String assetIndex, Runnable startupReady) throws Exception { LOGGER.info("Pre Splash Screen Backend: SDL + GL46"); + Preconditions.checkNotNull(gameDirectory); Preconditions.checkNotNull(assetsDirectory); Preconditions.checkNotNull(startupReady); @@ -142,6 +147,7 @@ public SdlSplashRenderer(File assetsDirectory, @Nullable String assetIndex, Runn gui = new SimpleGuiRuntime(shaders, dummyVao, PreSplashLayout.WIDTH, PreSplashLayout.HEIGHT); logoAnimation = new LogoAnimationDrawer(shaders, dummyVao); + icon = new IconDrawer(shaders, dummyVao, gameDirectory); var constructor = FreeTypeManager.class.getDeclaredConstructor(); constructor.setAccessible(true); @@ -460,12 +466,38 @@ public void render(int width, int height) { // if (introStage == IntroStage.FINISHED) { + Preconditions.checkNotNull(icon); + + int iconWidth = 120; + int iconHeight = 120; + icon.render((PreSplashLayout.WIDTH - iconWidth) / 2f, PreSplashLayout.HEIGHT * 0.15f, iconWidth, iconHeight); + text.begin(); - text.append(state.title(), 48, 106, 40, 0xFFF1F4FA); - text.append(state.message(), 48, 190, 30, 0xFFB9C7DB); - text.append(state.details(), 48, 286, 30, 0xFF8998AE); + var lineInfo = text.simulate(state.title(), 0, 0, 40); + text.append(state.title(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 200, 40, 0xFFF1F4FA); + lineInfo = text.simulate(state.message(), 0, 0, 25); + text.append(state.message(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 240, 25, 0xFFB9C7DB); + lineInfo = text.simulate(state.details(), 0, 0, 25); + text.append(state.details(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 290, 25, 0xFF8998AE); text.endDraw(); + gui.begin(); + gui.append(stream -> { + float barHeight = 7; + float barWidth = 300; + float segmentWidth = 80; + float barX = (PreSplashLayout.WIDTH - barWidth) / 2f; + float cycle = (mainStopWatch.getTime(TimeUnit.MILLISECONDS) % POST_INTRO_LOADING_BAR_CYCLE_MILLIS) / (float) POST_INTRO_LOADING_BAR_CYCLE_MILLIS; + float position = easeInOut(1f - Math.abs(cycle * 2f - 1f)); + stream.rectEx(barX, 273, barWidth, barHeight, 0xFF263448) + .radius(barHeight / 2f, 1) + .emit(); + stream.rectEx(barX + position * (barWidth - segmentWidth), 273, segmentWidth, barHeight, 0xFF8AB9E8) + .radius(barHeight / 2f, 1) + .emit(); + }); + gui.endDraw(); + long maskTime = postIntroMaskStopWatch.getTime(TimeUnit.MILLISECONDS); boolean maskFinished = postIntroMaskElapsedMillis >= POST_INTRO_MASK_FADE_OUT_MILLIS; if (!maskFinished) { @@ -512,39 +544,48 @@ public void close() throws Exception { LOGGER.info("Pre splash renderer finished in {}ms.", mainStopWatch.getTime(TimeUnit.MILLISECONDS)); } - fontLoader.close(); try { + fontLoader.close(); + } finally { try { if (introText != null && introText != text) { introText.close(); } - } finally { - if (text != null) { - text.close(); - } - } - } finally { - try { - if (logoAnimation != null) { - logoAnimation.close(); - } } finally { try { - if (gui != null) { - gui.close(); + if (text != null) { + text.close(); } } finally { try { - if (freeType != null) { - freeType.destroy(); + if (icon != null) { + icon.close(); } } finally { try { - if (mcFontData != null) { - MemoryUtil.memFree(mcFontData); + if (logoAnimation != null) { + logoAnimation.close(); } } finally { - scope.close(); + try { + if (gui != null) { + gui.close(); + } + } finally { + try { + if (freeType != null) { + freeType.destroy(); + } + } finally { + try { + if (mcFontData != null) { + MemoryUtil.memFree(mcFontData); + } + } finally { + scope.close(); + } + } + } } } } diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag new file mode 100644 index 000000000..1d4e11ea6 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag @@ -0,0 +1,60 @@ +#version 460 core + +in vec2 ViewportUV; +out vec4 Color; + +uniform vec2 resolution; +uniform float progress; +uniform sampler2D logoTexture; +uniform vec2 logoCenter; +uniform vec2 logoScale; +uniform vec3 background; + +const float INITIAL_SCALE = 0.94; +const float INITIAL_BLUR = 4.0; +const float INITIAL_OFFSET_Y = 7.0; + +vec4 sampleLogo(vec2 uv) +{ + if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec4(0.0); + vec4 color = texture(logoTexture, vec2(uv.x, 1.0 - uv.y)); + return vec4(color.rgb * color.a, color.a); +} + +void main() +{ + float t = clamp(progress, 0.0, 1.0); + float eased = 1.0 - pow(1.0 - t, 3.0); + float opacity = smoothstep(0.0, 0.72, t); + vec2 scale = logoScale * mix(INITIAL_SCALE, 1.0, eased); + vec2 center = logoCenter - vec2(0.0, INITIAL_OFFSET_Y / resolution.y) * (1.0 - eased); + vec2 uv = (ViewportUV - center) / scale + 0.5; + vec2 blurStep = INITIAL_BLUR * (1.0 - eased) / resolution / scale; + vec2 extent = blurStep * 2.0; + + if (opacity == 0.0 || any(lessThan(uv, -extent)) || any(greaterThan(uv, 1.0 + extent))) + { + Color = vec4(background, 1.0); + return; + } + + vec4 logo; + if (t == 1.0) + { + logo = sampleLogo(uv); + } + else + { + const float weights[5] = float[5](1.0, 4.0, 6.0, 4.0, 1.0); + logo = vec4(0.0); + for (int y = -2; y <= 2; y++) + { + for (int x = -2; x <= 2; x++) + { + logo += sampleLogo(uv + vec2(x, y) * blurStep) * weights[x + 2] * weights[y + 2] / 256.0; + } + } + } + + Color = vec4(background * (1.0 - logo.a * opacity) + logo.rgb * opacity, 1.0); +} diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert new file mode 100644 index 000000000..d0ba5f721 --- /dev/null +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.vert @@ -0,0 +1,10 @@ +#version 460 core + +out vec2 ViewportUV; + +void main() +{ + vec2 position = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); + ViewportUV = position; + gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java index a7199e041..24b7d8f86 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLTweaker.java @@ -149,7 +149,7 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) { PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.FML_SETUP); String assets = launchArgs.get("--assetsDir"); - PreSplashScreenContainer.start(assets == null ? new File(gameDir, "assets") : new File(assets), launchArgs.get("--assetIndex")); + PreSplashScreenContainer.start(gameDir.toPath(), assets == null ? new File(gameDir, "assets") : new File(assets), launchArgs.get("--assetIndex")); FMLLaunchHandler.configureForClientLaunch(classLoader, this); FMLLaunchHandler.appendCoreMods(); From d1bc11e45154ecdcd148ecc921108de62e5d5a1f Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:08:21 -0500 Subject: [PATCH 19/27] feat: loading details --- .../splash/pre/PreSplashManager.java | 42 +++++-- .../pre/renderer/SdlSplashRenderer.java | 6 +- .../discovery/CleanroomModDiscoverer.java | 21 ++++ .../fml/common/launcher/FMLDeobfTweaker.java | 15 +++ .../fml/relauncher/CoreModManager.java | 36 ++++++ .../net/minecraft/client/Minecraft.java.patch | 103 ++++++++++-------- 6 files changed, 166 insertions(+), 57 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java index b2510174d..e2a19a047 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashManager.java @@ -31,6 +31,20 @@ public final class PreSplashManager { private PreSplashManager() { } + private static String title() { + return "Cleanroom"; + } + + private static String phaseMsg(PreSplashPhase phase) { + return switch (phase) { + case FML_SETUP -> "Preparing Forge Mod Loader"; + case INITIAL_MOD_SCAN -> "Discovering mods"; + case CORE_MOD_LAUNCH -> "Loading core mods"; + case MINECRAFT_INIT -> "Initializing Minecraft"; + case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; + }; + } + /** * Thread-safe. * @@ -43,20 +57,30 @@ public synchronized void notifyPhase(PreSplashPhase phase) { "Expected pre splash phase: %s; Observed: %s", fsm.getState(), phase); fsm.next(); - String message = switch (phase) { - case FML_SETUP -> "Preparing Forge Mod Loader"; - case INITIAL_MOD_SCAN -> "Discovering mods"; - case CORE_MOD_LAUNCH -> "Loading core mods"; - case MINECRAFT_INIT -> "Initializing Minecraft"; - case RIGHT_BEFORE_SPLASH -> "Starting mod loading"; - }; - states.add(new PreSplashState("Cleanroom", message, "1")); + states.add(new PreSplashState(title(), phaseMsg(phase), "")); currentPhase = phase; } /** - * Thread-safe. Only intended to be read by after the first phase has been published. + * Thread-safe. Must be called after the first {@link #notifyPhase(PreSplashPhase)}. + * + * @param phase The current phase that owns this detail update (acts like a filter) + */ + @SuppressWarnings("DataFlowIssue") + @ApiStatus.Internal + public synchronized void notifyDetails(PreSplashPhase phase, String details) { + Preconditions.checkNotNull(phase); + Preconditions.checkNotNull(details); + Preconditions.checkNotNull(currentPhase); + + if (currentPhase == phase) { + states.add(new PreSplashState(title(), phaseMsg(currentPhase), details)); + } + } + + /** + * Thread-safe. Only intended to be read after the first phase has been published. */ @ApiStatus.Internal PreSplashPhase readPhase() { diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java index ffe3cbe07..51e3de369 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/SdlSplashRenderer.java @@ -477,8 +477,10 @@ public void render(int width, int height) { text.append(state.title(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 200, 40, 0xFFF1F4FA); lineInfo = text.simulate(state.message(), 0, 0, 25); text.append(state.message(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 240, 25, 0xFFB9C7DB); - lineInfo = text.simulate(state.details(), 0, 0, 25); - text.append(state.details(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 290, 25, 0xFF8998AE); + if (!state.details().isEmpty()) { + lineInfo = text.simulate(state.details(), 0, 0, 25); + text.append(state.details(), (PreSplashLayout.WIDTH - lineInfo.getLineWidth()) / 2f, 292, 25, 0xFF8998AE); + } text.endDraw(); gui.begin(); diff --git a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java index aeb3a3499..a2bead98c 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/discovery/CleanroomModDiscoverer.java @@ -178,7 +178,13 @@ private CleanroomModDiscoverer() { } } catch (URISyntaxException ignored) { } } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.INITIAL_MOD_SCAN, "Scanning mods"); + } this.discover(files); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.INITIAL_MOD_SCAN, "Finished discovering mods"); + } } public static CleanroomModDiscoverer instance() { @@ -428,6 +434,9 @@ public void discoverMixinMods() { if (!mod.hasMixinManifestAttributes()) { continue; } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading mixins: " + mod.file().getName()); + } if (mod.coremod() == null) { try { Launch.classLoader.addURL(mod.file().toURI().toURL()); @@ -453,6 +462,9 @@ public void discoverCoreMods(File minecraftDirectory, LaunchClassLoader classLoa File modsDir = setupCoreModDir(minecraftDirectory); findDerpMods(modsDir); if (fileDirector != null) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Installing mods with File Director"); + } discoverFileDirectorMods(minecraftDirectory, classLoader); } @@ -586,7 +598,13 @@ private void discoverFileDirectorMods(File gameDir, LaunchClassLoader classLoade return true; }); if (!installed.isEmpty()) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Scanning installed mods"); + } discover(installed); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Finished discovering installed mods"); + } } } @@ -740,6 +758,9 @@ private void discoverCoreMod( if (containNonMods) { addContainedDepsToClasspath(classLoader, attributes, containedDepsDir); } + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading launch plugin: " + file.getName()); + } CleanroomLog.get().info("Cascading tweaker {} from {}", discoveredMod.tweaker(), file.getName()); Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(attributes.getValue("TweakOrder"))); CoreModManager.injectDiscoveredCascadingTweaker( diff --git a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java index 806dedf1d..f3193836c 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/common/launcher/FMLDeobfTweaker.java @@ -22,7 +22,10 @@ import java.io.File; import java.util.List; +import com.cleanroommc.cleanroom.splash.pre.PreSplashManager; +import com.cleanroommc.cleanroom.splash.pre.PreSplashPhase; import com.cleanroommc.cleanmix.service.CleanMixService; +import com.cleanroommc.common.CleanroomEnvironment; import net.minecraft.launchwrapper.ITweaker; import net.minecraft.launchwrapper.LaunchClassLoader; import net.minecraftforge.fml.common.FMLLog; @@ -42,6 +45,10 @@ public void acceptOptions(List args, File gameDir, File assetsDir, Strin @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Preparing class transformers"); + } + // Deobfuscation transformer, always last, and the access transformer tweaker as well TransformerDelegate.registerRenameTransformer(new DeobfuscationTransformer()); // Add all the access transformers now as well @@ -55,10 +62,18 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.ItemBlockSpecialTransformer"); classLoader.registerTransformer("net.minecraftforge.fml.common.asm.transformers.PotionEffectTransformer"); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Initializing mixins"); + } + ((CleanMixService) MixinService.getService()).transitionToInit(); try { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Preparing Minecraft classes"); + } + FMLLog.log.debug("Validating minecraft"); Loader.injectData(FMLInjectionData.data()); Loader.instance(); diff --git a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java index 6757ffd94..211af3aff 100644 --- a/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java +++ b/module/forge/src/main/java/net/minecraftforge/fml/relauncher/CoreModManager.java @@ -105,6 +105,10 @@ public void acceptOptions(List args, File gameDir, File assetsDir, Strin @Override public void injectIntoClassLoader(LaunchClassLoader classLoader) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Registering transformers: " + name); + } + FMLLog.log.debug("Injecting coremod {} \\{{}\\} class transformers", name, coreModInstance.getClass().getName()); List ts = Lists.newArrayList(); String[] asmTransformerClass = coreModInstance.getASMTransformerClass(); @@ -123,6 +127,10 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) } FMLLog.log.debug("Injection complete"); + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Initializing core mod: " + name); + } + FMLLog.log.debug("Running coremod plugin for {} {{}}", name, coreModInstance.getClass().getName()); Map data = new HashMap<>(); data.put("mcLocation", mcDir); @@ -134,6 +142,10 @@ public void injectIntoClassLoader(LaunchClassLoader classLoader) String setupClass = coreModInstance.getSetupClass(); if (setupClass != null) { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Running setup: " + name); + } + try { IFMLCallHook call = (IFMLCallHook) Class.forName(setupClass, true, classLoader).getConstructor().newInstance(); @@ -249,10 +261,16 @@ public static void handleLaunch(File mcDir, LaunchClassLoader classLoader, FMLTw if (CleanroomEnvironment.side().isClient()) { PreSplashManager.INSTANCE.notifyPhase(PreSplashPhase.CORE_MOD_LAUNCH); + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Discovering core mods"); } // Coremods CleanroomModDiscoverer.instance().discoverCoreMods(mcDir, classLoader, tweaker); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Discovering mixin mods"); + } + // Mixin Mods CleanroomModDiscoverer.instance().discoverMixinMods(); } @@ -410,6 +428,10 @@ else if (deobfuscatedEnvironment && location == null) // This is probably a mod public static boolean loadCoreModFromDiscoveredJar(LaunchClassLoader classLoader, String coreModClass, File location) { + if (CleanroomEnvironment.side().isClient() && !loadedPlugins.contains(coreModClass)) { + String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1); + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading core mod: " + coreModName); + } return loadCoreMod(classLoader, coreModClass, location) != null; } @@ -427,8 +449,18 @@ public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectio List tweakers = (List) Launch.blackboard.get("Tweaks"); // Add the sorting tweaker first- it'll appear twice in the list tweakers.addFirst(fmlInjectionAndSortingTweaker); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading additional core mods"); + } + // Load rescued (ForceLoadAsMod) coremods CleanroomModDiscoverer.instance().rescueDroppedCoremods(); + + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Loading early mixins"); + } + // Early Mixin Loaders Instantiation CleanMixHooks.loadMixinBooterEarlyMixins(loadPlugins); // Add loadPlugins (including rescued coremods) @@ -439,6 +471,10 @@ public static void injectCoreModTweaks(FMLInjectionAndSortingTweaker fmlInjectio public static void sortTweakList() { + if (CleanroomEnvironment.side().isClient()) { + PreSplashManager.INSTANCE.notifyDetails(PreSplashPhase.CORE_MOD_LAUNCH, "Sorting launch plugins"); + } + @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. diff --git a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch index 6d370d26a..1d51573fc 100644 --- a/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch +++ b/module/minecraft/patches/net/minecraft/client/Minecraft.java.patch @@ -67,32 +67,43 @@ this.isDemo = gameConfig.gameInfo.isDemo; this.displayWidth = gameConfig.displayInfo.width > 0 ? gameConfig.displayInfo.width : 1; this.displayHeight = gameConfig.displayInfo.height > 0 ? gameConfig.displayInfo.height : 1; -@@ -447,6 +436,8 @@ +@@ -447,6 +436,10 @@ /** Starts the game: initializes the canvas, the title, the settings, etcetera. */ private void init() throws IOException, LWJGLException { + com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyPhase(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing video"); + com.cleanroommc.client.sdl.SDL.ensureVideo(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Loading game settings"); this.gameSettings = new GameSettings(this, this.gameDir); this.creativeSettings = new CreativeSettings(this, this.gameDir); this.defaultResourcePacks.add(this.defaultResourcePack); -@@ -455,8 +446,9 @@ +@@ -455,25 +448,33 @@ this.displayWidth = this.gameSettings.overrideWidth; this.displayHeight = this.gameSettings.overrideHeight; } - - LOGGER.info("LWJGL Version: {}", Sys.getVersion()); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Creating game window"); + com.cleanroommc.client.sdl.Window window = com.cleanroommc.client.sdl.SDL.createWindow().title("Cleanroom").size(this.displayWidth, this.displayHeight).resizable().vsync(this.gameSettings.enableVsync).openGL().build(); + com.cleanroommc.client.sdl.CleanroomWindowBridge.install(window); + LOGGER.info("LWJGL Version: {}", org.lwjgl.Version.getVersion()); this.setWindowIcon(); this.setInitialDisplayMode(); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing native resources"); this.createDisplay(); -@@ -468,12 +460,14 @@ + OpenGlHelper.initializeTextures(); + this.framebuffer = new Framebuffer(this.displayWidth, this.displayHeight, true); + this.framebuffer.setFramebufferColor(0.0F, 0.0F, 0.0F, 0.0F); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing resource manager"); + this.registerMetadataSerializers(); + this.resourcePackRepository = new ResourcePackRepository( this.fileResourcepacks, new File(this.gameDir, "server-resource-packs"), this.defaultResourcePack, this.metadataSerializer, this.gameSettings ); this.resourceManager = new SimpleReloadableResourceManager(this.metadataSerializer); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Initializing immediate client services"); + com.cleanroommc.kirino.ImmediateClientServices.initAndWarmUp(this.resourceManager); ++ com.cleanroommc.cleanroom.splash.pre.PreSplashManager.INSTANCE.notifyDetails(com.cleanroommc.cleanroom.splash.pre.PreSplashPhase.MINECRAFT_INIT, "Loading languages"); this.languageManager = new LanguageManager(this.metadataSerializer, this.gameSettings.language); this.resourceManager.registerReloadListener(this.languageManager); - this.refreshResources(); @@ -105,7 +116,7 @@ this.skinManager = new SkinManager(this.renderEngine, new File(this.fileAssets, "skins"), this.sessionService); this.saveLoader = new AnvilSaveConverter(new File(this.gameDir, "saves"), this.dataFixer); this.soundHandler = new SoundHandler(this.resourceManager, this.gameSettings); -@@ -491,6 +485,8 @@ +@@ -491,6 +492,8 @@ this.resourceManager.registerReloadListener(new GrassColorReloadListener()); this.resourceManager.registerReloadListener(new FoliageColorReloadListener()); this.mouseHelper = new MouseHelper(); @@ -114,7 +125,7 @@ this.checkGLError("Pre startup"); GlStateManager.enableTexture2D(); GlStateManager.shadeModel(7425); -@@ -504,19 +500,24 @@ +@@ -504,19 +507,24 @@ GlStateManager.loadIdentity(); GlStateManager.matrixMode(5888); this.checkGLError("Startup"); @@ -139,7 +150,7 @@ this.entityRenderer = new EntityRenderer(this, this.resourceManager); this.resourceManager.registerReloadListener(this.entityRenderer); this.blockRenderDispatcher = new BlockRendererDispatcher(this.modelManager.getBlockModelShapes(), this.blockColors); -@@ -527,18 +528,26 @@ +@@ -527,18 +535,26 @@ this.resourceManager.registerReloadListener(this.searchTreeManager); GlStateManager.viewport(0, 0, this.displayWidth, this.displayHeight); this.effectRenderer = new ParticleManager(this.world, this.renderEngine); @@ -169,7 +180,7 @@ if (this.gameSettings.fullScreen && !this.fullscreen) { this.toggleFullscreen(); } -@@ -599,34 +608,22 @@ +@@ -599,34 +615,22 @@ private void createDisplay() throws LWJGLException { Display.setResizable(true); @@ -215,7 +226,7 @@ } } -@@ -640,7 +637,7 @@ +@@ -640,7 +644,7 @@ inputstream = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_16x16.png")); inputstream1 = this.defaultResourcePack.getInputStreamAssets(new ResourceLocation("icons/icon_32x32.png")); if (inputstream != null && inputstream1 != null) { @@ -224,7 +235,7 @@ } } catch (IOException ioexception) { LOGGER.error("Couldn't set icon", ioexception); -@@ -679,6 +676,7 @@ +@@ -679,6 +683,7 @@ } private void startTimerHackThread() { @@ -232,7 +243,7 @@ Thread thread = new Thread("Timer hack thread") { @Override public void run() { -@@ -691,6 +689,7 @@ +@@ -691,6 +696,7 @@ } }; thread.setDaemon(true); @@ -240,7 +251,7 @@ thread.start(); } -@@ -704,22 +703,26 @@ +@@ -704,22 +710,26 @@ File file1 = new File(getMinecraft().gameDir, "crash-reports"); File file2 = new File(file1, "crash-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + "-client.txt"); Bootstrap.printToSYSOUT(crashReportIn.getCompleteReport()); @@ -270,7 +281,7 @@ public void refreshResources() { List list = Lists.newArrayList(this.defaultResourcePacks); if (this.integratedServer != null) { -@@ -902,16 +905,22 @@ +@@ -902,16 +912,22 @@ * @param guiScreenIn The {@link GuiScreen} to display. If it is {@code null}, any open GUI will be closed. */ public void displayGuiScreen(@Nullable GuiScreen guiScreenIn) { @@ -297,7 +308,7 @@ if (guiScreenIn instanceof GuiMainMenu || guiScreenIn instanceof GuiMultiplayer) { this.gameSettings.showDebugInfo = false; this.ingameGUI.getChatGUI().clearChatMessages(true); -@@ -962,7 +971,8 @@ +@@ -962,7 +978,8 @@ this.soundHandler.unloadSounds(); } finally { @@ -307,7 +318,7 @@ if (!this.hasCrashed) { System.exit(0); } -@@ -980,6 +990,8 @@ +@@ -980,6 +997,8 @@ } this.timer.updateTimer(); @@ -316,7 +327,7 @@ this.profiler.startSection("scheduledExecutables"); synchronized (this.scheduledTasks) { while (!this.scheduledTasks.isEmpty()) { -@@ -999,7 +1011,7 @@ +@@ -999,7 +1018,7 @@ long i1 = System.nanoTime() - l; this.checkGLError("Pre render"); this.profiler.endStartSection("sound"); @@ -325,7 +336,7 @@ this.profiler.endSection(); this.profiler.startSection("render"); GlStateManager.pushMatrix(); -@@ -1009,11 +1021,13 @@ +@@ -1009,11 +1028,13 @@ GlStateManager.enableTexture2D(); this.profiler.endSection(); if (!this.skipRenderWorld) { @@ -339,7 +350,7 @@ } this.profiler.endSection(); -@@ -1096,7 +1110,7 @@ +@@ -1096,7 +1117,7 @@ } protected void checkWindowResize() { @@ -348,7 +359,7 @@ int i = this.displayWidth; int j = this.displayHeight; this.displayWidth = Display.getWidth(); -@@ -1308,9 +1322,9 @@ +@@ -1308,9 +1329,9 @@ if (this.leftClickCounter <= 0 && !this.player.isHandActive()) { if (leftClick && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -361,7 +372,7 @@ this.player.swingArm(EnumHand.MAIN_HAND); } } else { -@@ -1333,7 +1347,8 @@ +@@ -1333,7 +1354,8 @@ break; case BLOCK: BlockPos blockpos = this.objectMouseOver.getBlockPos(); @@ -371,7 +382,7 @@ this.playerController.clickBlock(blockpos, this.objectMouseOver.sideHit); break; } -@@ -1343,6 +1358,7 @@ +@@ -1343,6 +1365,7 @@ } this.player.resetCooldown(); @@ -379,7 +390,7 @@ } this.player.swingArm(EnumHand.MAIN_HAND); -@@ -1399,6 +1415,7 @@ +@@ -1399,6 +1422,7 @@ } } @@ -387,7 +398,7 @@ if (!itemstack.isEmpty() && this.playerController.processRightClick(this.player, this.world, enumhand) == EnumActionResult.SUCCESS) { this.entityRenderer.itemRenderer.resetEquippedProgress(enumhand); -@@ -1414,7 +1431,12 @@ +@@ -1414,7 +1438,12 @@ try { this.fullscreen = !this.fullscreen; this.gameSettings.fullScreen = this.fullscreen; @@ -401,7 +412,7 @@ this.updateDisplayMode(); this.displayWidth = Display.getDisplayMode().getWidth(); this.displayHeight = Display.getDisplayMode().getHeight(); -@@ -1444,7 +1466,17 @@ +@@ -1444,7 +1473,17 @@ this.updateFramebufferSize(); } @@ -420,7 +431,7 @@ Display.setVSyncEnabled(this.gameSettings.enableVsync); this.updateDisplay(); } catch (Exception exception) { -@@ -1483,6 +1515,8 @@ +@@ -1483,6 +1522,8 @@ this.rightClickDelayTimer--; } @@ -429,7 +440,7 @@ this.profiler.startSection("gui"); if (!this.isGamePaused) { this.ingameGUI.updateTick(); -@@ -1632,6 +1666,7 @@ +@@ -1632,6 +1673,7 @@ } this.profiler.endSection(); @@ -437,7 +448,7 @@ this.systemTime = getSystemTime(); } -@@ -1705,6 +1740,7 @@ +@@ -1705,6 +1747,7 @@ } } } @@ -445,7 +456,7 @@ } this.processKeyBinds(); -@@ -1896,6 +1932,8 @@ +@@ -1896,6 +1939,8 @@ private void runTickMouse() throws IOException { while (Mouse.next()) { @@ -454,7 +465,7 @@ int i = Mouse.getEventButton(); KeyBinding.setKeyBindState(i - 100, Mouse.getEventButtonState()); if (Mouse.getEventButtonState()) { -@@ -1931,6 +1969,7 @@ +@@ -1931,6 +1976,7 @@ this.currentScreen.handleMouseInput(); } } @@ -462,7 +473,7 @@ } } -@@ -1949,6 +1988,7 @@ +@@ -1949,6 +1995,7 @@ /** Arguments: World foldername, World ingame name, WorldSettings */ public void launchIntegratedServer(String folderName, String worldName, @Nullable WorldSettings worldSettingsIn) { @@ -470,7 +481,7 @@ this.loadWorld(null); System.gc(); ISaveHandler isavehandler = this.saveLoader.getSaveLoader(folderName, false); -@@ -1990,6 +2030,11 @@ +@@ -1990,6 +2037,11 @@ this.loadingScreen.displaySavingString(I18n.format("menu.loadingLevel")); while (!this.integratedServer.serverIsInRunLoop()) { @@ -482,7 +493,7 @@ String s = this.integratedServer.getUserMessage(); if (s != null) { this.loadingScreen.displayLoadingString(I18n.format(s)); -@@ -2007,8 +2052,13 @@ +@@ -2007,8 +2059,13 @@ SocketAddress socketaddress = this.integratedServer.getNetworkSystem().addLocalEndpoint(); NetworkManager networkmanager = NetworkManager.provideLocalClient(socketaddress); networkmanager.setNetHandler(new NetHandlerLoginClient(networkmanager, this, null)); @@ -498,7 +509,7 @@ this.networkManager = networkmanager; } -@@ -2019,6 +2069,8 @@ +@@ -2019,6 +2076,8 @@ /** par2Str is displayed on the loading screen to the user unloads the current world first */ public void loadWorld(@Nullable WorldClient worldClientIn, String loadingMessage) { @@ -507,7 +518,7 @@ if (worldClientIn == null) { NetHandlerPlayClient nethandlerplayclient = this.getConnection(); if (nethandlerplayclient != null) { -@@ -2027,6 +2079,14 @@ +@@ -2027,6 +2086,14 @@ if (this.integratedServer != null && this.integratedServer.isAnvilFileSet()) { this.integratedServer.initiateShutdown(); @@ -522,7 +533,7 @@ } this.integratedServer = null; -@@ -2047,6 +2107,7 @@ +@@ -2047,6 +2114,7 @@ this.ingameGUI.resetPlayersOverlayFooterHeader(); this.setServerData(null); this.integratedServerIsRunning = false; @@ -530,7 +541,7 @@ } this.soundHandler.stopSounds(); -@@ -2060,6 +2121,8 @@ +@@ -2060,6 +2128,8 @@ } TileEntityRendererDispatcher.instance.setWorld(worldClientIn); @@ -539,7 +550,7 @@ if (worldClientIn != null) { if (!this.integratedServerIsRunning) { AuthenticationService authenticationservice = new YggdrasilAuthenticationService(this.proxy, UUID.randomUUID().toString()); -@@ -2112,6 +2175,7 @@ +@@ -2112,6 +2182,7 @@ this.player == null ? new RecipeBook() : this.player.getRecipeBook() ); this.player.getDataManager().setEntryValues(entityplayersp.getDataManager().getAll()); @@ -547,7 +558,7 @@ this.player.dimension = dimension; this.renderViewEntity = this.player; this.player.preparePlayerToSpawn(); -@@ -2153,110 +2217,8 @@ +@@ -2153,110 +2224,8 @@ /** Called when user clicked he's mouse middle button (pick block) */ private void middleClickMouse() { if (this.objectMouseOver != null && this.objectMouseOver.typeOfHit != RayTraceResult.Type.MISS) { @@ -660,7 +671,7 @@ } } -@@ -2288,12 +2250,16 @@ +@@ -2288,12 +2257,16 @@ }); theCrash.getCategory().addDetail("LWJGL", new ICrashReportDetail() { public String call() throws Exception { @@ -679,7 +690,7 @@ } }); theCrash.getCategory().addDetail("GL Caps", new ICrashReportDetail() { -@@ -2372,6 +2338,7 @@ +@@ -2372,6 +2345,7 @@ return instance; } @@ -687,7 +698,7 @@ public ListenableFuture scheduleResourcesRefresh() { return this.addScheduledTask(new Runnable() { @Override -@@ -2536,15 +2503,8 @@ +@@ -2536,15 +2510,8 @@ /** Used in the usage snooper. */ public static int getGLMaximumTextureSize() { @@ -705,7 +716,7 @@ } /** Returns whether snooping is enabled or not. */ -@@ -2658,6 +2618,9 @@ +@@ -2658,6 +2625,9 @@ } if (this.player != null) { @@ -715,7 +726,7 @@ if (this.player.world.provider instanceof WorldProviderHell) { return MusicTicker.MusicType.NETHER; } else if (this.player.world.provider instanceof WorldProviderEnd) { -@@ -2677,9 +2640,9 @@ +@@ -2677,9 +2647,9 @@ if (i != 0 && !Keyboard.isRepeatEvent()) { if (!(this.currentScreen instanceof GuiControls) || ((GuiControls)this.currentScreen).time <= getSystemTime() - 20L) { if (Keyboard.getEventKeyState()) { @@ -727,7 +738,7 @@ this.ingameGUI .getChatGUI() .printChatMessage(ScreenShotHelper.saveScreenshot(this.gameDir, this.displayWidth, this.displayHeight, this.framebuffer)); -@@ -2691,7 +2654,7 @@ +@@ -2691,7 +2661,7 @@ ((ScreenChatOptions)this.currentScreen).updateNarratorButton(); } } @@ -736,7 +747,7 @@ } } } -@@ -2720,7 +2683,7 @@ +@@ -2720,7 +2690,7 @@ try { return Futures.immediateFuture(callableToSchedule.call()); } catch (Exception exception) { @@ -745,7 +756,7 @@ } } else { ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callableToSchedule); -@@ -2798,11 +2761,24 @@ +@@ -2798,11 +2768,24 @@ return this.timer.elapsedPartialTicks; } @@ -771,7 +782,7 @@ public boolean isReducedDebug() { return this.player != null && this.player.hasReducedDebug() || this.gameSettings.reducedDebugInfo; } -@@ -2814,4 +2790,8 @@ +@@ -2814,4 +2797,8 @@ public Tutorial getTutorial() { return this.tutorial; } From baa0e0b7cddec2d764c95b025f4711ee7ec5b311 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:14:02 -0500 Subject: [PATCH 20/27] feat(sdl renderer): background glow --- .../splash/pre/renderer/IconDrawer.java | 10 ++++- .../splash/pre/renderer/PreSplashLayout.java | 1 + .../assets/cleanroom/shaders/icon.frag | 38 ++++++++++++++++++- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java index 1ec75d0c0..c4ca14c35 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java @@ -67,7 +67,7 @@ final class IconDrawer implements AutoCloseable { shaders.submitToGL(vertexShader, fragmentShader); program = shaders.makeProgram(vertexShader, fragmentShader); - for (String uniform : List.of("resolution", "progress", "logoTexture", "logoCenter", "logoScale", "background")) { + for (String uniform : List.of("resolution", "progress", "logoTexture", "logoCenter", "logoScale", "background", "glow", "time")) { Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); } @@ -77,6 +77,10 @@ final class IconDrawer implements AutoCloseable { ((PreSplashLayout.BACKGROUND >> 16) & 255) / 255f, ((PreSplashLayout.BACKGROUND >> 8) & 255) / 255f, (PreSplashLayout.BACKGROUND & 255) / 255f); + program.uniform3f("glow", + ((PreSplashLayout.GLOW_COLOR >> 16) & 255) / 255f, + ((PreSplashLayout.GLOW_COLOR >> 8) & 255) / 255f, + (PreSplashLayout.GLOW_COLOR & 255) / 255f); icon = loadIcon(gameDirectory); } catch (Throwable failure) { @@ -146,11 +150,13 @@ void render(float x, float y, float width, float height) { Preconditions.checkNotNull(icon); Preconditions.checkArgument(width > 0 && height > 0); - float progress = Math.min(1f, stopWatch.getTime(TimeUnit.MILLISECONDS) / (float) SdlSplashRenderer.ICON_ANIM_DURATION_MILLIS); + long elapsedMillis = stopWatch.getTime(TimeUnit.MILLISECONDS); + float progress = Math.min(1f, elapsedMillis / (float) SdlSplashRenderer.ICON_ANIM_DURATION_MILLIS); program.uniform2f("logoCenter", (x + width / 2f) / PreSplashLayout.WIDTH, 1f - (y + height / 2f) / PreSplashLayout.HEIGHT); program.uniform2f("logoScale", width / PreSplashLayout.WIDTH, height / PreSplashLayout.HEIGHT); program.uniform1f("progress", progress); + program.uniform1f("time", elapsedMillis / 1000f); icon.bindUnit(0); dummyVao.bind(); diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java index c49f05bd1..51547c3b7 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java @@ -16,6 +16,7 @@ public final class PreSplashLayout { public static final int HEIGHT = 360; public static final float SCREEN_PERCENTAGE = 0.35f; public static final int BACKGROUND = 0xFF0E1116; + public static final int GLOW_COLOR = 0xFF455D74; private PreSplashLayout() { } diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag index 1d4e11ea6..b79509c31 100644 --- a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag @@ -9,10 +9,43 @@ uniform sampler2D logoTexture; uniform vec2 logoCenter; uniform vec2 logoScale; uniform vec3 background; +uniform vec3 glow; +uniform float time; const float INITIAL_SCALE = 0.94; const float INITIAL_BLUR = 4.0; const float INITIAL_OFFSET_Y = 7.0; +const float GLOW_SPEED = 0.85; +const float GLOW_INTENSITY = 0.06; + +vec3 sampleBackground(vec2 uv) +{ + float glowTime = time * GLOW_SPEED; + float aspectRatio = resolution.x / max(resolution.y, 1.0); + float widthMix = 0.65 * smoothstep(1.3, 4.5, aspectRatio); + float materialWidth = mix(resolution.y, resolution.x, widthMix); + vec2 p = (uv - 0.5) * resolution * vec2(1.0, -1.0); + vec2 materialPos = p / max(vec2(materialWidth, resolution.y), vec2(1.0)); + + float centerGlow = 1.0 - smoothstep(0.05, 0.85, length(materialPos)); + vec3 color = background * (0.96 + centerGlow * 0.04); + + vec2 glowCenterA = vec2(0.42 * cos(glowTime), 0.23 * sin(glowTime * 2.0)); + vec2 deltaA = materialPos - glowCenterA; + float glowA = exp(-dot(deltaA, deltaA) * 4.5); + + vec2 glowCenterB = vec2(-0.34 * cos(glowTime * 2.0), 0.18 * sin(glowTime)); + vec2 deltaB = materialPos - glowCenterB; + float glowB = exp(-dot(deltaB, deltaB) * 7.0); + + float flowCoordinate = dot(materialPos, normalize(vec2(0.82, -0.57))); + float flowPosition = 0.55 * sin(glowTime); + float flowDelta = flowCoordinate - flowPosition; + float flowingBand = exp(-flowDelta * flowDelta * 5.5); + + float interiorLight = glowA * 0.55 + glowB * 0.28 + flowingBand * 0.42; + return color + glow * interiorLight * GLOW_INTENSITY; +} vec4 sampleLogo(vec2 uv) { @@ -25,6 +58,7 @@ void main() { float t = clamp(progress, 0.0, 1.0); float eased = 1.0 - pow(1.0 - t, 3.0); + vec3 backgroundColor = mix(background, sampleBackground(ViewportUV), eased); float opacity = smoothstep(0.0, 0.72, t); vec2 scale = logoScale * mix(INITIAL_SCALE, 1.0, eased); vec2 center = logoCenter - vec2(0.0, INITIAL_OFFSET_Y / resolution.y) * (1.0 - eased); @@ -34,7 +68,7 @@ void main() if (opacity == 0.0 || any(lessThan(uv, -extent)) || any(greaterThan(uv, 1.0 + extent))) { - Color = vec4(background, 1.0); + Color = vec4(backgroundColor, 1.0); return; } @@ -56,5 +90,5 @@ void main() } } - Color = vec4(background * (1.0 - logo.a * opacity) + logo.rgb * opacity, 1.0); + Color = vec4(backgroundColor * (1.0 - logo.a * opacity) + logo.rgb * opacity, 1.0); } From e4a8032b149e85f0538ed5e9f1984a00d72dbb4c Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:24:02 -0500 Subject: [PATCH 21/27] feat(sdl renderer): background glow toggle --- .../cleanroom/splash/pre/renderer/IconDrawer.java | 12 +++++++++++- .../splash/pre/renderer/PreSplashLayout.java | 1 + .../resources/assets/cleanroom/shaders/icon.frag | 3 +++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java index c4ca14c35..8ff54686d 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java @@ -67,7 +67,16 @@ final class IconDrawer implements AutoCloseable { shaders.submitToGL(vertexShader, fragmentShader); program = shaders.makeProgram(vertexShader, fragmentShader); - for (String uniform : List.of("resolution", "progress", "logoTexture", "logoCenter", "logoScale", "background", "glow", "time")) { + for (String uniform : List.of( + "resolution", + "progress", + "logoTexture", + "logoCenter", + "logoScale", + "background", + "glow", + "time", + "enableGlow")) { Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); } @@ -81,6 +90,7 @@ final class IconDrawer implements AutoCloseable { ((PreSplashLayout.GLOW_COLOR >> 16) & 255) / 255f, ((PreSplashLayout.GLOW_COLOR >> 8) & 255) / 255f, (PreSplashLayout.GLOW_COLOR & 255) / 255f); + program.uniform1b("enableGlow", PreSplashLayout.ENABLE_GLOW); icon = loadIcon(gameDirectory); } catch (Throwable failure) { diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java index 51547c3b7..69227fee4 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/PreSplashLayout.java @@ -17,6 +17,7 @@ public final class PreSplashLayout { public static final float SCREEN_PERCENTAGE = 0.35f; public static final int BACKGROUND = 0xFF0E1116; public static final int GLOW_COLOR = 0xFF455D74; + public static final boolean ENABLE_GLOW = false; private PreSplashLayout() { } diff --git a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag index b79509c31..ddfde822b 100644 --- a/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag +++ b/module/cleanroom/src/main/resources/assets/cleanroom/shaders/icon.frag @@ -11,6 +11,7 @@ uniform vec2 logoScale; uniform vec3 background; uniform vec3 glow; uniform float time; +uniform bool enableGlow; const float INITIAL_SCALE = 0.94; const float INITIAL_BLUR = 4.0; @@ -20,6 +21,8 @@ const float GLOW_INTENSITY = 0.06; vec3 sampleBackground(vec2 uv) { + if (!enableGlow) return background; + float glowTime = time * GLOW_SPEED; float aspectRatio = resolution.x / max(resolution.y, 1.0); float widthMix = 0.65 * smoothstep(1.3, 4.5, aspectRatio); From 2984179ffea0435a541936fee8b02da251569c8d Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:42:04 -0500 Subject: [PATCH 22/27] fix: MMC launcher native library already loaded in another classloader --- .../splash/pre/PreSplashClassLoader.java | 31 +++++++++++++++++-- .../splash/pre/PreSplashScreenContainer.java | 3 +- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java index 5c4670825..890e6295b 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashClassLoader.java @@ -10,18 +10,45 @@ package com.cleanroommc.cleanroom.splash.pre; +import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; /** * Motivation is to keep pre splash's untransformed classes out of the game's loader. * *

Note: Only applied to {@link PreSplashScreenContainer.SdlRenderer}.

*/ -final class PreSplashClassLoader extends ClassLoader { +final class PreSplashClassLoader extends URLClassLoader { PreSplashClassLoader(ClassLoader parent) { - super(parent); + super(nativeLibraryPaths(), parent); + } + + private static URL[] nativeLibraryPaths() { + List paths = new ArrayList<>(); + for (String property : List.of("org.lwjgl.librarypath", "java.library.path")) { + String value = System.getProperty(property); + if (value == null || value.isEmpty()) { + continue; + } + for (String directory : value.split(File.pathSeparator)) { + if (directory.isEmpty()) { + continue; + } + try { + paths.add(new File(directory).toURI().toURL()); + } catch (MalformedURLException e) { + throw new IllegalStateException("Invalid native library directory: " + directory, e); + } + } + } + return paths.toArray(URL[]::new); } private static boolean isIsolated(String name) { diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index d20566d72..118e201ee 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -249,8 +249,7 @@ private boolean runSdl() { ClassLoader previousContextLoader = renderThread.getContextClassLoader(); boolean[] unavailable = { false }; - try { - ClassLoader loader = new PreSplashClassLoader(PreSplashScreenContainer.class.getClassLoader()); + try (PreSplashClassLoader loader = new PreSplashClassLoader(PreSplashScreenContainer.class.getClassLoader())) { renderThread.setContextClassLoader(loader); Class renderer = Class.forName(PreSplashScreenContainer.class.getName() + "$SdlRenderer", true, loader); From 3cd5dfc806131ea0b717d363106c1e8d1888d0cb Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:30:20 -0500 Subject: [PATCH 23/27] fix: Windows specific fixes for a LWJGL 3.4.3 upstream issue --- .../splash/pre/PreSplashScreenContainer.java | 24 ++++++-- .../pre/renderer/WindowsAppRegistration.java | 55 +++++++++++++++++++ 2 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 118e201ee..cc0909604 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -15,6 +15,7 @@ import com.cleanroommc.cleanroom.splash.pre.renderer.PreSplashLogger; import com.cleanroommc.cleanroom.splash.pre.renderer.SdlSplashRenderer; import com.cleanroommc.cleanroom.splash.pre.renderer.SwingSplashRenderer; +import com.cleanroommc.cleanroom.splash.pre.renderer.WindowsAppRegistration; import com.google.common.base.Preconditions; import com.google.gson.JsonElement; @@ -42,6 +43,7 @@ import org.lwjgl.sdl.SDL_Rect; import org.lwjgl.system.Configuration; import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.Platform; import org.lwjgl.system.ThreadLocalUtil; import javax.swing.JDialog; @@ -365,6 +367,7 @@ static final class Window implements AutoCloseable { private boolean videoInitialized; private boolean initialized; private boolean glInitialized; + private @Nullable WindowsAppRegistration windowsAppRegistration; private @Nullable SDL_EventFilter watch; static Window open(Runnable stop) { @@ -393,6 +396,10 @@ private void initialize(Runnable stop) { Configuration.SHARED_LIBRARY_EXTRACT_DIRECTORY.set("cleanroom-pre-splash"); Configuration.SHARED_LIBRARY_EXTRACT_FORCE.set(true); + if (Platform.get() == Platform.WINDOWS) { + windowsAppRegistration = WindowsAppRegistration.register(); + } + // prefer native Wayland over XWayland if (System.getenv("WAYLAND_DISPLAY") != null && System.getenv("SDL_VIDEODRIVER") == null) { if (!SDLHints.SDL_SetHintWithPriority(SDLHints.SDL_HINT_VIDEO_DRIVER, "wayland,x11", SDLHints.SDL_HINT_DEFAULT)) { @@ -555,11 +562,18 @@ public void close() { SDLInit.SDL_QuitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS); } } finally { - if (!initialized) { - if (originalLibraryPath == null) { - System.clearProperty("org.lwjgl.librarypath"); - } else { - System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + try { + if (windowsAppRegistration != null) { + windowsAppRegistration.close(); + windowsAppRegistration = null; + } + } finally { + if (!initialized) { + if (originalLibraryPath == null) { + System.clearProperty("org.lwjgl.librarypath"); + } else { + System.setProperty("org.lwjgl.librarypath", originalLibraryPath); + } } } } diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java new file mode 100644 index 000000000..dece72966 --- /dev/null +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/WindowsAppRegistration.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2026 CleanroomMC contributors + * + * This file is licensed under the CleanroomMC License Version 1.0. + * See the applicable LICENSE file in this directory or a parent directory + * for the full licence terms. + * + * This is visible-source software and is not open-source software. + */ + +package com.cleanroommc.cleanroom.splash.pre.renderer; + +import com.google.common.base.Preconditions; +import org.lwjgl.sdl.SDL; +import org.lwjgl.sdl.SDLError; +import org.lwjgl.system.APIUtil; +import org.lwjgl.system.JNI; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; +import org.lwjgl.system.windows.User32; + +import java.util.UUID; + +public final class WindowsAppRegistration implements AutoCloseable { + + private long unregister; + + private WindowsAppRegistration(long unregister) { + this.unregister = unregister; + } + + public static WindowsAppRegistration register() { + // LWJGL 3.4.3's SDLBinding.kt adds SDL_ automatically, generating nonexistent SDL_SDL_* exports + + long register = APIUtil.apiGetFunctionAddress(SDL.getLibrary(), "SDL_RegisterApp"); + long unregister = APIUtil.apiGetFunctionAddress(SDL.getLibrary(), "SDL_UnregisterApp"); + try (MemoryStack stack = MemoryStack.stackPush()) { + // pre splash and game otherwise register SDL_app for the same process HINSTANCE + long name = MemoryUtil.memAddress(stack.UTF8("Cleanroom_PreSplash_" + UUID.randomUUID())); + + Preconditions.checkState(JNI.invokePPZ(name, User32.CS_BYTEALIGNCLIENT | User32.CS_OWNDC, 0L, register), + "SDL_RegisterApp: %s", SDLError.SDL_GetError()); + } + + return new WindowsAppRegistration(unregister); + } + + @Override + public void close() { + if (unregister != 0L) { + JNI.invokeV(unregister); + unregister = 0L; + } + } +} From 3aa7e10ed5648d59f6f68078d2b5c4f813731421 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:27:18 -0500 Subject: [PATCH 24/27] chore: update kirino --- module/kirino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/kirino b/module/kirino index 37b9abbf3..0fc2ea139 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 37b9abbf3d589ebbe2e342a4d6bad3c9f8baa136 +Subproject commit 0fc2ea139be04c5d546c3cf8415654b27cacb698 From f36ea76438a6225fa06a8b82ab0e5a04645f0179 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:34:30 -0500 Subject: [PATCH 25/27] chore: switch to compat profile --- .../cleanroom/splash/pre/PreSplashScreenContainer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index cc0909604..72da4fe2c 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -416,7 +416,7 @@ private void initialize(Runnable stop) { SDLVideo.SDL_GL_ResetAttributes(); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MAJOR_VERSION, 4), "GL major version"); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MINOR_VERSION, 6), "GL minor version"); - checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_PROFILE_MASK, SDLVideo.SDL_GL_CONTEXT_PROFILE_CORE), "GL profile"); + checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_PROFILE_MASK, SDLVideo.SDL_GL_CONTEXT_PROFILE_COMPATIBILITY), "GL profile"); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_DOUBLEBUFFER, 1), "GL double buffering"); int display = SDLVideo.SDL_GetPrimaryDisplay(); From c3082cfc2819e7f8e8a2e00f1db6f3fd1fce19a2 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:36:14 -0500 Subject: [PATCH 26/27] chore: migrate to latest kirino --- .../cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java | 2 +- .../cleanroom/splash/pre/renderer/LogoAnimationDrawer.java | 2 +- module/kirino | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java index 8ff54686d..654a6efee 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/IconDrawer.java @@ -65,7 +65,7 @@ final class IconDrawer implements AutoCloseable { vertexShader = shaders.makeShader(VERTEX_SHADER); fragmentShader = shaders.makeShader(FRAGMENT_SHADER); shaders.submitToGL(vertexShader, fragmentShader); - program = shaders.makeProgram(vertexShader, fragmentShader); + program = shaders.makeProgram(true, vertexShader, fragmentShader); for (String uniform : List.of( "resolution", diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java index 8b4568219..ac080cd60 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/renderer/LogoAnimationDrawer.java @@ -60,7 +60,7 @@ public LogoAnimationDrawer(ImmediateShaderAccess shaders, VAO dummyVao) throws I vertexShader = shaders.makeShader(VERTEX_SHADER); fragmentShader = shaders.makeShader(FRAGMENT_SHADER); shaders.submitToGL(vertexShader, fragmentShader); - program = shaders.makeProgram(vertexShader, fragmentShader); + program = shaders.makeProgram(true, vertexShader, fragmentShader); for (String uniform : List.of("resolution", "progress", "logoTexture", "background")) { Preconditions.checkState(program.uniformLocation(uniform) >= 0, "Missing uniform: %s", uniform); diff --git a/module/kirino b/module/kirino index 0fc2ea139..73939d44b 160000 --- a/module/kirino +++ b/module/kirino @@ -1 +1 @@ -Subproject commit 0fc2ea139be04c5d546c3cf8415654b27cacb698 +Subproject commit 73939d44b5228bca30c0c2a2e8638a6f92390f70 From da6051be35461eb5d2c734708620da5cdbf0f438 Mon Sep 17 00:00:00 2001 From: tttsaurus <72607439+tttsaurus@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:08:08 -0500 Subject: [PATCH 27/27] refactor: prefer XWayland + apply niri integration on both renderer + explicit GL init --- .../splash/pre/PreSplashScreenContainer.java | 236 ++++++++++-------- 1 file changed, 130 insertions(+), 106 deletions(-) diff --git a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java index 72da4fe2c..e689fc745 100644 --- a/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java +++ b/module/cleanroom/src/main/java/com/cleanroommc/cleanroom/splash/pre/PreSplashScreenContainer.java @@ -33,9 +33,9 @@ import org.jspecify.annotations.Nullable; import org.lwjgl.opengl.GL; +import org.lwjgl.opengl.GL11; import org.lwjgl.sdl.SDLError; import org.lwjgl.sdl.SDLEvents; -import org.lwjgl.sdl.SDLHints; import org.lwjgl.sdl.SDLInit; import org.lwjgl.sdl.SDLVideo; import org.lwjgl.sdl.SDL_Event; @@ -296,6 +296,108 @@ private void runSwing() throws IOException { // // + @ApiStatus.Internal + public static String createWindowTitle() { + String title = "Cleanroom Pre Splash"; + return System.getenv("NIRI_SOCKET") == null ? title : title + " [" + UUID.randomUUID() + "]"; + } + + private static final class NiriWindowPlacement { + + private NiriWindowPlacement() { + } + + private static @Nullable JsonElement niriMessage(String... arguments) { + List command = new ArrayList<>(List.of("niri", "msg", "--json")); + command.addAll(List.of(arguments)); + + Process message = null; + try { + message = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + if (message.waitFor(1, TimeUnit.SECONDS) && message.exitValue() == 0) { + try (InputStream input = message.getInputStream()) { + return JsonParser.parseString(new String(input.readAllBytes(), StandardCharsets.UTF_8)); + } + } + } catch (IOException | RuntimeException failure) { + LOGGER.debug("Could not communicate with niri for pre splash positioning.", failure); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } finally { + if (message != null && message.isAlive()) { + message.destroyForcibly(); + } + } + return null; + } + + public static boolean centerWindowOnNiri(String windowTitle) { + if (System.getenv("NIRI_SOCKET") == null) { + return true; + } + + try { + JsonElement windows = niriMessage("windows"); + if (windows == null) { + return false; + } + + JsonObject splash = null; + for (JsonElement element : windows.getAsJsonArray()) { + JsonObject window = element.getAsJsonObject(); + JsonElement title = window.get("title"); + if (title != null + && title.isJsonPrimitive() + && windowTitle.equals(title.getAsString()) + && window.get("is_floating").getAsBoolean()) { + if (splash != null) { + return false; + } + + splash = window; + } + } + + if (splash == null) { + return false; + } + + JsonElement workspaces = niriMessage("workspaces"); + JsonElement outputs = niriMessage("outputs"); + if (workspaces == null || outputs == null) { + return false; + } + + for (JsonElement element : workspaces.getAsJsonArray()) { + JsonObject workspace = element.getAsJsonObject(); + if (!workspace.get("id").equals(splash.get("workspace_id")) || workspace.get("output").isJsonNull()) { + continue; + } + + JsonObject output = outputs.getAsJsonObject().getAsJsonObject(workspace.get("output").getAsString()); + JsonObject logical = output.getAsJsonObject("logical"); + JsonObject layout = splash.getAsJsonObject("layout"); + var size = layout.getAsJsonArray("tile_size"); + var position = layout.getAsJsonArray("tile_pos_in_workspace_view"); + double x = (logical.get("width").getAsDouble() - size.get(0).getAsDouble()) / 2; + double y = (logical.get("height").getAsDouble() - size.get(1).getAsDouble()) / 2; + + niriMessage( + "action", + "move-floating-window", + "--id", splash.get("id").getAsString(), + "--x=" + String.format(Locale.ROOT, "%+.3f", x - position.get(0).getAsDouble()), + "--y=" + String.format(Locale.ROOT, "%+.3f", y - position.get(1).getAsDouble())); + + return true; + } + } catch (RuntimeException failure) { + LOGGER.debug("Could not center pre splash through niri.", failure); + } + return false; + } + } + /** * @see PreSplashScreenContainer#runSdl() */ @@ -362,6 +464,7 @@ static final class Window implements AutoCloseable { private static final int TARGET_FRAME_RATE = 60; private final @Nullable String originalLibraryPath = System.getProperty("org.lwjgl.librarypath"); + private final String windowTitle = createWindowTitle(); private long window; private long context; private boolean videoInitialized; @@ -395,24 +498,21 @@ private void initialize(Runnable stop) { Configuration.SHARED_LIBRARY_EXTRACT_PATH.set(null); Configuration.SHARED_LIBRARY_EXTRACT_DIRECTORY.set("cleanroom-pre-splash"); Configuration.SHARED_LIBRARY_EXTRACT_FORCE.set(true); + Configuration.OPENGL_EXPLICIT_INIT.set(true); if (Platform.get() == Platform.WINDOWS) { windowsAppRegistration = WindowsAppRegistration.register(); } - // prefer native Wayland over XWayland - if (System.getenv("WAYLAND_DISPLAY") != null && System.getenv("SDL_VIDEODRIVER") == null) { - if (!SDLHints.SDL_SetHintWithPriority(SDLHints.SDL_HINT_VIDEO_DRIVER, "wayland,x11", SDLHints.SDL_HINT_DEFAULT)) { - LOGGER.debug("Could not apply pre splash video driver preference; keeping the configured driver."); - } - } - checkSDL(SDLInit.SDL_InitSubSystem(SDLInit.SDL_INIT_VIDEO | SDLInit.SDL_INIT_EVENTS), "SDL_InitSubSystem"); videoInitialized = true; // on non-Apple platforms, the video initializing thread is SDL's main thread Preconditions.checkState(SDLInit.SDL_IsMainThread(), "Pre splash must run on its SDL video thread."); + String videoDriver = SDLVideo.SDL_GetCurrentVideoDriver(); + Preconditions.checkState(videoDriver != null, "SDL video driver is not initialized."); + SDLVideo.SDL_GL_ResetAttributes(); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MAJOR_VERSION, 4), "GL major version"); checkSDL(SDLVideo.SDL_GL_SetAttribute(SDLVideo.SDL_GL_CONTEXT_MINOR_VERSION, 6), "GL minor version"); @@ -430,7 +530,7 @@ private void initialize(Runnable stop) { int windowWidth = Math.max(1, Math.round(PreSplashLayout.WIDTH * scale)); int windowHeight = Math.max(1, Math.round(PreSplashLayout.HEIGHT * scale)); - window = SDLVideo.SDL_CreateWindow("Cleanroom Pre Splash", windowWidth, windowHeight, + window = SDLVideo.SDL_CreateWindow(windowTitle, windowWidth, windowHeight, SDLVideo.SDL_WINDOW_OPENGL | SDLVideo.SDL_WINDOW_HIGH_PIXEL_DENSITY | SDLVideo.SDL_WINDOW_HIDDEN @@ -446,8 +546,6 @@ private void initialize(Runnable stop) { } // Wayland does not support explicit positioning - String videoDriver = SDLVideo.SDL_GetCurrentVideoDriver(); - Preconditions.checkState(videoDriver != null, "SDL video driver is not initialized."); if (!"wayland".equals(videoDriver)) { int centered = SDLVideo.SDL_WINDOWPOS_CENTERED_DISPLAY(display); if (!SDLVideo.SDL_SetWindowPosition(window, centered, centered)) { @@ -459,15 +557,20 @@ private void initialize(Runnable stop) { Preconditions.checkState(context != 0, "SDL_GL_CreateContext: %s", SDLError.SDL_GetError()); checkSDL(SDLVideo.SDL_GL_MakeCurrent(window, context), "SDL_GL_MakeCurrent"); - // triggers class initializing - GL.getFunctionProvider(); + GL.create(SDLVideo::SDL_GL_GetProcAddress); glInitialized = true; boolean gl46 = GL.createCapabilities().OpenGL46; // release LWJGL's global table so the game's LWJGL can initialize ThreadLocalUtil.setFunctionMissingAddresses(0); + Preconditions.checkState(gl46, "Pre splash requires OpenGL 4.6."); + LOGGER.info("Pre splash GL context created.\nVideo Driver: {}\nGL Vendor: {}\nRenderer: {}\nVersion: {}", + videoDriver, + GL11.glGetString(GL11.GL_VENDOR), + GL11.glGetString(GL11.GL_RENDERER), + GL11.glGetString(GL11.GL_VERSION)); if (!SDLVideo.SDL_GL_SetSwapInterval(0)) { LOGGER.debug("Could not disable pre splash VSync: {}", SDLError.SDL_GetError()); @@ -500,6 +603,10 @@ private void initialize(Runnable stop) { void runLoop(BooleanSupplier running, BiConsumer draw) { checkSDL(SDLVideo.SDL_ShowWindow(window), "SDL_ShowWindow"); + + boolean centerPending = System.getenv("NIRI_SOCKET") != null; + long centerDeadline = 0; + try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer width = stack.mallocInt(1); IntBuffer height = stack.mallocInt(1); @@ -514,6 +621,14 @@ void runLoop(BooleanSupplier running, BiConsumer draw) { draw.accept(width.get(0), height.get(0)); checkSDL(SDLVideo.SDL_GL_SwapWindow(window), "SDL_GL_SwapWindow"); + + if (centerPending) { + if (centerDeadline == 0) { + centerDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(1); + } + centerPending = System.nanoTime() < centerDeadline && !NiriWindowPlacement.centerWindowOnNiri(windowTitle); + } + long remaining = TimeUnit.SECONDS.toNanos(1) / TARGET_FRAME_RATE - (System.nanoTime() - frameStart); if (remaining > 0) { LockSupport.parkNanos(remaining); @@ -748,7 +863,7 @@ private static void writeHelperClass(JarOutputStream output, Class type, Set< private void run() throws IOException { String renderer = SwingRenderer.class.getName() + "$Helper"; - String windowTitle = "Cleanroom Pre Splash [" + UUID.randomUUID() + "]"; + String windowTitle = createWindowTitle(); Path helperJar = Files.createTempFile("cleanroom-pre-splash-", ".jar"); Process helper = null; @@ -797,7 +912,7 @@ private void run() throws IOException { int reply; while (running.getAsBoolean() && (reply = reader.poll()) != 0) { if (reply == Protocol.READY && !ready) { - centerWindowOnNiri(windowTitle); + NiriWindowPlacement.centerWindowOnNiri(windowTitle); ready = true; startupReady.run(); } @@ -856,97 +971,6 @@ private static void stopHelper(Process helper) { } } } - - // - private static @Nullable JsonElement niriMessage(String... arguments) { - List command = new ArrayList<>(List.of("niri", "msg", "--json")); - command.addAll(List.of(arguments)); - - Process message = null; - try { - message = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); - if (message.waitFor(1, TimeUnit.SECONDS) && message.exitValue() == 0) { - try (InputStream input = message.getInputStream()) { - return JsonParser.parseString(new String(input.readAllBytes(), StandardCharsets.UTF_8)); - } - } - } catch (IOException | RuntimeException failure) { - LOGGER.debug("Could not communicate with niri for pre splash positioning.", failure); - } catch (InterruptedException ignored) { - Thread.currentThread().interrupt(); - } finally { - if (message != null && message.isAlive()) { - message.destroyForcibly(); - } - } - return null; - } - - private static void centerWindowOnNiri(String windowTitle) { - if (System.getenv("NIRI_SOCKET") == null) { - return; - } - - try { - JsonElement windows = niriMessage("windows"); - if (windows == null) { - return; - } - - JsonObject splash = null; - for (JsonElement element : windows.getAsJsonArray()) { - JsonObject window = element.getAsJsonObject(); - JsonElement title = window.get("title"); - if (title != null - && title.isJsonPrimitive() - && windowTitle.equals(title.getAsString()) - && window.get("is_floating").getAsBoolean()) { - if (splash != null) { - return; - } - - splash = window; - } - } - - if (splash == null) { - return; - } - - JsonElement workspaces = niriMessage("workspaces"); - JsonElement outputs = niriMessage("outputs"); - if (workspaces == null || outputs == null) { - return; - } - - for (JsonElement element : workspaces.getAsJsonArray()) { - JsonObject workspace = element.getAsJsonObject(); - if (!workspace.get("id").equals(splash.get("workspace_id")) || workspace.get("output").isJsonNull()) { - continue; - } - - JsonObject output = outputs.getAsJsonObject().getAsJsonObject(workspace.get("output").getAsString()); - JsonObject logical = output.getAsJsonObject("logical"); - JsonObject layout = splash.getAsJsonObject("layout"); - var size = layout.getAsJsonArray("tile_size"); - var position = layout.getAsJsonArray("tile_pos_in_workspace_view"); - double x = (logical.get("width").getAsDouble() - size.get(0).getAsDouble()) / 2; - double y = (logical.get("height").getAsDouble() - size.get(1).getAsDouble()) / 2; - - niriMessage( - "action", - "move-floating-window", - "--id", splash.get("id").getAsString(), - "--x=" + String.format(Locale.ROOT, "%+.3f", x - position.get(0).getAsDouble()), - "--y=" + String.format(Locale.ROOT, "%+.3f", y - position.get(1).getAsDouble())); - - return; - } - } catch (RuntimeException failure) { - LOGGER.debug("Could not center Swing pre splash through niri.", failure); - } - } - // } /**