initial commit for entity-atlases (#2272)

This commit is contained in:
Eclipse-Sol authored and GitHub committed 2026-10-18 19:31:16 -07:00
1 parent fa8842a64b
commit 2d9d1a45b7
31 files changed
+978 -141

No files matched your search

@@ -163,6 +163,10 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableCubeInstancing;
@Config.Comment("Stitch a texture atlas between entity and block entity models so different textures draw together (requires cube instancing)")
@Config.DefaultBoolean(true)
public static boolean enableEntityTextureAtlas;
@Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
@@ -199,6 +199,7 @@ public enum Mixins implements IMixins {
"angelica.entity.MixinRendererLivingEntity_GlintClock",
"angelica.entity.MixinRendererLivingEntity_ModelPassDraws",
"angelica.entity.MixinRender_BatchEligibility",
"angelica.entity.MixinRender_EntityFireBatch",
"angelica.entity.MixinRender_NameTagDraws",
"angelica.entity.MixinRender_ShadowBatch",
"angelica.entity.MixinTextureManager",
@@ -15,6 +15,7 @@ import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiVideoSettings;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.util.Direction;
import net.minecraft.util.MathHelper;
@@ -49,6 +50,7 @@ import com.gtnewhorizons.angelica.compat.mojang.CompatMathHelper;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.EntityTextureAtlas;
import com.gtnewhorizons.angelica.config.CompatConfig;
import com.gtnewhorizons.angelica.config.ConfigMigrator;
import com.gtnewhorizons.angelica.config.SystemProperties;
@@ -65,6 +67,7 @@ import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.backend.BackendStartGuard;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
import com.gtnewhorizons.angelica.iris.IrisGLSMBridge;
import com.gtnewhorizons.angelica.iris.ShaderWarmup;
@@ -208,6 +211,8 @@ public final class ClientProxy extends CommonProxy {
ItemRenderListManager.registerReloadListener();
BlockRenderListManager.registerReloadListener();
}
((IReloadableResourceManager) mc.getResourceManager()).registerReloadListener(manager -> EntityTextureAtlas.INSTANCE.clear());
TextureInfoCache.INSTANCE.addDeleteListener(EntityTextureAtlas.INSTANCE::onTextureDeleted);
FontProviderBitmap.registerReloadListener();
// Debug tooling
@@ -5,6 +5,7 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.resources.IReloadableResourceManager;
import org.lwjgl.opengl.GL11;
@@ -41,6 +42,11 @@ public class BlockRenderListManager {
return itemFrameDisplayLists[variant];
}
public static boolean rendersPlainItem(RenderBlocks rb, Block block, float brightness) {
return !isISBRH(block.getRenderType()) && !rb.enableAO && rb.overrideBlockTexture == null && brightness == 1.0F && rb.useInventoryTint
&& rb.blockAccess == null && (rb.uvRotateEast | rb.uvRotateWest | rb.uvRotateSouth | rb.uvRotateNorth | rb.uvRotateTop | rb.uvRotateBottom) == 0;
}
public static int callOrStartCompiling(int cached) {
if (cached != 0) {
GLStateManager.glCallList(cached);
@@ -35,6 +35,7 @@ public final class DroppedItemInstancer {
private static final AngelicaTesrMeshCache.GtnhMeshBackend iconBackend = new AngelicaTesrMeshCache.GtnhMeshBackend();
private static BakedTransformCapture blockBackend;
private static boolean basePart;
private static int itemsDrawingBlocks;
private static final GlintCapture glintCapture = new GlintCapture();
private static boolean glintSeen;
private static final ItemPropCache.ItemProp glintProperties = new ItemPropCache.ItemProp();
@@ -199,6 +200,24 @@ public final class DroppedItemInstancer {
}
public static long block(ItemStack stack, RenderBlocks rb, Block block, int meta, float brightness, boolean unfilteredAtlas) {
final long part = itemBlock(stack, rb, block, meta, brightness, unfilteredAtlas);
if (part != SKIP) itemsDrawingBlocks++;
return part;
}
public static void endBlock(long part) {
if (part != SKIP) itemsDrawingBlocks--;
endPart(part);
}
public static long directBlock(RenderBlocks rb, Block block, int meta, float brightness) {
if (itemsDrawingBlocks != 0 || !ModelPartBatcher.INSTANCE.entitiesActive()) return RUN;
if (!BatchEligibility.batchingAllowed()) return GLStateManager.drawCalls;
final TesrMaterial material = EntityMaterials.itemFromCurrentState(false);
return material != null ? batchBlock(material, rb, block, meta, brightness) : GLStateManager.drawCalls;
}
private static long itemBlock(ItemStack stack, RenderBlocks rb, Block block, int meta, float brightness, boolean unfilteredAtlas) {
final TesrMaterial material = material(stack, unfilteredAtlas);
if (material == null) {
return RUN;
@@ -246,6 +265,10 @@ public final class DroppedItemInstancer {
}
}
public static void forgetItemDraws() {
itemsDrawingBlocks = 0;
}
public static void clear() {
icons.clear();
blocks.clear();
@@ -307,10 +330,7 @@ public final class DroppedItemInstancer {
private static BailReason blockStateBail(RenderBlocks renderBlocks, Block block, float brightness) {
if (BlockRenderListManager.isISBRH(block.getRenderType())) return BailReason.ISBRH;
if (renderBlocks.enableAO || renderBlocks.overrideBlockTexture != null || brightness != 1.0F || !renderBlocks.useInventoryTint
|| renderBlocks.blockAccess != null || (renderBlocks.uvRotateEast | renderBlocks.uvRotateWest | renderBlocks.uvRotateSouth
| renderBlocks.uvRotateNorth | renderBlocks.uvRotateTop | renderBlocks.uvRotateBottom) != 0) return BailReason.BLOCK_STATE;
return null;
return BlockRenderListManager.rendersPlainItem(renderBlocks, block, brightness) ? null : BailReason.BLOCK_STATE;
}
private static final class IconMesh {
@@ -0,0 +1,332 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.iris.texture.pbr.PBRTextureManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL30;
import java.nio.ByteBuffer;
/**
* Copies entity and block entity textures into a shared atlas, so model boxes with different textures land in one instanced draw.
*/
public final class EntityTextureAtlas {
public static final EntityTextureAtlas INSTANCE = new EntityTextureAtlas();
static final int PAGE_SIZE = 2048;
private static final int MAX_PAGES = 4;
private static final int MAX_EDGE = 512;
private static final int MAX_QUICK_REFRESHES = 8;
private static final long QUICK_REFRESH_MS = 1000L;
public static final class Slot {
static final Slot WHOLE_TEXTURE = new Slot();
final Page page;
final int width, height;
final int x, y;
final float u, v, w, h;
final Matrix4f uvMatrix;
Slot(Page page, int x, int y, int width, int height) {
this.page = page;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.u = (x + 1) / (float) PAGE_SIZE;
this.v = (y + 1) / (float) PAGE_SIZE;
this.w = width / (float) PAGE_SIZE;
this.h = height / (float) PAGE_SIZE;
this.uvMatrix = new Matrix4f().translation(u, v, 0.0f).scale(w, h, 1.0f);
}
private Slot() {
this.page = null;
this.x = this.y = this.width = this.height = 0;
this.u = this.v = 0.0f;
this.w = this.h = 1.0f;
this.uvMatrix = new Matrix4f();
}
}
private static final class Shelf {
final int y, height;
int x;
Shelf(int y, int height) {
this.y = y;
this.height = height;
}
}
static final class Page {
final ResourceLocation location;
final int texture;
final ObjectArrayList<Shelf> shelves = new ObjectArrayList<>();
int nextShelfY;
Page(ResourceLocation location, int texture) {
this.location = location;
this.texture = texture;
}
long place(int width, int height) {
Shelf best = null;
for (Shelf shelf : shelves) {
if (shelf.height >= height && PAGE_SIZE - shelf.x >= width && (best == null || shelf.height < best.height)) best = shelf;
}
if (best != null && best.height > 2 * height && PAGE_SIZE - nextShelfY >= height) best = null;
if (best == null) {
if (PAGE_SIZE - nextShelfY < height || width > PAGE_SIZE) return -1L;
best = new Shelf(nextShelfY, height);
shelves.add(best);
nextShelfY += height;
}
final long at = ((long) best.x << 32) | best.y;
best.x += width;
return at;
}
void empty() {
shelves.clear();
nextShelfY = 0;
}
}
private static final class PageTexture extends AbstractTexture {
PageTexture(int texture) {
this.glTextureId = texture;
}
@Override
public void loadTexture(IResourceManager resourceManager) {}
}
private static final class Entry {
final TextureInfo info;
int uploadGeneration;
int quickRefreshes;
long lastRefreshMs;
Slot slot;
int noRoomWidth = -1, noRoomHeight = -1;
Entry(TextureInfo info) {
this.info = info;
}
}
private final Int2ObjectOpenHashMap<Entry> entries = new Int2ObjectOpenHashMap<>();
private final ObjectArrayList<Page> pages = new ObjectArrayList<>();
private final ObjectArrayList<Slot> freeSlots = new ObjectArrayList<>();
private final ObjectArrayList<Slot> releasedThisPass = new ObjectArrayList<>();
private int readFbo, drawFbo;
private int drawFboPage;
private int lastTexture = -1;
private boolean lastPbrPipeline;
private TextureInfo lastInfo;
private int lastChangeStamp, lastDeleteCount, lastPbrHolderChanges;
private Slot lastSlot;
private EntityTextureAtlas() {}
Slot slotFor(int texture, boolean pbrPipeline) {
if (texture == lastTexture && pbrPipeline == lastPbrPipeline && lastInfo.getChangeStamp() == lastChangeStamp
&& TextureInfoCache.INSTANCE.deleteCount() == lastDeleteCount && PBRTextureManager.INSTANCE.holderChanges() == lastPbrHolderChanges) {
return lastSlot;
}
final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texture);
if (info == null) return null;
lastSlot = lookUp(texture, info, pbrPipeline);
lastTexture = texture;
lastPbrPipeline = pbrPipeline;
lastInfo = info;
lastChangeStamp = info.getChangeStamp();
lastDeleteCount = TextureInfoCache.INSTANCE.deleteCount();
lastPbrHolderChanges = PBRTextureManager.INSTANCE.holderChanges();
return lastSlot;
}
private Slot lookUp(int texture, TextureInfo info, boolean pbrPipeline) {
Entry entry = entries.get(texture);
if (entry == null || entry.info != info) {
if (entry != null) release(entry);
entry = new Entry(info);
entries.put(texture, entry);
}
if (!eligible(texture, entry, pbrPipeline)) {
if (info.isWrittenOutsideUploads()) release(entry);
return null;
}
final int width = info.getWidth(), height = info.getHeight();
if (entry.slot != null && (entry.slot.width != width || entry.slot.height != height)) release(entry);
if (entry.slot == null) {
entry.slot = takeFreeSlot(width, height);
if (entry.slot == null && (width != entry.noRoomWidth || height != entry.noRoomHeight)) entry.slot = placeOnPage(width, height);
if (entry.slot == null) {
entry.noRoomWidth = width;
entry.noRoomHeight = height;
return null;
}
} else if (entry.uploadGeneration == info.getUploadGeneration()) {
return entry.slot;
} else if (recordRefresh(entry)) {
release(entry);
return null;
}
copy(texture, entry.slot);
entry.uploadGeneration = info.getUploadGeneration();
return entry.slot;
}
private static boolean recordRefresh(Entry entry) {
final long now = System.currentTimeMillis();
entry.quickRefreshes = now - entry.lastRefreshMs < QUICK_REFRESH_MS ? entry.quickRefreshes + 1 : 1;
entry.lastRefreshMs = now;
return entry.quickRefreshes > MAX_QUICK_REFRESHES;
}
private static boolean eligible(int texture, Entry entry, boolean pbrPipeline) {
final TextureInfo info = entry.info;
final int width = info.getWidth();
final int height = info.getHeight();
if (width <= 0 || height <= 0 || width > MAX_EDGE || height > MAX_EDGE) return false;
if (info.getTarget() != GL11.GL_TEXTURE_2D || info.isWrittenOutsideUploads() || entry.quickRefreshes > MAX_QUICK_REFRESHES) return false;
final int format = info.getInternalFormat();
if (format != GL11.GL_RGBA && format != GL11.GL_RGBA8) return false;
if (info.getMinFilter() != GL11.GL_NEAREST || info.getMagFilter() != GL11.GL_NEAREST) return false;
return !pbrPipeline || !PBRTextureManager.INSTANCE.hasLoadedPbrTextures(texture);
}
private void release(Entry entry) {
if (entry.slot != null) releasedThisPass.add(entry.slot);
entry.slot = null;
}
void recycleReleasedRegions() {
if (releasedThisPass.isEmpty()) return;
freeSlots.addAll(releasedThisPass);
releasedThisPass.clear();
}
public void onTextureDeleted(int texture) {
final Entry entry = entries.remove(texture);
if (entry != null) release(entry);
}
private Slot takeFreeSlot(int width, int height) {
for (int i = 0, n = freeSlots.size(); i < n; i++) {
final Slot free = freeSlots.get(i);
if (free.width == width && free.height == height) return freeSlots.remove(i);
}
return null;
}
private Slot placeOnPage(int width, int height) {
for (int i = 0, n = pages.size(); i <= n; i++) {
final Page page = i < n ? pages.get(i) : newPage();
if (page == null) return null;
final long at = page.place(width + 2, height + 2);
if (at >= 0) return new Slot(page, (int) (at >>> 32), (int) at, width, height);
}
return null;
}
private Page newPage() {
if (pages.size() == MAX_PAGES) return null;
final int previous = GLStateManager.getBoundTextureForServerState();
final int texture = GLStateManager.glGenTextures();
BatchStateGuard.suspend();
try {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 0);
GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, PAGE_SIZE, PAGE_SIZE, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
} finally {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous);
BatchStateGuard.resume();
}
final ResourceLocation location = new ResourceLocation("angelica", "entity_atlas_" + pages.size());
Minecraft.getMinecraft().getTextureManager().loadTexture(location, new PageTexture(texture));
final Page page = new Page(location, texture);
pages.add(page);
return page;
}
private void copy(int texture, Slot slot) {
if (readFbo == 0) {
readFbo = GLStateManager.glGenFramebuffers();
drawFbo = GLStateManager.glGenFramebuffers();
}
final int previousRead = GLStateManager.getReadFramebuffer();
final int previousDraw = GLStateManager.getDrawFramebuffer();
final boolean scissor = GLStateManager.glIsEnabled(GL11.GL_SCISSOR_TEST);
BatchStateGuard.suspend();
try {
if (scissor) GLStateManager.glDisable(GL11.GL_SCISSOR_TEST);
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, readFbo);
GLStateManager.attachTextureForReading(GL30.GL_COLOR_ATTACHMENT0, texture);
GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, drawFbo);
assert slot.page != null;
if (drawFboPage != slot.page.texture) {
GLStateManager.glFramebufferTexture2D(GL30.GL_DRAW_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, slot.page.texture, 0);
drawFboPage = slot.page.texture;
}
final int w = slot.width, h = slot.height, x = slot.x + 1, y = slot.y + 1;
final int[] fromX = {0, 0, w - 1}, widths = {w, 1, 1}, toX = {x, x - 1, x + w};
final int[] fromY = {0, 0, h - 1}, heights = {h, 1, 1}, toY = {y, y - 1, y + h};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) blit(fromX[col], fromY[row], widths[col], heights[row], toX[col], toY[row]);
}
} finally {
GLStateManager.attachTextureForReading(GL30.GL_COLOR_ATTACHMENT0, 0);
GLStateManager.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, previousRead);
GLStateManager.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, previousDraw);
if (scissor) GLStateManager.glEnable(GL11.GL_SCISSOR_TEST);
BatchStateGuard.resume();
}
}
private static void blit(int srcX, int srcY, int width, int height, int dstX, int dstY) {
GLStateManager.glBlitFramebuffer(srcX, srcY, srcX + width, srcY + height, dstX, dstY, dstX + width, dstY + height, GL11.GL_COLOR_BUFFER_BIT, GL11.GL_NEAREST);
}
public void clear() {
for (Page page : pages) page.empty();
entries.clear();
freeSlots.clear();
releasedThisPass.clear();
lastTexture = -1;
lastInfo = null;
lastSlot = null;
}
void freePages() {
if (pages.isEmpty() && readFbo == 0) return;
clear();
for (Page page : pages) GLStateManager.glDeleteTextures(page.texture);
pages.clear();
if (readFbo != 0) {
GLStateManager.glDeleteFramebuffers(readFbo);
GLStateManager.glDeleteFramebuffers(drawFbo);
readFbo = 0;
drawFbo = 0;
}
drawFboPage = 0;
}
}
@@ -178,12 +178,13 @@ final class InstancedTemplateRenderer {
final int light = data.lights.getInt(i);
final int overlay = data.overlays.getInt(i);
final long info = data.infos.getLong(i);
for (int p = 0, n = partCubes.length; p < n; p++) {
final CubeParams cube = partCubes[p];
final EntityTextureAtlas.Slot slot = data.atlasSlot(run, i);
final EntityTextureAtlas.Slot region = slot != null ? slot : EntityTextureAtlas.Slot.WHOLE_TEXTURE;
for (final CubeParams cube : partCubes) {
cube.writeRows(ptr, data.matrices, off, scale);
InstancedAttribs.writeTail(ptr, color, overlay, info);
InstancedAttribs.writeLightmap(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE, light);
cube.writeTexture(ptr);
cube.writeTexture(ptr, region.u, region.v, region.w, region.h);
ptr += CubeInstancedAttribs.STRIDE;
}
}
@@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.UnitCubeMesh;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.model.PositionTextureVertex;
import net.minecraft.client.model.TexturedQuad;
@@ -11,6 +13,10 @@ public final class ModelBoxCapture {
private ModelBoxCapture() {}
public static CubeParams capture(ModelBox box, TexturedQuad[] quads, ModelRenderer part, int texU, int texV, int sizeX, int sizeY, int sizeZ, float inflate) {
return capture(quads, part.textureWidth, part.textureHeight, part.mirror, texU, texV, box.posX1, box.posY1, box.posZ1, sizeX, sizeY, sizeZ, inflate);
}
public static CubeParams capture(TexturedQuad[] quads, float texWidth, float texHeight, boolean mirror, int texU, int texV, float x, float y, float z, int sizeX, int sizeY, int sizeZ, float inflate) {
if (quads == null || quads.length != UnitCubeMesh.FACE_COUNT) return null;
final CubeParams params = CubeParams.of(texWidth, texHeight, mirror, texU, texV, x, y, z, sizeX, sizeY, sizeZ, inflate);
@@ -14,6 +14,7 @@ import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.streaming.TessellatorEntityIds;
@@ -103,6 +104,7 @@ public final class ModelPartBatcher {
private boolean texCaptured;
private boolean texIdentity;
private boolean active;
private int entityFireDepth;
private Mode mode = Mode.BLOCK_ENTITIES;
private boolean instancedThisCycle;
private DeferredWorldRenderingPipeline shaderPipeline;
@@ -141,6 +143,7 @@ public final class ModelPartBatcher {
private static final class PartTemplate {
TemplateBuffer template;
CubeParams[] cubes;
boolean cubesInsideTexture;
float scale;
long lastUsedMs;
boolean emptyVanillaPart;
@@ -248,6 +251,8 @@ public final class ModelPartBatcher {
if (entityPass && entityTranslucentsHeld) {
discardHeldEntities();
}
// Held entity translucents draw after deferred and can still sample regions released before them
if (!entityTranslucentsHeld) recycleAtlas();
active = true;
final long nowMs = System.currentTimeMillis();
mvCaptured = false;
@@ -350,6 +355,7 @@ public final class ModelPartBatcher {
if (instancedThisCycle) {
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
}
recycleAtlas();
AngelicaBufferSource.rebindPass();
} finally {
if (wrap) GbufferPrograms.endEntities();
@@ -367,6 +373,15 @@ public final class ModelPartBatcher {
private void discardHeldEntities() {
entityTranslucentsHeld = false;
entitySource.discard();
recycleAtlas();
}
private static void recycleAtlas() {
if (AngelicaConfig.enableEntityTextureAtlas) {
EntityTextureAtlas.INSTANCE.recycleReleasedRegions();
} else {
EntityTextureAtlas.INSTANCE.freePages();
}
}
public boolean isActive() {
@@ -514,7 +529,11 @@ public final class ModelPartBatcher {
}
public boolean entityPassActive() {
return active && mode == Mode.ENTITIES && !shadow;
return entitiesActive() && !shadow;
}
public boolean entitiesActive() {
return active && mode == Mode.ENTITIES;
}
public boolean isShadowPass() {
@@ -555,18 +574,18 @@ public final class ModelPartBatcher {
if (shadow && isDepthEqualDecalState()) {
return true;
}
return queueTemplate(entry.template, entry.cubes, scale, null, false);
return queueTemplate(entry.template, entry.cubes, entry.cubesInsideTexture, scale, null, false);
}
public boolean queueTemplate(TemplateBuffer template, TesrMaterial material) {
return queueTemplate(template, null, 1.0f, material, false);
return queueTemplate(template, null, false, 1.0f, material, false);
}
public boolean queueTemplate(TemplateBuffer template, TesrMaterial material, boolean afterGlint) {
return queueTemplate(template, null, 1.0f, material, afterGlint);
return queueTemplate(template, null, false, 1.0f, material, afterGlint);
}
private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, float scale, TesrMaterial explicitMaterial, boolean afterGlint) {
private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, boolean cubesInsideTexture, float scale, TesrMaterial explicitMaterial, boolean afterGlint) {
if (!active) {
bail(BailReason.INACTIVE);
return false;
@@ -613,7 +632,8 @@ public final class ModelPartBatcher {
final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT;
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final boolean lit = DrawState.liveLit(material);
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, DrawState.liveLightmap(), afterGlint);
final EntityTextureAtlas.Slot atlasSlot = texMatrix == null && cubesInsideTexture ? atlasSlotFor(material) : null;
final RenderLayer layer = layerFor(atlasSlot != null ? Objects.requireNonNull(atlasSlot.page).location : texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit, DrawState.liveLightmap(), afterGlint);
// Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id
final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
final Color4 color = GLStateManager.getColor();
@@ -621,11 +641,20 @@ public final class ModelPartBatcher {
final int overlayABGR = currentOverlay();
final long entityInfo = currentEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedItem());
final int packedLight = GLSMConfig.packedLastBrightness();
activeGroups.queue(template, cubes, scale, layer, material, currentModelView(), packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix);
activeGroups.queue(template, cubes, scale, layer, material, currentModelView(), packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix, atlasSlot);
parts++;
return true;
}
private EntityTextureAtlas.Slot atlasSlotFor(TesrMaterial material) {
if (!AngelicaConfig.enableEntityTextureAtlas) return null;
// Glint, overlay and custom shaders sample their own textures
if (material.special() != TesrMaterial.SpecialRender.NONE || material.shader() != null || material.isUnfilteredAtlas() || material == EntityMaterials.OVERLAY) return null;
if (!activeGroups.instancesCubes(material)) return null;
if (shaderPipeline != null && !shaderPipeline.hasInstancedVariant(Instancing.CUBE)) return null;
return EntityTextureAtlas.INSTANCE.slotFor(lastBoundGlId, shaderPipeline != null);
}
private enum TessellatorRoute { DRAW_NOW, DRAW_NOW_EXPECTED, QUEUE }
public static int drawTessellator(Tessellator tess) {
@@ -650,8 +679,13 @@ public final class ModelPartBatcher {
}
}
public void beginEntityFire() { entityFireDepth++; }
public void endEntityFire() { entityFireDepth--; }
private TessellatorRoute routeTessellatorDraw(Tessellator tess) {
if (!active || mode != Mode.BLOCK_ENTITIES || !GLStateManager.isMainThread() || !BatchEligibility.insideRenderer()) return TessellatorRoute.DRAW_NOW;
if (!active || !GLStateManager.isMainThread()) return TessellatorRoute.DRAW_NOW;
final boolean entityFire = entityFireDepth != 0 && mode == Mode.ENTITIES;
if (!entityFire && (mode != Mode.BLOCK_ENTITIES || !BatchEligibility.insideRenderer())) return TessellatorRoute.DRAW_NOW;
if (!tess.isDrawing || tess.drawMode != GL11.GL_QUADS || tess.vertexCount == 0 || (tess.vertexCount & 3) != 0) return TessellatorRoute.DRAW_NOW;
if (shaderPipeline != null && TessellatorEntityIds.hasIdChanges(tess)) return TessellatorRoute.DRAW_NOW;
if (DisplayListManager.isRecording() || !GLStateManager.glIsEnabled(GL11.GL_DEPTH_TEST) || !unitTexIdentity()) return TessellatorRoute.DRAW_NOW;
@@ -659,7 +693,7 @@ public final class ModelPartBatcher {
final TesrMaterial material = EntityMaterials.fromCurrentState(true);
if (material == null || material == EntityMaterials.OVERLAY) return TessellatorRoute.DRAW_NOW;
if (lastBoundLocation == null || GLStateManager.getBoundTextureForServerState() != lastBoundGlId) return TessellatorRoute.DRAW_NOW;
if (!BatchEligibility.batchingAllowed()) return TessellatorRoute.DRAW_NOW_EXPECTED;
if (!entityFire && !BatchEligibility.batchingAllowed()) return TessellatorRoute.DRAW_NOW_EXPECTED;
final PassOverride pass = shaderPipeline != null ? PassOverride.capture() : PassOverride.NONE;
final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL);
@@ -667,7 +701,8 @@ public final class ModelPartBatcher {
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final RenderLayer layer = layerFor(lastBoundLocation, material, pass, offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f,
ShaderGlint.NO_TINT, cullCode, DrawState.liveLit(material), DrawState.liveLightmap());
final int groupId = groupId(shaderPipeline != null, pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
// Flames carry entity_flame, which some packs may voxelize as a light source in the shadow pass
final int groupId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
TessellatorStreamingDrawer.fillMissingAttributes(tess);
activeGroups.streamVertices(layer, groupId, tess.rawBuffer, tess.vertexCount, currentModelView());
return TessellatorRoute.QUEUE;
@@ -724,6 +759,7 @@ public final class ModelPartBatcher {
entry.scale = scale;
entry.template = null;
entry.cubes = null;
entry.cubesInsideTexture = false;
entry.emptyVanillaPart = false;
final List<ModelBox> boxes = part.cubeList;
if (builder != null) {
@@ -758,6 +794,7 @@ public final class ModelPartBatcher {
cubes[i] = params;
}
entry.cubes = cubes;
entry.cubesInsideTexture = CubeParams.allInsideTexture(cubes);
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit, boolean lightmap) {
@@ -794,6 +831,7 @@ public final class ModelPartBatcher {
}
public void clear() {
entityFireDepth = 0;
shadows.reset();
groups.clear();
entityGroups.clear();
@@ -94,6 +94,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
static final class InstanceColumns {
final ObjectArrayList<TemplateBuffer> templates = new ObjectArrayList<>();
final ObjectArrayList<CubeParams[]> cubes = new ObjectArrayList<>();
final ObjectArrayList<EntityTextureAtlas.Slot> atlasSlots = new ObjectArrayList<>();
boolean anyAtlasSlot;
final FloatArrayList scales = new FloatArrayList();
final IntArrayList lights = new IntArrayList();
final IntArrayList colors = new IntArrayList();
@@ -122,8 +124,18 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
size++;
}
void addCubes(TemplateBuffer templateOrNull, CubeParams[] cubeParams, float scale, Matrix4fc mv, int light, int color, int overlay, long info) {
EntityTextureAtlas.Slot atlasSlot(int i) {
return anyAtlasSlot ? atlasSlots.get(i) : null;
}
EntityTextureAtlas.Slot atlasSlot(TexRun run, int i) {
return run.source != null ? null : atlasSlot(i);
}
void addCubes(TemplateBuffer templateOrNull, CubeParams[] cubeParams, float scale, Matrix4fc mv, int light, int color, int overlay, long info, EntityTextureAtlas.Slot atlasSlot) {
cubes.add(cubeParams);
atlasSlots.add(atlasSlot);
anyAtlasSlot |= atlasSlot != null;
scales.add(scale);
add(templateOrNull, mv, light, color, overlay, info);
}
@@ -140,6 +152,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
if (src.cubes.size() == src.size) {
for (int i = start; i < end; i++) cubes.add(src.cubes.get(i));
atlasSlots.size(atlasSlots.size() + n);
scales.addElements(scales.size(), src.scales.elements(), start, n);
}
fill(lights, n, light);
@@ -158,6 +171,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
void clear() {
templates.clear();
cubes.clear();
atlasSlots.clear();
anyAtlasSlot = false;
scales.clear();
lights.clear();
colors.clear();
@@ -477,10 +492,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix) {
queue(template, null, 1.0f, layer, material, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, id, texMatrix);
queue(template, null, 1.0f, layer, material, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, id, texMatrix, null);
}
void queue(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix) {
boolean instancesCubes(TesrMaterial material) {
return instanceableMaterial(material) && glintCapture == null;
}
void queue(TemplateBuffer template, CubeParams[] cubes, float scale, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int overlayABGR, long entityInfo, int id, Matrix4f texMatrix, EntityTextureAtlas.Slot atlasSlot) {
final Group group = groupFor(layer, material, id);
touch(group, layer);
if (group.stream) {
@@ -488,7 +507,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final boolean capturingBase = glintCapture != null && glintCapture.capturesBase();
if (instanceable && cubes != null) {
final TexRun run = group.openOrExtendRun(group.cubeColumns, texMatrix, false, capturingBase && group.opaque);
group.cubeColumns.addCubes(deferred != null ? template : null, cubes, scale, currentMV, packedLight, colorABGR, overlayABGR, entityInfo);
group.cubeColumns.addCubes(deferred != null ? template : null, cubes, scale, currentMV, packedLight, colorABGR, overlayABGR, entityInfo, atlasSlot);
run.last.end = group.cubeColumns.size;
run.parts++;
run.instances += cubes.length;
@@ -706,7 +725,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (group.cubeColumns.hasInstances()) {
if (cubeAvailable) {
need |= NEED_CUBE;
} else if (matrixAvailable) {
} else if (matrixAvailable && !group.cubeColumns.anyAtlasSlot) {
need |= NEED_MATRIX;
} else {
drawInstancesCpu(group, group.cubeColumns);
@@ -724,7 +743,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final boolean fixedFunction = deferred == null && GLStateManager.getActiveProgram() == 0;
drawTemplateRuns(group.templateColumns, group.material.special() == TesrMaterial.SpecialRender.GLINT && fixedFunction, group.material == EntityMaterials.ITEM_GLINT);
}
if (!cubeAvailable && group.cubeColumns.hasInstances()) {
if (!cubeAvailable && group.cubeColumns.hasInstances() && !group.cubeColumns.anyAtlasSlot) {
drawTemplateRuns(group.cubeColumns, group.material == EntityMaterials.GLINT && deferred == null, false);
}
}
@@ -904,7 +923,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
System.arraycopy(data.matrices, i * 16, matScratch, 0, 16);
scratchMat.set(matScratch);
final int color = head.source != null ? head.color : data.colors.getInt(i);
ptr = VertexTransform.writeInstance(ptr, format, templates.get(i), scratchMat, scratchVec, color, data.lights.getInt(i), texMatrix);
final EntityTextureAtlas.Slot slot = data.atlasSlot(head, i);
ptr = VertexTransform.writeInstance(ptr, format, templates.get(i), scratchMat, scratchVec, color, data.lights.getInt(i), slot != null ? slot.uvMatrix : texMatrix);
}
fallbackScratch.position((int) (ptr - base));
fallbackScratch.flip();
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer;
import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer;
public final class TesrLifecycle {
@@ -10,6 +11,8 @@ public final class TesrLifecycle {
public static void reset() {
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
EntityTextureAtlas.INSTANCE.clear();
DroppedItemInstancer.forgetItemDraws();
ParticleInstancer.clear();
RenderLayer.clearInterningAndHooks();
@@ -2610,7 +2610,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private static final ProgramId[] INSTANCED_PROGRAM_IDS = {
ProgramId.Block, ProgramId.BlockTrans, ProgramId.Entities, ProgramId.EntitiesTrans,
ProgramId.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint
ProgramId.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint, ProgramId.SpiderEyes
};
private static final ProgramId[] PARTICLE_PROGRAM_IDS = {
@@ -28,6 +28,7 @@ public class PBRTextureManager {
}
private final Int2ObjectMap<PBRTextureHolder> holders = new Int2ObjectOpenHashMap<>();
private int holderChanges;
private final PBRTextureConsumerImpl consumer = new PBRTextureConsumerImpl();
private NativeImageBackedSingleColorTexture defaultNormalTexture;
@@ -61,15 +62,24 @@ public class PBRTextureManager {
return holder;
}
public boolean hasLoadedPbrTextures(int id) {
return getHolder(id) != defaultHolder;
}
public PBRTextureHolder getOrLoadHolder(int id) {
PBRTextureHolder holder = holders.get(id);
if (holder == null) {
holder = loadHolder(id);
holders.put(id, holder);
holderChanges++;
}
return holder;
}
public int holderChanges() {
return holderChanges;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private PBRTextureHolder loadHolder(int id) {
AbstractTexture texture = TextureTracker.INSTANCE.getTexture(id);
@@ -96,6 +106,7 @@ public class PBRTextureManager {
PBRTextureHolder holder = holders.remove(id);
if (holder != null) {
closeHolder(holder);
holderChanges++;
}
}
@@ -106,6 +117,7 @@ public class PBRTextureManager {
}
}
holders.clear();
holderChanges++;
}
public void close() {