Cut more per-frame allocations in terrain and rendering (#2193)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-10-02 22:06:57 -07:00
1 parent 85892c0f7f
commit d876a203da
46 files changed
+833 -150

No files matched your search

@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.client.font;
import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack;
import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer;
import com.gtnewhorizon.gtnhlib.util.font.FontRendering;
import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
@@ -48,9 +47,9 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetByte;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetFloat;
@@ -160,6 +159,7 @@ public class BatchingFontRenderer {
private static long vertexDataAddress = memAddress0(vertexData);
private static int vboCapacity;
private static final FloatBuffer FLUSH_MVP = memAllocFloat(16);
// OpenGL objects (static, can be used between multiple BatchingFontRenderer)
private static int vbo;
@@ -720,26 +720,23 @@ public class BatchingFontRenderer {
deferredSegments.get(0).owner.setupFontDrawState();
flushLastTexture = -1;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
boolean curDepthTest = GLStateManager.getDepthTest().isEnabled();
boolean curDepthMask = GLStateManager.isEffectiveDepthMaskEnabled();
for (final TextSegment segment : deferredSegments) {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, mvpBuf);
uploadLightmap(segment.owner.lightmapLocation, segment.lightmapActive, segment.lightmapU,
segment.lightmapV, segment.lightmapTexture);
if (segment.depthTest != curDepthTest) {
if (segment.depthTest) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
curDepthTest = segment.depthTest;
}
if (segment.depthMask != curDepthMask) {
GLStateManager.glDepthMask(segment.depthMask);
curDepthMask = segment.depthMask;
}
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
boolean curDepthTest = GLStateManager.getDepthTest().isEnabled();
boolean curDepthMask = GLStateManager.isEffectiveDepthMaskEnabled();
for (final TextSegment segment : deferredSegments) {
FLUSH_MVP.clear();
segment.mvp.get(FLUSH_MVP);
GLStateManager.glUniformMatrix4(segment.owner.mvpMatrixLocation, false, FLUSH_MVP);
uploadLightmap(segment.owner.lightmapLocation, segment.lightmapActive, segment.lightmapU,
segment.lightmapV, segment.lightmapTexture);
if (segment.depthTest != curDepthTest) {
if (segment.depthTest) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
curDepthTest = segment.depthTest;
}
if (segment.depthMask != curDepthMask) {
GLStateManager.glDepthMask(segment.depthMask);
curDepthMask = segment.depthMask;
}
drawCommands(segment.owner.batchCommands.elements(), segment.cmdStart, segment.cmdEnd, segment.owner);
}
} finally {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
@@ -849,21 +846,20 @@ public class BatchingFontRenderer {
setupFontDrawState();
flushLastTexture = -1;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
try {
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
FLUSH_MVP.clear();
segment.mvp.get(FLUSH_MVP);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, FLUSH_MVP);
uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture);
drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this);
}
if (batchSealedEnd < cmdCount) {
mvpBuf.clear();
FLUSH_MVP.clear();
resolveMvp(scratchMvp);
scratchMvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
scratchMvp.get(FLUSH_MVP);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, FLUSH_MVP);
uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId);
drawCommands(cmds, batchSealedEnd, cmdCount, this);
}
@@ -17,21 +17,25 @@ public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
public ExtendedBlockStorageExt(Chunk chunk, ExtendedBlockStorage storage) {
super(storage.yBase, storage.getSkylightArray() != null);
copyFrom(chunk, storage);
}
public void copyFrom(Chunk chunk, ExtendedBlockStorage storage) {
this.yBase = storage.yBase;
final boolean srcHasSky = storage.getSkylightArray() != null;
this.hasSky = srcHasSky;
if (ModStatus.isChunkAPILoaded) {
if (storage.getSkylightArray() != null) {
hasSky = true;
}
// ChunkAPI BlocklightManager.cloneSubChunk repoints the source at our array
final NibbleArray liveBlocklight = storage.getBlocklightArray();
DataRegistry.cloneSubChunk(chunk, storage, this);
storage.setBlocklightArray(liveBlocklight);
} else {
int arrayLen;
if (ModStatus.isNEIDLoaded){
final short[] block16BArray = ((IExtendedBlockStorageMixin)(Object)this).getBlock16BArray();
System.arraycopy(((IExtendedBlockStorageMixin)(Object)storage).getBlock16BArray(), 0, block16BArray, 0, block16BArray.length);
if(storage.getBlockMSBArray() != null) {
this.setBlockMSBArray(new NibbleArray(block16BArray.length, 4));
copyNibbleArray(storage.getBlockMSBArray(), this.getBlockMSBArray());
}
copyMSB(storage, block16BArray.length);
arrayLen = block16BArray.length;
if (ModStatus.isNEIDMetadataExtended) {
final short[] block16BMetaArray = ((IExtendedBlockStorageMixin)(Object)this).getBlock16BMetaArray();
@@ -41,27 +45,37 @@ public class ExtendedBlockStorageExt extends ExtendedBlockStorage {
else {
final byte[] blockLSBArray = this.getBlockLSBArray();
System.arraycopy(storage.getBlockLSBArray(), 0, blockLSBArray, 0, blockLSBArray.length);
if(storage.getBlockMSBArray() != null) {
this.setBlockMSBArray(new NibbleArray(blockLSBArray.length, 4));
copyNibbleArray(storage.getBlockMSBArray(), this.getBlockMSBArray());
}
copyMSB(storage, blockLSBArray.length);
arrayLen = blockLSBArray.length;
}
if (!ModStatus.isNEIDMetadataExtended) copyNibbleArray(storage.getMetadataArray(), this.getMetadataArray());
copyNibbleArray(storage.getBlocklightArray(), this.getBlocklightArray());
if(storage.getSkylightArray() != null) {
hasSky = true;
if (srcHasSky) {
if(this.getSkylightArray() == null) {
this.setSkylightArray(new NibbleArray(arrayLen, 4));
}
copyNibbleArray(storage.getSkylightArray(), this.getSkylightArray());
} else {
this.setSkylightArray(null);
}
}
this.blockRefCount = storage.blockRefCount;
}
private void copyMSB(ExtendedBlockStorage storage, int len) {
final NibbleArray src = storage.getBlockMSBArray();
if (src == null) {
this.setBlockMSBArray(null);
return;
}
if (this.getBlockMSBArray() == null) {
this.setBlockMSBArray(new NibbleArray(len, 4));
}
copyNibbleArray(src, this.getBlockMSBArray());
}
private static void copyNibbleArray(NibbleArray srcArray, NibbleArray dstArray) {
if (srcArray == null || dstArray == null) {
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureMap;
@@ -27,8 +28,6 @@ public final class Tc4JarMeshes {
private static final double MIN_X = 0.25, MIN_Y = 0.0625, MIN_Z = 0.25, MAX_X = 0.75, MAX_Z = 0.75;
private static final double OFF_X = -0.5, OFF_Y = 0.0, OFF_Z = -0.5;
private record LiquidKey(int color, int level64) {}
private static final class Holder {
final Object cacheKey = new Object();
final TesrMaterial material;
@@ -40,7 +39,7 @@ public final class Tc4JarMeshes {
}
}
private static final Map<LiquidKey, Holder> HOLDERS = new HashMap<>();
private static final Long2ObjectOpenHashMap<Holder> HOLDERS = new Long2ObjectOpenHashMap<>();
private static final RenderBlocks FALLBACK_RENDER_BLOCKS = new RenderBlocks();
private static final ResourceLocation LABEL_TEXTURE = new ResourceLocation("thaumcraft", "textures/models/label.png");
@@ -118,7 +117,12 @@ public final class Tc4JarMeshes {
applyBrightness(jarBrightness(te));
final Holder holder = HOLDERS.computeIfAbsent(new LiquidKey(color, level64), k -> new Holder(k.color()));
final long liquidKey = ((long) color << 32) | (level64 & 0xFFFFFFFFL);
Holder holder = HOLDERS.get(liquidKey);
if (holder == null) {
holder = new Holder(color);
HOLDERS.put(liquidKey, holder);
}
GLStateManager.glPushMatrix();
GLStateManager.glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
BUILDER.material = holder.material;
@@ -432,6 +432,7 @@ public enum Mixins implements IMixins {
, "celeritas.biome_blending.MixinWorld"
, "celeritas.biome_blending.MixinRenderBlocks"
, "celeritas.threading.MixinForgeHooksClient"
, "celeritas.threading.MixinChunkJobTyped"
, "celeritas.terrain.MixinChunk"
, "celeritas.terrain.MixinWorldClient_WorkerAccess"
, "celeritas.terrain.MixinWorld_WorkerMutationGuard"
@@ -439,10 +440,16 @@ public enum Mixins implements IMixins {
, "celeritas.terrain.MixinNetHandlerPlayClient_DescriptorRepair"
, "celeritas.terrain.MixinWorld_AwaitingDescriptor"
, "celeritas.terrain.MixinRenderRegion"
, "celeritas.terrain.MixinChunkRenderList"
, "celeritas.terrain.MixinVisibleChunkCollector"
, "celeritas.terrain.MixinRenderListManager"
, "celeritas.terrain.MixinSectionRenderDataStorage"
, "celeritas.terrain.MixinSharedQuadIndexBuffer"
, "celeritas.terrain.MixinRenderRegionManager"
, "celeritas.terrain.MixinShaderLoader"
, "celeritas.terrain.MixinGlUniformMatrix4f"
, "celeritas.terrain.MixinGlUniformMatrix3f"
, "celeritas.terrain.MixinDefaultChunkRenderer"
)
),
@@ -0,0 +1,5 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
public interface ChunkRenderListReuse {
void angelica$reset();
}
@@ -0,0 +1,7 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
public interface VisibleChunkCollectorPool {
void angelica$setRecycled(ChunkRenderList[] slot);
}
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.render;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -20,20 +21,28 @@ import org.lwjgl.opengl.GL13;
final class CloudRenderResources {
private final Map<ResourceLocation, Texture> textures = new HashMap<>();
private final Map<Integer, GlProgram<CloudUniforms>> programs = new HashMap<>(4);
@SuppressWarnings("unchecked")
private final GlProgram<CloudUniforms>[] programs = (GlProgram<CloudUniforms>[]) new GlProgram[4];
Texture texture(ResourceLocation location) {
return textures.computeIfAbsent(location, Texture::new);
}
GlProgram<CloudUniforms> program(boolean faces, boolean untextured) {
int key = (faces ? 2 : 0) | (untextured ? 1 : 0);
return programs.computeIfAbsent(key, ignored -> buildProgram(faces, untextured));
final int key = (faces ? 2 : 0) | (untextured ? 1 : 0);
GlProgram<CloudUniforms> program = programs[key];
if (program == null) {
program = buildProgram(faces, untextured);
programs[key] = program;
}
return program;
}
void clear() {
for (GlProgram<CloudUniforms> program : programs.values()) program.delete();
programs.clear();
for (GlProgram<CloudUniforms> program : programs) {
if (program != null) program.delete();
}
Arrays.fill(programs, null);
textures.clear();
}
@@ -42,6 +42,7 @@ import net.minecraft.util.Vec3;
import net.minecraftforge.client.IRenderHandler;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -65,6 +66,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
private final Map<String, CloudLayerRenderer> layers = new HashMap<>();
private final List<CloudLayerRenderer> drawOrder = new ArrayList<>();
private final Set<String> activeIds = new HashSet<>();
private double sortCameraY;
private final Comparator<CloudLayerRenderer> farthestFirst = (a, b) -> Double.compare(distanceToLayer(b.layer, sortCameraY), distanceToLayer(a.layer, sortCameraY));
private WorldClient world;
private int cloudMode = MODE_FAST, renderDistance, scaleMult = 1, lastCloudTicks;
private boolean enabled;
@@ -144,7 +147,7 @@ public class CloudRenderer implements IResourceManagerReloadListener {
renderer.configure(description, cloudMode, renderDistance, scaleMult);
if (description.alpha() > 0.0f) drawOrder.add(renderer);
}
layers.entrySet().removeIf(entry -> {
if (layers.size() != activeIds.size()) layers.entrySet().removeIf(entry -> {
if (activeIds.contains(entry.getKey())) return false;
entry.getValue().delete();
return true;
@@ -154,7 +157,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
cloudView.update(GLStateManager.getProjectionMatrix(), GLStateManager.getModelViewMatrix(), viewport.width, viewport.height);
final Entity view = mc.renderViewEntity;
final double cameraY = view.lastTickPosY + (view.posY - view.lastTickPosY) * partialTicks + cloudView.offsetY;
drawOrder.sort((a, b) -> Double.compare(distanceToLayer(b.layer, cameraY), distanceToLayer(a.layer, cameraY)));
sortCameraY = cameraY;
drawOrder.sort(farthestFirst);
boolean rendered = descriptions.isEmpty();
for (CloudLayerRenderer renderer : drawOrder) rendered |= renderer.render(partialTicks, cloudView);
return rendered;
@@ -13,6 +13,11 @@ import java.util.concurrent.ConcurrentHashMap;
@SideOnly(Side.CLIENT)
public final class EmissiveTextureHelper {
private static final ConcurrentHashMap<String, IIcon> EMISSIVE_ICON_CACHE = new ConcurrentHashMap<>();
private static volatile boolean anyEmissive;
public static boolean hasAnyEmissive() {
return anyEmissive;
}
public static IIcon getEmissiveIcon(Block block, int side, int metadata) {
IIcon baseIcon = block.getIcon(side, metadata);
@@ -26,10 +31,12 @@ public final class EmissiveTextureHelper {
public static void clearCache() {
EMISSIVE_ICON_CACHE.clear();
anyEmissive = false;
}
public static void cacheEmissive(String baseIconName, IIcon emissiveIcon) {
EMISSIVE_ICON_CACHE.put(baseIconName, emissiveIcon);
anyEmissive = true;
}
public static void renderEmissiveBlockOverlay(RenderBlocks renderer, Block block, int x, int y, int z, int metadata) {
@@ -15,6 +15,7 @@ import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink;
import com.gtnewhorizons.angelica.rendering.voxelization.ShadowVoxelizer;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.program.ComputeProgram;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
@@ -40,7 +41,9 @@ import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderListIterable;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.BatchAssembler;
import org.embeddedt.embeddium.impl.render.chunk.multidraw.CachedBatch;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkFogMode;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderBindingPoints;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderComponent;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderInterface;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderOptions;
import org.embeddedt.embeddium.impl.render.chunk.shader.ChunkShaderTextureSlot;
@@ -75,6 +78,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
private final GpuTerrainCuller culler;
private final SdlShadowVoxelizationSink shadowVoxelSink = new SdlShadowVoxelizationSink();
private final ReusableCachedBatch gpuBatch = new ReusableCachedBatch();
private final Reference2ObjectOpenHashMap<TerrainRenderPass, GlProgram<ChunkShaderInterface>[]> programsByPass = new Reference2ObjectOpenHashMap<>();
private static final ShadowVoxelizer shadowVoxelizer = new ShadowVoxelizer();
private static int loggedVoxelizationSkips;
@@ -172,13 +176,39 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
// Fall back to default shader
this.usingIrisProgram = false;
this.irisProgram = null;
super.begin(pass);
beginDefault(pass);
bindTerrainSampler();
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
@SuppressWarnings("unchecked")
private void beginDefault(TerrainRenderPass pass) {
final ChunkShaderComponent.Factory<?> fog = this.environment.fogService().getFogMode();
if (!(fog instanceof ChunkFogMode mode)) {
super.begin(pass);
return;
}
GlProgram<ChunkShaderInterface>[] programs = this.programsByPass.get(pass);
if (programs == null) {
programs = (GlProgram<ChunkShaderInterface>[]) new GlProgram[ChunkFogMode.values().length];
this.programsByPass.put(pass, programs);
}
GlProgram<ChunkShaderInterface> program = programs[mode.ordinal()];
if (program == null) {
final List<ChunkShaderComponent.Factory<?>> components = getShaderComponents();
program = compileProgram(new ChunkShaderOptions(components, pass));
programs[mode.ordinal()] = program;
}
pass.startDrawing();
this.activeProgram = program;
if (program != null) {
program.bind();
program.getInterface().setupState(pass);
}
}
@Override
protected void end(TerrainRenderPass pass) {
unbindTerrainSampler();
@@ -273,6 +303,7 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
@Override
public void delete(CommandList commandList) {
super.delete(commandList);
programsByPass.clear();
if (culler != null) {
culler.delete();
@@ -97,6 +97,7 @@ public class DeferredMeshScheduler {
results.add(m.complete(mainContext()));
} finally {
releaseBuffers(m.buffers);
m.slice.releaseContext();
slices.release(m.slice);
pending.decrementAndGet();
}
@@ -0,0 +1,32 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import com.gtnewhorizons.angelica.mixins.interfaces.ChunkRenderListReuse;
import org.embeddedt.embeddium.impl.render.chunk.lists.ChunkRenderList;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegion;
import java.util.Arrays;
// Two slots are enough only while submitSearch rejects a second in-flight search per manager
public final class RenderListPool {
private final ChunkRenderList[][] slots = { new ChunkRenderList[0], new ChunkRenderList[0] };
private int generation;
public ChunkRenderList[] beginSearch(int regionIdsLength) {
final int s = generation++ & 1;
ChunkRenderList[] slot = slots[s];
if (slot.length < regionIdsLength) {
slot = slots[s] = Arrays.copyOf(slot, regionIdsLength);
}
return slot;
}
public static ChunkRenderList acquire(ChunkRenderList[] slot, RenderRegion region) {
final int id = region.getId();
final ChunkRenderList list = slot[id];
if (list != null && list.getRegion() == region) {
((ChunkRenderListReuse) list).angelica$reset();
return list;
}
return slot[id] = new ChunkRenderList(region);
}
}
@@ -102,6 +102,10 @@ public class ThreadedAngelicaChunkBuilderMeshingTask extends AngelicaChunkBuilde
return renderContext != null;
}
public void releaseUnstartedContext() {
if (this.renderContext != null) this.renderContext.release();
}
@Override
protected void onEnterExecute() {
enteredLocalMode = !TessellatorManager.isOnMainThread();
@@ -92,6 +92,8 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
// Local section copies
private ClonedChunkSection[] sections;
private ChunkRenderContext context;
// Biome data for each chunk section
private final BiomeGenBase[][] biomeData;
@@ -146,13 +148,18 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
final ClonedChunkSection[] sections = new ClonedChunkSection[SECTION_TABLE_ARRAY_SIZE];
for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
for (int chunkY = minChunkY; chunkY <= maxChunkY; chunkY++) {
sections[getLocalSectionIndex(chunkX - minChunkX, chunkY - minChunkY, chunkZ - minChunkZ)] =
sectionCache.acquire(chunkX, chunkY, chunkZ);
try {
for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
for (int chunkY = minChunkY; chunkY <= maxChunkY; chunkY++) {
sections[getLocalSectionIndex(chunkX - minChunkX, chunkY - minChunkY, chunkZ - minChunkZ)] =
sectionCache.acquire(chunkX, chunkY, chunkZ);
}
}
}
} catch (RuntimeException e) {
sectionCache.release(sections);
throw e;
}
return new ChunkRenderContext(origin, sections, volume);
@@ -197,6 +204,10 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
}
public void copyData(ChunkRenderContext context) {
if (this.context != context) {
releaseContext();
}
this.context = context;
this.origin = context.getOrigin();
this.sections = context.getSections();
this.volume = context.getVolume();
@@ -242,6 +253,14 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess {
}
}
public void releaseContext() {
final ChunkRenderContext c = this.context;
if (c != null) {
this.context = null;
c.release();
}
}
public ChunkSectionPos getOrigin() {
return this.origin;
}
@@ -8,6 +8,7 @@ public class ChunkRenderContext {
private final ChunkSectionPos origin;
private final ClonedChunkSection[] sections;
private final StructureBoundingBox volume;
private boolean released;
public ChunkRenderContext(ChunkSectionPos origin, ClonedChunkSection[] sections, StructureBoundingBox volume) {
this.origin = origin;
@@ -26,4 +27,10 @@ public class ChunkRenderContext {
public StructureBoundingBox getVolume() {
return this.volume;
}
public void release() {
if (this.released) return;
this.released = true;
this.sections[0].getBackingCache().release(this.sections);
}
}
@@ -37,12 +37,15 @@ public class ClonedChunkSection {
private ChunkSectionPos pos;
private ExtendedBlockStorageExt data;
private BiomeGenBase[] biomeData;
private final BiomeGenBase[] biomeData = new BiomeGenBase[BIOME_DATA_LENGTH];
private SectionLightData sectionLightData;
private final Short2ObjectOpenHashMap<TileEntity> tileEntities;
private long lastUsedTimestamp = Long.MAX_VALUE;
int refs;
boolean cached;
ClonedChunkSection(ClonedChunkSectionCache backingCache, World world) {
this.backingCache = backingCache;
this.world = world;
@@ -50,6 +53,7 @@ public class ClonedChunkSection {
}
public void init(ChunkSectionPos pos) {
if (refs != 0 || cached) throw new IllegalStateException("Reusing a live ClonedChunkSection (refs=" + refs + ", cached=" + cached + ")");
final Chunk chunk = world.getChunkFromChunkCoords(pos.x, pos.z);
if (chunk == null) {
@@ -69,9 +73,11 @@ public class ClonedChunkSection {
}
this.pos = pos;
this.data = new ExtendedBlockStorageExt(chunk, section);
this.biomeData = new BiomeGenBase[BIOME_DATA_LENGTH];
if (this.data == null) {
this.data = new ExtendedBlockStorageExt(chunk, section);
} else {
this.data.copyFrom(chunk, section);
}
copyBlockEntities(chunk, pos);
@@ -114,8 +120,6 @@ public class ClonedChunkSection {
} finally {
map.readUnlock();
}
this.tileEntities.trim();
}
public Block getBlock(int x, int y, int z) {
@@ -4,14 +4,17 @@ import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos;
import it.unimi.dsi.fastutil.longs.Long2ReferenceLinkedOpenHashMap;
import net.minecraft.world.World;
import java.util.ArrayDeque;
import java.util.concurrent.TimeUnit;
public class ClonedChunkSectionCache {
private static final int MAX_CACHE_SIZE = 512;
private static final long MAX_CACHE_DURATION = TimeUnit.SECONDS.toNanos(5);
private static final int MAX_FREE = 64;
private final World world;
private final Long2ReferenceLinkedOpenHashMap<ClonedChunkSection> byPosition = new Long2ReferenceLinkedOpenHashMap<>();
private final ArrayDeque<ClonedChunkSection> free = new ArrayDeque<>();
private long time;
public ClonedChunkSectionCache(World world) {
@@ -26,7 +29,7 @@ public class ClonedChunkSectionCache {
if (this.time <= oldest.getLastUsedTimestamp() + MAX_CACHE_DURATION) {
break;
}
this.byPosition.removeFirst();
evict(this.byPosition.removeFirst());
}
}
@@ -36,24 +39,52 @@ public class ClonedChunkSectionCache {
if (section == null) {
while (this.byPosition.size() >= MAX_CACHE_SIZE) {
this.byPosition.removeFirst();
evict(this.byPosition.removeFirst());
}
section = this.createSection(key, x, y, z);
}
section.refs++;
section.setLastUsedTimestamp(this.time);
return section;
}
private ClonedChunkSection createSection(long key, int x, int y, int z) {
final ClonedChunkSection section = new ClonedChunkSection(this, this.world);
ClonedChunkSection section = this.free.pollLast();
if (section == null) {
section = new ClonedChunkSection(this, this.world);
}
section.init(ChunkSectionPos.from(x, y, z));
section.cached = true;
this.byPosition.putAndMoveToLast(key, section);
return section;
}
public synchronized void invalidate(int x, int y, int z) {
this.byPosition.remove(ChunkSectionPos.asLong(x, y, z));
final ClonedChunkSection section = this.byPosition.remove(ChunkSectionPos.asLong(x, y, z));
if (section != null) {
evict(section);
}
}
public synchronized void release(ClonedChunkSection[] sections) {
for (final ClonedChunkSection section : sections) {
if (section != null) {
section.refs--;
recycleIfIdle(section);
}
}
}
private void evict(ClonedChunkSection section) {
section.cached = false;
recycleIfIdle(section);
}
private void recycleIfIdle(ClonedChunkSection section) {
if (!section.cached && section.refs == 0 && this.free.size() < MAX_FREE) {
this.free.addLast(section);
}
}
private static long getMonotonicTimeSource() {
@@ -159,7 +159,7 @@ public final class ModelPartBatcher {
boolean afterGlint;
boolean matches(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean lightmap, boolean afterGlint) {
return this.texture == texture && this.material == material && pass.equals(this.pass) && this.offsetFactor == offsetFactor
return this.texture == texture && this.material == material && pass == this.pass && this.offsetFactor == offsetFactor
&& this.offsetUnits == offsetUnits && this.glintSlot == glintSlot && this.cull == cull && this.lit == lit && this.lightmap == lightmap
&& this.afterGlint == afterGlint;
}
@@ -182,7 +182,7 @@ public final class ModelPartBatcher {
public boolean equals(Object o) {
if (!(o instanceof LayerKey other)) return false;
return Objects.equals(texture, other.texture) && Objects.equals(material, other.material)
&& Objects.equals(pass, other.pass)
&& pass == other.pass
&& Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor)
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)
&& glintSlot == other.glintSlot && cull == other.cull && lit == other.lit && lightmap == other.lightmap && afterGlint == other.afterGlint;
@@ -190,7 +190,7 @@ public final class ModelPartBatcher {
@Override
public int hashCode() {
int h = (Objects.hashCode(texture) * 31 + Objects.hashCode(material)) * 31 + Objects.hashCode(pass);
int h = (Objects.hashCode(texture) * 31 + Objects.hashCode(material)) * 31 + System.identityHashCode(pass);
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
h = h * 31 + glintSlot;
@@ -246,7 +246,7 @@ public final class TesrBatchRenderer {
&& depthOnly == other.depthOnly
&& Float.floatToIntBits(cutoutAlpha) == Float.floatToIntBits(other.cutoutAlpha)
&& depthEqual == other.depthEqual && special == other.special && shader == other.shader && noPass == other.noPass
&& Objects.equals(pass, other.pass)
&& pass == other.pass
&& Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor)
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)
&& cull == other.cull && lit == other.lit && lightmap == other.lightmap;
@@ -265,7 +265,7 @@ public final class TesrBatchRenderer {
h = h * 31 + Objects.hashCode(special);
h = h * 31 + System.identityHashCode(shader);
h = h * 31 + (noPass ? 1 : 0);
h = h * 31 + Objects.hashCode(pass);
h = h * 31 + System.identityHashCode(pass);
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
h = h * 31 + cull;
@@ -294,7 +294,7 @@ public final class TesrBatchRenderer {
private RenderLayer lastImmediateLayer;
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit, boolean lightmap) {
if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass)
if (texture == lastLayerTexture && material == lastLayerMaterial && pass == lastLayerPass
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && cullCode == lastLayerCull && lit == lastLayerLit
&& lightmap == lastLayerLightmap) {
return lastLayer;
@@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshBuilder;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import net.minecraft.client.model.ModelChest;
import net.minecraft.client.model.ModelRenderer;
@@ -13,7 +14,6 @@ import net.minecraft.client.model.ModelSkeletonHead;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.ResourceLocation;
import java.util.HashMap;
import java.util.Map;
/** Cached-mesh entry points for the vanilla chest/sign/skull TESR mixins. */
@@ -36,9 +36,7 @@ public final class VanillaModelMeshes {
private static final Object KEY_SIGN_STANDING = new Object();
private static final Object KEY_SIGN_WALL = new Object();
private record SkullKey(ModelSkeletonHead model, ResourceLocation texture) {}
private static final Map<SkullKey, Object> SKULL_KEYS = new HashMap<>();
private static final Map<ModelSkeletonHead, Map<ResourceLocation, Object>> SKULL_KEYS = new Reference2ObjectOpenHashMap<>();
private static final Builder BUILDER = new Builder();
@@ -87,7 +85,7 @@ public final class VanillaModelMeshes {
if (texture == null) {
return false;
}
final Object key = SKULL_KEYS.computeIfAbsent(new SkullKey(model, texture), k -> new Object());
final Object key = SKULL_KEYS.computeIfAbsent(model, m -> new Object2ObjectOpenHashMap<>()).computeIfAbsent(texture, t -> new Object());
GLStateManager.glPushMatrix();
if (yawDegrees != 0.0f) {
GLStateManager.glRotatef(yawDegrees, 0.0f, 1.0f, 0.0f);
@@ -9,7 +9,6 @@ import com.gtnewhorizons.angelica.mixins.interfaces.ITexturesCache;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
@@ -63,8 +62,8 @@ public class AnimationsRenderUtils {
}
public static void markBlockTextureForUpdate(IIcon icon, IBlockAccess blockAccess) {
final TextureMap textureMap = Minecraft.getMinecraft().getTextureMapBlocks();
final TextureAtlasSprite textureAtlasSprite = textureMap.getAtlasSprite(icon.getIconName());
final TextureAtlasSprite textureAtlasSprite = icon instanceof TextureAtlasSprite s ? s
: Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(icon.getIconName());
if (textureAtlasSprite != null && textureAtlasSprite.hasAnimationMetadata()) {
// null if called by anything but chunk render cache update (for example to get blocks rendered as items in
@@ -205,28 +205,41 @@ public class CTMUtils {
return local;
}
private static boolean hasCandidates(Block block, IIcon icon) {
return (!overrides.block.isEmpty() && overrides.block.get(block) != null)
|| (!overrides.tile.isEmpty() && overrides.tile.get(icon.getIconName()) != null);
}
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);
local.renderBlockState.blockAccess = null;
if (lastOverride != null) {
return skipDefaultRendering(block) ? RenderBlocksUtils.blankIcon : local.ijkIterator.getIcon();
if (!hasCandidates(block, icon)) {
clearCurrentCompact();
} else {
final StateAndIterator local = getStateAndIterator();
local.renderBlockState.setBlock(block, blockAccess, x, y, z);
local.renderBlockState.setFace(face);
TileOverride lastOverride = local.ijkIterator.go(local.renderBlockState, icon);
local.renderBlockState.blockAccess = null;
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();
if (!hasCandidates(block, icon)) {
clearCurrentCompact();
} else {
final StateAndIterator local = getStateAndIterator();
local.renderBlockState.setBlockMetadata(block, metadata, face);
TileOverride lastOverride = local.metadataIterator.go(local.renderBlockState, icon);
if (lastOverride != null) {
return local.metadataIterator.getIcon();
}
}
}
return icon;