Compare commits

...
Author SHA1 Message Date
Alexdoru 8e26a0179b Speedup block transformer by transforming every class directly (#1420)
* speedup block transformer by transforming every class directly

* stop using the cstpoolparser.add method
2026-02-24 15:45:35 +01:00
Alexdoru 1d96af8e3a re-enable Block Transformer when not running with rfb (#1418) 2026-02-23 14:58:40 -08:00
Yan Huang f7eb86cdb6 Parallelizing CTMUtils (#1393) 2026-02-23 20:21:35 +00:00
Alexdoru b38fafa831 ASM redirectors micro optimizations (#1416)
* redirector transformer micro optimizations

* use map for block fields redirect
2026-02-23 20:20:38 +01:00
Jason Mitchell 7dc2625f8c Maybe less leaky (#1414) 2026-02-23 08:57:21 -08:00
9 changed files with 246 additions and 195 deletions

No files matched your search

@@ -142,6 +142,9 @@ public class AngelicaTweaker implements IFMLLoadingPlugin, IEarlyMixinLoader {
boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE;
if (!rfbLoaded) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.AngelicaLateTweaker");
if (AngelicaConfig.enableCeleritas) {
tweaks.add("com.gtnewhorizons.angelica.loading.fml.tweakers.CeleritasLateTweaker");
}
}
}
}
@@ -2,26 +2,25 @@ package com.gtnewhorizons.angelica.loading.fml.transformers;
import com.gtnewhorizons.angelica.loading.AngelicaTweaker;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.AngelicaRedirector;
import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.tree.ClassNode;
public class SodiumBlockTransformer implements IClassTransformer {
public class CeleritasBlockTransformer implements IClassTransformer {
private final SodiumBlockTransform inner;
private final CeleritasBlockTransform inner;
private final String[] exclusions;
public SodiumBlockTransformer() {
this.inner = new SodiumBlockTransform(AngelicaTweaker.isObfEnv());
public CeleritasBlockTransformer() {
this.inner = new CeleritasBlockTransform(AngelicaTweaker.isObfEnv());
this.exclusions = inner.getTransformerExclusions();
this.inner.setCeleritasSetting();
}
/**
* Delete the global vanilla bounding box fields off the Block object. {@link AngelicaRedirector}
* Delete the global vanilla bounding box fields off the Block object. {@link CeleritasBlockTransform}
* replaces these with a thread-safe alternative.
*/
@Override
@@ -31,10 +30,6 @@ public class SodiumBlockTransformer implements IClassTransformer {
if (transformedName.startsWith(exclusion)) return basicClass;
}
if (!inner.shouldTransform(basicClass)) {
return basicClass;
}
final ClassReader cr = new ClassReader(basicClass);
final ClassNode cn = new ClassNode();
cr.accept(cn, 0);
@@ -0,0 +1,35 @@
package com.gtnewhorizons.angelica.loading.fml.tweakers;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.Launch;
import net.minecraft.launchwrapper.LaunchClassLoader;
import java.io.File;
import java.util.List;
public class CeleritasLateTweaker implements ITweaker {
@Override
public void acceptOptions(List<String> args, File gameDir, File assetsDir, String profile) {
// no-op
}
@Override
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
// no-op
}
@Override
public String getLaunchTarget() {
return null;
}
@Override
public String[] getLaunchArguments() {
String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.CeleritasBlockTransformer";
FMLRelaunchLog.finer("Registering transformer %s", transformer);
Launch.classLoader.registerTransformer(transformer);
return new String[0];
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.loading.rfb;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBAngelicaRedirector;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBSodiumBlockTransformer;
import com.gtnewhorizons.angelica.loading.rfb.transformers.RFBCeleritasBlockTransformer;
import com.gtnewhorizons.retrofuturabootstrap.api.PluginContext;
import com.gtnewhorizons.retrofuturabootstrap.api.RetroFuturaBootstrap;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
@@ -27,7 +27,7 @@ public class AngelicaRfbPlugin implements RfbPlugin {
final boolean isObf = RetroFuturaBootstrap.API.launchClassLoader().findClassMetadata("net.minecraft.world.World") == null;
return new RfbClassTransformer[] {
new RFBAngelicaRedirector(),
new RFBSodiumBlockTransformer(isObf)
new RFBCeleritasBlockTransformer(isObf)
};
}
}
@@ -1,7 +1,7 @@
package com.gtnewhorizons.angelica.loading.rfb.transformers;
import com.gtnewhorizons.angelica.loading.shared.AngelicaClassDump;
import com.gtnewhorizons.angelica.loading.shared.transformers.SodiumBlockTransform;
import com.gtnewhorizons.angelica.loading.shared.transformers.CeleritasBlockTransform;
import com.gtnewhorizons.retrofuturabootstrap.api.ClassNodeHandle;
import com.gtnewhorizons.retrofuturabootstrap.api.ExtensibleClassLoader;
import com.gtnewhorizons.retrofuturabootstrap.api.RfbClassTransformer;
@@ -11,12 +11,12 @@ import org.jetbrains.annotations.Nullable;
import java.util.jar.Manifest;
public class RFBSodiumBlockTransformer implements RfbClassTransformer {
public class RFBCeleritasBlockTransformer implements RfbClassTransformer {
private final SodiumBlockTransform inner;
private final CeleritasBlockTransform inner;
public RFBSodiumBlockTransformer(boolean isObf) {
inner = new SodiumBlockTransform(isObf);
public RFBCeleritasBlockTransformer(boolean isObf) {
inner = new CeleritasBlockTransform(isObf);
}
@Pattern("[a-z0-9-]+")
@@ -44,14 +44,7 @@ public class RFBSodiumBlockTransformer implements RfbClassTransformer {
public boolean shouldTransformClass(@NotNull ExtensibleClassLoader classLoader,
@NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className,
@NotNull ClassNodeHandle classNode) {
if (!classNode.isPresent()) {
return false;
}
if (!classNode.isOriginal()) {
// If a class is already a transformed ClassNode, conservatively continue processing.
return true;
}
return inner.shouldTransform(classNode.getOriginalBytes());
return classNode.isPresent();
}
@Override
@@ -1,31 +1,23 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* This transformer redirects many GL calls to our custom GLStateManager
@@ -73,10 +65,10 @@ public final class AngelicaRedirector {
"initializeTextures", "func_77474_a"
);
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(GL11, GL12, GL13, GL14, GL20, OpenGlHelper, EXTBlendFunc, ARBMultiTexture, Project);
private static final Map<String, Map<String, String>> methodRedirects = new HashMap<>();
private static final Map<String, Map<String, String>> interfaceRedirects = new HashMap<>();
private static final Map<Integer, String> glCapRedirects = new HashMap<>();
private static final ClassConstantPoolParser cstPoolParser;
static {
glCapRedirects.put(org.lwjgl.opengl.GL11.GL_ALPHA_TEST, "AlphaTest");
@@ -302,17 +294,27 @@ public final class AngelicaRedirector {
.add("glBindVertexArray")
);
cstPoolParser.addString(UniversalVAO);
cstPoolParser.addString(VaoFunctions);
cstPoolParser.addString(LWJGLService);
final List<String> stringsToSearch = new ArrayList<>();
stringsToSearch.add(GL11);
stringsToSearch.add(GL12);
stringsToSearch.add(GL13);
stringsToSearch.add(GL14);
stringsToSearch.add(GL20);
stringsToSearch.add(OpenGlHelper);
stringsToSearch.add(EXTBlendFunc);
stringsToSearch.add(ARBMultiTexture);
stringsToSearch.add(Project);
stringsToSearch.add(UniversalVAO);
stringsToSearch.add(VaoFunctions);
stringsToSearch.add(LWJGLService);
final String glPrefix = "org/lwjgl/opengl/GL";
for (var entry : new HashMap<>(methodRedirects).entrySet()) {
if (entry.getKey().startsWith(glPrefix)) {
methodRedirects.put(entry.getKey() + "C", entry.getValue());
cstPoolParser.addString(entry.getKey() + "C");
stringsToSearch.add(entry.getKey() + "C");
}
}
cstPoolParser = new ClassConstantPoolParser(stringsToSearch.toArray(new String[0]));
}
public String[] getTransformerExclusions() {
@@ -331,19 +333,17 @@ public final class AngelicaRedirector {
/** @return Was the class changed? */
public boolean transformClassNode(String transformedName, ClassNode cn) {
if (cn == null) {
return false;
}
boolean changed = false;
final boolean isOpenGlHelper = transformedName.equals("net.minecraft.client.renderer.OpenGlHelper");
final boolean isUniversalVAO = transformedName.startsWith(UniversalVAODot);
for (MethodNode mn : cn.methods) {
if (transformedName.equals("net.minecraft.client.renderer.OpenGlHelper") && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) {
if (isOpenGlHelper && (mn.name.equals("glBlendFunc") || mn.name.equals("func_148821_a"))) {
continue;
}
boolean redirectInMethod = false;
for (AbstractInsnNode node : mn.instructions.toArray()) {
if (node instanceof MethodInsnNode mNode) {
if ((mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable")) && mNode.desc.equals("(I)V")) {
if (mNode.desc.equals("(I)V") && (mNode.owner.equals(GL11) || mNode.owner.equals(GL11C)) && (mNode.name.equals("glEnable") || mNode.name.equals("glDisable"))) {
final AbstractInsnNode prevNode = node.getPrevious();
String name = null;
if (prevNode instanceof LdcInsnNode ldcNode) {
@@ -373,7 +373,7 @@ public final class AngelicaRedirector {
}
changed = true;
redirectInMethod = true;
} else if (mNode.owner.startsWith(Drawable) && mNode.name.equals("makeCurrent")) {
} else if (mNode.name.equals("makeCurrent") && mNode.owner.startsWith(Drawable)) {
mNode.setOpcode(Opcodes.INVOKESTATIC);
mNode.owner = GLStateManager;
mNode.desc = "(L" + Drawable + ";)V";
@@ -387,7 +387,7 @@ public final class AngelicaRedirector {
if (redirects != null) {
final String glsmName = redirects.get(mNode.name);
// Skip VAO method redirects inside UniversalVAO
if (glsmName != null && !(transformedName.startsWith(UniversalVAODot) && UniversalVAOSkippedMethods.contains(glsmName))) {
if (glsmName != null && !(isUniversalVAO && UniversalVAOSkippedMethods.contains(glsmName))) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, mNode.desc);
@@ -403,7 +403,7 @@ public final class AngelicaRedirector {
final Map<String, String> ifaceRedirects = interfaceRedirects.get(mNode.owner);
if (ifaceRedirects != null) {
final String glsmName = ifaceRedirects.get(mNode.name);
if (glsmName != null && !(transformedName.startsWith(UniversalVAODot) && UniversalVAOSkippedMethods.contains(glsmName))) {
if (glsmName != null && !(isUniversalVAO && UniversalVAOSkippedMethods.contains(glsmName))) {
if (LOG_SPAM) {
final String shortOwner = mNode.owner.substring(mNode.owner.lastIndexOf("/") + 1);
LOGGER.info("Redirecting interface call in {} from {}.{}{} to GLStateManager.{}{}", transformedName, shortOwner, mNode.name, mNode.desc, glsmName, "(I)V");
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.loading.shared.transformers;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizon.gtnhlib.asm.ClassConstantPoolParser;
import net.minecraft.launchwrapper.Launch;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.logging.log4j.LogManager;
@@ -18,32 +17,40 @@ import org.objectweb.asm.tree.MethodNode;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class SodiumBlockTransform {
public final class CeleritasBlockTransform {
public SodiumBlockTransform(boolean isObf) {
this.IS_OBF = isObf;
private final List<String> blockFieldNames = new ArrayList<>();
private final Map<String, String> blockFieldRedirects = new HashMap<>();
public CeleritasBlockTransform(boolean isObf) {
final List<Pair<String, String>> mappings = ImmutableList.of(
Pair.of("minX", "field_149759_B"),
Pair.of("minY", "field_149760_C"),
Pair.of("minZ", "field_149754_D"),
Pair.of("maxX", "field_149755_E"),
Pair.of("maxY", "field_149756_F"),
Pair.of("maxZ", "field_149757_G")
);
for (Pair<String, String> pair : mappings) {
final String name = isObf ? pair.getRight() : pair.getLeft();
this.blockFieldNames.add(name);
this.blockFieldRedirects.put(name, pair.getLeft());
}
}
private final boolean IS_OBF;
private static final boolean LOG_SPAM = Boolean.getBoolean("angelica.redirectorLogspam");
private static final Logger LOGGER = LogManager.getLogger("SodiumBlockTransformer");
private static final Logger LOGGER = LogManager.getLogger("CeleritasBlockTransformer");
private static final String BlockClass = "net/minecraft/block/Block";
private static final String BlockPackage = "net/minecraft/block/Block";
private static final String ThreadedBlockData = "com/gtnewhorizons/angelica/glsm/ThreadedBlockData";
private static final List<Pair<String, String>> BlockBoundsFields = ImmutableList.of(
Pair.of("minX", "field_149759_B"),
Pair.of("minY", "field_149760_C"),
Pair.of("minZ", "field_149754_D"),
Pair.of("maxX", "field_149755_E"),
Pair.of("maxY", "field_149756_F"),
Pair.of("maxZ", "field_149757_G")
);
/** All classes in <tt>net.minecraft.block.*</tt> are the block subclasses save for these. */
private static final String[] VanillaBlockExclusions = {
"net/minecraft/block/IGrowable",
@@ -53,7 +60,6 @@ public class SodiumBlockTransform {
"net/minecraft/block/material/"
};
private static final ClassConstantPoolParser cstPoolParser = new ClassConstantPoolParser(BlockPackage);
private static final Set<String> moddedBlockSubclasses = Collections.newSetFromMap(new ConcurrentHashMap<>());
// Block owners we *shouldn't* redirect because they shadow one of our fields
private static final Set<String> blockOwnerExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>());
@@ -95,10 +101,6 @@ public class SodiumBlockTransform {
return isVanillaBlockSubclass(className) || moddedBlockSubclasses.contains(className);
}
private String getFieldName(Pair<String, String> fieldPair) {
return IS_OBF ? fieldPair.getRight() : fieldPair.getLeft();
}
public String[] getTransformerExclusions() {
return new String[]{
"org.lwjgl",
@@ -109,50 +111,32 @@ public class SodiumBlockTransform {
};
}
public boolean shouldTransform(byte[] basicClass) {
return cstPoolParser.find(basicClass, true);
}
/** @return Was the class changed? */
public boolean transformClassNode(String transformedName, ClassNode cn) {
if (cn == null) {
return false;
}
if ("net.minecraft.block.Block".equals(transformedName) && isCeleritasEnabled()) {
cn.fields.removeIf(field -> BlockBoundsFields.stream().anyMatch(pair -> field.name.equals(pair.getLeft()) || field.name.equals(pair.getRight())));
cn.fields.removeIf(field -> blockFieldNames.stream().anyMatch(name -> field.name.equals(name)));
}
// Track subclasses of Block
if (!isVanillaBlockSubclass(cn.name) && isBlockSubclass(cn.superName)) {
moddedBlockSubclasses.add(cn.name);
cstPoolParser.addString(cn.name);
}
// Check if this class shadows any fields of the parent class
if (moddedBlockSubclasses.contains(cn.name)) {
// If a superclass shadows, then so do we, because JVM will resolve a reference on our class to that
// superclass
boolean doWeShadow;
boolean doWeShadow = false;
if (blockOwnerExclusions.contains(cn.superName)) {
doWeShadow = true;
} else {
// Check if we declare any known field names
boolean b = false;
for (Pair<String, String> pair : BlockBoundsFields) {
boolean result = false;
for (FieldNode field : cn.fields) {
if (field.name.equals(getFieldName(pair))) {
result = true;
break;
}
}
if (result) {
b = true;
for (FieldNode field : cn.fields) {
if (blockFieldNames.contains(field.name)) {
doWeShadow = true;
break;
}
}
doWeShadow = b;
}
if (doWeShadow) {
LOGGER.info("Class '{}' shadows one or more block bounds fields, these accesses won't be redirected!", cn.name);
@@ -160,21 +144,22 @@ public class SodiumBlockTransform {
}
}
if (!isCeleritasEnabled()) {
return false;
}
boolean changed = false;
for (MethodNode mn : cn.methods) {
for (AbstractInsnNode node : mn.instructions.toArray()) {
if ((node.getOpcode() == Opcodes.GETFIELD || node.getOpcode() == Opcodes.PUTFIELD) && node instanceof FieldInsnNode fNode) {
if (!blockOwnerExclusions.contains(fNode.owner) && isBlockSubclass(fNode.owner) && isCeleritasEnabled()) {
Pair<String, String> fieldToRedirect = BlockBoundsFields.stream()
.filter(pair -> fNode.name.equals(getFieldName(pair)))
.findFirst()
.orElse(null);
if (fieldToRedirect != null) {
if (!blockOwnerExclusions.contains(fNode.owner) && isBlockSubclass(fNode.owner)) {
String fieldRedirect = blockFieldRedirects.get(fNode.name);
if (fieldRedirect != null) {
if (LOG_SPAM) {
LOGGER.info("Redirecting Block.{} in {} to thread-safe wrapper", fNode.name, transformedName);
}
// Perform the redirect
fNode.name = fieldToRedirect.getLeft(); // use unobfuscated name
fNode.name = fieldRedirect; // use unobfuscated name
fNode.owner = ThreadedBlockData;
// Inject getter before the field access, to turn Block -> ThreadedBlockData
final MethodInsnNode getter = new MethodInsnNode(Opcodes.INVOKESTATIC, ThreadedBlockData, "get", "(L" + BlockClass + ";)L" + ThreadedBlockData + ";", false);
@@ -230,6 +230,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
private int renderCulledTileEntities(TileEntityRenderContext renderContext) {
int count = 0;
sortedTileEntities.clear();
SortedRenderLists renderLists = renderSectionManager.getRenderLists();
Iterator<ChunkRenderList> renderListIterator = renderLists.iterator();
@@ -7,8 +7,8 @@ import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.StampedLock;
import net.minecraft.block.Block;
import net.minecraft.util.IIcon;
@@ -33,19 +33,36 @@ public class CTMUtils {
private static final MCLogger logger = MCLogger.getLogger(MCLogger.Category.CONNECTED_TEXTURES, "CTM");
private static final List<TileOverride> allOverrides = new ArrayList<>();
private static final Map<Block, List<BlockStateMatcher>> blockOverrides = new IdentityHashMap<>();
private static final Map<String, List<TileOverride>> tileOverrides = new HashMap<>();
private static class Overrides {
private final List<TileOverride> all = new ArrayList<>();
private final Map<Block, List<BlockStateMatcher>> block = new IdentityHashMap<>();
private final Map<String, List<TileOverride>> tile = new HashMap<>();
}
private static Overrides overrides = new Overrides();
private static Overrides newOverrides = null;
private static TileLoader tileLoader;
private static TileOverride lastOverride;
private static final Lock lock = new ReentrantLock();
private static final StampedLock lock = new StampedLock();
private static final TileOverrideIterator.IJK ijkIterator = newIJKIterator();
private static final TileOverrideIterator.Metadata metadataIterator = newMetadataIterator();
private static class StateAndIterator {
private final TileOverrideIterator.IJK ijkIterator = CTMUtils.newIJKIterator();
private final TileOverrideIterator.Metadata metadataIterator = CTMUtils.newMetadataIterator();
private final BlockOrientation renderBlockState = new BlockOrientation();
private final int texturePackChangeCounter;
private static boolean haveBlockFace;
private static final BlockOrientation renderBlockState = new BlockOrientation();
public StateAndIterator() {
this.texturePackChangeCounter = 0;
}
public StateAndIterator(int texturePackChangeCounter) {
this.texturePackChangeCounter = texturePackChangeCounter;
}
}
private static final ThreadLocal<StateAndIterator> stateAndIterator = ThreadLocal.withInitial(StateAndIterator::new);
private static final AtomicInteger texturePackChangeCounter = new AtomicInteger(0);
static {
try {
@@ -61,7 +78,7 @@ public class CTMUtils {
@Override
public void beforeChange() {
lock.lock();
long stamp = lock.writeLock();
try {
RenderPassAPI.instance.clear();
try {
@@ -71,39 +88,39 @@ public class CTMUtils {
} catch (Exception e) {
e.printStackTrace();
}
renderBlockState.clear();
ijkIterator.clear();
metadataIterator.clear();
allOverrides.clear();
blockOverrides.clear();
tileOverrides.clear();
lastOverride = null;
RenderBlocksUtils.blankIcon = null;
tileLoader = new TileLoader("textures/blocks", logger);
RenderPassAPI.instance.refreshBlendingOptions();
logger.info("loading CTM overrides");
newOverrides = new Overrides();
if (MCPatcherForgeConfig.ConnectedTextures.standard || MCPatcherForgeConfig.ConnectedTextures.nonStandard) {
for (ResourceLocation resource : ResourceList.getInstance()
.listResources(TexturePackAPI.MCPATCHER_SUBDIR + "ctm", ".properties", true)) {
registerOverride(TileOverride.create(resource, tileLoader));
registerOverrideWithoutLock(newOverrides, TileOverride.create(resource, tileLoader));
}
}
for (ResourceLocation resource : BlendMethod.getAllBlankResources()) {
tileLoader.preloadTile(resource, false);
}
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
@Override
public void afterChange() {
lock.lock();
if (newOverrides == null) {
logger.error("CTM overrides were not initialized during texture pack change");
logger.error("Maybe beforeChange was not called, or threw an exception?");
return;
}
long stamp = lock.writeLock();
try {
for (TileOverride override : allOverrides) {
for (TileOverride override : newOverrides.all) {
override.registerIcons();
}
for (Map.Entry<Block, List<BlockStateMatcher>> entry : blockOverrides.entrySet()) {
for (Map.Entry<Block, List<BlockStateMatcher>> entry : newOverrides.block.entrySet()) {
for (BlockStateMatcher matcher : entry.getValue()) {
TileOverride override = (TileOverride) matcher.getData();
if (override.getRenderPass() >= 0) {
@@ -111,67 +128,90 @@ public class CTMUtils {
}
}
}
for (List<BlockStateMatcher> overrides : blockOverrides.values()) {
for (List<BlockStateMatcher> overrides : newOverrides.block.values()) {
overrides.sort((m1, m2) -> {
TileOverride o1 = (TileOverride) m1.getData();
TileOverride o2 = (TileOverride) m2.getData();
return o1.compareTo(o2);
});
}
for (List<TileOverride> overrides : tileOverrides.values()) {
for (List<TileOverride> overrides : newOverrides.tile.values()) {
Collections.sort(overrides);
}
setBlankResource();
setBlankResourceWithoutLock();
overrides = newOverrides;
newOverrides = null;
texturePackChangeCounter.getAndIncrement();
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
});
}
private static void clearBlockFace() {
haveBlockFace = false;
private static StateAndIterator getStateAndIterator() {
int globalTexturePackChangeCounter = texturePackChangeCounter.get();
StateAndIterator local = stateAndIterator.get();
if (local.texturePackChangeCounter < globalTexturePackChangeCounter) {
local = new StateAndIterator(globalTexturePackChangeCounter);
stateAndIterator.set(local);
}
return local;
}
private static IIcon getBlockIconWithoutLock(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
StateAndIterator local = getStateAndIterator();
if (blockAccess != null && checkFace(face)) {
local.renderBlockState.setBlock(block, blockAccess, x, y, z);
local.renderBlockState.setFace(face);
TileOverride lastOverride = local.ijkIterator.go(local.renderBlockState, icon);
if (lastOverride != null) {
return skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : local.ijkIterator.getIcon();
}
}
return skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
}
private static IIcon getBlockIconWithoutLock(IIcon icon, Block block, int face, int metadata) {
StateAndIterator local = getStateAndIterator();
if (checkFace(face) && checkRenderType(block)) {
local.renderBlockState.setBlockMetadata(block, metadata, face);
TileOverride lastOverride = local.metadataIterator.go(local.renderBlockState, icon);
if (lastOverride != null) {
return local.metadataIterator.getIcon();
}
}
return icon;
}
public static IIcon getBlockIcon(IIcon icon, Block block, IBlockAccess blockAccess,
int x, int y, int z, int face) {
lock.lock();
try {
lastOverride = null;
if (blockAccess != null && checkFace(face)) {
if (!haveBlockFace) {
renderBlockState.setBlock(block, blockAccess, x, y, z);
renderBlockState.setFace(face);
}
lastOverride = ijkIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = ijkIterator.getIcon();
}
long stamp = lock.tryOptimisticRead();
IIcon value = getBlockIconWithoutLock(icon, block, blockAccess, x, y, z, face);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
value = getBlockIconWithoutLock(icon, block, blockAccess, x, y, z, face);
} finally {
lock.unlockRead(stamp);
}
clearBlockFace();
IIcon result = lastOverride == null && skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : icon;
return result;
} finally {
lock.unlock();
}
return value;
}
public static IIcon getBlockIcon(IIcon icon, Block block, int face, int metadata) {
lock.lock();
try {
lastOverride = null;
if (checkFace(face) && checkRenderType(block)) {
renderBlockState.setBlockMetadata(block, metadata, face);
lastOverride = metadataIterator.go(renderBlockState, icon);
if (lastOverride != null) {
icon = metadataIterator.getIcon();
}
long stamp = lock.tryOptimisticRead();
IIcon value = getBlockIconWithoutLock(icon, block, face, metadata);
if (!lock.validate(stamp)) {
stamp = lock.readLock();
try {
value = getBlockIconWithoutLock(icon, block, face, metadata);
} finally {
lock.unlockRead(stamp);
}
return icon;
} finally {
lock.unlock();
}
return value;
}
public static IIcon getBlockIcon(IIcon icon, Block block, int face) {
@@ -197,56 +237,55 @@ public class CTMUtils {
return RenderPassAPI.instance.skipDefaultRendering(block);
}
private static void registerOverride(TileOverride override) {
lock.lock();
try {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
}
Block block = matcher.getBlock();
List<BlockStateMatcher> list = blockOverrides.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
private static void registerOverrideWithoutLock(Overrides overrides, TileOverride override) {
if (override != null && !override.isDisabled()) {
boolean registered = false;
List<BlockStateMatcher> matchingBlocks = override.getMatchingBlocks();
if (!MCPatcherUtils.isNullOrEmpty(matchingBlocks)) {
for (BlockStateMatcher matcher : matchingBlocks) {
if (matcher == null) {
continue;
}
}
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = tileOverrides.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
allOverrides.add(override);
Block block = matcher.getBlock();
List<BlockStateMatcher> list = overrides.block.computeIfAbsent(block, k -> new ArrayList<>());
list.add(matcher);
logger.fine("using %s for block %s", override, BlockAPI.getBlockName(block));
registered = true;
}
}
} finally {
lock.unlock();
Set<String> matchingTiles = override.getMatchingTiles();
if (!MCPatcherUtils.isNullOrEmpty(matchingTiles)) {
for (String name : matchingTiles) {
List<TileOverride> list = overrides.tile.computeIfAbsent(name, k -> new ArrayList<>());
list.add(override);
logger.fine("using %s for tile %s", override, name);
registered = true;
}
}
if (registered) {
overrides.all.add(override);
}
}
}
private static void setBlankResourceWithoutLock() {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
}
public static void setBlankResource() {
lock.lock();
long stamp = lock.writeLock();
try {
RenderBlocksUtils.blankIcon = tileLoader.getIcon(RenderPassAPI.instance.getBlankResource());
setBlankResourceWithoutLock();
} finally {
lock.unlock();
lock.unlockWrite(stamp);
}
}
private static TileOverrideIterator.IJK newIJKIterator() {
return new TileOverrideIterator.IJK(blockOverrides, tileOverrides);
return new TileOverrideIterator.IJK(overrides.block, overrides.tile);
}
private static TileOverrideIterator.Metadata newMetadataIterator() {
return new TileOverrideIterator.Metadata(blockOverrides, tileOverrides);
return new TileOverrideIterator.Metadata(overrides.block, overrides.tile);
}
}