diff --git a/build.gradle b/build.gradle index 2ad7c22..d63b938 100644 --- a/build.gradle +++ b/build.gradle @@ -1,27 +1,33 @@ buildscript { repositories { - maven { url = 'https://repo.spongepowered.org/maven' } + maven { url = 'https://repo.spongepowered.org/repository/maven-public/' } + mavenCentral() } dependencies { - classpath 'org.spongepowered:mixingradle:0.7.+' + classpath 'org.spongepowered:mixingradle:0.7-SNAPSHOT' } } plugins { - id 'net.minecraftforge.gradle' version '5.1.+' + id 'eclipse' + id 'idea' + id 'net.minecraftforge.gradle' version '[6.0.16,6.2)' } apply plugin: 'org.spongepowered.mixin' -group = 'ccr4ft3r' -version = "${mc_version}-${mod_version}" +group = mod_group_id +version = mod_version java { - archivesBaseName = 'lightspeed' toolchain.languageVersion = JavaLanguageVersion.of(17) } +base { + archivesName = mod_id +} + minecraft { // The mappings can be changed at any time and must be in the following format. // Channel: Version: @@ -36,87 +42,51 @@ minecraft { // // Use non-default mappings at your own risk. They may not always work. // Simply re-run your setup task after changing the mappings to update your workspace. - mappings channel: 'official', version: mc_version + mappings channel: mapping_channel, version: mapping_version + + copyIdeResources = true // Default run configurations. // These can be tweaked, removed, or duplicated as needed. runs { - client { + configureEach { workingDirectory project.file('run') - // Recommended logging data for a userdev environment - // The markers can be added/remove as needed separated by commas. - // "SCAN": For mods scan. - // "REGISTRIES": For firing of registry events. - // "REGISTRYDUMP": For getting the contents of all registries. property 'forge.logging.markers', 'REGISTRIES' - - - // Recommended logging level for the console - // You can set various levels here. - // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels property 'forge.logging.console.level', 'debug' - // Comma-separated list of namespaces to load gametests from. Empty = all namespaces. - property 'forge.enabledGameTestNamespaces', 'lightspeed' - mods { - lightspeed { + "${mod_id}" { source sourceSets.main } } } + client { + property 'forge.enabledGameTestNamespaces', mod_id + property 'mixin.env.remapRefMap', 'true' + property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" + } + server { - workingDirectory project.file('run') - - property 'forge.logging.markers', 'REGISTRIES' - - property 'forge.logging.console.level', 'debug' - - property 'forge.enabledGameTestNamespaces', 'lightspeed' - - mods { - lightspeed { - source sourceSets.main - } - } + property 'forge.enabledGameTestNamespaces', mod_id + property 'mixin.env.remapRefMap', 'true' + property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg" + args '--nogui' } // This run config launches GameTestServer and runs all registered gametests, then exits. // By default, the server will crash when no gametests are provided. // The gametest system is also enabled by default for other run configs under the /test command. gameTestServer { - workingDirectory project.file('run') - - property 'forge.logging.markers', 'REGISTRIES' - - property 'forge.logging.console.level', 'debug' - - property 'forge.enabledGameTestNamespaces', 'lightspeed' - - mods { - lightspeed { - source sourceSets.main - } - } + property 'forge.enabledGameTestNamespaces', mod_id } data { - workingDirectory project.file('run') - - property 'forge.logging.markers', 'REGISTRIES' - - property 'forge.logging.console.level', 'debug' + workingDirectory project.file('run-data') // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - args '--mod', 'lightspeed', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') - - mods { - lightspeed { - source sourceSets.main - } - } + args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/') } } } @@ -144,16 +114,16 @@ dependencies { // Specify the version of Minecraft to use. If this is any group other than 'net.minecraft' it is assumed // that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied. // The userdev artifact is a special name and will get all sorts of transformations applied to it. - minecraft "net.minecraftforge:forge:${mc_version}-${forge_version}" + minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" annotationProcessor 'org.spongepowered:mixin:0.8.5:processor' // Real mod deobf dependency examples - these get remapped to your current mappings - // compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency - // runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency - // implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency + // compileOnly fg.deobf("mezz.jei:jei-${minecraft_version}:${jei_version}:api") // Adds JEI API as a compile dependency + // runtimeOnly fg.deobf("mezz.jei:jei-${minecraft_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency + // implementation fg.deobf("com.tterrag.registrate:Registrate:MC${minecraft_version}-${registrate_version}") // Adds registrate as a dependency // Examples using mod jars from ./libs - // implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}") + // implementation fg.deobf("blank:coolmod-${minecraft_version}:${coolmod_version}") // For more info... // http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html @@ -161,27 +131,49 @@ dependencies { } mixin { - add sourceSets.main, "lightspeed.refmap.json" - config "lightspeed.mixins.json" + add sourceSets.main, "${mod_id}.refmap.json" + config "${mod_id}.mixins.json" } -// Example for how to get properties into the manifest for reading at runtime. -jar { - manifest { - attributes([ - "Specification-Title" : "lightspeed", - "Specification-Vendor" : "CCr4ft3r", - "Specification-Version" : "1", // We are version 1 of ourselves - "Implementation-Title" : project.name, - "Implementation-Version" : project.jar.archiveVersion, - "Implementation-Vendor" : "CCr4ft3r", - "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") - ]) +tasks.named('processResources', ProcessResources).configure { + var replaceProperties = [ + minecraft_version : minecraft_version, + minecraft_version_range: minecraft_version_range, + forge_version : forge_version, + forge_version_range : forge_version_range, + loader_version_range: loader_version_range, + mod_id : mod_id, + mod_name : mod_name, + mod_license : mod_license, + mod_version : mod_version, + mod_authors : mod_authors, + mod_description : mod_description + ] + + inputs.properties replaceProperties + + filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) { + expand replaceProperties + [project: project] } } -jar.finalizedBy('reobfJar') +// Example for how to get properties into the manifest for reading at runtime. +tasks.named('jar', Jar).configure { + manifest { + attributes([ + "Specification-Title" : mod_id, + "Specification-Vendor" : mod_authors, + "Specification-Version" : "1", // We are version 1 of ourselves + "Implementation-Title" : project.name, + "Implementation-Version" : project.jar.archiveVersion, + "Implementation-Vendor" : mod_authors, + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } + + finalizedBy 'reobfJar' +} tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index c5810ba..794819c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,17 @@ org.gradle.jvmargs=-Xmx3G org.gradle.daemon=false -mc_version=1.20.1 -forge_version=47.4.10 -mod_version=1.1.2hotfix \ No newline at end of file +minecraft_version=1.20.1 +minecraft_version_range=[1.20.1,1.21) +forge_version=47.4.20 +forge_version_range=[47,) +loader_version_range=[47,) +mapping_channel=official +mapping_version=1.20.1 +mod_id=lightspeed +mod_name=Lightspeed +mod_license=All Rights Reserved +mod_version=1.20.1-1.2.0 +mod_group_id=com.ccr4ft3r +mod_authors=CCr4ft3r,kltyton +mod_description=Buys you time by loading heavy modpacks significantly faster. \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index aa991fc..88f6a5f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ +#Wed Jul 01 19:20:59 CST 2026 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.5-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/settings.gradle b/settings.gradle index 9f453f4..30c5b7f 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,8 +1,16 @@ pluginManagement { repositories { gradlePluginPortal() - maven { url = 'https://maven.minecraftforge.net/' } + maven { + name = 'MinecraftForge' + url = 'https://maven.minecraftforge.net/' + } + mavenCentral() } } +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' +} + rootProject.name = 'lightspeed' diff --git a/src/main/java/com/ccr4ft3r/lightspeed/Main.java b/src/main/java/com/ccr4ft3r/lightspeed/Main.java index 816efc5..43a0392 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/Main.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/Main.java @@ -1,20 +1,52 @@ package com.ccr4ft3r.lightspeed; import com.ccr4ft3r.lightspeed.cache.GlobalCache; -import com.ccr4ft3r.lightspeed.util.CompatUtil; +import com.ccr4ft3r.lightspeed.config.LightspeedConfig; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.config.ModConfig; +import net.minecraftforge.fml.event.config.ModConfigEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; + +import java.util.List; @Mod(ModConstants.MOD_ID) public class Main { public Main() { + IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); + modEventBus.addListener(this::onConfigEvent); + ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, LightspeedConfig.SPEC); updateCacheFlags(); } + private void onConfigEvent(ModConfigEvent event) { + if (event.getConfig().getSpec() == LightspeedConfig.SPEC) { + updateCacheFlags(); + } + } + private void updateCacheFlags() { + try { + GlobalCache.shouldAsyncPreloadPacks = LightspeedConfig.COMMON.asyncPreloadPacks.get(); + GlobalCache.shouldParallelizeResourcePackLookup = LightspeedConfig.COMMON.parallelResourceLookup.get(); + GlobalCache.shouldIsolateModdedResourceReloadFailures = LightspeedConfig.COMMON.isolateModdedResourceReloadFailures.get(); + GlobalCache.isolatedResourceReloadListenerPatterns = LightspeedConfig.COMMON.isolatedResourceReloadListenerPatterns.get() + .stream() + .map(String::valueOf) + .toList(); + } catch (IllegalStateException ignored) { + // Forge has not attached the TOML yet; keep the default-on startup flags. + GlobalCache.isolatedResourceReloadListenerPatterns = List.of("*"); + } + + if (ModList.get().isLoaded(ModConstants.SOPHISTICATED_STORAGE_ID) && ModList.get().isLoaded(ModConstants.JSON_THINGS_ID)) { + GlobalCache.shouldCacheWalkedPaths = false; + } if (ModList.get().isLoaded(ModConstants.MULTIBLOCKED_ID)) { GlobalCache.shouldCacheMaterials = false; } } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java b/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java index e6aa477..394f619 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java @@ -4,43 +4,182 @@ import com.ccr4ft3r.lightspeed.interfaces.ICache; import com.ccr4ft3r.lightspeed.util.CacheUtil; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import com.mojang.logging.LogUtils; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.resources.IoSupplier; +import org.slf4j.Logger; import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import static com.ccr4ft3r.lightspeed.util.CacheUtil.*; public class GlobalCache { - public static Boolean isEnabled = true; - public static Boolean shouldCacheEmptyNamespaces = true; - public static Boolean shouldCacheMaterials = true; + private static final Logger LOGGER = LogUtils.getLogger(); + private static final AtomicInteger THREAD_ID = new AtomicInteger(); + private static final AtomicBoolean PERSISTED_CACHE_LOAD_STARTED = new AtomicBoolean(false); + private static volatile CompletableFuture persistedCacheLoad = CompletableFuture.completedFuture(null); + + public static volatile boolean isEnabled = true; + public static volatile boolean shouldCacheWalkedPaths = true; + public static volatile boolean shouldCacheEmptyNamespaces = true; + public static volatile boolean shouldCacheMaterials = true; + public static volatile boolean shouldAsyncPreloadPacks = true; + public static volatile boolean shouldParallelizeResourcePackLookup = true; + public static volatile boolean shouldIsolateModdedResourceReloadFailures = true; + public static volatile List isolatedResourceReloadListenerPatterns = List.of("*"); public static final Map> SPLITTED_STRINGS_BY_SEQUENCE = Maps.newConcurrentMap(); public static final Map CANONICAL_PATH_PER_FILE = Maps.newConcurrentMap(); private static final Set CACHES = Sets.newConcurrentHashSet(); public static final Map> PERSISTED_EXISTENCES_BY_MOD = Maps.newConcurrentMap(); public static final Map>> PERSISTED_NAMESPACES_BY_MOD = Maps.newConcurrentMap(); - public static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); + public static final int WORKER_COUNT = getWorkerCount(); + public static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(WORKER_COUNT, runnable -> { + Thread thread = new Thread(runnable, "Lightspeed-" + THREAD_ID.incrementAndGet()); + thread.setDaemon(true); + return thread; + }); public static void add(ICache cache) { CACHES.add(cache); } - @SuppressWarnings("ResultOfMethodCallIgnored") + public static CompletableFuture loadPersistedCachesAsync() { + if (PERSISTED_CACHE_LOAD_STARTED.compareAndSet(false, true)) { + persistedCacheLoad = CompletableFuture.allOf( + loadPersistedCaches(HAS_RESOURCE_CACHE_DIR, PERSISTED_EXISTENCES_BY_MOD), + loadPersistedCaches(NAMESPACE_CACHE_DIR, PERSISTED_NAMESPACES_BY_MOD) + ).exceptionally(throwable -> { + LOGGER.error("Lightspeed failed to load persisted caches", throwable); + return null; + }); + } + return persistedCacheLoad; + } + + public static void awaitPersistedCachesLoaded() { + try { + loadPersistedCachesAsync().get(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOGGER.warn("Lightspeed cache loading interrupted; continuing without waiting for all cache files", e); + } catch (ExecutionException e) { + LOGGER.warn("Lightspeed cache loading failed; continuing with in-memory caches", e); + } catch (TimeoutException e) { + LOGGER.warn("Lightspeed cache loading timed out; continuing while remaining files load in the background", e); + } + } + + public static CompletableFuture executeLogged(String taskName, Runnable task) { + return CompletableFuture.runAsync(() -> { + try { + task.run(); + } catch (Exception e) { + LOGGER.error("Lightspeed task failed: {}", taskName, e); + } + }, EXECUTOR); + } + + public static IoSupplier findFirstResource(List packs, PackType type, ResourceLocation location) { + if (packs.isEmpty()) { + return null; + } + if (packs.size() == 1) { + return packs.get(0).getResource(type, location); + } + + List>> futures = new ArrayList<>(packs.size()); + try { + for (PackResources pack : packs) { + futures.add(CompletableFuture.supplyAsync(() -> pack.getResource(type, location), EXECUTOR)); + } + } catch (RuntimeException e) { + LOGGER.warn("Lightspeed parallel resource lookup rejected; falling back to sequential lookup", e); + return findFirstResourceSequential(packs, type, location); + } + + for (CompletableFuture> future : futures) { + try { + IoSupplier supplier = future.get(); + if (supplier != null) { + return supplier; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return findFirstResourceSequential(packs, type, location); + } catch (ExecutionException e) { + LOGGER.warn("Lightspeed parallel resource lookup failed for {}", location, e); + } + } + return null; + } + public static void disablePersistAndClear() { isEnabled = false; - CacheUtil.getCacheFiles(HAS_RESOURCE_CACHE_DIR).forEach(File::delete); - CacheUtil.getCacheFiles(NAMESPACE_CACHE_DIR).forEach(File::delete); - CACHES.forEach(ICache::lightspeed$persistAndClearCache); + awaitPersistedCachesLoaded(); + + List> tasks = new ArrayList<>(); + CacheUtil.getCacheFiles(HAS_RESOURCE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file))); + CacheUtil.getCacheFiles(NAMESPACE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file))); + CACHES.forEach(cache -> tasks.add(executeLogged(cache.getClass().getName(), cache::lightspeed$persistAndClearCache))); + + CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join(); SPLITTED_STRINGS_BY_SEQUENCE.clear(); CANONICAL_PATH_PER_FILE.clear(); CACHES.clear(); PERSISTED_EXISTENCES_BY_MOD.clear(); PERSISTED_NAMESPACES_BY_MOD.clear(); } -} \ No newline at end of file + + private static int getWorkerCount() { + int configured = Integer.getInteger("lightspeed.workers", 0); + if (configured > 0) { + return configured; + } + return Math.max(2, Math.min(Runtime.getRuntime().availableProcessors(), 32)); + } + + private static CompletableFuture loadPersistedCaches(File dir, Map> targetMap) { + dir.mkdirs(); + CompletableFuture[] futures = CacheUtil.getCacheFiles(dir) + .map(file -> CompletableFuture.runAsync(() -> { + String id = org.apache.commons.io.FilenameUtils.getBaseName(file.getName()); + targetMap.put(id, CacheUtil.load(file)); + }, EXECUTOR)) + .toArray(CompletableFuture[]::new); + return CompletableFuture.allOf(futures); + } + + private static CompletableFuture deleteAsync(File file) { + return executeLogged("delete cache file " + file, () -> { + if (!file.delete() && file.exists()) { + LOGGER.warn("Lightspeed could not delete old cache file {}", file); + } + }); + } + + private static IoSupplier findFirstResourceSequential(List packs, PackType type, ResourceLocation location) { + for (PackResources pack : packs) { + IoSupplier supplier = pack.getResource(type, location); + if (supplier != null) { + return supplier; + } + } + return null; + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/compat/FusionPackCompat.java b/src/main/java/com/ccr4ft3r/lightspeed/compat/FusionPackCompat.java new file mode 100644 index 0000000..bb15215 --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/compat/FusionPackCompat.java @@ -0,0 +1,73 @@ +package com.ccr4ft3r.lightspeed.compat; + +import net.minecraftforge.fml.ModList; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public final class FusionPackCompat { + private static final String[] OVERRIDE_FIELD_SUFFIXES = { + "overridesFolderName", + "overridesFolderRoot", + "overridesFolder" + }; + private static final ConcurrentMap, List> OVERRIDE_FIELDS_BY_CLASS = new ConcurrentHashMap<>(); + + private FusionPackCompat() { + } + + public static boolean hasOverrides(Object packResources) { + if (packResources == null || !isFusionLoaded()) { + return false; + } + + for (Field field : OVERRIDE_FIELDS_BY_CLASS.computeIfAbsent(packResources.getClass(), FusionPackCompat::findOverrideFields)) { + try { + if (field.get(packResources) != null) { + return true; + } + } catch (IllegalAccessException | RuntimeException ignored) { + // Fusion is optional; if reflection is blocked, keep the normal Lightspeed path. + } + } + return false; + } + + private static boolean isFusionLoaded() { + try { + return ModList.get().isLoaded("fusion"); + } catch (RuntimeException ignored) { + return false; + } + } + + private static List findOverrideFields(Class type) { + List fields = new ArrayList<>(); + for (Class current = type; current != null; current = current.getSuperclass()) { + for (Field field : current.getDeclaredFields()) { + if (!isFusionOverrideField(field.getName())) { + continue; + } + try { + field.setAccessible(true); + fields.add(field); + } catch (RuntimeException ignored) { + // Leave inaccessible fields out of the compatibility check. + } + } + } + return List.copyOf(fields); + } + + private static boolean isFusionOverrideField(String fieldName) { + for (String suffix : OVERRIDE_FIELD_SUFFIXES) { + if (fieldName.equals(suffix) || fieldName.endsWith("$" + suffix) || fieldName.endsWith(suffix)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/compat/ResourceReloadFailureGuard.java b/src/main/java/com/ccr4ft3r/lightspeed/compat/ResourceReloadFailureGuard.java new file mode 100644 index 0000000..e1cb78f --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/compat/ResourceReloadFailureGuard.java @@ -0,0 +1,120 @@ +package com.ccr4ft3r.lightspeed.compat; + +import com.ccr4ft3r.lightspeed.cache.GlobalCache; +import com.mojang.logging.LogUtils; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.profiling.ProfilerFiller; +import org.slf4j.Logger; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; + +public final class ResourceReloadFailureGuard { + private static final Logger LOGGER = LogUtils.getLogger(); + + private ResourceReloadFailureGuard() { + } + + public static List wrap(List listeners) { + if (!GlobalCache.shouldIsolateModdedResourceReloadFailures) { + return listeners; + } + return listeners.stream() + .map(listener -> shouldWrap(listener) ? new GuardedReloadListener(listener) : listener) + .toList(); + } + + private static boolean shouldWrap(PreparableReloadListener listener) { + String className = listener.getClass().getName(); + return !isCoreClass(className) && matchesConfiguredPattern(className); + } + + private static boolean shouldIsolate(PreparableReloadListener listener, Throwable throwable) { + return GlobalCache.shouldIsolateModdedResourceReloadFailures + && !isFatal(throwable) + && shouldWrap(listener); + } + + private static boolean matchesConfiguredPattern(String className) { + for (String pattern : GlobalCache.isolatedResourceReloadListenerPatterns) { + if ("*".equals(pattern)) { + return true; + } + if (pattern.endsWith(".*") && className.startsWith(pattern.substring(0, pattern.length() - 1))) { + return true; + } + if (className.equals(pattern) || className.startsWith(pattern)) { + return true; + } + } + return false; + } + + private static boolean isCoreClass(String className) { + return className.startsWith("net.minecraft.") + || className.startsWith("net.minecraftforge.") + || className.startsWith("com.mojang.") + || className.startsWith("java.") + || className.startsWith("javax."); + } + + private static boolean isFatal(Throwable throwable) { + return throwable instanceof VirtualMachineError || throwable instanceof ThreadDeath; + } + + private static Throwable unwrap(Throwable throwable) { + Throwable current = throwable; + while ((current instanceof CompletionException || current instanceof ExecutionException) && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private record GuardedReloadListener(PreparableReloadListener delegate) implements PreparableReloadListener { + @Override + public CompletableFuture reload(PreparationBarrier barrier, ResourceManager resourceManager, + ProfilerFiller preparationsProfiler, ProfilerFiller reloadProfiler, + Executor backgroundExecutor, Executor gameExecutor) { + CompletableFuture future; + try { + future = delegate.reload(barrier, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor); + } catch (Throwable throwable) { + return handleFailure(throwable); + } + return future.handle((ignored, throwable) -> { + if (throwable == null) { + return null; + } + Throwable cause = unwrap(throwable); + if (shouldIsolate(delegate, cause)) { + logIsolated(cause); + return null; + } + throw new CompletionException(cause); + }); + } + + @Override + public String getName() { + return delegate.getName(); + } + + private CompletableFuture handleFailure(Throwable throwable) { + Throwable cause = unwrap(throwable); + if (shouldIsolate(delegate, cause)) { + logIsolated(cause); + return CompletableFuture.completedFuture(null); + } + return CompletableFuture.failedFuture(cause); + } + + private void logIsolated(Throwable throwable) { + LOGGER.error("Lightspeed isolated resource reload failure in {} ({})", + delegate.getName(), delegate.getClass().getName(), throwable); + } + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java b/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java new file mode 100644 index 0000000..e41c6ab --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java @@ -0,0 +1,47 @@ +package com.ccr4ft3r.lightspeed.config; + +import net.minecraftforge.common.ForgeConfigSpec; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.List; + +public final class LightspeedConfig { + public static final ForgeConfigSpec SPEC; + public static final Common COMMON; + + static { + Pair pair = new ForgeConfigSpec.Builder().configure(Common::new); + COMMON = pair.getLeft(); + SPEC = pair.getRight(); + } + + private LightspeedConfig() { + } + + public static final class Common { + public final ForgeConfigSpec.BooleanValue asyncPreloadPacks; + public final ForgeConfigSpec.BooleanValue parallelResourceLookup; + public final ForgeConfigSpec.BooleanValue isolateModdedResourceReloadFailures; + public final ForgeConfigSpec.ConfigValue> isolatedResourceReloadListenerPatterns; + + private Common(ForgeConfigSpec.Builder builder) { + builder.push("startup"); + asyncPreloadPacks = builder + .comment("Preload Forge path resource packs on Lightspeed worker threads during startup.") + .define("asyncPreloadPacks", true); + parallelResourceLookup = builder + .comment("Query candidate resource packs concurrently while preserving pack priority order for the selected result.") + .define("parallelResourceLookup", true); + builder.pop(); + + builder.push("compatibility"); + isolateModdedResourceReloadFailures = builder + .comment("Complete failed third-party client resource reload listeners instead of letting one mod crash the whole loading overlay.") + .define("isolateModdedResourceReloadFailures", true); + isolatedResourceReloadListenerPatterns = builder + .comment("Class-name prefixes that may be isolated when resource reload fails. Use * for all non-core mod listeners.") + .defineList("isolatedResourceReloadListenerPatterns", List.of("*"), value -> value instanceof String string && !string.isBlank()); + builder.pop(); + } + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/events/TitleScreenInjector.java b/src/main/java/com/ccr4ft3r/lightspeed/events/TitleScreenInjector.java index 9a5c101..f99022f 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/events/TitleScreenInjector.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/events/TitleScreenInjector.java @@ -50,7 +50,12 @@ public class TitleScreenInjector { InvocationTargetException e) { LogUtils.getLogger().error("Cannot add launch time to title screen", e); } - GlobalCache.EXECUTOR.execute(GlobalCache::disablePersistAndClear); - GlobalCache.EXECUTOR.shutdown(); + GlobalCache.EXECUTOR.execute(() -> { + try { + GlobalCache.disablePersistAndClear(); + } finally { + GlobalCache.EXECUTOR.shutdown(); + } + }); } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/interfaces/IPathResourcePack.java b/src/main/java/com/ccr4ft3r/lightspeed/interfaces/IPathResourcePack.java index 3f0111d..3272c7e 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/interfaces/IPathResourcePack.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/interfaces/IPathResourcePack.java @@ -5,4 +5,6 @@ import net.minecraftforge.forgespi.locating.IModFile; public interface IPathResourcePack extends PackResources, IPackResources { void lightspeed$setModFile(IModFile modFile); -} \ No newline at end of file + + void lightspeed$startAsyncPreload(); +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/MinecraftMainMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/MinecraftMainMixin.java index ab975af..aaa78b5 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/MinecraftMainMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/MinecraftMainMixin.java @@ -1,40 +1,17 @@ package com.ccr4ft3r.lightspeed.mixin; import com.ccr4ft3r.lightspeed.cache.GlobalCache; -import com.ccr4ft3r.lightspeed.util.CacheUtil; import net.minecraft.client.main.Main; -import org.apache.commons.io.FilenameUtils; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import java.io.File; -import java.util.Map; - -import static com.ccr4ft3r.lightspeed.util.CacheUtil.HAS_RESOURCE_CACHE_DIR; -import static com.ccr4ft3r.lightspeed.util.CacheUtil.NAMESPACE_CACHE_DIR; - @Mixin(Main.class) public class MinecraftMainMixin { @Inject(method = "main", at = @At(value = "INVOKE", target = "Lnet/minecraft/SharedConstants;tryDetectVersion()V", shift = At.Shift.AFTER)) - private static void mainTryDetecVersionInjected(String[] p_129642_, CallbackInfo ci) { - GlobalCache.EXECUTOR.execute(() -> { - lightspeed$loadPersistedCaches(HAS_RESOURCE_CACHE_DIR, GlobalCache.PERSISTED_EXISTENCES_BY_MOD); - lightspeed$loadPersistedCaches(NAMESPACE_CACHE_DIR, GlobalCache.PERSISTED_NAMESPACES_BY_MOD); - }); + private static void mainTryDetecVersionInjected(String[] args, CallbackInfo ci) { + GlobalCache.loadPersistedCachesAsync(); } - - - @Unique - @SuppressWarnings("ResultOfMethodCallIgnored") - private static void lightspeed$loadPersistedCaches(File dir, Map> targetMap) { - dir.mkdirs(); - CacheUtil.getCacheFiles(dir).forEach(file -> { - String id = FilenameUtils.getBaseName(file.getName()); - targetMap.put(id, CacheUtil.load(file)); - }); - } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/misc/ResourcePackLoaderMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/misc/ResourcePackLoaderMixin.java index 73a659b..1f1b1ef 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/misc/ResourcePackLoaderMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/misc/ResourcePackLoaderMixin.java @@ -10,15 +10,17 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -@Mixin(ResourcePackLoader.class) +@Mixin(value = ResourcePackLoader.class, remap = false) public abstract class ResourcePackLoaderMixin { - @Inject(method = "createPackForMod", at = @At("HEAD"), remap = false, cancellable = true) - private static void createPackForModHeadInjected(IModFileInfo mf, CallbackInfoReturnable cir) { + @Inject(method = "createPackForMod", at = @At("RETURN"), remap = false) + private static void createPackForModReturnInjected(IModFileInfo mf, CallbackInfoReturnable cir) { if (!GlobalCache.isEnabled) return; - PathPackResources resourcePack = new PathPackResources(mf.getFile().getFileName(),true, mf.getFile().getFilePath()); - ((IPathResourcePack) resourcePack).lightspeed$setModFile(mf.getFile()); - cir.setReturnValue(resourcePack); + PathPackResources resourcePack = cir.getReturnValue(); + if (!(resourcePack instanceof IPathResourcePack lightspeedPack)) + return; + lightspeedPack.lightspeed$setModFile(mf.getFile()); + lightspeedPack.lightspeed$startAsyncPreload(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/DelegatingResourcePackMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/DelegatingResourcePackMixin.java index 00a02a3..507ec36 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/DelegatingResourcePackMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/DelegatingResourcePackMixin.java @@ -14,7 +14,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.io.InputStream; import java.util.List; -import java.util.Objects; @Mixin(DelegatingPackResources.class) public abstract class DelegatingResourcePackMixin { @@ -23,14 +22,9 @@ public abstract class DelegatingResourcePackMixin { @Inject(method = "getResource(Lnet/minecraft/server/packs/PackType;Lnet/minecraft/resources/ResourceLocation;)Lnet/minecraft/server/packs/resources/IoSupplier;", at = @At(value = "HEAD"), cancellable = true) public void getResourceHeadInjected(PackType type, ResourceLocation location, CallbackInfoReturnable> cir) { - if (!GlobalCache.isEnabled) + if (!GlobalCache.isEnabled || !GlobalCache.shouldParallelizeResourcePackLookup) return; - IoSupplier result = getCandidatePacks(type, location) - .parallelStream() - .map(pack -> pack.getResource(type, location)) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); + IoSupplier result = GlobalCache.findFirstResource(getCandidatePacks(type, location), type, location); cir.setReturnValue(result); } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FilePackResourcesMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FilePackResourcesMixin.java index 2ad609a..e8b7da0 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FilePackResourcesMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FilePackResourcesMixin.java @@ -1,6 +1,7 @@ package com.ccr4ft3r.lightspeed.mixin.resources; import com.ccr4ft3r.lightspeed.cache.GlobalCache; +import com.ccr4ft3r.lightspeed.compat.FusionPackCompat; import com.ccr4ft3r.lightspeed.interfaces.IPackResources; import com.google.common.collect.Maps; import net.minecraft.resources.ResourceLocation; @@ -39,7 +40,7 @@ public abstract class FilePackResourcesMixin implements IPackResources { @Inject(method = "listResources", at = @At("HEAD"), cancellable = true) public void listResourcesHeadInjected(PackType packType, String namespace, String path, PackResources.ResourceOutput resourceOutput, CallbackInfo ci) { - if (!GlobalCache.isEnabled) + if (!GlobalCache.isEnabled || FusionPackCompat.hasOverrides(this)) return; ZipFile zip = this.getOrCreateZipFile(); @@ -76,4 +77,4 @@ public abstract class FilePackResourcesMixin implements IPackResources { public void lightspeed$persistAndClearCache() { lightspeed$entriesByPackType.clear(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java index b77bd7f..5446148 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java @@ -1,11 +1,15 @@ package com.ccr4ft3r.lightspeed.mixin.resources; import com.ccr4ft3r.lightspeed.cache.GlobalCache; +import com.ccr4ft3r.lightspeed.compat.FusionPackCompat; import com.ccr4ft3r.lightspeed.interfaces.IPackResources; import com.ccr4ft3r.lightspeed.interfaces.IPathResourcePack; import com.ccr4ft3r.lightspeed.util.CacheUtil; import com.google.common.collect.Maps; -// 注意: ResourceOutput 在这里 +import net.minecraft.FileUtil; +import net.minecraft.Util; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PackResources; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.resources.IoSupplier; import net.minecraftforge.forgespi.locating.IModFile; @@ -19,9 +23,14 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.io.File; +import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static com.ccr4ft3r.lightspeed.util.CacheUtil.*; @@ -32,11 +41,14 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR @Shadow protected abstract Path resolve(String... paths); - private final Map lightspeed$resolvedPathByResource = Maps.newConcurrentMap(); + @Unique + private Map lightspeed$resolvedPathByResource; - private final Map> lightspeed$namespacesByPackType = Maps.newConcurrentMap(); + @Unique + private Map> lightspeed$namespacesByPackType; - private final Map>> lightspeed$filePathsByRootByPackType = lightspeed$initPathsMap(); + @Unique + private Map>> lightspeed$filePathsByRootByPackType; @Unique @@ -46,8 +58,12 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR private String lightspeed$id; @Inject(method = "", at = @At("RETURN")) public void initReturnInjected(String packId, boolean isBuiltin, Path source, CallbackInfo ci) { - if (GlobalCache.isEnabled) + if (GlobalCache.isEnabled) { + lightspeed$resolvedPaths(); + lightspeed$namespaces(); + lightspeed$filePathsByRoot(); GlobalCache.add(this); + } } @@ -76,7 +92,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR } Path path = lightspeed$getResolvedPath(paths); if (path == null) - lightspeed$resolvedPathByResource.put(Arrays.toString(paths), path = lightspeed$modFile.findResource(paths)); + lightspeed$resolvedPaths().put(Arrays.toString(paths), path = lightspeed$modFile.findResource(paths)); cir.setReturnValue(path); } @@ -85,12 +101,12 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR public void resolveReturnInjected(String[] paths, CallbackInfoReturnable cir) { if (!GlobalCache.isEnabled || lightspeed$modFile != null) return; - lightspeed$resolvedPathByResource.put(Arrays.toString(paths), cir.getReturnValue()); + lightspeed$resolvedPaths().put(Arrays.toString(paths), cir.getReturnValue()); } @Inject(method = "getNamespaces", at = @At("HEAD"), cancellable = true) public void getNamespacesHeadInjected(PackType type, CallbackInfoReturnable> cir) { - if (!GlobalCache.isEnabled) + if (!GlobalCache.isEnabled || FusionPackCompat.hasOverrides(this)) return; Set namespaces = lightspeed$getCachedNamespaces(type); if (namespaces != null) @@ -99,7 +115,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR @Inject(method = "getNamespaces", at = @At("RETURN")) public void getNamespacesReturnInjected(PackType type, CallbackInfoReturnable> cir) { - if (!GlobalCache.isEnabled) + if (!GlobalCache.isEnabled || FusionPackCompat.hasOverrides(this)) return; if (GlobalCache.shouldCacheEmptyNamespaces || cir.getReturnValue() != null && !cir.getReturnValue().isEmpty()) lightspeed$cacheNamespaces(type, cir.getReturnValue()); @@ -132,31 +148,86 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR boolean exists = cir.getReturnValue() != null; lightspeed$cacheExists(cacheKey, exists); } + + @Inject(method = "listResources", at = @At("HEAD"), cancellable = true) + public void listResourcesHeadInjected(PackType type, String namespace, String path, PackResources.ResourceOutput resourceOutput, CallbackInfo ci) { + if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheWalkedPaths || FusionPackCompat.hasOverrides(this)) { + return; + } + + FileUtil.decomposePath(path).get().ifLeft(parts -> { + Path root = resolve(type.getDirectory(), namespace).toAbsolutePath(); + Path requestedRoot = FileUtil.resolvePath(root, parts); + List cachedPaths = lightspeed$getFilePaths(type, namespace, root); + + for (Path candidate : cachedPaths) { + if (!candidate.startsWith(requestedRoot)) { + continue; + } + + String relativePath = root.relativize(candidate).toString().replace(candidate.getFileSystem().getSeparator(), "/"); + ResourceLocation location = ResourceLocation.tryBuild(namespace, relativePath); + if (location == null) { + Util.logAndPauseIfInIde(String.format(Locale.ROOT, "Invalid path in pack: %s:%s, ignoring", namespace, relativePath)); + } else { + resourceOutput.accept(location, IoSupplier.create(candidate)); + } + } + }).ifRight(dataResult -> LOGGER.error("Invalid path {}: {}", path, dataResult.message())); + + ci.cancel(); + } + @Override public void lightspeed$persistAndClearCache() { if (lightspeed$modFile != null) { CacheUtil.persist(lightspeed$getExistenceByResource(), new File(HAS_RESOURCE_CACHE_DIR.getPath(), lightspeed$id + ".ser")); - CacheUtil.persist(lightspeed$namespacesByPackType, new File(NAMESPACE_CACHE_DIR.getPath(), lightspeed$id + ".ser")); + CacheUtil.persist(lightspeed$namespaces(), new File(NAMESPACE_CACHE_DIR.getPath(), lightspeed$id + ".ser")); } lightspeed$getExistenceByResource().clear(); - lightspeed$resolvedPathByResource.clear(); - lightspeed$namespacesByPackType.clear(); - lightspeed$filePathsByRootByPackType.clear(); + lightspeed$resolvedPaths().clear(); + lightspeed$namespaces().clear(); + lightspeed$filePathsByRoot().clear(); } @Override public void lightspeed$setModFile(IModFile modFile) { + GlobalCache.awaitPersistedCachesLoaded(); this.lightspeed$modFile = modFile; this.lightspeed$id = modFile.getModFileInfo().moduleName() + modFile.getModFileInfo().versionString() + "-" + FilenameUtils.getBaseName(modFile.getFilePath().toString()).replaceAll("[^a-zA-Z0-9.-]", ""); lightspeed$setExistenceByResource(GlobalCache.PERSISTED_EXISTENCES_BY_MOD.computeIfAbsent( lightspeed$id, i -> Maps.newConcurrentMap())); + lightspeed$namespaces().putAll(GlobalCache.PERSISTED_NAMESPACES_BY_MOD.computeIfAbsent( + lightspeed$id, i -> Maps.newConcurrentMap())); + } + + @Override + public void lightspeed$startAsyncPreload() { + if (!GlobalCache.isEnabled || !GlobalCache.shouldAsyncPreloadPacks) { + return; + } + + for (PackType packType : PackType.values()) { + GlobalCache.executeLogged("preload " + lightspeed$id + " " + packType, () -> { + Set namespaces = lightspeed$getCachedNamespaces(packType); + if (namespaces == null) { + namespaces = lightspeed$scanNamespaces(packType); + lightspeed$cacheNamespaces(packType, namespaces); + } + + for (String namespace : namespaces) { + Path root = resolve(packType.getDirectory(), namespace).toAbsolutePath(); + lightspeed$getFilePaths(packType, namespace, root); + } + }); + } } @Unique public Path lightspeed$getResolvedPath(String... paths) { - return lightspeed$resolvedPathByResource.get(Arrays.toString(paths)); + return lightspeed$resolvedPaths().get(Arrays.toString(paths)); } @@ -171,14 +242,81 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR lightspeed$getExistenceByResource().put(resourceName, exists); } + @Unique + public List lightspeed$getFilePaths(PackType packType, String resourceNamespace, Path root) { + return lightspeed$getFilePathsMap(packType).computeIfAbsent(resourceNamespace, ignored -> lightspeed$scanFilePaths(root)); + } + + @Unique + private Map> lightspeed$getFilePathsMap(PackType packType) { + return lightspeed$filePathsByRoot().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap()); + } + @Unique public void lightspeed$cacheNamespaces(PackType packType, Set namespaces) { - lightspeed$namespacesByPackType.put(packType, namespaces); + lightspeed$namespaces().put(packType, namespaces); } @Unique public Set lightspeed$getCachedNamespaces(PackType packType) { - return lightspeed$namespacesByPackType.get(packType); + return lightspeed$namespaces().get(packType); } -} \ No newline at end of file + + @Unique + private Map lightspeed$resolvedPaths() { + if (lightspeed$resolvedPathByResource == null) { + lightspeed$resolvedPathByResource = Maps.newConcurrentMap(); + } + return lightspeed$resolvedPathByResource; + } + + @Unique + private Map> lightspeed$namespaces() { + if (lightspeed$namespacesByPackType == null) { + lightspeed$namespacesByPackType = Maps.newConcurrentMap(); + } + return lightspeed$namespacesByPackType; + } + + @Unique + private Map>> lightspeed$filePathsByRoot() { + if (lightspeed$filePathsByRootByPackType == null) { + lightspeed$filePathsByRootByPackType = lightspeed$initPathsMap(); + } + return lightspeed$filePathsByRootByPackType; + } + + @Unique + private List lightspeed$scanFilePaths(Path root) { + try (Stream stream = Files.find(root, Integer.MAX_VALUE, (candidate, attributes) -> attributes.isRegularFile())) { + return stream.collect(Collectors.toList()); + } catch (NoSuchFileException ignored) { + return Collections.emptyList(); + } catch (IOException e) { + LOGGER.error("Failed to list path {}", root, e); + return Collections.emptyList(); + } + } + + @Unique + private Set lightspeed$scanNamespaces(PackType type) { + try { + Path root = resolve(type.getDirectory()); + try (Stream walker = Files.walk(root, 1)) { + return walker + .filter(Files::isDirectory) + .map(root::relativize) + .filter(path -> path.getNameCount() > 0) + .map(path -> path.toString().replaceAll("/$", "")) + .filter(namespace -> !namespace.isEmpty()) + .collect(Collectors.toSet()); + } + } catch (IOException e) { + if (type == PackType.SERVER_DATA) { + return lightspeed$scanNamespaces(PackType.CLIENT_RESOURCES); + } + return Collections.emptySet(); + } + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/SimpleReloadInstanceMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/SimpleReloadInstanceMixin.java new file mode 100644 index 0000000..192a146 --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/SimpleReloadInstanceMixin.java @@ -0,0 +1,36 @@ +package com.ccr4ft3r.lightspeed.mixin.resources; + +import com.ccr4ft3r.lightspeed.compat.ResourceReloadFailureGuard; +import net.minecraft.server.packs.resources.PreparableReloadListener; +import net.minecraft.server.packs.resources.ProfiledReloadInstance; +import net.minecraft.server.packs.resources.ReloadInstance; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.SimpleReloadInstance; +import net.minecraft.util.Unit; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +@Mixin(SimpleReloadInstance.class) +public abstract class SimpleReloadInstanceMixin { + @Inject(method = "create", at = @At("HEAD"), cancellable = true) + private static void createHeadInjected(ResourceManager resourceManager, List listeners, + Executor backgroundExecutor, Executor gameExecutor, + CompletableFuture initialStage, boolean profiled, + CallbackInfoReturnable cir) { + List guardedListeners = ResourceReloadFailureGuard.wrap(listeners); + if (guardedListeners == listeners) { + return; + } + + ReloadInstance reloadInstance = profiled + ? new ProfiledReloadInstance(resourceManager, guardedListeners, backgroundExecutor, gameExecutor, initialStage) + : SimpleReloadInstance.of(resourceManager, guardedListeners, backgroundExecutor, gameExecutor, initialStage); + cir.setReturnValue(reloadInstance); + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/VanillaPackResourcesMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/VanillaPackResourcesMixin.java index 1eddef8..28de69d 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/VanillaPackResourcesMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/VanillaPackResourcesMixin.java @@ -4,7 +4,7 @@ import com.ccr4ft3r.lightspeed.cache.GlobalCache; import com.ccr4ft3r.lightspeed.interfaces.IPackResources; import com.ccr4ft3r.lightspeed.util.CacheUtil; import com.google.common.collect.Maps; -import net.minecraft.client.Minecraft; +import net.minecraft.SharedConstants; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.PackType; import net.minecraft.server.packs.VanillaPackResources; @@ -40,11 +40,8 @@ public abstract class VanillaPackResourcesMixin implements IPackResources { return; GlobalCache.add(this); - try { - lightspeed$versionId = Minecraft.getInstance().getLaunchedVersion(); - } catch (Exception e) { - lightspeed$versionId = "unknown"; - } + GlobalCache.awaitPersistedCachesLoaded(); + lightspeed$versionId = SharedConstants.getCurrentVersion().getId(); lightspeed$existencePerClientResource = PERSISTED_EXISTENCES_BY_MOD.computeIfAbsent( lightspeed$versionId + "-client", k -> Maps.newConcurrentMap()); @@ -99,4 +96,4 @@ public abstract class VanillaPackResourcesMixin implements IPackResources { lightspeed$existencePerClientResource.clear(); lightspeed$existencePerServerResource.clear(); } -} \ No newline at end of file +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java b/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java index eea2f89..12f131f 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java @@ -20,6 +20,9 @@ public class CacheUtil { public static final File NAMESPACE_CACHE_DIR = new File(CACHE_DIR, "namespaces"); public static Stream getCacheFiles(File dir) { + if (!dir.isDirectory()) { + return Stream.empty(); + } File[] caches = dir.listFiles((dir1, name) -> name.toLowerCase().endsWith(".ser")); if (caches == null) return Stream.empty(); @@ -28,13 +31,14 @@ public class CacheUtil { } public static void persist(Map toPersist, File file) { - try { - FileOutputStream fos = new FileOutputStream(file); - ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos)); + File parent = file.getParentFile(); + if (parent != null && !parent.isDirectory() && !parent.mkdirs()) { + LogUtils.getLogger().warn("Cannot create cache directory: {}", parent); + } + try (FileOutputStream fos = new FileOutputStream(file); + ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos))) { oos.writeObject(toPersist); oos.flush(); - oos.close(); - fos.close(); } catch (Exception e) { LogUtils.getLogger().error("Cannot create cache file: {}", file, e); } @@ -42,16 +46,16 @@ public class CacheUtil { @SuppressWarnings("unchecked") public static Map load(File file) { - try { - FileInputStream fis = new FileInputStream(file); - ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); - ConcurrentHashMap loaded = (ConcurrentHashMap) ois.readObject(); - ois.close(); - fis.close(); - return loaded; + try (FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis))) { + Object loaded = ois.readObject(); + if (loaded instanceof Map map) { + return new ConcurrentHashMap<>((Map) map); + } + LogUtils.getLogger().warn("Cache file did not contain a map: {}", file.getName()); } catch (Exception e) { LogUtils.getLogger().error("Cannot load cache file: {}", file.getName(), e); } return Maps.newConcurrentMap(); } -} \ No newline at end of file +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index c9d2656..b54b925 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -6,22 +6,20 @@ # The name of the mod loader type to load - for regular FML @Mod mods it should be javafml modLoader = "javafml" #mandatory # A version range to match for said mod loader - for regular FML @Mod it will be the forge version -loaderVersion = "[40,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. +loaderVersion = "${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. # The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. # Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. -license = "All Rights Reserved" +license = "${mod_license}" # A URL to refer people to when problems occur with this mod #issueTrackerURL="http://my.issue.tracker/" #optional # A list of mods - how many allowed here is determined by the individual mod loader [[mods]] #mandatory # The modid of the mod -modId = "lightspeed" #mandatory -# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it -# ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata -# see the associated build.gradle script for how to populate this completely automatically during a build -version = "${file.jarVersion}" #mandatory +modId = "${mod_id}" #mandatory +# The version number of the mod +version = "${mod_version}" #mandatory # A display name for the mod -displayName = "Lightspeed" #mandatory +displayName = "${mod_name}" #mandatory # A URL to query for updates for this mod. See the JSON update specification #updateJSONURL="http://myurl.me/" #optional # A URL for the "homepage" for this mod, displayed in the mod UI @@ -31,28 +29,28 @@ displayName = "Lightspeed" #mandatory # A text field displayed in the mod UI #credits="Thanks for this example mod goes to Java" #optional # A text field displayed in the mod UI -authors = "CCr4ft3r,kltyton" #optional +authors = "${mod_authors}" #optional # The description text for the mod (multi line!) (#mandatory) description = ''' -Buys you time by loading heavy modpacks significantly faster +${mod_description} ''' # A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional. -[[dependencies.lightspeed]] #optional +[[dependencies."${mod_id}"]] #optional # the modid of the dependency modId = "forge" #mandatory # Does this dependency have to exist - if not, ordering below must be specified mandatory = true #mandatory # The version range of the dependency -versionRange = "[40,)" #mandatory +versionRange = "${forge_version_range}" #mandatory # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory ordering = "NONE" # Side this dependency is applied on - BOTH, CLIENT or SERVER side = "BOTH" # Here's another dependency -[[dependencies.lightspeed]] +[[dependencies."${mod_id}"]] modId = "minecraft" mandatory = true # This version range declares a minimum of the current minecraft version up to but not including the next major version -versionRange = "(1.19.2,1.20.1]" +versionRange = "${minecraft_version_range}" ordering = "NONE" -side = "BOTH" \ No newline at end of file +side = "BOTH" diff --git a/src/main/resources/lightspeed.mixins.json b/src/main/resources/lightspeed.mixins.json index 2726681..5c7704f 100644 --- a/src/main/resources/lightspeed.mixins.json +++ b/src/main/resources/lightspeed.mixins.json @@ -20,7 +20,8 @@ "resources.DelegatingResourcePackMixin", "resources.FilePackResourcesMixin", "resources.PathResourcePackMixin", + "resources.SimpleReloadInstanceMixin", "resources.VanillaPackResourcesMixin" ], "minVersion": "0.8" -} \ No newline at end of file +} diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index c9db42b..79224e3 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,8 +1,6 @@ { "pack": { "description": "lightspeed resources", - "pack_format": 8, - "forge:resource_pack_format": 8, - "forge:data_pack_format": 9 + "pack_format": 15 } } \ No newline at end of file diff --git a/测试.mp4 b/测试.mp4 deleted file mode 100644 index d48ae1e..0000000 Binary files a/测试.mp4 and /dev/null differ