1.20.1-1.2.0

This commit is contained in:
kltyton
2026-07-01 21:25:53 +08:00
parent 868d677f76
commit 6bc1a57dc6
23 changed files with 777 additions and 201 deletions
@@ -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;
}
}
}
}
+148 -9
View File
@@ -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<Void> 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<String> isolatedResourceReloadListenerPatterns = List.of("*");
public static final Map<CharSequence, List<String>> SPLITTED_STRINGS_BY_SEQUENCE = Maps.newConcurrentMap();
public static final Map<String, String> CANONICAL_PATH_PER_FILE = Maps.newConcurrentMap();
private static final Set<ICache> CACHES = Sets.newConcurrentHashSet();
public static final Map<String, Map<String, Boolean>> PERSISTED_EXISTENCES_BY_MOD = Maps.newConcurrentMap();
public static final Map<String, Map<PackType, Set<String>>> 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<Void> 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<Void> 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<InputStream> findFirstResource(List<PackResources> packs, PackType type, ResourceLocation location) {
if (packs.isEmpty()) {
return null;
}
if (packs.size() == 1) {
return packs.get(0).getResource(type, location);
}
List<CompletableFuture<IoSupplier<InputStream>>> 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<IoSupplier<InputStream>> future : futures) {
try {
IoSupplier<InputStream> 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<CompletableFuture<Void>> 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();
}
}
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 <K, V> CompletableFuture<Void> loadPersistedCaches(File dir, Map<String, Map<K, V>> 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<Void> 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<InputStream> findFirstResourceSequential(List<PackResources> packs, PackType type, ResourceLocation location) {
for (PackResources pack : packs) {
IoSupplier<InputStream> supplier = pack.getResource(type, location);
if (supplier != null) {
return supplier;
}
}
return null;
}
}
@@ -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<Class<?>, List<Field>> 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<Field> findOverrideFields(Class<?> type) {
List<Field> 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;
}
}
@@ -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<PreparableReloadListener> wrap(List<PreparableReloadListener> 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<Void> reload(PreparationBarrier barrier, ResourceManager resourceManager,
ProfilerFiller preparationsProfiler, ProfilerFiller reloadProfiler,
Executor backgroundExecutor, Executor gameExecutor) {
CompletableFuture<Void> 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<Void> 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);
}
}
}
@@ -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<Common, ForgeConfigSpec> 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<List<? extends String>> 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();
}
}
}
@@ -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();
}
});
}
}
}
@@ -5,4 +5,6 @@ import net.minecraftforge.forgespi.locating.IModFile;
public interface IPathResourcePack extends PackResources, IPackResources {
void lightspeed$setModFile(IModFile modFile);
}
void lightspeed$startAsyncPreload();
}
@@ -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 <K, V> void lightspeed$loadPersistedCaches(File dir, Map<String, Map<K, V>> targetMap) {
dir.mkdirs();
CacheUtil.getCacheFiles(dir).forEach(file -> {
String id = FilenameUtils.getBaseName(file.getName());
targetMap.put(id, CacheUtil.load(file));
});
}
}
}
@@ -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<PathPackResources> cir) {
@Inject(method = "createPackForMod", at = @At("RETURN"), remap = false)
private static void createPackForModReturnInjected(IModFileInfo mf, CallbackInfoReturnable<PathPackResources> 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();
}
}
}
@@ -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<IoSupplier<InputStream>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || !GlobalCache.shouldParallelizeResourcePackLookup)
return;
IoSupplier<InputStream> result = getCandidatePacks(type, location)
.parallelStream()
.map(pack -> pack.getResource(type, location))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
IoSupplier<InputStream> result = GlobalCache.findFirstResource(getCandidatePacks(type, location), type, location);
cir.setReturnValue(result);
}
}
}
@@ -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();
}
}
}
@@ -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<String, Path> lightspeed$resolvedPathByResource = Maps.newConcurrentMap();
@Unique
private Map<String, Path> lightspeed$resolvedPathByResource;
private final Map<PackType, Set<String>> lightspeed$namespacesByPackType = Maps.newConcurrentMap();
@Unique
private Map<PackType, Set<String>> lightspeed$namespacesByPackType;
private final Map<PackType, Map<String, List<Path>>> lightspeed$filePathsByRootByPackType = lightspeed$initPathsMap();
@Unique
private Map<PackType, Map<String, List<Path>>> lightspeed$filePathsByRootByPackType;
@Unique
@@ -46,8 +58,12 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
private String lightspeed$id;
@Inject(method = "<init>", 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<Path> 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<Set<String>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || FusionPackCompat.hasOverrides(this))
return;
Set<String> 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<Set<String>> 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<Path> 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<String> 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<Path> lightspeed$getFilePaths(PackType packType, String resourceNamespace, Path root) {
return lightspeed$getFilePathsMap(packType).computeIfAbsent(resourceNamespace, ignored -> lightspeed$scanFilePaths(root));
}
@Unique
private Map<String, List<Path>> lightspeed$getFilePathsMap(PackType packType) {
return lightspeed$filePathsByRoot().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap());
}
@Unique
public void lightspeed$cacheNamespaces(PackType packType, Set<String> namespaces) {
lightspeed$namespacesByPackType.put(packType, namespaces);
lightspeed$namespaces().put(packType, namespaces);
}
@Unique
public Set<String> lightspeed$getCachedNamespaces(PackType packType) {
return lightspeed$namespacesByPackType.get(packType);
return lightspeed$namespaces().get(packType);
}
}
@Unique
private Map<String, Path> lightspeed$resolvedPaths() {
if (lightspeed$resolvedPathByResource == null) {
lightspeed$resolvedPathByResource = Maps.newConcurrentMap();
}
return lightspeed$resolvedPathByResource;
}
@Unique
private Map<PackType, Set<String>> lightspeed$namespaces() {
if (lightspeed$namespacesByPackType == null) {
lightspeed$namespacesByPackType = Maps.newConcurrentMap();
}
return lightspeed$namespacesByPackType;
}
@Unique
private Map<PackType, Map<String, List<Path>>> lightspeed$filePathsByRoot() {
if (lightspeed$filePathsByRootByPackType == null) {
lightspeed$filePathsByRootByPackType = lightspeed$initPathsMap();
}
return lightspeed$filePathsByRootByPackType;
}
@Unique
private List<Path> lightspeed$scanFilePaths(Path root) {
try (Stream<Path> 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<String> lightspeed$scanNamespaces(PackType type) {
try {
Path root = resolve(type.getDirectory());
try (Stream<Path> 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();
}
}
}
@@ -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<PreparableReloadListener> listeners,
Executor backgroundExecutor, Executor gameExecutor,
CompletableFuture<Unit> initialStage, boolean profiled,
CallbackInfoReturnable<ReloadInstance> cir) {
List<PreparableReloadListener> 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);
}
}
@@ -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();
}
}
}
@@ -20,6 +20,9 @@ public class CacheUtil {
public static final File NAMESPACE_CACHE_DIR = new File(CACHE_DIR, "namespaces");
public static Stream<File> 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 <K, V> Map<K, V> load(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis));
ConcurrentHashMap<K, V> loaded = (ConcurrentHashMap<K, V>) 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<K, V>) 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();
}
}
}