mirror of
https://github.com/GTNewHorizons/Angelica.git
synced 2026-11-25 22:54:28 +00:00
Parallelize atlas loading and fix SDL-GPU mip-level targets (#2167)
This commit is contained in:
1 parent
2f4ac2a9b7
commit
c10d30b2da
56 files changed
+4167
-409
No files matched your search
@@ -0,0 +1,161 @@
|
||||
package com.gtnewhorizons.angelica.client.gui;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.client.gui.GuiButton;
|
||||
import net.minecraft.client.gui.GuiScreen;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.client.resources.I18n;
|
||||
import net.minecraft.util.EnumChatFormatting;
|
||||
|
||||
import org.lwjgl.input.Keyboard;
|
||||
import org.lwjgl.input.Mouse;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.textures.atlas.AtlasPackPolicy;
|
||||
|
||||
import net.coderbot.iris.gui.element.IrisGuiSlot;
|
||||
import net.coderbot.iris.gui.element.widget.IrisButton;
|
||||
|
||||
public class AtlasPackScreen extends GuiScreen {
|
||||
|
||||
private static final String ENABLED_PREFIX = EnumChatFormatting.GREEN + "[x] " + EnumChatFormatting.WHITE;
|
||||
private static final String DISABLED_PREFIX = EnumChatFormatting.DARK_GRAY + "[ ] " + EnumChatFormatting.GRAY;
|
||||
|
||||
private final GuiScreen parent;
|
||||
private final String title = I18n.format("options.angelica.atlasPacks.title");
|
||||
private final String info = I18n.format("options.angelica.atlasPacks.info");
|
||||
private final String builtinSuffix = " - " + I18n.format("options.angelica.atlasPacks.builtin");
|
||||
|
||||
private final List<String> packs;
|
||||
private boolean dirty;
|
||||
|
||||
private PackRowList rowList;
|
||||
|
||||
public AtlasPackScreen(GuiScreen parent) {
|
||||
this.parent = parent;
|
||||
this.packs = AtlasPackPolicy.knownPackClasses();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initGui() {
|
||||
Keyboard.enableRepeatEvents(true);
|
||||
|
||||
this.rowList = new PackRowList();
|
||||
|
||||
this.buttonList.add(new IrisButton(this.width / 2 - 75, this.height - 27, 150, 20, I18n.format("gui.done"), button -> this.onClose()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGuiClosed() {
|
||||
Keyboard.enableRepeatEvents(false);
|
||||
}
|
||||
|
||||
private void onClose() {
|
||||
if (this.dirty) {
|
||||
ConfigurationManager.save(AngelicaConfig.class);
|
||||
this.dirty = false;
|
||||
}
|
||||
this.mc.displayGuiScreen(this.parent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
|
||||
this.drawDefaultBackground();
|
||||
this.rowList.drawScreen(mouseX, mouseY, partialTicks);
|
||||
super.drawScreen(mouseX, mouseY, partialTicks);
|
||||
|
||||
drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 8, 0xFFFFFF);
|
||||
drawCenteredString(this.fontRendererObj, this.info, this.width / 2, 20, 0xA0A0A0);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) {
|
||||
if (!this.rowList.mouseClicked(mouseX, mouseY, mouseButton)) {
|
||||
super.mouseClicked(mouseX, mouseY, mouseButton);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void mouseMovedOrUp(int mouseX, int mouseY, int state) {
|
||||
if (state == -1 || !this.rowList.mouseReleased(mouseX, mouseY, Mouse.getEventButton())) {
|
||||
super.mouseMovedOrUp(mouseX, mouseY, state);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void actionPerformed(GuiButton button) {
|
||||
if (button.enabled && button instanceof IrisButton irisButton) {
|
||||
irisButton.onPress();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void keyTyped(char typedChar, int keyCode) {
|
||||
if (keyCode == Keyboard.KEY_ESCAPE) {
|
||||
this.onClose();
|
||||
return;
|
||||
}
|
||||
super.keyTyped(typedChar, keyCode);
|
||||
}
|
||||
|
||||
private class PackRowList extends IrisGuiSlot {
|
||||
|
||||
PackRowList() {
|
||||
super(AtlasPackScreen.this.mc, AtlasPackScreen.this.width, AtlasPackScreen.this.height, 36, AtlasPackScreen.this.height - 44, 18);
|
||||
this.setRenderBackground(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getSize() {
|
||||
return packs.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isSelected(int index) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawBackground() {}
|
||||
|
||||
@Override
|
||||
public int getListWidth() {
|
||||
return Math.min(400, AtlasPackScreen.this.width - 40);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean elementClicked(int index, boolean doubleClick, int mouseX, int mouseY, int button) {
|
||||
if (button != 0 || index >= packs.size()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final var name = packs.get(index);
|
||||
AtlasPackPolicy.setTrusted(name, !AtlasPackPolicy.isTrusted(name));
|
||||
dirty = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void drawSlot(int index, int x, int y, int slotHeight, Tessellator tessellator, int mouseX, int mouseY) {
|
||||
final var name = packs.get(index);
|
||||
final var trusted = AtlasPackPolicy.isTrusted(name);
|
||||
|
||||
int simpleStart = name.lastIndexOf('.') + 1;
|
||||
final var packageName = simpleStart > 0 ? name.substring(0, simpleStart - 1) : "";
|
||||
var simpleName = name.substring(simpleStart);
|
||||
final int innerStart = simpleName.lastIndexOf('$') + 1;
|
||||
if (innerStart > 0) {
|
||||
simpleName = simpleName.substring(innerStart);
|
||||
}
|
||||
|
||||
var label = (trusted ? ENABLED_PREFIX : DISABLED_PREFIX) + simpleName + EnumChatFormatting.DARK_GRAY + " (" + packageName + ")";
|
||||
if (AtlasPackPolicy.isBuiltIn(name)) {
|
||||
label += builtinSuffix;
|
||||
}
|
||||
|
||||
drawString(fontRendererObj, fontRendererObj.trimStringToWidth(label, this.getListWidth() - 8), x, y + 5, 0xFFFFFF);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,36 @@ public class AngelicaConfig {
|
||||
@Config.RequiresWorldRestart
|
||||
public static int chunkBuilderThreadCount;
|
||||
|
||||
@Config.Comment("Decode block and item textures on multiple threads for faster startup. Disable if you notice missing or broken textures.")
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean enableParallelAtlasDecode;
|
||||
|
||||
@Config.Comment("Generate texture mipmaps on multiple threads for faster startup. Disable if you notice broken mipmaps.")
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean enableParallelAtlasMipmaps;
|
||||
|
||||
@Config.Comment("Upload the block and item texture atlas in large batches instead of one texture at a time. Disable if you notice missing or broken textures.")
|
||||
@Config.DefaultBoolean(true)
|
||||
public static boolean enableBatchedAtlasUpload;
|
||||
|
||||
@Config.Comment("Resource pack classes the player allows to be read on worker threads during texture loading.")
|
||||
@Config.DefaultStringList({})
|
||||
public static String[] atlasTrustedPacks;
|
||||
|
||||
@Config.Comment("Built-in trusted resource pack classes the player has turned off.")
|
||||
@Config.DefaultStringList({})
|
||||
public static String[] atlasDistrustedPacks;
|
||||
|
||||
@Config.Comment("Resource pack classes seen during texture loading that are not trusted. Recorded automatically; trust them from Video Settings > Performance.")
|
||||
@Config.DefaultStringList({})
|
||||
public static String[] atlasObservedPacks;
|
||||
|
||||
@Config.Comment("Worker threads for startup and shader loading work. 0 = automatic.")
|
||||
@Config.DefaultInt(0)
|
||||
@Config.RangeInt(min = 0, max = 32)
|
||||
@Config.RequiresMcRestart
|
||||
public static int workerThreadCount;
|
||||
|
||||
@Config.Comment("Enable NotFine Options")
|
||||
@Config.DefaultBoolean(false)
|
||||
public static boolean enableNotFineOptions;
|
||||
|
||||
@@ -10,12 +10,9 @@ import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
|
||||
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
|
||||
import org.taumc.glsl.grammar.GLSLParser;
|
||||
import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
|
||||
import net.coderbot.iris.Iris;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
import net.coderbot.iris.gbuffer_overrides.state.StateTracker;
|
||||
import net.coderbot.iris.gl.blending.AlphaTestStorage;
|
||||
import net.coderbot.iris.gl.blending.BlendModeStorage;
|
||||
@@ -104,12 +101,6 @@ public class IrisGLSMBridge {
|
||||
public static void register() {
|
||||
GLSMConfig.expandVertexFormats = Iris.enabled;
|
||||
IrisSamplers.initRenderer();
|
||||
GLSMHooks.shaderWorkSubmitter = new ShaderWorkSubmitter() {
|
||||
@Override
|
||||
public <T> CompletableFuture<T> submit(Supplier<T> work) {
|
||||
return Iris.ShaderTransformExecutor.submitTracked(work);
|
||||
}
|
||||
};
|
||||
installPostTransformHook();
|
||||
GLSMHooks.blendHandler = new DeferredBlendHandler() {
|
||||
@Override
|
||||
|
||||
+4
-1
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.loading.rfb.transformers;
|
||||
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
|
||||
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
|
||||
import com.gtnewhorizons.angelica.loading.shared.transformers.TileEntityMarkerTransform;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.api.BytePatternMatcher;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.api.ClassHeaderMetadata;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
|
||||
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
|
||||
@@ -19,10 +20,12 @@ public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
|
||||
|
||||
private final CeleritasBlockTransform inner;
|
||||
private final TileEntityMarkerTransform tileEntities;
|
||||
private final BytePatternMatcher cstPoolMatcher;
|
||||
|
||||
public RFBCeleritasBlockTransformer(boolean isObf) {
|
||||
inner = new CeleritasBlockTransform(isObf);
|
||||
tileEntities = new TileEntityMarkerTransform(isObf, RetroFuturaBootstrap.API.newestAsmVersion());
|
||||
cstPoolMatcher = new BytePatternMatcher(inner.getConstantPoolSearchStrings(), BytePatternMatcher.Mode.Equals);
|
||||
}
|
||||
|
||||
@Pattern("[a-z0-9-]+")
|
||||
@@ -68,7 +71,7 @@ public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
|
||||
tileEntities.track(thisName, superName);
|
||||
if (tileEntities.markersFor(thisName, originalBytes) != 0) return true;
|
||||
}
|
||||
return inner.shouldTransform(originalBytes);
|
||||
return metadata.matchesBytes(originalBytes, cstPoolMatcher);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+8
-2
@@ -43,6 +43,7 @@ public final class CeleritasBlockTransform implements Opcodes {
|
||||
// Block subclass owners we shouldn't redirect because they shadow some fields we want to redirect
|
||||
private final Set<String> blockSubclassExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>());
|
||||
private final ClassConstantPoolParser cstPoolParser;
|
||||
private final String[] constantPoolSearchStrings;
|
||||
|
||||
public CeleritasBlockTransform(boolean isObf) {
|
||||
final List<Pair<String, String>> mappings = ImmutableList.of(
|
||||
@@ -58,7 +59,12 @@ public final class CeleritasBlockTransform implements Opcodes {
|
||||
this.fieldNameToRedirect.put(name, pair.getLeft());
|
||||
}
|
||||
|
||||
this.cstPoolParser = new ClassConstantPoolParser(this.fieldNameToRedirect.keySet().toArray(new String[0]));
|
||||
this.constantPoolSearchStrings = this.fieldNameToRedirect.keySet().toArray(new String[0]);
|
||||
this.cstPoolParser = new ClassConstantPoolParser(this.constantPoolSearchStrings);
|
||||
}
|
||||
|
||||
public String[] getConstantPoolSearchStrings() {
|
||||
return constantPoolSearchStrings.clone();
|
||||
}
|
||||
|
||||
private boolean isVanillaBlockSubclass(String className) {
|
||||
@@ -74,7 +80,7 @@ public final class CeleritasBlockTransform implements Opcodes {
|
||||
}
|
||||
|
||||
private boolean isBlockSubclass(String className) {
|
||||
return isVanillaBlockSubclass(className) || moddedBlockSubclasses.contains(className);
|
||||
return className != null && (isVanillaBlockSubclass(className) || moddedBlockSubclasses.contains(className));
|
||||
}
|
||||
|
||||
// This method needs to be called for every class, including the ones we don't want to transform.
|
||||
|
||||
@@ -214,6 +214,14 @@ public enum Mixins implements IMixins {
|
||||
)
|
||||
),
|
||||
|
||||
ANGELICA_PARALLEL_ATLAS_LOADING(new MixinBuilder("Decode atlas sprites and generate their mipmaps on worker threads")
|
||||
.setPhase(Phase.EARLY)
|
||||
.addClientMixins(
|
||||
"angelica.textures.MixinTextureMap_ParallelLoad"
|
||||
)
|
||||
),
|
||||
|
||||
|
||||
THAUMCRAFT_SCANNER_SCREEN(new MixinBuilder("Render the held Thaumometer screen after world transparency")
|
||||
.setPhase(Phase.LATE)
|
||||
.addRequiredMod(TargetedMod.THAUMCRAFT)
|
||||
|
||||
@@ -17,4 +17,8 @@ public interface SpriteExtension {
|
||||
int angelica$getGutterWidth();
|
||||
|
||||
void angelica$setGutterWidth(int gutter);
|
||||
|
||||
void angelica$setUploaded(boolean uploaded);
|
||||
|
||||
boolean angelica$takeUploaded();
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package com.gtnewhorizons.angelica.textures.atlas;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.GLStateManager;
|
||||
import com.gtnewhorizons.angelica.glsm.texture.TextureStaging;
|
||||
import com.gtnewhorizons.angelica.glsm.threading.AngelicaWorkers;
|
||||
import com.gtnewhorizons.angelica.rendering.celeritas.SpriteExtension;
|
||||
import com.gtnewhorizons.angelica.utils.SpritePadding;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public final class AtlasAssembler {
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
private static final long BAND_BYTES = 4L << 20;
|
||||
|
||||
private AtlasAssembler() {}
|
||||
|
||||
private record Placement(TextureAtlasSprite sprite, int[][] frame, int width, int height, int gutter, int x, int y, int paddedWidth, int paddedHeight) {}
|
||||
|
||||
private static final class Band {
|
||||
final int y0;
|
||||
final int y1;
|
||||
final int width;
|
||||
final TextureStaging[] stagings;
|
||||
CompletableFuture<Void> work;
|
||||
|
||||
Band(int y0, int y1, int width, int levels) {
|
||||
this.y0 = y0;
|
||||
this.y1 = y1;
|
||||
this.width = width;
|
||||
this.stagings = new TextureStaging[levels];
|
||||
}
|
||||
}
|
||||
|
||||
public static void upload(List<TextureAtlasSprite> sprites, int mipmapLevels, int atlasWidth, int atlasHeight) {
|
||||
for (TextureAtlasSprite sprite : sprites) {
|
||||
((SpriteExtension) sprite).angelica$setUploaded(false);
|
||||
}
|
||||
if (!AngelicaConfig.enableBatchedAtlasUpload || sprites.isEmpty() || atlasWidth <= 0 || atlasHeight <= 0) return;
|
||||
if (Minecraft.getMinecraft().gameSettings.anaglyph) return;
|
||||
|
||||
final Placement[] placements = collect(sprites, mipmapLevels, atlasWidth, atlasHeight);
|
||||
if (placements == null || placements.length == 0) return;
|
||||
|
||||
final int align = 1 << mipmapLevels;
|
||||
final int levels = mipmapLevels + 1;
|
||||
final int bandRows = Math.max(align, (int) Math.min(atlasHeight, BAND_BYTES / (atlasWidth * 4L)) / align * align);
|
||||
final int bandCount = (atlasHeight + bandRows - 1) / bandRows;
|
||||
final boolean[] bandOk = new boolean[bandCount];
|
||||
int maxPaddedHeight = 0;
|
||||
for (Placement p : placements) maxPaddedHeight = Math.max(maxPaddedHeight, p.paddedHeight);
|
||||
|
||||
Band previous = null;
|
||||
Band current = null;
|
||||
try {
|
||||
for (int b = 0; b < bandCount; b++) {
|
||||
final int y0 = b * bandRows;
|
||||
current = open(y0, Math.min(atlasHeight, y0 + bandRows), levels, atlasWidth);
|
||||
if (current != null) submit(current, placements, maxPaddedHeight, align);
|
||||
if (previous != null) {
|
||||
final Band done = previous;
|
||||
previous = null;
|
||||
bandOk[done.y0 / bandRows] = finish(done);
|
||||
}
|
||||
previous = current;
|
||||
current = null;
|
||||
if (previous == null) break;
|
||||
}
|
||||
if (previous != null) {
|
||||
final Band done = previous;
|
||||
previous = null;
|
||||
bandOk[done.y0 / bandRows] = finish(done);
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
LOGGER.warn("Batched atlas upload failed, remaining sprites use the per-sprite path", t);
|
||||
discard(previous);
|
||||
discard(current);
|
||||
} finally {
|
||||
GLStateManager.trimTextureStaging();
|
||||
}
|
||||
|
||||
final TextureAtlasSprite last = sprites.getLast();
|
||||
for (Placement p : placements) {
|
||||
if (p.sprite != last && covered(bandOk, bandRows, p.y, p.y + p.paddedHeight)) {
|
||||
((SpriteExtension) p.sprite).angelica$setUploaded(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Placement[] collect(List<TextureAtlasSprite> sprites, int mipmapLevels, int atlasWidth, int atlasHeight) {
|
||||
final int alignMask = (1 << mipmapLevels) - 1;
|
||||
final Set<TextureAtlasSprite> seen = Collections.newSetFromMap(new IdentityHashMap<>(sprites.size() * 2));
|
||||
final ArrayList<Placement> all = new ArrayList<>(sprites.size());
|
||||
final ArrayList<Placement> eligible = new ArrayList<>(sprites.size());
|
||||
boolean anyNonSquare = false;
|
||||
int maxPaddedHeight = 0;
|
||||
|
||||
for (TextureAtlasSprite sprite : sprites) {
|
||||
if (!seen.add(sprite)) continue;
|
||||
final int w = sprite.getIconWidth();
|
||||
final int h = sprite.getIconHeight();
|
||||
final int g = Math.max(0, ((SpriteExtension) sprite).angelica$getGutterWidth());
|
||||
final int x = sprite.getOriginX() - g;
|
||||
final int y = sprite.getOriginY() - g;
|
||||
final int pw = w + 2 * g;
|
||||
final int ph = h + 2 * g;
|
||||
if (w <= 0 || h <= 0 || x < 0 || y < 0 || (x & alignMask) != 0 || (y & alignMask) != 0 || (long) x + pw > atlasWidth || (long) y + ph > atlasHeight) {
|
||||
return null;
|
||||
}
|
||||
final Placement p = new Placement(sprite, eligibleFrame(sprite, w, h, g, mipmapLevels), w, h, g, x, y, pw, ph);
|
||||
all.add(p);
|
||||
if (p.frame != null) eligible.add(p);
|
||||
anyNonSquare |= w != h;
|
||||
maxPaddedHeight = Math.max(maxPaddedHeight, ph);
|
||||
}
|
||||
|
||||
if (anyNonSquare && overlaps(all, maxPaddedHeight)) return null;
|
||||
final Placement[] result = eligible.toArray(Placement[]::new);
|
||||
Arrays.sort(result, Comparator.comparingInt(Placement::y));
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int[][] eligibleFrame(TextureAtlasSprite sprite, int w, int h, int g, int mipmapLevels) {
|
||||
if (sprite.getFrameCount() <= 0) return null;
|
||||
final int[][] frame = sprite.getFrameTextureData(0);
|
||||
if (frame == null || frame.length != mipmapLevels + 1) return null;
|
||||
for (int l = 0; l <= mipmapLevels; l++) {
|
||||
final int lw = w >> l;
|
||||
final int lh = h >> l;
|
||||
final int lg = SpritePadding.gutterForLevel(g, l);
|
||||
if (lw <= 0 || lh <= 0 || frame[l] == null || frame[l].length < lw * lh) return null;
|
||||
if (((w + 2 * g) >> l) != lw + 2 * lg || ((h + 2 * g) >> l) != lh + 2 * lg) return null;
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
private static boolean overlaps(ArrayList<Placement> all, int maxPaddedHeight) {
|
||||
final Placement[] sorted = all.toArray(Placement[]::new);
|
||||
Arrays.sort(sorted, Comparator.comparingInt(Placement::y));
|
||||
for (final Placement s : sorted) {
|
||||
if (s.width == s.height) continue;
|
||||
for (int j = lowerBound(sorted, s.y - maxPaddedHeight + 1); j < sorted.length && sorted[j].y < s.y + s.paddedHeight; j++) {
|
||||
final Placement o = sorted[j];
|
||||
if (o != s && o.y + o.paddedHeight > s.y && o.x < s.x + s.paddedWidth && o.x + o.paddedWidth > s.x) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Band open(int y0, int y1, int levels, int atlasWidth) {
|
||||
final Band band = new Band(y0, y1, atlasWidth, levels);
|
||||
try {
|
||||
for (int l = 0; l < levels; l++) {
|
||||
final int ly0 = y0 >> l;
|
||||
final int rows = (y1 >> l) - ly0;
|
||||
final int lw = atlasWidth >> l;
|
||||
if (rows <= 0 || lw <= 0) continue;
|
||||
final TextureStaging staging = GLStateManager.beginTextureStaging(l, 0, ly0, lw, rows);
|
||||
if (staging == null) {
|
||||
abandon(band, 0);
|
||||
return null;
|
||||
}
|
||||
band.stagings[l] = staging;
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
abandon(band, 0);
|
||||
throw t;
|
||||
}
|
||||
return band;
|
||||
}
|
||||
|
||||
private static void submit(Band band, Placement[] placements, int maxPaddedHeight, int align) {
|
||||
final int threads = AngelicaWorkers.threads();
|
||||
final int perStripe = (band.y1 - band.y0 + threads - 1) / threads;
|
||||
final int stripeRows = Math.max(align, (perStripe + align - 1) / align * align);
|
||||
final ArrayList<CompletableFuture<Void>> stripes = new ArrayList<>(threads);
|
||||
try {
|
||||
for (int sy0 = band.y0; sy0 < band.y1; sy0 += stripeRows) {
|
||||
final int stripeY0 = sy0;
|
||||
final int stripeY1 = Math.min(band.y1, sy0 + stripeRows);
|
||||
final int lo = lowerBound(placements, stripeY0 - maxPaddedHeight + 1);
|
||||
final int hi = lowerBound(placements, stripeY1);
|
||||
stripes.add(AngelicaWorkers.run(() -> fillStripe(band, placements, lo, hi, stripeY0, stripeY1)));
|
||||
}
|
||||
} finally {
|
||||
band.work = CompletableFuture.allOf(stripes.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
}
|
||||
|
||||
private static void fillStripe(Band band, Placement[] placements, int lo, int hi, int stripeY0, int stripeY1) {
|
||||
for (int l = 0; l < band.stagings.length; l++) {
|
||||
final TextureStaging staging = band.stagings[l];
|
||||
if (staging == null) continue;
|
||||
final int stride = (band.width >> l) * 4;
|
||||
final int levelY0 = band.y0 >> l;
|
||||
final long address = MemoryUtilities.memAddress(staging.buffer());
|
||||
final int clipY0 = (stripeY0 >> l) - levelY0;
|
||||
final int clipY1 = (stripeY1 >> l) - levelY0;
|
||||
if (clipY1 <= clipY0) continue;
|
||||
MemoryUtilities.memSet(address + (long) clipY0 * stride, 0, (long) (clipY1 - clipY0) * stride);
|
||||
final boolean swap = !staging.bgra();
|
||||
for (int i = lo; i < hi; i++) {
|
||||
final Placement p = placements[i];
|
||||
if (p.y + p.paddedHeight <= stripeY0) continue;
|
||||
SpritePadding.writePaddedLevel(p.frame[l], p.width >> l, p.height >> l, SpritePadding.gutterForLevel(p.gutter, l),
|
||||
address, stride, p.x >> l, (p.y >> l) - levelY0, clipY0, clipY1, swap);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean finish(Band band) {
|
||||
try {
|
||||
band.work.join();
|
||||
} catch (Throwable t) {
|
||||
LOGGER.warn("Batched atlas upload failed for rows {}-{}, those sprites use the per-sprite path", band.y0, band.y1, t);
|
||||
abandon(band, 0);
|
||||
return false;
|
||||
}
|
||||
for (int l = 0; l < band.stagings.length; l++) {
|
||||
final TextureStaging staging = band.stagings[l];
|
||||
if (staging == null) continue;
|
||||
band.stagings[l] = null;
|
||||
boolean committed = false;
|
||||
try {
|
||||
committed = GLStateManager.commitTextureStaging(staging);
|
||||
} finally {
|
||||
if (!committed) abandon(band, l + 1);
|
||||
}
|
||||
if (!committed) {
|
||||
LOGGER.warn("Batched atlas upload could not commit level {} for rows {}-{}, those sprites use the per-sprite path", l, band.y0, band.y1);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void discard(Band band) {
|
||||
if (band == null) return;
|
||||
if (band.work != null) band.work.handle((v, e) -> null).join();
|
||||
abandon(band, 0);
|
||||
}
|
||||
|
||||
private static void abandon(Band band, int fromLevel) {
|
||||
for (int l = fromLevel; l < band.stagings.length; l++) {
|
||||
final TextureStaging staging = band.stagings[l];
|
||||
if (staging == null) continue;
|
||||
band.stagings[l] = null;
|
||||
GLStateManager.abandonTextureStaging(staging);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean covered(boolean[] bandOk, int bandRows, int y0, int y1) {
|
||||
for (int b = y0 / bandRows, last = (y1 - 1) / bandRows; b <= last; b++) {
|
||||
if (!bandOk[b]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int lowerBound(Placement[] placements, int y) {
|
||||
int lo = 0;
|
||||
int hi = placements.length;
|
||||
while (lo < hi) {
|
||||
final int mid = (lo + hi) >>> 1;
|
||||
if (placements[mid].y < y) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package com.gtnewhorizons.angelica.textures.atlas;
|
||||
|
||||
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import com.gtnewhorizons.angelica.glsm.threading.AngelicaWorkers;
|
||||
import com.gtnewhorizons.angelica.utils.PrefetchLane;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
import net.minecraft.client.renderer.texture.TextureMap;
|
||||
import net.minecraft.client.resources.IResource;
|
||||
import net.minecraft.client.resources.IResourceManager;
|
||||
import net.minecraft.client.resources.IResourcePack;
|
||||
import net.minecraft.client.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.client.resources.data.IMetadataSerializer;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
public final class AtlasLoadSession {
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
private static final Consumer<TextureAtlasSprite> KEEP = _ -> {};
|
||||
|
||||
public record Decoded(ResourceLocation location, IResource resource, BufferedImage image) {}
|
||||
|
||||
private final IResourceManager manager;
|
||||
private final int textureType;
|
||||
private final boolean decodeEnabled;
|
||||
private final boolean mipmapsEnabled;
|
||||
private int eligibleDomains;
|
||||
private PrefetchLane<TextureAtlasSprite, Decoded> decodes;
|
||||
private Function<InputStream, BufferedImage> decoder;
|
||||
private InputStream pendingStream;
|
||||
private BufferedImage pendingImage;
|
||||
private int substituted;
|
||||
private PrefetchLane<TextureAtlasSprite, TextureAtlasSprite> mipmaps;
|
||||
private int mipmapsOffloaded;
|
||||
private int mipmapLevels;
|
||||
private boolean closed;
|
||||
|
||||
private AtlasLoadSession(TextureMap map, IResourceManager manager, boolean decodeEnabled, boolean mipmapsEnabled) {
|
||||
this.manager = manager;
|
||||
this.textureType = map.getTextureType();
|
||||
this.decodeEnabled = decodeEnabled;
|
||||
this.mipmapsEnabled = mipmapsEnabled;
|
||||
}
|
||||
|
||||
public static AtlasLoadSession begin(TextureMap map, IResourceManager manager) {
|
||||
final boolean decodeEnabled = AngelicaConfig.enableParallelAtlasDecode;
|
||||
final boolean mipmapsEnabled = AngelicaConfig.enableParallelAtlasMipmaps;
|
||||
if ((!decodeEnabled && !mipmapsEnabled) || map.skipFirst) {
|
||||
return null;
|
||||
}
|
||||
final AtlasLoadSession session = new AtlasLoadSession(map, manager, decodeEnabled, mipmapsEnabled);
|
||||
if (!decodeEnabled) {
|
||||
return session;
|
||||
}
|
||||
if (manager.getClass() != SimpleReloadableResourceManager.class || !metadataReady()) {
|
||||
LOGGER.warn("Parallel atlas decode disabled for atlas {}: resource manager {} or metadata serializer not supported", session.textureType, manager.getClass().getName());
|
||||
return session;
|
||||
}
|
||||
final String[] observed = AngelicaConfig.atlasObservedPacks;
|
||||
final Map<String, List<IResourcePack>> eligible = AtlasPackPolicy.eligibleDomains((SimpleReloadableResourceManager) manager);
|
||||
if (AngelicaConfig.atlasObservedPacks != observed) {
|
||||
ConfigurationManager.save(AngelicaConfig.class);
|
||||
}
|
||||
session.eligibleDomains = eligible.size();
|
||||
if (eligible.isEmpty()) {
|
||||
return session;
|
||||
}
|
||||
final PrefetchLane<TextureAtlasSprite, Decoded> lane = new PrefetchLane<>(AngelicaWorkers::submit, lookahead(), AtlasLoadSession::dispose);
|
||||
final Map<String, TextureAtlasSprite> sprites = map.mapRegisteredSprites;
|
||||
for (Map.Entry<String, TextureAtlasSprite> entry : sprites.entrySet()) {
|
||||
final TextureAtlasSprite sprite = entry.getValue();
|
||||
lane.add(sprite, session.decodeTask(map, eligible, entry.getKey(), sprite));
|
||||
}
|
||||
session.decodes = lane;
|
||||
return session;
|
||||
}
|
||||
|
||||
private static int lookahead() {
|
||||
return 32 * AngelicaWorkers.threads();
|
||||
}
|
||||
|
||||
private static boolean metadataReady() {
|
||||
final IMetadataSerializer serializer = Minecraft.getMinecraft().metadataSerializer_;
|
||||
return serializer != null && serializer.gson != null;
|
||||
}
|
||||
|
||||
private Callable<Decoded> decodeTask(TextureMap map, Map<String, List<IResourcePack>> eligible, String key,
|
||||
TextureAtlasSprite sprite) {
|
||||
if (sprite == null || sprite.getClass() != TextureAtlasSprite.class) {
|
||||
return null;
|
||||
}
|
||||
final ResourceLocation candidate;
|
||||
final List<IResourcePack> claimChecked;
|
||||
try {
|
||||
final ResourceLocation location = new ResourceLocation(key);
|
||||
claimChecked = eligible.get(location.getResourceDomain());
|
||||
if (claimChecked == null) {
|
||||
return null;
|
||||
}
|
||||
candidate = map.completeResourceLocation(location, 0);
|
||||
} catch (RuntimeException _) {
|
||||
return null;
|
||||
}
|
||||
if (!claimChecked.isEmpty() && AtlasPackPolicy.isClaimed(claimChecked, candidate)) {
|
||||
return null;
|
||||
}
|
||||
return () -> decode(candidate);
|
||||
}
|
||||
|
||||
private Decoded decode(ResourceLocation candidate) throws IOException {
|
||||
IResource resource = null;
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
resource = this.manager.getResource(candidate);
|
||||
image = this.decoder.apply(resource.getInputStream());
|
||||
if (image == null) {
|
||||
IOUtils.closeQuietly(resource.getInputStream());
|
||||
return null;
|
||||
}
|
||||
resource.getMetadata("texture");
|
||||
resource.getMetadata("animation");
|
||||
return new Decoded(candidate, resource, image);
|
||||
} catch (Throwable t) {
|
||||
closeImage(image);
|
||||
if (resource != null) {
|
||||
IOUtils.closeQuietly(resource.getInputStream());
|
||||
}
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
public IResource takeResource(IResourceManager manager, TextureAtlasSprite sprite, ResourceLocation location) {
|
||||
if (this.decodes == null) {
|
||||
return null;
|
||||
}
|
||||
releasePending();
|
||||
final Decoded decoded = this.decodes.take(sprite);
|
||||
if (decoded == null) {
|
||||
return null;
|
||||
}
|
||||
if (manager != this.manager || !location.equals(decoded.location())) {
|
||||
dispose(decoded);
|
||||
return null;
|
||||
}
|
||||
this.pendingStream = decoded.resource().getInputStream();
|
||||
this.pendingImage = decoded.image();
|
||||
this.substituted++;
|
||||
return decoded.resource();
|
||||
}
|
||||
|
||||
public BufferedImage takeImage(InputStream stream) {
|
||||
if (this.pendingStream == null || stream != this.pendingStream) {
|
||||
return null;
|
||||
}
|
||||
final BufferedImage image = this.pendingImage;
|
||||
this.pendingStream = null;
|
||||
this.pendingImage = null;
|
||||
return image;
|
||||
}
|
||||
|
||||
public boolean wantsDecoder() {
|
||||
return this.decodes != null && this.decoder == null;
|
||||
}
|
||||
|
||||
public void onMainDecode(Function<InputStream, BufferedImage> decoder) {
|
||||
if (this.decodes == null || this.decoder != null) {
|
||||
return;
|
||||
}
|
||||
this.decoder = decoder;
|
||||
this.decodes.start();
|
||||
}
|
||||
|
||||
public void beginMipmaps(Collection<TextureAtlasSprite> sprites, int levels) {
|
||||
closeDecodes();
|
||||
if (!this.mipmapsEnabled || this.mipmaps != null) {
|
||||
return;
|
||||
}
|
||||
this.mipmapLevels = levels;
|
||||
final PrefetchLane<TextureAtlasSprite, TextureAtlasSprite> lane = new PrefetchLane<>(AngelicaWorkers::submit, lookahead(), KEEP);
|
||||
final Set<TextureAtlasSprite> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
for (TextureAtlasSprite sprite : sprites) {
|
||||
if (sprite != null && MipmapSafety.isSafe(sprite.getClass()) && seen.add(sprite)) {
|
||||
lane.add(sprite, () -> {
|
||||
sprite.generateMipmaps(levels);
|
||||
return sprite;
|
||||
});
|
||||
} else {
|
||||
lane.add(sprite, null);
|
||||
}
|
||||
}
|
||||
this.mipmaps = lane;
|
||||
lane.start();
|
||||
}
|
||||
|
||||
public boolean joinMipmaps(TextureAtlasSprite sprite, int levels) {
|
||||
if (this.mipmaps == null) {
|
||||
return false;
|
||||
}
|
||||
final boolean joined = this.mipmaps.take(sprite) != null;
|
||||
if (joined && levels == this.mipmapLevels) {
|
||||
this.mipmapsOffloaded++;
|
||||
return true;
|
||||
}
|
||||
if (this.mipmaps.isDesynced()) {
|
||||
this.mipmaps.awaitQuiescence();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.closed = true;
|
||||
closeDecodes();
|
||||
if (this.mipmaps != null) {
|
||||
this.mipmaps.close();
|
||||
this.mipmaps.awaitQuiescence();
|
||||
}
|
||||
final PrefetchLane<TextureAtlasSprite, Decoded> d = this.decodes;
|
||||
final PrefetchLane<TextureAtlasSprite, TextureAtlasSprite> m = this.mipmaps;
|
||||
LOGGER.debug("Parallel atlas load {}: {} eligible domains, {} decodes submitted, {} substituted, {} decode failures (first: {}), decode desync {}, {} mipmaps offloaded, {} mipmap failures (first: {}), mipmap desync {}",
|
||||
this.textureType, this.eligibleDomains,
|
||||
d == null ? 0 : d.submitted(), this.substituted,
|
||||
d == null ? 0 : d.failures(), d == null ? null : d.firstFailure(), d != null && d.isDesynced(),
|
||||
this.mipmapsOffloaded,
|
||||
m == null ? 0 : m.failures(), m == null ? null : m.firstFailure(), m != null && m.isDesynced());
|
||||
}
|
||||
|
||||
private void closeDecodes() {
|
||||
if (this.decodes != null) {
|
||||
this.decodes.close();
|
||||
this.decodes.awaitQuiescence();
|
||||
}
|
||||
releasePending();
|
||||
}
|
||||
|
||||
private void releasePending() {
|
||||
if (this.pendingImage != null) {
|
||||
closeImage(this.pendingImage);
|
||||
}
|
||||
this.pendingStream = null;
|
||||
this.pendingImage = null;
|
||||
}
|
||||
|
||||
private static void dispose(Decoded decoded) {
|
||||
closeImage(decoded.image());
|
||||
IOUtils.closeQuietly(decoded.resource().getInputStream());
|
||||
}
|
||||
|
||||
private static void closeImage(BufferedImage image) {
|
||||
if (image instanceof AutoCloseable closeable) {
|
||||
try {
|
||||
closeable.close();
|
||||
} catch (Exception _) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package com.gtnewhorizons.angelica.textures.atlas;
|
||||
|
||||
import com.gtnewhorizons.angelica.config.AngelicaConfig;
|
||||
import cpw.mods.fml.client.FMLFileResourcePack;
|
||||
import cpw.mods.fml.client.FMLFolderResourcePack;
|
||||
import net.minecraft.client.resources.DefaultResourcePack;
|
||||
import net.minecraft.client.resources.FallbackResourceManager;
|
||||
import net.minecraft.client.resources.FileResourcePack;
|
||||
import net.minecraft.client.resources.FolderResourcePack;
|
||||
import net.minecraft.client.resources.IResourcePack;
|
||||
import net.minecraft.client.resources.SimpleReloadableResourceManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class AtlasPackPolicy {
|
||||
|
||||
private static final Logger LOGGER = LogManager.getLogger("Angelica");
|
||||
|
||||
private static final Set<String> BUILT_IN_TRUSTED = Set.of(
|
||||
"glowredman.txloader.TXResourcePack",
|
||||
"com.hfstudio.guidenh.guide.internal.DefaultGuideResourcePackManager$NamedFileResourcePack",
|
||||
"com.mitchej123.hodgepodge.mixins.hooks.IC2ResourcePack",
|
||||
"ganymedes01.etfuturum.client.BuiltInResourcePack$BuiltInFileResourcePack",
|
||||
"ganymedes01.etfuturum.client.BuiltInResourcePack$BuiltInFolderResourcePack",
|
||||
"ganymedes01.etfuturum.client.GrayscaleWaterResourcePack",
|
||||
"ganymedes01.etfuturum.client.DynamicSoundsResourcePack");
|
||||
|
||||
private static final Set<String> BUILT_IN_CLAIM_CHECKED = Set.of(
|
||||
"com.rwtema.extrautils.modintegration.TConTextureResourcePackBedrockium",
|
||||
"com.rwtema.extrautils.modintegration.TConTextureResourcePackMagicWood",
|
||||
"com.rwtema.extrautils.modintegration.TConTextureResourcePackUnstableIngot",
|
||||
"fox.spiteful.avaritia.compat.ticon.InfinityIcons",
|
||||
"fox.spiteful.avaritia.compat.ticon.NeutroniumIcons",
|
||||
"com.arc.bloodarsenal.common.tinkers.TextureResourcePackBloodInfusedIron");
|
||||
|
||||
private static final ResourceLocation PREWARM = new ResourceLocation("angelica", "atlas_prefetch_prewarm");
|
||||
private static final String PREWARM_ITEM_PATH = "textures/items/angelica_atlas_prefetch_prewarm.png";
|
||||
private static final Set<String> LOGGED_UNTRUSTED = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private enum Kind {
|
||||
PLAIN, ZIP, AUDITED, CLAIM_CHECKED
|
||||
}
|
||||
|
||||
private static final Map<Class<?>, Kind> BASE_KINDS = buildBaseKinds();
|
||||
|
||||
private static Map<Class<?>, Kind> buildBaseKinds() {
|
||||
final Map<Class<?>, Kind> map = new HashMap<>();
|
||||
map.put(DefaultResourcePack.class, Kind.PLAIN);
|
||||
map.put(FolderResourcePack.class, Kind.PLAIN);
|
||||
map.put(FMLFolderResourcePack.class, Kind.PLAIN);
|
||||
map.put(FileResourcePack.class, Kind.ZIP);
|
||||
map.put(FMLFileResourcePack.class, Kind.ZIP);
|
||||
return map;
|
||||
}
|
||||
|
||||
private static final class Trust {
|
||||
final Set<String> trusted = new HashSet<>(Arrays.asList(AngelicaConfig.atlasTrustedPacks));
|
||||
final Set<String> distrusted = new HashSet<>(Arrays.asList(AngelicaConfig.atlasDistrustedPacks));
|
||||
final Set<String> observed = new HashSet<>(Arrays.asList(AngelicaConfig.atlasObservedPacks));
|
||||
}
|
||||
|
||||
private AtlasPackPolicy() {
|
||||
}
|
||||
|
||||
public static Map<String, List<IResourcePack>> eligibleDomains(SimpleReloadableResourceManager manager) {
|
||||
final Trust trust = new Trust();
|
||||
final Map<String, List<IResourcePack>> eligible = new HashMap<>();
|
||||
final Map<String, List<String>> untrustedDomains = new HashMap<>();
|
||||
for (Map.Entry<String, FallbackResourceManager> entry : manager.domainResourceManagers.entrySet()) {
|
||||
final List<IResourcePack> claimChecked = eligiblePacks(entry.getKey(), entry.getValue(), trust, untrustedDomains);
|
||||
if (claimChecked != null) {
|
||||
eligible.put(entry.getKey(), claimChecked);
|
||||
}
|
||||
}
|
||||
recordUntrusted(trust, untrustedDomains);
|
||||
return eligible;
|
||||
}
|
||||
|
||||
private static List<IResourcePack> eligiblePacks(String domainName, FallbackResourceManager domain, Trust trust,
|
||||
Map<String, List<String>> untrustedDomains) {
|
||||
if (domain == null || domain.getClass() != FallbackResourceManager.class) {
|
||||
return null;
|
||||
}
|
||||
boolean eligible = true;
|
||||
List<IResourcePack> claimChecked = List.of();
|
||||
for (IResourcePack pack : domain.resourcePacks) {
|
||||
if (pack == null) {
|
||||
eligible = false;
|
||||
continue;
|
||||
}
|
||||
Kind kind = BASE_KINDS.get(pack.getClass());
|
||||
if (kind == null) {
|
||||
final String className = pack.getClass().getName();
|
||||
if (trust.distrusted.contains(className)) {
|
||||
eligible = false;
|
||||
continue;
|
||||
}
|
||||
if (BUILT_IN_TRUSTED.contains(className) || trust.trusted.contains(className)) {
|
||||
kind = Kind.AUDITED;
|
||||
} else if (BUILT_IN_CLAIM_CHECKED.contains(className)) {
|
||||
kind = Kind.CLAIM_CHECKED;
|
||||
} else {
|
||||
eligible = false;
|
||||
untrustedDomains.computeIfAbsent(className, _ -> new ArrayList<>()).add(domainName);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
switch (kind) {
|
||||
case ZIP -> {
|
||||
try {
|
||||
((FileResourcePack) pack).getResourcePackZipFile();
|
||||
} catch (IOException | RuntimeException _) {
|
||||
eligible = false;
|
||||
}
|
||||
}
|
||||
case AUDITED -> {
|
||||
try {
|
||||
pack.resourceExists(PREWARM);
|
||||
} catch (RuntimeException _) {
|
||||
eligible = false;
|
||||
}
|
||||
}
|
||||
case CLAIM_CHECKED -> {
|
||||
try {
|
||||
pack.resourceExists(new ResourceLocation(domainName, PREWARM_ITEM_PATH));
|
||||
if (claimChecked.isEmpty()) {
|
||||
claimChecked = new ArrayList<>(4);
|
||||
}
|
||||
claimChecked.add(pack);
|
||||
} catch (RuntimeException _) {
|
||||
eligible = false;
|
||||
}
|
||||
}
|
||||
case PLAIN -> {}
|
||||
}
|
||||
}
|
||||
return eligible ? claimChecked : null;
|
||||
}
|
||||
|
||||
private static void recordUntrusted(Trust trust, Map<String, List<String>> untrustedDomains) {
|
||||
if (untrustedDomains.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
boolean changed = false;
|
||||
final TreeSet<String> observed = new TreeSet<>(trust.observed);
|
||||
for (Map.Entry<String, List<String>> entry : untrustedDomains.entrySet()) {
|
||||
final String className = entry.getKey();
|
||||
if (LOGGED_UNTRUSTED.add(className)) {
|
||||
LOGGER.info("Resource pack {} is not trusted for parallel texture loading; domains {} load serially. Trust it in Video Settings > Performance > Texture loading.", className, entry.getValue());
|
||||
}
|
||||
if (observed.add(className)) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
AngelicaConfig.atlasObservedPacks = observed.toArray(String[]::new);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isClaimed(List<IResourcePack> claimCheckedPacks, ResourceLocation candidate) {
|
||||
if (claimCheckedPacks.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
final ResourceLocation mcmeta = new ResourceLocation(candidate.getResourceDomain(), candidate.getResourcePath() + ".mcmeta");
|
||||
for (IResourcePack pack : claimCheckedPacks) {
|
||||
try {
|
||||
if (pack.resourceExists(candidate) || pack.resourceExists(mcmeta)) {
|
||||
return true;
|
||||
}
|
||||
} catch (RuntimeException _) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static Set<String> builtInTrusted() {
|
||||
return BUILT_IN_TRUSTED;
|
||||
}
|
||||
|
||||
public static Set<String> builtInClaimChecked() {
|
||||
return BUILT_IN_CLAIM_CHECKED;
|
||||
}
|
||||
|
||||
public static boolean isBuiltIn(String className) {
|
||||
return BUILT_IN_TRUSTED.contains(className) || BUILT_IN_CLAIM_CHECKED.contains(className);
|
||||
}
|
||||
|
||||
public static boolean isTrusted(String className) {
|
||||
if (Arrays.asList(AngelicaConfig.atlasDistrustedPacks).contains(className)) {
|
||||
return false;
|
||||
}
|
||||
if (isBuiltIn(className)) {
|
||||
return true;
|
||||
}
|
||||
return Arrays.asList(AngelicaConfig.atlasTrustedPacks).contains(className);
|
||||
}
|
||||
|
||||
public static void setTrusted(String className, boolean trusted) {
|
||||
if (isBuiltIn(className)) {
|
||||
if (trusted) {
|
||||
AngelicaConfig.atlasDistrustedPacks = withRemoved(AngelicaConfig.atlasDistrustedPacks, className);
|
||||
} else {
|
||||
AngelicaConfig.atlasDistrustedPacks = withAdded(AngelicaConfig.atlasDistrustedPacks, className);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (trusted) {
|
||||
AngelicaConfig.atlasTrustedPacks = withAdded(AngelicaConfig.atlasTrustedPacks, className);
|
||||
AngelicaConfig.atlasObservedPacks = withRemoved(AngelicaConfig.atlasObservedPacks, className);
|
||||
} else {
|
||||
AngelicaConfig.atlasTrustedPacks = withRemoved(AngelicaConfig.atlasTrustedPacks, className);
|
||||
AngelicaConfig.atlasObservedPacks = withAdded(AngelicaConfig.atlasObservedPacks, className);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> knownPackClasses() {
|
||||
final TreeSet<String> all = new TreeSet<>();
|
||||
all.addAll(BUILT_IN_TRUSTED);
|
||||
all.addAll(BUILT_IN_CLAIM_CHECKED);
|
||||
all.addAll(Arrays.asList(AngelicaConfig.atlasTrustedPacks));
|
||||
all.addAll(Arrays.asList(AngelicaConfig.atlasDistrustedPacks));
|
||||
all.addAll(Arrays.asList(AngelicaConfig.atlasObservedPacks));
|
||||
return new ArrayList<>(all);
|
||||
}
|
||||
|
||||
private static String[] withAdded(String[] array, String value) {
|
||||
final TreeSet<String> set = new TreeSet<>(Arrays.asList(array));
|
||||
set.add(value);
|
||||
return set.toArray(String[]::new);
|
||||
}
|
||||
|
||||
private static String[] withRemoved(String[] array, String value) {
|
||||
final TreeSet<String> set = new TreeSet<>(Arrays.asList(array));
|
||||
set.remove(value);
|
||||
return set.toArray(String[]::new);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.gtnewhorizons.angelica.textures.atlas;
|
||||
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.List;
|
||||
|
||||
final class MipmapSafety {
|
||||
|
||||
private static final Method SET_FRAMES = resolveSetFrames();
|
||||
|
||||
private static final ClassValue<Boolean> CACHE = new ClassValue<Boolean>() {
|
||||
|
||||
@Override
|
||||
protected Boolean computeValue(Class<?> type) {
|
||||
if (SET_FRAMES == null) {
|
||||
return false;
|
||||
}
|
||||
for (Class<?> c = type; c != null && c != TextureAtlasSprite.class; c = c.getSuperclass()) {
|
||||
for (Method m : c.getDeclaredMethods()) {
|
||||
final String name = m.getName();
|
||||
final Class<?>[] params = m.getParameterTypes();
|
||||
if ((name.equals("generateMipmaps") || name.equals("func_147963_d")) && params.length == 1
|
||||
&& params[0] == int.class) {
|
||||
return false;
|
||||
}
|
||||
if (name.equals(SET_FRAMES.getName()) && params.length == 1 && params[0] == List.class) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private MipmapSafety() {
|
||||
}
|
||||
|
||||
public static boolean isSafe(Class<?> spriteClass) {
|
||||
if (spriteClass == TextureAtlasSprite.class) {
|
||||
return true;
|
||||
}
|
||||
return CACHE.get(spriteClass);
|
||||
}
|
||||
|
||||
private static Method resolveSetFrames() {
|
||||
Method found = null;
|
||||
for (Method m : TextureAtlasSprite.class.getDeclaredMethods()) {
|
||||
final Class<?>[] params = m.getParameterTypes();
|
||||
if (m.getReturnType() == void.class && params.length == 1 && params[0] == List.class
|
||||
&& !Modifier.isStatic(m.getModifiers())) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = m;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package com.gtnewhorizons.angelica.utils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public final class PrefetchLane<K, V> {
|
||||
|
||||
private final Function<Supplier<V>, CompletableFuture<V>> submitter;
|
||||
private final int window;
|
||||
private final Consumer<V> sink;
|
||||
private final ArrayList<Slot<K, V>> slots = new ArrayList<>();
|
||||
private final ArrayList<CompletableFuture<V>> inflight = new ArrayList<>();
|
||||
private int pruneAt;
|
||||
private int cursor;
|
||||
private int next;
|
||||
private int ahead;
|
||||
private boolean started;
|
||||
private boolean closed;
|
||||
private boolean desynced;
|
||||
private int submitted;
|
||||
private int failures;
|
||||
private Throwable firstFailure;
|
||||
|
||||
public PrefetchLane(Function<Supplier<V>, CompletableFuture<V>> submitter, int window, Consumer<? super V> disposer) {
|
||||
if (window < 1) {
|
||||
throw new IllegalArgumentException("window must be positive: " + window);
|
||||
}
|
||||
this.submitter = submitter;
|
||||
this.window = window;
|
||||
this.pruneAt = window;
|
||||
this.sink = value -> {
|
||||
if (value != null) {
|
||||
disposer.accept(value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void add(K key, Callable<? extends V> task) {
|
||||
if (this.closed) {
|
||||
throw new IllegalStateException("PrefetchLane is closed");
|
||||
}
|
||||
this.slots.add(new Slot<>(key, task));
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (this.started || this.closed) {
|
||||
return;
|
||||
}
|
||||
this.started = true;
|
||||
fill();
|
||||
}
|
||||
|
||||
public V take(K key) {
|
||||
if (this.closed) {
|
||||
return null;
|
||||
}
|
||||
final int size = this.slots.size();
|
||||
for (int i = this.cursor; i < size; i++) {
|
||||
final Slot<K, V> slot = this.slots.get(i);
|
||||
if (slot.key != key) {
|
||||
continue;
|
||||
}
|
||||
for (int j = this.cursor; j < i; j++) {
|
||||
release(this.slots.set(j, null));
|
||||
}
|
||||
this.slots.set(i, null);
|
||||
this.cursor = i + 1;
|
||||
if (slot.future != null) {
|
||||
this.ahead--;
|
||||
}
|
||||
fill();
|
||||
return join(slot);
|
||||
}
|
||||
this.desynced = true;
|
||||
close();
|
||||
return null;
|
||||
}
|
||||
|
||||
public void close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.closed = true;
|
||||
final int size = this.slots.size();
|
||||
for (int i = this.cursor; i < size; i++) {
|
||||
release(this.slots.get(i));
|
||||
}
|
||||
this.slots.clear();
|
||||
this.cursor = 0;
|
||||
this.next = 0;
|
||||
this.ahead = 0;
|
||||
}
|
||||
|
||||
public void awaitQuiescence() {
|
||||
final int size = this.inflight.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
try {
|
||||
this.inflight.get(i).join();
|
||||
} catch (CompletionException | CancellationException _) {
|
||||
}
|
||||
}
|
||||
this.inflight.clear();
|
||||
this.pruneAt = this.window;
|
||||
}
|
||||
|
||||
public int submitted() {
|
||||
return this.submitted;
|
||||
}
|
||||
|
||||
public int failures() {
|
||||
return this.failures;
|
||||
}
|
||||
|
||||
public Throwable firstFailure() {
|
||||
return this.firstFailure;
|
||||
}
|
||||
|
||||
public boolean isDesynced() {
|
||||
return this.desynced;
|
||||
}
|
||||
|
||||
private void fill() {
|
||||
if (!this.started || this.closed) {
|
||||
return;
|
||||
}
|
||||
if (this.next < this.cursor) {
|
||||
this.next = this.cursor;
|
||||
}
|
||||
final int size = this.slots.size();
|
||||
while (this.ahead < this.window && this.next < size) {
|
||||
final Slot<K, V> slot = this.slots.get(this.next++);
|
||||
if (slot.task == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
slot.future = this.submitter.apply(slot);
|
||||
} catch (RuntimeException e) {
|
||||
fail(e);
|
||||
continue;
|
||||
}
|
||||
pruneInflight();
|
||||
this.inflight.add(slot.future);
|
||||
this.submitted++;
|
||||
this.ahead++;
|
||||
}
|
||||
}
|
||||
|
||||
private void pruneInflight() {
|
||||
if (this.inflight.size() < this.pruneAt) {
|
||||
return;
|
||||
}
|
||||
this.inflight.removeIf(CompletableFuture::isDone);
|
||||
this.pruneAt = Math.max(this.window, (int) Math.min(Integer.MAX_VALUE, 2L * this.inflight.size()));
|
||||
}
|
||||
|
||||
private void release(Slot<K, V> slot) {
|
||||
slot.discarded = true;
|
||||
if (slot.future != null) {
|
||||
this.ahead--;
|
||||
slot.future.thenAccept(this.sink);
|
||||
}
|
||||
}
|
||||
|
||||
private V join(Slot<K, V> slot) {
|
||||
if (slot.future == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return slot.future.join();
|
||||
} catch (CompletionException e) {
|
||||
fail(e.getCause() != null ? e.getCause() : e);
|
||||
} catch (CancellationException e) {
|
||||
fail(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void fail(Throwable t) {
|
||||
this.failures++;
|
||||
if (this.firstFailure == null) {
|
||||
this.firstFailure = t;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Slot<K, V> implements Supplier<V> {
|
||||
|
||||
final K key;
|
||||
final Callable<? extends V> task;
|
||||
CompletableFuture<V> future;
|
||||
volatile boolean discarded;
|
||||
|
||||
Slot(K key, Callable<? extends V> task) {
|
||||
this.key = key;
|
||||
this.task = task;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V get() {
|
||||
if (this.discarded) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return this.task.call();
|
||||
} catch (RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new CompletionException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@ package com.gtnewhorizons.angelica.utils;
|
||||
|
||||
import net.minecraft.client.renderer.texture.TextureUtil;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt;
|
||||
|
||||
public final class SpritePadding {
|
||||
|
||||
private static int[][] scratch;
|
||||
@@ -20,6 +24,86 @@ public final class SpritePadding {
|
||||
return 1 << mipmapLevels;
|
||||
}
|
||||
|
||||
public static int gutterForLevel(int gutter, int level) {
|
||||
return gutter >> level;
|
||||
}
|
||||
|
||||
public static void writePaddedLevel(int[] src, int levelW, int levelH, int gutter, long dstAddress,
|
||||
int dstStrideBytes, int dstX, int dstY, int clipY0, int clipY1, boolean swapRB) {
|
||||
writeLevel(src, levelW, levelH, gutter, levelH, null, 0, 0, dstAddress, dstStrideBytes, dstX, dstY, clipY0,
|
||||
clipY1, swapRB);
|
||||
}
|
||||
|
||||
private static void writeLevel(int[] src, int levelW, int levelH, int gutter, int availableRows,
|
||||
int[] dstArray, int dstArrayStride, int dstArrayOffset, long dstAddress, int dstStrideBytes, int dstX,
|
||||
int dstY, int clipY0, int clipY1, boolean swapRB) {
|
||||
final int paddedH = levelH + 2 * gutter;
|
||||
final int rowStart = Math.max(0, clipY0 - dstY);
|
||||
final int rowEnd = Math.min(paddedH, clipY1 - dstY);
|
||||
final int lastAvailableRow = availableRows - 1;
|
||||
|
||||
for (int py = rowStart; py < rowEnd; py++) {
|
||||
int cy = clampCoord(py - gutter, levelH);
|
||||
if (cy > lastAvailableRow) {
|
||||
cy = lastAvailableRow;
|
||||
}
|
||||
if (cy < 0) {
|
||||
continue;
|
||||
}
|
||||
final int rowBase = cy * levelW;
|
||||
final int firstValue = src[rowBase];
|
||||
final int lastValue = src[rowBase + levelW - 1];
|
||||
|
||||
if (dstArray != null) {
|
||||
final int rowOffset = dstArrayOffset + (dstY + py) * dstArrayStride + dstX;
|
||||
Arrays.fill(dstArray, rowOffset, rowOffset + gutter, firstValue);
|
||||
System.arraycopy(src, rowBase, dstArray, rowOffset + gutter, levelW);
|
||||
Arrays.fill(dstArray, rowOffset + gutter + levelW, rowOffset + gutter + levelW + gutter, lastValue);
|
||||
} else {
|
||||
final long rowAddress = dstAddress + (long) (dstY + py) * dstStrideBytes + (long) dstX * 4;
|
||||
final long interiorAddress = rowAddress + (long) gutter * 4;
|
||||
final long rightAddress = interiorAddress + (long) levelW * 4;
|
||||
if (swapRB) {
|
||||
final int firstSwapped = swapRedBlue(firstValue);
|
||||
final int lastSwapped = swapRedBlue(lastValue);
|
||||
for (int i = 0; i < gutter; i++) {
|
||||
memPutInt(rowAddress + (long) i * 4, firstSwapped);
|
||||
}
|
||||
for (int i = 0; i < levelW; i++) {
|
||||
memPutInt(interiorAddress + (long) i * 4, swapRedBlue(src[rowBase + i]));
|
||||
}
|
||||
for (int i = 0; i < gutter; i++) {
|
||||
memPutInt(rightAddress + (long) i * 4, lastSwapped);
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < gutter; i++) {
|
||||
memPutInt(rowAddress + (long) i * 4, firstValue);
|
||||
}
|
||||
for (int i = 0; i < levelW; i++) {
|
||||
memPutInt(interiorAddress + (long) i * 4, src[rowBase + i]);
|
||||
}
|
||||
for (int i = 0; i < gutter; i++) {
|
||||
memPutInt(rightAddress + (long) i * 4, lastValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int swapRedBlue(int argb) {
|
||||
return (argb & 0xFF00FF00) | ((argb & 0x00FF0000) >>> 16) | ((argb & 0x000000FF) << 16);
|
||||
}
|
||||
|
||||
private static int clampCoord(int coord, int limit) {
|
||||
if (coord < 0) {
|
||||
return 0;
|
||||
}
|
||||
if (coord >= limit) {
|
||||
return limit - 1;
|
||||
}
|
||||
return coord;
|
||||
}
|
||||
|
||||
public static void uploadPadded(int[][] frameData, int width, int height, int originX, int originY, int gutter,
|
||||
boolean blur, boolean clamp) {
|
||||
if (gutter <= 0) {
|
||||
@@ -45,9 +129,10 @@ public final class SpritePadding {
|
||||
|
||||
final int levelWidth = width >> level;
|
||||
final int levelHeight = height >> level;
|
||||
final int levelGutter = gutter >> level;
|
||||
final int levelGutter = gutterForLevel(gutter, level);
|
||||
final int stride = levelWidth + 2 * levelGutter;
|
||||
final int size = stride * (levelHeight + 2 * levelGutter);
|
||||
final int paddedHeight = levelHeight + 2 * levelGutter;
|
||||
final int size = stride * paddedHeight;
|
||||
|
||||
int[] target = padded[level];
|
||||
if (target == null || target.length < size) {
|
||||
@@ -55,44 +140,10 @@ public final class SpritePadding {
|
||||
padded[level] = target;
|
||||
}
|
||||
|
||||
int remaining = Math.min(levelData.length, levelWidth * levelHeight);
|
||||
for (int y = 0; y < levelHeight && remaining > 0; y++) {
|
||||
final int run = Math.min(levelWidth, remaining);
|
||||
System.arraycopy(levelData, y * levelWidth, target,
|
||||
(y + levelGutter) * stride + levelGutter, run);
|
||||
remaining -= run;
|
||||
}
|
||||
clampBorderToEdge(target, stride, levelHeight + 2 * levelGutter, levelGutter);
|
||||
final int availableRows = levelWidth > 0 ? Math.min(levelHeight, levelData.length / levelWidth) : 0;
|
||||
writeLevel(levelData, levelWidth, levelHeight, levelGutter, availableRows, target, stride, 0, 0L, 0, 0,
|
||||
0, 0, paddedHeight, false);
|
||||
}
|
||||
return padded;
|
||||
}
|
||||
|
||||
private static void clampBorderToEdge(int[] image, int paddedWidth, int paddedHeight, int border) {
|
||||
if (border <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
final int contentWidth = paddedWidth - 2 * border;
|
||||
final int contentHeight = paddedHeight - 2 * border;
|
||||
if (contentWidth <= 0 || contentHeight <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int y = 0; y < contentHeight; y++) {
|
||||
final int row = border + (y + border) * paddedWidth;
|
||||
final int left = image[row];
|
||||
final int right = image[row + contentWidth - 1];
|
||||
for (int i = 1; i <= border; i++) {
|
||||
image[row - i] = left;
|
||||
image[row + contentWidth - 1 + i] = right;
|
||||
}
|
||||
}
|
||||
|
||||
final int top = border * paddedWidth;
|
||||
final int bottom = (border + contentHeight - 1) * paddedWidth;
|
||||
for (int i = 1; i <= border; i++) {
|
||||
System.arraycopy(image, top, image, top - i * paddedWidth, paddedWidth);
|
||||
System.arraycopy(image, bottom, image, bottom + i * paddedWidth, paddedWidth);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@ package com.prupe.mcpatcher.mal.resource;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -31,8 +32,7 @@ public class ResourceList {
|
||||
private static final Map<IResourcePack, Integer> resourcePackOrder = new WeakHashMap<>();
|
||||
|
||||
private final IResourcePack resourcePack;
|
||||
private final Set<ResourceLocationWithSource> allResources = new TreeSet<>(
|
||||
new ResourceLocationWithSource.Comparator1());
|
||||
private final Map<ResourceLocationWithSource, ResourceLocationWithSource> resources = new HashMap<>();
|
||||
|
||||
public static ResourceList getInstance() {
|
||||
if (instance == null) {
|
||||
@@ -43,7 +43,7 @@ public class ResourceList {
|
||||
resourcePackOrder.put(resourcePack, order);
|
||||
order--;
|
||||
}
|
||||
instance = new ResourceList();
|
||||
instance = new ResourceList(resourcePacks);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
@@ -57,9 +57,9 @@ public class ResourceList {
|
||||
return i == null ? Integer.MAX_VALUE : i;
|
||||
}
|
||||
|
||||
private ResourceList() {
|
||||
private ResourceList(List<IResourcePack> resourcePacks) {
|
||||
this.resourcePack = null;
|
||||
for (IResourcePack resourcePack : TexturePackAPI.getResourcePacks(null)) {
|
||||
for (IResourcePack resourcePack : resourcePacks) {
|
||||
ResourceList sublist;
|
||||
if (resourcePack instanceof FileResourcePack) {
|
||||
sublist = new ResourceList((FileResourcePack) resourcePack);
|
||||
@@ -70,12 +70,15 @@ public class ResourceList {
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
allResources.removeAll(sublist.allResources);
|
||||
allResources.addAll(sublist.allResources);
|
||||
for (ResourceLocationWithSource resource : sublist.resources.values()) {
|
||||
resources.put(resource, resource);
|
||||
}
|
||||
}
|
||||
logger.fine("new %s", this);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
for (ResourceLocationWithSource resource : allResources) {
|
||||
List<ResourceLocationWithSource> sorted = new ArrayList<>(resources.values());
|
||||
sorted.sort(new ResourceLocationWithSource.Comparator1());
|
||||
for (ResourceLocationWithSource resource : sorted) {
|
||||
logger.finest(
|
||||
"%s -> %s",
|
||||
resource,
|
||||
@@ -120,7 +123,7 @@ public class ResourceList {
|
||||
addResource(resource, file.isFile(), file.isDirectory());
|
||||
}
|
||||
}
|
||||
if (!allResources.isEmpty()) {
|
||||
if (!resources.isEmpty()) {
|
||||
logger.fine("new %s", this);
|
||||
}
|
||||
}
|
||||
@@ -147,7 +150,9 @@ public class ResourceList {
|
||||
if (zipFile == null) {
|
||||
return;
|
||||
}
|
||||
for (ZipEntry entry : Collections.list(zipFile.entries())) {
|
||||
Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String path = entry.getName();
|
||||
ResourceLocation resource = TexturePackAPI.parsePath(path);
|
||||
if (resource != null) {
|
||||
@@ -173,16 +178,20 @@ public class ResourceList {
|
||||
|
||||
private void addResource(ResourceLocation resource, boolean isFile, boolean isDirectory) {
|
||||
if (isFile) {
|
||||
allResources.add(new ResourceLocationWithSource(resourcePack, resource));
|
||||
put(new ResourceLocationWithSource(resourcePack, resource));
|
||||
} else if (isDirectory) {
|
||||
if (!resource.getResourcePath()
|
||||
.endsWith("/")) {
|
||||
resource = new ResourceLocation(resource.getResourceDomain(), resource.getResourcePath() + '/');
|
||||
}
|
||||
allResources.add(new ResourceLocationWithSource(resourcePack, resource));
|
||||
put(new ResourceLocationWithSource(resourcePack, resource));
|
||||
}
|
||||
}
|
||||
|
||||
private void put(ResourceLocationWithSource resource) {
|
||||
resources.putIfAbsent(resource, resource);
|
||||
}
|
||||
|
||||
public List<ResourceLocation> listResources(String directory, String suffix, boolean sortByFilename) {
|
||||
return listResources(directory, suffix, true, false, sortByFilename);
|
||||
}
|
||||
@@ -206,7 +215,7 @@ public class ResourceList {
|
||||
Set<ResourceLocationWithSource> tmpList = new TreeSet<>(
|
||||
new ResourceLocationWithSource.Comparator1(true, sortByFilename ? suffix : null));
|
||||
boolean allNamespaces = MCPatcherUtils.isNullOrEmpty(namespace);
|
||||
for (ResourceLocationWithSource resource : allResources) {
|
||||
for (ResourceLocationWithSource resource : resources.values()) {
|
||||
if (directories != resource.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
@@ -244,7 +253,7 @@ public class ResourceList {
|
||||
int fileCount = 0;
|
||||
int directoryCount = 0;
|
||||
Set<String> namespaces = new HashSet<>();
|
||||
for (ResourceLocationWithSource resource : allResources) {
|
||||
for (ResourceLocationWithSource resource : resources.values()) {
|
||||
if (resource.isDirectory()) {
|
||||
directoryCount++;
|
||||
} else {
|
||||
|
||||
Reference in new issue
Block a user