Instance more things (#2104)

* Flyby: pin the start origin and fly just above the route's terrain

* Instancing: particles, dropped items, entity cubes + shadow batching and some SDL-GPU fixes
This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-09-16 14:56:24 -07:00
1 parent 94ee37bfed
commit 3876f7e693
158 files changed
+9956 -1404

No files matched your search

@@ -21,7 +21,7 @@ public final class TesrMaterial {
private static final ConcurrentHashMap<TesrMaterial, TesrMaterial> INTERNED = new ConcurrentHashMap<>();
public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, Transparency.OPAQUE, SpecialRender.NONE, null));
public static final TesrMaterial CURRENT_STATE = intern(new TesrMaterial(false, 0, 0, 0, 0, false, 0, 0, false, false, false, false, false, 0, false, false, Transparency.OPAQUE, SpecialRender.NONE, null));
private static TesrMaterial intern(TesrMaterial material) {
final TesrMaterial existing = INTERNED.putIfAbsent(material, material);
@@ -39,6 +39,7 @@ public final class TesrMaterial {
private final boolean isStream;
private final float cutoutAlpha;
private final boolean isDepthEqual;
private final boolean isUnfilteredAtlas;
private final Transparency transparency;
private final SpecialRender special;
private final TesrShader shader;
@@ -59,6 +60,7 @@ public final class TesrMaterial {
private boolean stream;
private float cutoutAlpha;
private boolean depthEqual;
private boolean unfilteredAtlas;
private Transparency transparency = Transparency.OPAQUE;
private SpecialRender special = SpecialRender.NONE;
private TesrShader shader;
@@ -119,6 +121,11 @@ public final class TesrMaterial {
return this;
}
public Builder unfilteredAtlas() {
this.unfilteredAtlas = true;
return this;
}
/** Standard alpha blending (glass, liquids). SRC_ALPHA, ONE_MINUS_SRC_ALPHA */
public Builder translucent() {
this.transparency = Transparency.TRANSLUCENT;
@@ -158,7 +165,7 @@ public final class TesrMaterial {
if (special != SpecialRender.NONE && shader != null) {
throw new IllegalStateException("special() and shader() are mutually exclusive");
}
return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, transparency, special, shader));
return intern(new TesrMaterial(hasColor, red, green, blue, alpha, hasLightmap, lightmapX, lightmapY, noCull, unlit, noDepthWrite, depthOnly, stream, cutoutAlpha, depthEqual, unfilteredAtlas, transparency, special, shader));
}
}
}
@@ -1,5 +1,5 @@
/** TESR mesh cache/batch API (Render thread only) */
@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "1")
@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "2")
package com.gtnewhorizons.angelica.api.tesr;
import cpw.mods.fml.common.API;
@@ -5,7 +5,6 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.ITessellatorInstance;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.minecraft.client.renderer.Tessellator;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
@@ -28,8 +27,7 @@ class DeferredBatchTessellator extends DirectTessellator {
record DrawRange(long stateKey, int byteOffset, int byteLength, int vertexCount, int drawMode, int flags) {}
private final List<DrawRange> ranges = new ArrayList<>();
private final Matrix4f defaultModelview = new Matrix4f();
private final Matrix4f defaultModelviewInverse = new Matrix4f();
private final ModelViewDelta modelViewDelta = new ModelViewDelta();
private final Matrix4f deltaMatrix = new Matrix4f(); // reusable scratch
private final Vector3f scratch = new Vector3f();
private Matrix4fc currentTransform;
@@ -68,22 +66,14 @@ class DeferredBatchTessellator extends DirectTessellator {
/** Snapshot the current modelview as the "default" for this bracket. */
void snapshotDefaultModelview() {
defaultModelview.set(GLStateManager.getModelViewMatrix());
defaultModelview.invert(defaultModelviewInverse);
modelViewDelta.snapshot();
}
@Override
protected int interceptDraw(Tessellator tess) {
inIntercept = true;
try {
// Compute delta: if current MV differs from default, pre-transform vertices
final Matrix4f currentMV = GLStateManager.getModelViewMatrix();
if (!currentMV.equals(defaultModelview)) {
defaultModelviewInverse.mul(currentMV, deltaMatrix);
this.currentTransform = deltaMatrix;
} else {
this.currentTransform = null;
}
this.currentTransform = modelViewDelta.deltaOrNull(deltaMatrix);
final int byteOffsetBefore = bufferLimit();
final int vertCount = tess.vertexCount;
@@ -0,0 +1,22 @@
package com.gtnewhorizons.angelica.client.rendering;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
public final class ModelViewDelta {
private final Matrix4f base = new Matrix4f();
private final Matrix4f baseInverse = new Matrix4f();
public void snapshot() {
base.set(GLStateManager.getModelViewMatrix());
base.invert(baseInverse);
}
public Matrix4fc deltaOrNull(Matrix4f scratch) {
final Matrix4f current = GLStateManager.getModelViewMatrix();
if (current.equals(base)) return null;
return baseInverse.mul(current, scratch);
}
}
@@ -14,6 +14,7 @@ import net.coderbot.batchedentityrendering.impl.BatchVertexFormats;
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.layer.PassOverride;
import net.minecraft.util.ResourceLocation;
@@ -69,9 +70,9 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
return TRANSLUCENT;
}
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
private static MultiPhaseParameters.Builder tesrMaterialPhases(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
final MultiPhaseParameters.Builder b = MultiPhaseParameters.builder();
b.texture(texture != null ? new RenderPhase.Texture(texture, false, false) : NO_TEXTURE);
b.texture(texture != null ? new RenderPhase.Texture(texture, false, false, material.isUnfilteredAtlas()) : NO_TEXTURE);
if (material.isNoCull()) {
b.cull(DISABLE_CULLING);
}
@@ -95,7 +96,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
}
boolean shaderPhaseTaken = true;
switch (material.special()) {
case GLINT -> b.shader(SPECIAL_GLINT);
case GLINT -> b.shader(glintShader(glintSlot));
case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM);
case NONE -> {
final TesrShader shader = material.shader();
@@ -113,19 +114,35 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
return b;
}
private static final RenderPhase.Shader SPECIAL_GLINT = new RenderPhase.Shader("angelica_special_glint",
() -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT),
GbufferPrograms::teardownSpecialRenderCondition);
private static final RenderPhase.Shader[] GLINT_SHADERS = new RenderPhase.Shader[ShaderGlint.TINT_SLOTS + 1];
private static RenderPhase.Shader glintShader(int slot) {
RenderPhase.Shader shader = GLINT_SHADERS[slot + 1];
if (shader == null) {
shader = new RenderPhase.Shader("angelica_special_glint_" + slot,
() -> {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT);
ShaderGlint.bindTintedGlint(slot);
},
GbufferPrograms::teardownSpecialRenderCondition);
GLINT_SHADERS[slot + 1] = shader;
}
return shader;
}
private static final RenderPhase.Shader SPECIAL_BEACON_BEAM = new RenderPhase.Shader("angelica_special_beacon_beam",
() -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM),
GbufferPrograms::teardownSpecialRenderCondition);
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material) {
return tesr(texture, material, PassOverride.NONE, 0.0f, 0.0f);
return tesr(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT);
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material, pass, offsetFactor, offsetUnits).shadeModel(SMOOTH_SHADE_MODEL);
return tesr(texture, material, pass, offsetFactor, offsetUnits, ShaderGlint.NO_TINT);
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
final MultiPhaseParameters.Builder b = tesrMaterialPhases(texture, material, pass, offsetFactor, offsetUnits, glintSlot).shadeModel(SMOOTH_SHADE_MODEL);
final boolean sortsTranslucent = material.transparency() != TesrMaterial.Transparency.OPAQUE;
return of("angelica_tesr_" + material.transparency().name().toLowerCase(Locale.ROOT) + pass.nameSuffix()
+ (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits),
@@ -135,7 +152,7 @@ public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material) {
return of("angelica_tesr_nopass_" + material.transparency().name().toLowerCase(Locale.ROOT),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, false,
tesrMaterialPhases(texture, material, PassOverride.NONE, 0.0f, 0.0f).build(false));
tesrMaterialPhases(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT).build(false));
}
public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) {
@@ -5,6 +5,7 @@ import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
@@ -406,18 +407,30 @@ public abstract class RenderPhase {
private final Optional<ResourceLocation> id;
protected boolean bilinear;
protected boolean mipmap;
protected boolean unfilteredAtlas;
public Texture(ResourceLocation id, boolean bilinear, boolean mipmap) {
this(id, bilinear, mipmap, false);
}
public Texture(ResourceLocation id, boolean bilinear, boolean mipmap, boolean unfilteredAtlas) {
super("texture", () -> {
GLStateManager.enableTexture();
TextureManager lv = Minecraft.getMinecraft().getTextureManager();
lv.bindTexture(id);
//GLStateManager.setFilter(bilinear, mipmap); // breaks textures. TODO find out why
if (unfilteredAtlas) {
TextureUtil.func_152777_a(false, false, 1.0F);
}
}, () -> {
if (unfilteredAtlas) {
TextureUtil.func_147945_b();
}
});
this.id = Optional.of(id);
this.bilinear = bilinear;
this.mipmap = mipmap;
this.unfilteredAtlas = unfilteredAtlas;
}
public Texture() {
@@ -425,6 +438,7 @@ public abstract class RenderPhase {
this.id = Optional.empty();
this.bilinear = false;
this.mipmap = false;
this.unfilteredAtlas = false;
}
@Override
@@ -433,7 +447,7 @@ public abstract class RenderPhase {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
Texture lv = (Texture)object;
return this.id.equals(lv.id) && this.bilinear == lv.bilinear && this.mipmap == lv.mipmap;
return this.id.equals(lv.id) && this.bilinear == lv.bilinear && this.mipmap == lv.mipmap && this.unfilteredAtlas == lv.unfilteredAtlas;
} else {
return false;
}
@@ -446,7 +460,7 @@ public abstract class RenderPhase {
@Override
public String toString() {
return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ")]";
return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ", unfilteredAtlas=" + this.unfilteredAtlas + ")]";
}
protected Optional<ResourceLocation> getId() {
@@ -127,11 +127,16 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean enableTESRChestCache;
@Config.Comment("Batch and instance living-entity model parts on FFP-managed passes")
@Config.Comment("Batch and instance entity model parts, items, and shadows on FFP-managed passes")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableEntityBatching;
@Config.Comment("Draw cuboid model parts from a shared unit cube (requires entity batching)")
@Config.DefaultBoolean(true)
@Config.RequiresMcRestart
public static boolean enableCubeInstancing;
@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
@@ -251,7 +256,7 @@ public class AngelicaConfig {
@Config.RequiresMcRestart
public static boolean optimizeInWorldItemRendering;
@Config.Comment("Upper limit for the amount of VBO's to cache for optimized item rendering. Higher number can potentially use more VRAM.")
@Config.Comment("Upper limit for the amount of cached item meshes (VBOs and batched item templates) for optimized item rendering. Higher number can potentially use more memory and VRAM.")
@Config.DefaultInt(512)
@Config.RangeInt(min = 256, max = 1024)
public static int itemRendererCacheSize;
@@ -463,6 +468,10 @@ public class AngelicaConfig {
GpuCulling.setMode(gpuCullingMode == null ? GpuCullingMode.CPU_ONLY : gpuCullingMode);
}
public static boolean cubeInstancingEnabled() {
return enableEntityBatching && enableCubeInstancing;
}
public static GLProfile getEffectiveGlProfile() {
final String sys = SystemProperties.GL_PROFILE.trim().toUpperCase();
if ("GLES".equals(sys)) return GLProfile.ES;
@@ -15,9 +15,11 @@ final class FlybyCommandSender implements ICommandSender {
private static final String NAME = "Flyby";
private final EntityPlayerMP player;
private final ChunkCoordinates anchor;
FlybyCommandSender(EntityPlayerMP player) {
FlybyCommandSender(EntityPlayerMP player, ChunkCoordinates anchor) {
this.player = player;
this.anchor = anchor;
}
@Override
@@ -42,7 +44,7 @@ final class FlybyCommandSender implements ICommandSender {
@Override
public ChunkCoordinates getPlayerCoordinates() {
return this.player.getPlayerCoordinates();
return this.anchor;
}
@Override
@@ -0,0 +1,15 @@
package com.gtnewhorizons.angelica.debug.flyby;
record FlybyOrigin(double x, double z, float yaw) {
static FlybyOrigin parse(String raw) {
if (raw == null || raw.isBlank()) return null;
final String[] parts = raw.split(",", -1);
if (parts.length != 2 && parts.length != 3) throw new IllegalArgumentException("Expected x,z[,yaw] but got '" + raw + "'");
try {
return new FlybyOrigin(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()), parts.length == 3 ? Float.parseFloat(parts[2].trim()) : 0.0F);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Expected x,z[,yaw] but got '" + raw + "'", e);
}
}
}
@@ -15,19 +15,23 @@ import net.minecraft.client.gui.GuiMainMenu;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.MathHelper;
import net.minecraft.world.MinecraftException;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.Display;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
/** Flies a deterministic camera path */
public final class FlybyRunner {
public static final FlybyRunner INSTANCE = new FlybyRunner();
private static final Logger LOGGER = LogManager.getLogger("Angelica/Flyby");
private static final long[] NO_FRAMES = new long[0];
private static final double[] NO_PATH = new double[0];
@@ -36,7 +40,9 @@ public final class FlybyRunner {
private static final String[] NO_COMMANDS = new String[0];
private static final int MAX_RECORDED_FRAMES = 200_000;
private enum State { IDLE, WAITING, WARMUP, RUNNING, SETTLE, EXITING, DONE }
public static final FlybyRunner INSTANCE = new FlybyRunner();
private enum State { IDLE, WAITING, PREPARING, WARMUP, RUNNING, SETTLE, EXITING, DONE }
private static final int EXIT_TICKS = 20;
private static final int SETTLE_TICKS = 40;
@@ -52,10 +58,9 @@ public final class FlybyRunner {
private boolean waitForFocus;
private boolean exitWhenDone;
private boolean startedFromProperties;
private volatile boolean freezeRequested;
private final AtomicReference<FlybyRequest> pendingRequest = new AtomicReference<>();
private FlybyRequest activeRequest;
private String[] sceneCommands = NO_COMMANDS;
private String scenePlayerName;
private volatile boolean sceneRequested;
private volatile boolean sceneClearRequested;
private int sceneSpawnTotal;
private boolean pauseOnLostFocusSaved;
@@ -65,8 +70,13 @@ public final class FlybyRunner {
private static volatile boolean sceneGuarded;
private static volatile boolean worldChangesDiscarded;
private double originX, originY, originZ;
private float originYaw, originPitch;
private double parkedX, parkedY, parkedZ;
private float parkedYaw, parkedPitch;
private double originX, originZ;
private float originYaw;
private FlybyOrigin fixedOrigin;
private float eyeOffset;
private double flightY;
private double[] pathX = NO_PATH;
private double[] pathZ = NO_PATH;
@@ -111,8 +121,17 @@ public final class FlybyRunner {
return;
}
final FlybyOrigin origin;
try {
origin = FlybyOrigin.parse(SystemProperties.FLYBY_ORIGIN);
} catch (IllegalArgumentException e) {
LOGGER.error("Invalid flyby origin '{}', expected x,z[,yaw]", SystemProperties.FLYBY_ORIGIN);
return;
}
this.startedFromProperties = true;
this.start(configured, SystemProperties.FLYBY_LENGTH, SystemProperties.FLYBY_WARMUP_TICKS, SystemProperties.FLYBY_SPEED);
this.fixedOrigin = origin;
this.waitForTracy = SystemProperties.FLYBY_WAIT_FOR_TRACY;
this.waitForFocus = SystemProperties.FLYBY_WAIT_FOR_FOCUS;
this.exitWhenDone = SystemProperties.FLYBY_EXIT_WHEN_DONE;
@@ -137,6 +156,7 @@ public final class FlybyRunner {
this.waitForTracy = false;
this.waitForFocus = false;
this.exitWhenDone = false;
this.fixedOrigin = null;
sceneGuarded = false;
this.state = State.WAITING;
}
@@ -160,7 +180,7 @@ public final class FlybyRunner {
}
if (this.state == State.IDLE || this.state == State.DONE) return;
if (mc.theWorld == null && (this.state == State.WARMUP || this.state == State.RUNNING || this.state == State.SETTLE)) {
if (mc.theWorld == null && (this.state == State.PREPARING || this.state == State.WARMUP || this.state == State.RUNNING || this.state == State.SETTLE)) {
this.cancel();
return;
}
@@ -182,6 +202,12 @@ public final class FlybyRunner {
if (this.waitForFocus && !Display.isActive()) return;
this.begin(mc, player);
}
case PREPARING -> {
final Double feetY = this.activeRequest.feetY().getNow(null);
if (feetY == null) return;
this.flightY = feetY + this.eyeOffset;
this.startRun(mc);
}
case WARMUP -> {
this.applyPosition(player, 0);
if (++this.tick >= this.warmupTicks) {
@@ -231,25 +257,49 @@ public final class FlybyRunner {
mc.gameSettings.pauseOnLostFocus = false;
}
this.originX = player.posX;
this.originY = player.posY;
this.originZ = player.posZ;
this.originPitch = player.rotationPitch;
this.parkedX = player.posX;
this.parkedY = player.posY;
this.parkedZ = player.posZ;
this.parkedYaw = player.rotationYaw;
this.parkedPitch = player.rotationPitch;
this.eyeOffset = player.yOffset;
this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F;
if (this.originYaw != player.rotationYaw) {
LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw);
final boolean creative = player.capabilities.isCreativeMode;
if (!creative) {
LOGGER.warn("Flyby: player is not in creative mode, flying at the player height{}", this.fixedOrigin != null ? " and ignoring the pinned origin" : "");
}
if (creative && this.fixedOrigin != null) {
this.originX = this.fixedOrigin.x();
this.originZ = this.fixedOrigin.z();
this.originYaw = this.fixedOrigin.yaw();
} else {
this.originX = player.posX;
this.originZ = player.posZ;
this.originYaw = Math.round(player.rotationYaw / 90.0F) * 90.0F;
if (this.originYaw != player.rotationYaw) {
LOGGER.info("Flyby snapped heading {} -> {}", player.rotationYaw, this.originYaw);
}
}
this.buildPath();
this.freezeTimeAndWeather(mc);
if (this.sceneCommands.length > 0 && mc.getIntegratedServer() != null) {
this.scenePlayerName = player.getCommandSenderName();
this.sceneRequested = true;
}
this.suppressPacing();
this.tick = 0;
if (mc.getIntegratedServer() != null) {
final FlybyRequest request = new FlybyRequest(this.pathX, this.pathZ, this.originX, this.originZ, player.posY - this.eyeOffset, player.getCommandSenderName(), creative, this.sceneCommands.length > 0, new CompletableFuture<>());
this.activeRequest = request;
sceneGuarded = true;
this.pendingRequest.set(request);
this.state = State.PREPARING;
} else {
LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather or sample terrain - flying at the player height, results may not be comparable");
this.flightY = player.posY;
this.startRun(mc);
}
}
private void startRun(Minecraft mc) {
this.tick = 0;
if (this.warmupTicks > 0) {
this.state = State.WARMUP;
@@ -258,8 +308,7 @@ public final class FlybyRunner {
this.beginMeasuring(mc);
}
LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(),
this.originX, this.originY, this.originZ, this.originYaw);
LOGGER.info("Flyby {} starting at {} {} {} yaw {}", this.route.id(), this.originX, this.flightY, this.originZ, this.originYaw);
}
private void suppressPacing() {
@@ -393,12 +442,12 @@ public final class FlybyRunner {
player.ySize = 0.0F;
player.prevPosX = player.lastTickPosX = this.pathX[last];
player.prevPosY = player.lastTickPosY = this.originY;
player.prevPosY = player.lastTickPosY = this.flightY;
player.prevPosZ = player.lastTickPosZ = this.pathZ[last];
player.prevRotationYaw = player.rotationYaw = this.pathYaw[last];
player.prevRotationYawHead = player.rotationYawHead = this.pathYaw[last];
player.prevRotationPitch = player.rotationPitch = this.originPitch;
player.setPosition(this.pathX[last], this.originY, this.pathZ[last]);
player.prevRotationPitch = player.rotationPitch = this.parkedPitch;
player.setPosition(this.pathX[last], this.flightY, this.pathZ[last]);
}
private void applyPosition(EntityClientPlayerMP player, int index) {
@@ -418,37 +467,23 @@ public final class FlybyRunner {
player.ySize = 0.0F;
player.prevPosX = player.lastTickPosX = prevX;
player.prevPosY = player.lastTickPosY = this.originY;
player.prevPosY = player.lastTickPosY = this.flightY;
player.prevPosZ = player.lastTickPosZ = prevZ;
player.prevRotationYaw = prevYaw;
player.rotationYaw = yaw;
player.prevRotationYawHead = prevYaw;
player.rotationYawHead = yaw;
player.prevRotationPitch = player.rotationPitch = this.originPitch;
player.prevRotationPitch = player.rotationPitch = this.parkedPitch;
player.setPosition(x, this.originY, z);
}
/** Requests the freeze; the write happens on the server thread in {@link #onServerTick}. */
private void freezeTimeAndWeather(Minecraft mc) {
final MinecraftServer server = mc.getIntegratedServer();
if (server == null) {
LOGGER.warn("Flyby: not singleplayer, cannot freeze time/weather - results may not be comparable");
return;
}
sceneGuarded = true;
this.freezeRequested = true;
player.setPosition(x, this.flightY, z);
}
@SubscribeEvent
public void onServerTick(TickEvent.ServerTickEvent event) {
if (event.phase != TickEvent.Phase.END) return;
final boolean clear = this.sceneClearRequested;
final boolean freeze = this.freezeRequested;
final boolean scene = this.sceneRequested;
if (!clear && !freeze && !scene) return;
if (!clear && this.pendingRequest.get() == null) return;
final MinecraftServer server = MinecraftServer.getServer();
if (server == null) return;
@@ -457,16 +492,16 @@ public final class FlybyRunner {
this.sceneClearRequested = false;
this.clearScene(server);
}
if (freeze || scene) {
this.discardWorldChanges(server);
}
if (freeze) {
this.freezeRequested = false;
this.applyFreeze(server);
}
if (scene) {
this.sceneRequested = false;
this.runScene(server);
final FlybyRequest request = this.pendingRequest.getAndSet(null);
if (request == null) return;
this.discardWorldChanges(server);
final double feetY = this.flightFeetY(server, request);
request.feetY().complete(feetY);
this.applyFreeze(server);
if (request.scene()) {
this.runScene(server, request, feetY);
}
}
@@ -511,16 +546,52 @@ public final class FlybyRunner {
}
}
private void runScene(MinecraftServer server) {
final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(this.scenePlayerName);
private double flightFeetY(MinecraftServer server, FlybyRequest request) {
if (!request.sampleTerrain()) return request.parkedFeetY();
final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(request.playerName());
if (player == null) {
LOGGER.warn("Flyby scene: no server player named '{}', skipping scene", this.scenePlayerName);
LOGGER.warn("Flyby terrain: no server player named '{}', flying at the parked feet Y {}", request.playerName(), request.parkedFeetY());
return request.parkedFeetY();
}
final WorldServer world = player.getServerForPlayer();
if (world.provider.hasNoSky) {
LOGGER.info("Flyby terrain: dimension has a ceiling, flying at the parked feet Y {}", request.parkedFeetY());
return request.parkedFeetY();
}
final IChunkProvider chunks = world.getChunkProvider();
final int floor = FlybyTerrain.routeFloor(request.pathX(), request.pathZ(), FlybyTerrain.CORRIDOR_RADIUS, (x, z) -> precipitationHeight(chunks, x, z));
if (floor < 1) {
LOGGER.info("Flyby terrain: no ground within {} blocks of the path, flying at the parked feet Y {}", FlybyTerrain.CORRIDOR_RADIUS, request.parkedFeetY());
return request.parkedFeetY();
}
final double feetY = floor + FlybyTerrain.HOVER_BLOCKS;
LOGGER.info("Flyby terrain: route floor {} within {} blocks of the path, flight feet Y {}", floor, FlybyTerrain.CORRIDOR_RADIUS, feetY);
if (Tracy.ENABLED) Tracy.message("flyby terrain floor=" + floor + " radius=" + FlybyTerrain.CORRIDOR_RADIUS + " feetY=" + feetY);
return feetY;
}
private static int precipitationHeight(IChunkProvider chunks, int x, int z) {
final int chunkX = x >> 4;
final int chunkZ = z >> 4;
Chunk chunk = chunks.loadChunk(chunkX, chunkZ);
if (chunk == null) chunk = chunks.provideChunk(chunkX, chunkZ);
return chunk == null ? Integer.MIN_VALUE : chunk.getPrecipitationHeight(x & 15, z & 15);
}
private void runScene(MinecraftServer server, FlybyRequest request, double feetY) {
final EntityPlayerMP player = server.getConfigurationManager().func_152612_a(request.playerName());
if (player == null) {
LOGGER.warn("Flyby scene: no server player named '{}', skipping scene", request.playerName());
return;
}
this.clearScene(server);
final FlybyCommandSender sender = new FlybyCommandSender(player);
final FlybyCommandSender sender = new FlybyCommandSender(player, new ChunkCoordinates(MathHelper.floor_double(request.originX()), MathHelper.floor_double(feetY + 0.5D), MathHelper.floor_double(request.originZ())));
for (String line : this.sceneCommands) {
if (server.getCommandManager().executeCommand(sender, line) == 0) {
LOGGER.warn("flyby scene command did not execute: {}", line);
@@ -603,11 +674,11 @@ public final class FlybyRunner {
player.motionY = 0.0D;
player.motionZ = 0.0D;
player.ySize = 0.0F;
player.setPositionAndRotation(this.originX, this.originY, this.originZ, this.originYaw, this.originPitch);
player.lastTickPosX = this.originX;
player.lastTickPosY = this.originY;
player.lastTickPosZ = this.originZ;
LOGGER.info("Flyby returned to origin {} {} {}", this.originX, this.originY, this.originZ);
player.setPositionAndRotation(this.parkedX, this.parkedY, this.parkedZ, this.parkedYaw, this.parkedPitch);
player.lastTickPosX = this.parkedX;
player.lastTickPosY = this.parkedY;
player.lastTickPosZ = this.parkedZ;
LOGGER.info("Flyby returned to {} {} {}", this.parkedX, this.parkedY, this.parkedZ);
}
private String summarise(long elapsedNs, EntityClientPlayerMP player) {
@@ -656,8 +727,8 @@ public final class FlybyRunner {
FramePacer.endStats();
final Minecraft mc = Minecraft.getMinecraft();
this.restorePauseOnLostFocus(mc);
this.freezeRequested = false;
this.sceneRequested = false;
this.pendingRequest.set(null);
this.activeRequest = null;
sceneGuarded = false;
this.sceneClearRequested = this.sceneCommands.length > 0;
this.restorePacing(mc);
@@ -667,4 +738,6 @@ public final class FlybyRunner {
public boolean startedFromProperties() {
return this.startedFromProperties;
}
private record FlybyRequest(double[] pathX, double[] pathZ, double originX, double originZ, double parkedFeetY, String playerName, boolean sampleTerrain, boolean scene, CompletableFuture<Double> feetY) {}
}
@@ -0,0 +1,30 @@
package com.gtnewhorizons.angelica.debug.flyby;
import java.util.function.IntBinaryOperator;
final class FlybyTerrain {
static final int CORRIDOR_RADIUS = 2;
static final int HOVER_BLOCKS = 2;
private FlybyTerrain() {}
static int routeFloor(double[] pathX, double[] pathZ, int radius, IntBinaryOperator heights) {
int floor = Integer.MIN_VALUE;
int prevCellX = 0;
int prevCellZ = 0;
for (int i = 0; i < pathX.length; i++) {
final int cellX = (int) Math.floor(pathX[i]);
final int cellZ = (int) Math.floor(pathZ[i]);
if (i > 0 && cellX == prevCellX && cellZ == prevCellZ) continue;
prevCellX = cellX;
prevCellZ = cellZ;
for (int x = cellX - radius; x <= cellX + radius; x++) {
for (int z = cellZ - radius; z <= cellZ + radius; z++) {
floor = Math.max(floor, heights.applyAsInt(x, z));
}
}
}
return floor;
}
}
@@ -2,6 +2,9 @@ package com.gtnewhorizons.angelica.helpers;
import static com.gtnewhorizons.angelica.client.font.ColorCodeUtils.FORMATTING_CHAR;
import net.minecraft.client.renderer.entity.RenderDragon;
import net.minecraft.client.renderer.entity.RenderEnderman;
import net.minecraft.client.renderer.entity.RenderSpider;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
@@ -11,6 +14,10 @@ public final class RendererLivingEntityHelper {
private RendererLivingEntityHelper() {}
public static boolean hasEyePass(Object renderer) {
return renderer instanceof RenderSpider || renderer instanceof RenderEnderman || renderer instanceof RenderDragon;
}
public static String getUpsideDownName(EntityLivingBase entity) {
if (entity instanceof EntityLiving living) {
return living.hasCustomNameTag() ? entity.getCommandSenderName() : "";
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.iris;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.rendering.items.ItemRenderListManager;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
@@ -81,6 +82,7 @@ public final class ImmediateExtendedAttribs implements ImmediateExtendedAttribHa
@Override
public boolean wantsExtended() {
GLSMHooks.resolvePendingProgram();
return Iris.enabled && currentProgramWants != 0 && GLStateManager.getActiveProgram() != 0;
}
@@ -42,10 +42,6 @@ public class IrisGLSMBridge {
private static Runnable fogDensityListener = null;
private static Runnable colorModulatorListener = null;
private static boolean inputsDeferred = false;
private static boolean blendDeferred = false;
private static boolean programRestoreDeferred = false;
private static final Int2IntOpenHashMap programLastUpdatedFrame = new Int2IntOpenHashMap();
@@ -269,32 +265,19 @@ public class IrisGLSMBridge {
}
if (!updatePipeline) return;
if (GLStateManager.isForeignDraw()) {
inputsDeferred = true;
return;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setInputs(StateTracker.INSTANCE.getInputs());
}
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
});
GLSMHooks.VANILLA_BLEND_CHANGE.addListener(event -> {
if (!Iris.enabled) return;
if (GLStateManager.isForeignDraw()) {
blendDeferred = true;
return;
}
refreshBlendCondition();
});
GLSMHooks.FOREIGN_DRAW_END.addListener(event -> {
if (!Iris.enabled) return;
if (inputsDeferred) {
inputsDeferred = false;
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setInputs(StateTracker.INSTANCE.getInputs()));
}
if (blendDeferred) {
blendDeferred = false;
refreshBlendCondition();
}
if (programRestoreDeferred) {
programRestoreDeferred = false;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
@@ -64,6 +64,7 @@ public enum Mixins implements IMixins {
, "angelica.ffp.MixinTessellator_CoreProfile"
, "angelica.glsm.MixinSplashProgressCaching"
, "angelica.gui.MixinGuiOptions"
, "angelica.optimizations.MixinRenderBiped_ArmorResource"
, "angelica.optimizations.MixinRendererLivingEntity"
, "angelica.rendering.MixinRenderGlobal_SelectionBox"
, "angelica.gui.MixinGuiIngameForge_ModernF3"
@@ -170,15 +171,29 @@ public enum Mixins implements IMixins {
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableEntityBatching)
.addClientMixins(
"angelica.entity.MixinItemRenderer_Instanced",
"angelica.entity.MixinModelRenderer",
"angelica.entity.MixinRenderGlobal_EntityBatch",
"angelica.entity.MixinRenderItem_Instanced",
"angelica.entity.MixinRenderManager_BatchEligibility",
"angelica.entity.MixinRendererLivingEntity_EquippedDraws",
"angelica.entity.MixinRendererLivingEntity_GlintClock",
"angelica.entity.MixinRendererLivingEntity_ModelPassDraws",
"angelica.entity.MixinRender_BatchEligibility",
"angelica.entity.MixinRender_ShadowBatch",
"angelica.entity.MixinTextureManager",
"angelica.tesr.MixinTileEntitySpecialRenderer_BatchEligibility"
)
),
ANGELICA_CUBE_INSTANCING(new MixinBuilder("Capture cuboid parameters so model cubes can be drawn from a shared unit cube")
.setPhase(Phase.EARLY)
.setApplyIf(AngelicaConfig::cubeInstancingEnabled)
.addClientMixins(
"angelica.entity.MixinModelBox_CubeParams"
)
),
ANGELICA_SKIP_END_FRAME_FLUSH(new MixinBuilder("Skip the end-of-frame glFlush before the buffer swap")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.skipEndOfFrameFlush)
@@ -298,9 +313,9 @@ public enum Mixins implements IMixins {
.setPhase(Phase.EARLY)
.addClientMixins("angelica.optimizations.MixinGLAllocation")),
ANGELICA_DEFERRED_TESSELLATOR_BATCH(new MixinBuilder("Deferred tessellator batching for particles to reduce draw calls")
ANGELICA_PARTICLE_BATCH(new MixinBuilder("Particle instancing, with deferred tessellator batching as the fallback")
.setPhase(Phase.EARLY)
.addClientMixins("angelica.particles.MixinEffectRenderer_DeferredBatch")),
.addClientMixins("angelica.particles.MixinEffectRenderer_ParticleBatch")),
// Not compatible with the lwjgl debug callbacks, so disable if that's enabled
ARCHAIC_SPLASH(new MixinBuilder()
@@ -785,6 +800,11 @@ public enum Mixins implements IMixins {
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer")
),
DRAGONAPI_PARTICLE_BATCH(new MixinBuilder("Particle instancing for DragonAPI's replacement particle renderer")
.setPhase(Phase.LATE)
.addRequiredMod(TargetedMod.DRAGON_API)
.addClientMixins("client.dragonapi.MixinThrottleableEffectRenderer_ParticleBatch")
),
MCPATCHER_FORGE(new MixinBuilder()
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableMCPatcherForgeFeatures)
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.mixins.interfaces;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
public interface ModelBoxData {
CubeParams angelica$cubeParams();
}
@@ -10,6 +10,7 @@ import net.minecraft.client.Minecraft;
public final class BailClassCounts {
public static final BailClassCounts MATERIAL = new BailClassCounts("tesr.bailCls.mat.", "BailMat");
public static final BailClassCounts TEMPLATE = new BailClassCounts("tesr.bailCls.tmpl.", "BailTmpl");
public static final BailClassCounts PARTICLE_SPILL = new BailClassCounts("particles.spillCls.", "PartSpill");
private final String plotPrefix;
private final String label;
@@ -14,6 +14,8 @@ import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import com.gtnewhorizons.angelica.rendering.celeritas.TerrainDrawStats;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink;
import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer;
import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
@@ -24,31 +26,21 @@ import org.embeddedt.embeddium.impl.render.chunk.SharedQuadIndexBuffer;
import org.embeddedt.embeddium.impl.render.chunk.region.RenderRegionManager;
public final class TracyFramePlots {
private static long lastChunkUpdates;
private static long lastDrawCalls, lastTexBindMisses, lastProgramSwitches, lastListPlaybacks;
private static long lastStreamedBytes, lastStreamDraws, lastOrphanFallbacks, lastStreamContiguous;
private static long lastRingWraps, lastVariantSwitches;
private static long lastTesrRebuilds, lastTesrRetainedDraws, lastTesrInstDraws, lastTesrInstInstances;
private static long lastTesrStreamedInstances, lastTesrPromotions, lastTesrCacheHits, lastTesrCacheMisses;
private static long lastBatcherParts, lastBatcherLiveFallbacks;
private static final long[] lastBails = new long[ModelPartBatcher.BailReason.VALUES.length];
private static long lastSectionsUploaded, lastBytesUploaded, lastIndexBufferGrowths;
private static final long P_ALLOC_RATE = Tracy.plotHandle("allocRate", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_HEAP_USED = Tracy.plotHandle("heapUsed", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_CHUNK_UPDATES = Tracy.plotHandle("chunkUpdates");
private static final PlotDelta P_CHUNK_UPDATES = new PlotDelta("chunkUpdates");
private static final long P_ENTITIES_RENDERED = Tracy.plotHandle("entitiesRendered");
private static final long P_ENTITIES_TOTAL = Tracy.plotHandle("entitiesTotal");
private static final long P_GL_DRAW_CALLS = Tracy.plotHandle("gl.drawCalls");
private static final long P_GL_TEX_BIND_MISSES = Tracy.plotHandle("gl.texBindMisses");
private static final long P_GL_PROGRAM_SWITCHES = Tracy.plotHandle("gl.programSwitches");
private static final long P_GL_LIST_PLAYBACKS = Tracy.plotHandle("gl.listPlaybacks");
private static final long P_GL_STREAMED_BYTES = Tracy.plotHandle("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_GL_STREAM_DRAWS = Tracy.plotHandle("gl.streamDraws");
private static final long P_GL_ORPHAN_FALLBACKS = Tracy.plotHandle("gl.orphanFallbacks");
private static final long P_GL_STREAM_CONTIGUOUS = Tracy.plotHandle("gl.streamContiguous");
private static final long P_GL_RING_WRAPS = Tracy.plotHandle("gl.ringWraps");
private static final PlotDelta P_GL_DRAW_CALLS = new PlotDelta("gl.drawCalls");
private static final PlotDelta P_GL_TEX_BIND_MISSES = new PlotDelta("gl.texBindMisses");
private static final PlotDelta P_GL_PROGRAM_SWITCHES = new PlotDelta("gl.programSwitches");
private static final PlotDelta P_GL_LIST_PLAYBACKS = new PlotDelta("gl.listPlaybacks");
private static final PlotDelta P_GL_STREAMED_BYTES = new PlotDelta("gl.streamedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final PlotDelta P_GL_STREAM_DRAWS = new PlotDelta("gl.streamDraws");
private static final PlotDelta P_GL_ORPHAN_FALLBACKS = new PlotDelta("gl.orphanFallbacks");
private static final PlotDelta P_GL_STREAM_CONTIGUOUS = new PlotDelta("gl.streamContiguous");
private static final PlotDelta P_GL_RING_WRAPS = new PlotDelta("gl.ringWraps");
private static final long P_GL_SECTION_META_BYTES = Tracy.plotHandle("gl.sectionMetaBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_SHADOW_RELAY_FRAMES = Tracy.plotHandle("shadow.relayFrames");
@@ -59,7 +51,7 @@ public final class TracyFramePlots {
private static final long P_VOX_DISPATCHES = Tracy.plotHandle("voxelization.dispatches");
private static final long P_VOX_REGIONS = Tracy.plotHandle("voxelization.regions");
private static final long P_DRAW_BATCH_REBUILDS = Tracy.plotHandle("draw.batchRebuilds");
private static final long P_DRAW_INDEX_BUFFER_GROWTHS = Tracy.plotHandle("draw.indexBufferGrowths");
private static final PlotDelta P_DRAW_INDEX_BUFFER_GROWTHS = new PlotDelta("draw.indexBufferGrowths");
private static final long P_CULL_COMMANDS_SUBMITTED = Tracy.plotHandle("cull.commandsSubmitted");
private static final long P_CULL_REGIONS_DRAWN = Tracy.plotHandle("cull.regionsDrawn");
@@ -79,24 +71,37 @@ public final class TracyFramePlots {
private static final long P_FFP_STAGED_CLIP_PLANES = Tracy.plotHandle("ffp.stagedClipPlanes");
private static final long P_FFP_STAGED_MISC = Tracy.plotHandle("ffp.stagedMisc");
private static final long P_FFP_PROGRAMS = Tracy.plotHandle("ffp.programs");
private static final long P_FFP_VARIANT_SWITCHES = Tracy.plotHandle("ffp.variantSwitches");
private static final PlotDelta P_FFP_VARIANT_SWITCHES = new PlotDelta("ffp.variantSwitches");
private static final long P_TESR_REBUILDS = Tracy.plotHandle("tesr.rebuilds");
private static final long P_TESR_RETAINED_DRAWS = Tracy.plotHandle("tesr.retainedDraws");
private static final long P_TESR_INSTANCED_DRAWS = Tracy.plotHandle("tesr.instancedDraws");
private static final long P_TESR_INSTANCED_INSTANCES = Tracy.plotHandle("tesr.instancedInstances");
private static final long P_TESR_STREAMED_INSTANCES = Tracy.plotHandle("tesr.streamedInstances");
private static final long P_TESR_VOLATILE_PROMOTIONS = Tracy.plotHandle("tesr.volatilePromotions");
private static final PlotDelta P_TESR_REBUILDS = new PlotDelta("tesr.rebuilds");
private static final PlotDelta P_TESR_RETAINED_DRAWS = new PlotDelta("tesr.retainedDraws");
private static final PlotDelta P_TESR_INSTANCED_DRAWS = new PlotDelta("tesr.instancedDraws");
private static final PlotDelta P_TESR_INSTANCED_INSTANCES = new PlotDelta("tesr.instancedInstances");
private static final PlotDelta P_TESR_CUBE_INSTANCES = new PlotDelta("tesr.cubeInstances");
private static final PlotDelta P_TESR_TEXMAT_RUNS = new PlotDelta("tesr.texMatrixRuns");
private static final PlotDelta P_TESR_STREAMED_INSTANCES = new PlotDelta("tesr.streamedInstances");
private static final PlotDelta P_TESR_VOLATILE_PROMOTIONS = new PlotDelta("tesr.volatilePromotions");
private static final long P_TESR_RETAINED_BYTES = Tracy.plotHandle("tesr.retainedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_TESR_BUFFER_SOURCE_BYTES = Tracy.plotHandle("tesr.bufferSourceBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_TESR_CACHE_HITS = Tracy.plotHandle("tesr.cacheHits");
private static final long P_TESR_CACHE_MISSES = Tracy.plotHandle("tesr.cacheMisses");
private static final long P_TESR_MODEL_PARTS = Tracy.plotHandle("tesr.modelParts");
private static final long P_TESR_LIVE_FALLBACKS = Tracy.plotHandle("tesr.liveFallbacks");
private static final long[] P_TESR_BAILS = bailHandles();
private static final PlotDelta P_TESR_CACHE_HITS = new PlotDelta("tesr.cacheHits");
private static final PlotDelta P_TESR_CACHE_MISSES = new PlotDelta("tesr.cacheMisses");
private static final PlotDelta P_TESR_MODEL_PARTS = new PlotDelta("tesr.modelParts");
private static final PlotDelta P_TESR_LIVE_FALLBACKS = new PlotDelta("tesr.liveFallbacks");
private static final PlotDelta P_ITEMS_INSTANCED = new PlotDelta("items.instanced");
private static final PlotDelta P_ITEMS_FALLBACK = new PlotDelta("items.fallback");
private static final PlotDelta P_ITEMS_GLINT_INSTANCED = new PlotDelta("items.glintInstanced");
private static final PlotDelta P_PARTICLES_DIRECT = new PlotDelta("particles.direct");
private static final PlotDelta P_PARTICLES_CAPTURED = new PlotDelta("particles.captured");
private static final PlotDelta P_PARTICLES_SPILLED = new PlotDelta("particles.spilled");
private static final PlotDelta P_PARTICLES_UNDECODABLE = new PlotDelta("particles.undecodable");
private static final PlotDelta P_PARTICLES_DRAWS = new PlotDelta("particles.draws");
private static final PlotDelta[] TESR_BAILS = bailHandles();
private static final PlotDelta[] ITEM_BAILS = itemBailHandles();
private static final PlotDelta P_ENTITY_SHADOW_QUADS = new PlotDelta("entity.shadowQuads");
private static final PlotDelta P_ENTITY_SHADOW_DRAWS = new PlotDelta("entity.shadowDraws");
private static final long P_MESH_UPLOADED_SECTIONS = Tracy.plotHandle("mesh.uploadedSections");
private static final long P_MESH_UPLOADED_BYTES = Tracy.plotHandle("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final PlotDelta P_MESH_UPLOADED_SECTIONS = new PlotDelta("mesh.uploadedSections");
private static final PlotDelta P_MESH_UPLOADED_BYTES = new PlotDelta("mesh.uploadedBytes", TracyBackend.PLOT_FORMAT_MEMORY);
private static final long P_MESH_META_SLOTS = Tracy.plotHandle("mesh.metaSlots");
private static final long P_MT_QUEUE_DEPTH = Tracy.plotHandle("mtQueue.depth");
private static final long P_MT_QUEUE_TASKS = Tracy.plotHandle("mtQueue.tasksRan");
@@ -110,10 +115,17 @@ public final class TracyFramePlots {
private static final long P_DYN_UPDATES = Tracy.plotHandle("dyn.updates");
private static final long P_DYN_PENDING_REBUILDS = Tracy.plotHandle("dyn.pendingRebuilds");
private static long[] bailHandles() {
private static PlotDelta[] bailHandles() {
final ModelPartBatcher.BailReason[] reasons = ModelPartBatcher.BailReason.VALUES;
final long[] out = new long[reasons.length];
for (int i = 0; i < reasons.length; i++) out[i] = Tracy.plotHandle(reasons[i].plotName);
final PlotDelta[] out = new PlotDelta[reasons.length];
for (int i = 0; i < reasons.length; i++) out[i] = new PlotDelta(reasons[i].plotName);
return out;
}
private static PlotDelta[] itemBailHandles() {
final DroppedItemInstancer.BailReason[] reasons = DroppedItemInstancer.BailReason.VALUES;
final PlotDelta[] out = new PlotDelta[reasons.length];
for (int i = 0; i < reasons.length; i++) out[i] = new PlotDelta(reasons[i].plotName);
return out;
}
@@ -153,9 +165,7 @@ public final class TracyFramePlots {
Tracy.plotInt(P_PACER_LOCKED, FramePacer.locked() ? 1 : 0);
Tracy.plotInt(P_PACER_PROBING, FramePacer.probing() ? 1 : 0);
final int chunksUpdated = WorldRenderer.chunksUpdated;
Tracy.plotInt(P_CHUNK_UPDATES, chunksUpdated - lastChunkUpdates);
lastChunkUpdates = chunksUpdated;
P_CHUNK_UPDATES.plot(WorldRenderer.chunksUpdated);
if (mc.renderGlobal != null) {
Tracy.plotInt(P_ENTITIES_RENDERED, mc.renderGlobal.countEntitiesRendered);
}
@@ -163,15 +173,15 @@ public final class TracyFramePlots {
Tracy.plotInt(P_ENTITIES_TOTAL, mc.theWorld.loadedEntityList.size());
}
lastDrawCalls = delta(P_GL_DRAW_CALLS, GLStateManager.drawCalls, lastDrawCalls);
lastTexBindMisses = delta(P_GL_TEX_BIND_MISSES, GLStateManager.texBindMisses, lastTexBindMisses);
lastProgramSwitches = delta(P_GL_PROGRAM_SWITCHES, GLStateManager.programSwitches, lastProgramSwitches);
lastListPlaybacks = delta(P_GL_LIST_PLAYBACKS, DisplayListManager.listPlaybacks, lastListPlaybacks);
lastStreamedBytes = delta(P_GL_STREAMED_BYTES, TessellatorStreamingDrawer.streamedBytes, lastStreamedBytes);
lastStreamDraws = delta(P_GL_STREAM_DRAWS, TessellatorStreamingDrawer.streamDraws, lastStreamDraws);
lastOrphanFallbacks = delta(P_GL_ORPHAN_FALLBACKS, TessellatorStreamingDrawer.orphanFallbacks, lastOrphanFallbacks);
lastStreamContiguous = delta(P_GL_STREAM_CONTIGUOUS, TessellatorStreamingDrawer.streamContiguous, lastStreamContiguous);
lastRingWraps = delta(P_GL_RING_WRAPS, TessellatorStreamingDrawer.ringWraps(), lastRingWraps);
P_GL_DRAW_CALLS.plot(GLStateManager.drawCalls);
P_GL_TEX_BIND_MISSES.plot(GLStateManager.texBindMisses);
P_GL_PROGRAM_SWITCHES.plot(GLStateManager.programSwitches);
P_GL_LIST_PLAYBACKS.plot(DisplayListManager.listPlaybacks);
P_GL_STREAMED_BYTES.plot(TessellatorStreamingDrawer.streamedBytes);
P_GL_STREAM_DRAWS.plot(TessellatorStreamingDrawer.streamDraws);
P_GL_ORPHAN_FALLBACKS.plot(TessellatorStreamingDrawer.orphanFallbacks);
P_GL_STREAM_CONTIGUOUS.plot(TessellatorStreamingDrawer.streamContiguous);
P_GL_RING_WRAPS.plot(TessellatorStreamingDrawer.ringWraps());
Tracy.plotInt(P_GL_SECTION_META_BYTES, TerrainDrawStats.takeSectionMetaBytes());
Tracy.plotInt(P_SHADOW_RELAY_FRAMES, ShadowRenderer.SHADOW_TERRAIN_RELAID ? 1 : 0);
Tracy.plotInt(P_TERRAIN_DRAW_COMMANDS, TerrainDrawStats.takeCommandsSubmitted());
@@ -199,33 +209,47 @@ public final class TracyFramePlots {
Tracy.plotInt(P_FFP_STAGED_CLIP_PLANES, ffp.statLastFrameStagedClipPlanes());
Tracy.plotInt(P_FFP_STAGED_MISC, ffp.statLastFrameStagedMisc());
Tracy.plotInt(P_FFP_PROGRAMS, ffp.statProgramCount());
lastVariantSwitches = delta(P_FFP_VARIANT_SWITCHES, ShaderManager.variantSwitches, lastVariantSwitches);
P_FFP_VARIANT_SWITCHES.plot(ShaderManager.variantSwitches);
final TesrBatchRenderer tesr = TesrBatchRenderer.INSTANCE;
final ModelPartBatcher batcher = ModelPartBatcher.INSTANCE;
lastTesrRebuilds = delta(P_TESR_REBUILDS, tesr.statRebuilds(), lastTesrRebuilds);
lastTesrRetainedDraws = delta(P_TESR_RETAINED_DRAWS, tesr.statRetainedDraws(), lastTesrRetainedDraws);
lastTesrInstDraws = delta(P_TESR_INSTANCED_DRAWS, tesr.statInstancedDraws(), lastTesrInstDraws);
lastTesrInstInstances = delta(P_TESR_INSTANCED_INSTANCES, tesr.statInstancedInstances(), lastTesrInstInstances);
lastTesrStreamedInstances = delta(P_TESR_STREAMED_INSTANCES, tesr.statStreamedInstances(), lastTesrStreamedInstances);
lastTesrPromotions = delta(P_TESR_VOLATILE_PROMOTIONS, tesr.statVolatilePromotions(), lastTesrPromotions);
P_TESR_REBUILDS.plot(tesr.statRebuilds());
P_TESR_RETAINED_DRAWS.plot(tesr.statRetainedDraws());
P_TESR_INSTANCED_DRAWS.plot(tesr.statInstancedDraws() + batcher.statInstancedDraws());
P_TESR_INSTANCED_INSTANCES.plot(tesr.statInstancedInstances() + batcher.statInstancedInstances());
P_TESR_CUBE_INSTANCES.plot(batcher.statCubeInstances());
P_TESR_TEXMAT_RUNS.plot(batcher.statTexMatrixRuns());
P_TESR_STREAMED_INSTANCES.plot(tesr.statStreamedInstances());
P_TESR_VOLATILE_PROMOTIONS.plot(tesr.statVolatilePromotions());
if (plots) {
Tracy.plotInt(P_TESR_RETAINED_BYTES, tesr.statRetainedBytes());
Tracy.plotInt(P_TESR_BUFFER_SOURCE_BYTES, tesr.statBufferSourceBytes());
}
lastTesrCacheHits = delta(P_TESR_CACHE_HITS, AngelicaTesrMeshCache.cacheHits, lastTesrCacheHits);
lastTesrCacheMisses = delta(P_TESR_CACHE_MISSES, AngelicaTesrMeshCache.cacheMisses, lastTesrCacheMisses);
lastBatcherParts = delta(P_TESR_MODEL_PARTS, batcher.statParts(), lastBatcherParts);
lastBatcherLiveFallbacks = delta(P_TESR_LIVE_FALLBACKS, batcher.statLiveFallbacks(), lastBatcherLiveFallbacks);
P_TESR_CACHE_HITS.plot(AngelicaTesrMeshCache.cacheHits);
P_TESR_CACHE_MISSES.plot(AngelicaTesrMeshCache.cacheMisses);
P_TESR_MODEL_PARTS.plot(batcher.statParts());
P_TESR_LIVE_FALLBACKS.plot(batcher.statLiveFallbacks());
P_ITEMS_INSTANCED.plot(DroppedItemInstancer.statInstanced());
P_ITEMS_FALLBACK.plot(DroppedItemInstancer.statFallback());
P_ITEMS_GLINT_INSTANCED.plot(DroppedItemInstancer.statGlintInstanced());
for (final DroppedItemInstancer.BailReason reason : DroppedItemInstancer.BailReason.VALUES) {
ITEM_BAILS[reason.ordinal()].plot(DroppedItemInstancer.statBail(reason));
}
P_PARTICLES_DIRECT.plot(ParticleInstancer.getDirect());
P_PARTICLES_CAPTURED.plot(ParticleInstancer.getCaptured());
P_PARTICLES_SPILLED.plot(ParticleInstancer.getSpilled());
P_PARTICLES_UNDECODABLE.plot(ParticleInstancer.getUndecodable());
P_PARTICLES_DRAWS.plot(ParticleInstancer.getDraws());
P_ENTITY_SHADOW_QUADS.plot(batcher.statShadowQuads());
P_ENTITY_SHADOW_DRAWS.plot(batcher.statShadowDraws());
for (final ModelPartBatcher.BailReason reason : ModelPartBatcher.BailReason.VALUES) {
final int i = reason.ordinal();
lastBails[i] = delta(P_TESR_BAILS[i], batcher.statBail(reason), lastBails[i]);
TESR_BAILS[reason.ordinal()].plot(batcher.statBail(reason));
}
lastSectionsUploaded = delta(P_MESH_UPLOADED_SECTIONS, RenderRegionManager.getSectionsUploaded(), lastSectionsUploaded);
lastBytesUploaded = delta(P_MESH_UPLOADED_BYTES, RenderRegionManager.getBytesUploaded(), lastBytesUploaded);
lastIndexBufferGrowths = delta(P_DRAW_INDEX_BUFFER_GROWTHS, SharedQuadIndexBuffer.getGrowths(), lastIndexBufferGrowths);
P_MESH_UPLOADED_SECTIONS.plot(RenderRegionManager.getSectionsUploaded());
P_MESH_UPLOADED_BYTES.plot(RenderRegionManager.getBytesUploaded());
P_DRAW_INDEX_BUFFER_GROWTHS.plot(SharedQuadIndexBuffer.getGrowths());
Tracy.plotInt(P_MESH_META_SLOTS, GpuCulling.sectionMeta().getHighWaterMark());
Tracy.plotInt(P_MT_QUEUE_DEPTH, AngelicaRenderQueue.getQueueDepth());
Tracy.plotInt(P_MT_QUEUE_TASKS, AngelicaRenderQueue.getLastFrameTasksRan());
@@ -253,10 +277,24 @@ public final class TracyFramePlots {
RenderClassTimings.TESR.flushFrame(plots);
BailClassCounts.MATERIAL.flushFrame(plots);
BailClassCounts.TEMPLATE.flushFrame(plots);
BailClassCounts.PARTICLE_SPILL.flushFrame(plots);
}
private static long delta(long handle, long now, long last) {
Tracy.plotInt(handle, now - last);
return now;
private static final class PlotDelta {
private final long handle;
private long last;
PlotDelta(String name) {
this(name, TracyBackend.PLOT_FORMAT_NUMBER);
}
PlotDelta(String name, int format) {
handle = Tracy.plotHandle(name, format);
}
void plot(long now) {
Tracy.plotInt(handle, now - last);
last = now;
}
}
}
@@ -0,0 +1,38 @@
package com.gtnewhorizons.angelica.rendering;
import java.util.Arrays;
public final class ArmorTexturePaths {
private static final int STRIDE = 5;
private static String[] table = new String[0];
public static String path(String prefix, int renderIndex, int slot, String type) {
if (prefix == null || (type != null && !"overlay".equals(type))) return format(prefix, slot, type);
String[] t = table;
final int base = renderIndex * STRIDE;
if (base >= t.length) {
t = Arrays.copyOf(t, base + STRIDE);
table = t;
}
if (t[base] != prefix) {
t[base + 1] = null;
t[base + 2] = null;
t[base + 3] = null;
t[base + 4] = null;
t[base] = prefix;
}
final int k = base + 1 + (slot == 2 ? 1 : 0) + (type == null ? 0 : 2);
String p = t[k];
if (p == null) {
p = format(prefix, slot, type);
t[k] = p;
}
return p;
}
private static String format(String prefix, int slot, String type) {
return "textures/models/armor/" + prefix + (slot == 2 ? "_layer_2" : "_layer_1") + (type == null ? ".png" : "_" + type + ".png");
}
private ArmorTexturePaths() {}
}
@@ -0,0 +1,56 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import org.joml.Matrix4fc;
public final class GlintClock {
private static final double SPEED0 = 0.001;
private static final double SPEED1 = 0.001 + 0.003;
private static final double SIN0 = Math.sin(Math.toRadians(30.0));
private static final double COS0 = Math.cos(Math.toRadians(30.0));
private static final double SIN1 = Math.sin(Math.toRadians(-30.0));
private static final double COS1 = Math.cos(Math.toRadians(-30.0));
private static long millis;
private static float armorU0, armorV0, armorU1, armorV1;
public static void beginFrame(long nowMillis) {
millis = nowMillis;
final double ticks = nowMillis / 50.0;
final double f0 = ticks * SPEED0 * 20.0;
final double du0 = frac(-f0 * SIN0 / 3.0);
final double dv0 = frac(f0 * COS0 / 3.0);
armorU0 = (float) (3.0 * (COS0 * du0 + SIN0 * dv0));
armorV0 = (float) (3.0 * (-SIN0 * du0 + COS0 * dv0));
final double f1 = ticks * SPEED1 * 20.0;
final double du1 = frac(-f1 * SIN1 / 3.0);
final double dv1 = frac(f1 * COS1 / 3.0);
armorU1 = (float) (3.0 * (COS1 * du1 + SIN1 * dv1));
armorV1 = (float) (3.0 * (-SIN1 * du1 + COS1 * dv1));
}
public static long millis() {
return millis;
}
static boolean secondArmorLayer(Matrix4fc textureMatrix) {
return textureMatrix.m01() < 0f;
}
public static void translateArmorGlint() {
if (secondArmorLayer(GLStateManager.getMatrixStack())) {
GLStateManager.glTranslatef(armorU1, armorV1, 0f);
} else {
GLStateManager.glTranslatef(armorU0, armorV0, 0f);
}
}
private static double frac(double x) {
return x - Math.floor(x);
}
private GlintClock() {}
}
@@ -0,0 +1,14 @@
package com.gtnewhorizons.angelica.rendering;
public final class OperationArgs {
private OperationArgs() {}
public static Object boxed(Object prev, float v) {
return prev instanceof Float f && Float.floatToRawIntBits(f) == Float.floatToRawIntBits(v) ? prev : Float.valueOf(v);
}
public static Object boxed(Object prev, int v) {
return prev instanceof Integer i && i == v ? prev : Integer.valueOf(v);
}
}
@@ -49,6 +49,10 @@ public final class ParticleRunSplitter {
}
}
public static boolean currentRunTranslucent() {
return runTranslucent;
}
public static boolean isTranslucent(EntityFX particle) {
if (particle.particleIcon instanceof TextureAtlasSprite sprite) {
return ((SpriteExtension) sprite).celeritas$getTransparencyLevel() == SpriteTransparencyLevel.TRANSLUCENT;
@@ -88,6 +88,7 @@ public class CeleritasDebugScreenHandler {
addIfPresent(lines, RenderClassTimings.SHADOW_ENTITY.debugLine());
addIfPresent(lines, BailClassCounts.MATERIAL.debugLine());
addIfPresent(lines, BailClassCounts.TEMPLATE.debugLine());
addIfPresent(lines, BailClassCounts.PARTICLE_SPILL.debugLine());
}
}
lines.add("");
@@ -54,6 +54,7 @@ import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.TileEntityRenderBoundsRegistry;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
@@ -168,6 +169,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
ShadowRenderer.globalTileEntities.clear();
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
ParticleInstancer.clear();
GpuCulling.onWorldUnload();
FfpExtendedAttribs.reset();
BopFogBlend.invalidate();
@@ -80,9 +80,9 @@ public class BlockRenderListManager {
}
private static final class BlockMeta {
private Block block;
private int meta;
static final class BlockMeta {
Block block;
int meta;
public BlockMeta() {
@@ -0,0 +1,304 @@
package com.gtnewhorizons.angelica.rendering.items;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.rendering.OperationArgs;
import com.gtnewhorizons.angelica.rendering.items.BlockRenderListManager.BlockMeta;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.BakedTransformCapture;
import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility;
import com.gtnewhorizons.angelica.rendering.tesr.EntityMaterials;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.item.ItemStack;
public final class DroppedItemInstancer {
private static final int CAPTURE_BYTES = 64 * 1024;
private static final ItemPropCache<IconMesh> icons = new ItemPropCache<>(() -> AngelicaConfig.itemRendererCacheSize, IconMesh::new, null);
private static final Object2ObjectOpenHashMap<BlockMeta, BlockMesh> blocks = new Object2ObjectOpenHashMap<>();
private static final BlockMeta blockKey = new BlockMeta();
private static final AngelicaTesrMeshCache.GtnhMeshBackend iconBackend = new AngelicaTesrMeshCache.GtnhMeshBackend();
private static final Object[] ICON_ARGS = new Object[8];
private static final Object[] GLINT_ARGS = new Object[8];
private static final Object[] BLOCK_ARGS = new Object[4];
private static BakedTransformCapture blockBackend;
private static boolean basePart;
private static long instanced;
private static long glintInstanced;
private static long fallback;
public enum BailReason {
INELIGIBLE("items.bail.ineligible"),
NO_MATERIAL("items.bail.material"),
ISBRH("items.bail.isbrh"),
BLOCK_STATE("items.bail.blockState"),
NOT_ALLOWED("items.bail.notAllowed"),
TEMPLATE("items.bail.template"),
QUEUE("items.bail.queue");
public static final BailReason[] VALUES = values();
public final String plotName;
BailReason(String plotName) {
this.plotName = plotName;
}
}
private static final long[] bails = new long[BailReason.VALUES.length];
private DroppedItemInstancer() {}
public static long statInstanced() {
return instanced;
}
public static long statGlintInstanced() {
return glintInstanced;
}
public static long statFallback() {
return fallback;
}
public static long statBail(BailReason reason) {
return bails[reason.ordinal()];
}
private static void bail(BailReason reason) {
bails[reason.ordinal()]++;
}
private static boolean glintEligible(ItemStack stack) {
return stack != null && stack.getItem() != null && ModelPartBatcher.INSTANCE.isActive() && !GLStateManager.isRecordingDisplayList() && !TessellatorManager.isCurrentlyCapturing() && !TessellatorManager.shouldInterceptDraw(Tessellator.instance);
}
static TesrMaterial material(ItemStack stack, boolean unfilteredAtlas) {
if (stack == null) return null;
if (!glintEligible(stack)) {
fallback++;
bail(BailReason.INELIGIBLE);
return null;
}
final TesrMaterial material = EntityMaterials.itemFromCurrentState(unfilteredAtlas);
if (material == null) {
fallback++;
bail(BailReason.NO_MATERIAL);
}
return material;
}
public static void icon(ItemStack stack, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
final TesrMaterial material = material(stack, true);
if (material == null) {
basePart = false;
callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
return;
}
basePart = batchIcon(material, t, maxU, minV, minU, maxV, width, height, thickness, original);
}
static boolean batchIcon(TesrMaterial material, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
final long drawsBefore = GLStateManager.drawCalls;
if (BatchEligibility.batchingAllowed()) {
final TemplateBuffer template = iconTemplate(ICON_ARGS, maxU, minV, minU, maxV, width, height, thickness, original);
if (template == null) {
callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
fallback++;
bail(BailReason.TEMPLATE);
return false;
}
if (ModelPartBatcher.INSTANCE.queueTemplate(template, material)) {
instanced++;
BatchEligibility.onPartQueued();
return true;
}
fallback++;
bail(BailReason.QUEUE);
} else {
bail(BailReason.NOT_ALLOWED);
}
callIcon(ICON_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls);
return true;
}
public static void glint(Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
if (!basePart) {
callIcon(GLINT_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
return;
}
final boolean allowed = BatchEligibility.batchingAllowed();
if (allowed && ModelPartBatcher.INSTANCE.isShadowPass()) {
BatchEligibility.onPartQueued();
return;
}
final long drawsBefore = GLStateManager.drawCalls;
if (allowed) {
final TemplateBuffer template = iconTemplate(GLINT_ARGS, maxU, minV, minU, maxV, width, height, thickness, original);
if (template != null && ModelPartBatcher.INSTANCE.queueTemplate(template, EntityMaterials.GLINT)) {
glintInstanced++;
BatchEligibility.onPartQueued();
return;
}
fallback++;
bail(template == null ? BailReason.TEMPLATE : BailReason.QUEUE);
} else {
bail(BailReason.NOT_ALLOWED);
}
callIcon(GLINT_ARGS, original, t, maxU, minV, minU, maxV, width, height, thickness);
BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls);
}
public static void block(ItemStack stack, RenderBlocks rb, Block block, int meta, float brightness, boolean unfilteredAtlas, Operation<Void> original) {
final TesrMaterial material = material(stack, unfilteredAtlas);
if (material == null) {
callBlock(original, rb, block, meta, brightness);
return;
}
final BailReason stateBail = blockStateBail(rb, block, brightness);
if (stateBail != null) {
fallback++;
bail(stateBail);
callBlock(original, rb, block, meta, brightness);
return;
}
batchBlock(material, rb, block, meta, brightness, original);
}
static void batchBlock(TesrMaterial material, RenderBlocks rb, Block block, int meta, float brightness, Operation<Void> original) {
final long drawsBefore = GLStateManager.drawCalls;
if (BatchEligibility.batchingAllowed()) {
BlockMesh mesh = lookupBlock(block, meta);
if (mesh == null) {
mesh = captureBlock(rb, block, meta, brightness, original);
} else if (mesh.template() != null) {
GLStateManager.glColor4f(mesh.red(), mesh.green(), mesh.blue(), mesh.alpha());
}
if (mesh.template() == null) {
callBlock(original, rb, block, meta, brightness);
fallback++;
bail(BailReason.TEMPLATE);
return;
}
if (ModelPartBatcher.INSTANCE.queueTemplate(mesh.template(), material)) {
instanced++;
BatchEligibility.onPartQueued();
return;
}
fallback++;
bail(BailReason.QUEUE);
} else {
bail(BailReason.NOT_ALLOWED);
}
callBlock(original, rb, block, meta, brightness);
BatchEligibility.onPartFallback(drawsBefore, GLStateManager.drawCalls);
}
public static void clear() {
icons.clear();
blocks.clear();
blockKey.block = null;
basePart = false;
if (blockBackend != null) {
blockBackend.delete();
blockBackend = null;
}
}
private static void callIcon(Object[] args, Operation<Void> original, Tessellator t, float maxU, float minV, float minU, float maxV, int width, int height, float thickness) {
args[0] = t;
args[1] = OperationArgs.boxed(args[1], maxU);
args[2] = OperationArgs.boxed(args[2], minV);
args[3] = OperationArgs.boxed(args[3], minU);
args[4] = OperationArgs.boxed(args[4], maxV);
args[5] = OperationArgs.boxed(args[5], width);
args[6] = OperationArgs.boxed(args[6], height);
args[7] = OperationArgs.boxed(args[7], thickness);
try {
original.call(args);
} finally {
args[0] = null;
}
}
private static void callBlock(Operation<Void> original, RenderBlocks rb, Block block, int meta, float brightness) {
final Object[] args = BLOCK_ARGS;
args[0] = rb;
args[1] = block;
args[2] = OperationArgs.boxed(args[2], meta);
args[3] = OperationArgs.boxed(args[3], brightness);
try {
original.call(args);
} finally {
args[0] = null;
args[1] = null;
}
}
private static TemplateBuffer iconTemplate(Object[] args, float maxU, float minV, float minU, float maxV, int width, int height, float thickness, Operation<Void> original) {
final IconMesh hit = icons.get(maxU, minV, minU, maxV, width, height, thickness);
if (hit != null) return hit.template;
final Tessellator capture = iconBackend.beginCapture(DefaultVertexFormat.POSITION_TEXTURE_NORMAL);
final TemplateBuffer template;
try {
callIcon(args, original, capture, maxU, minV, minU, maxV, width, height, thickness);
} finally {
template = iconBackend.endCaptureToTemplate();
}
if (template == null) return null;
icons.insert().template = template;
return template;
}
private static BlockMesh captureBlock(RenderBlocks rb, Block block, int meta, float brightness, Operation<Void> original) {
if (blockBackend == null) {
blockBackend = new BakedTransformCapture(CAPTURE_BYTES);
}
final TemplateBuffer template;
GLStateManager.glPushMatrix();
try {
blockBackend.begin();
try {
callBlock(original, rb, block, meta, brightness);
} finally {
template = blockBackend.end();
}
} finally {
GLStateManager.glPopMatrix();
}
final Color4 color = GLStateManager.getColor();
final BlockMesh mesh = new BlockMesh(template, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
blocks.put(new BlockMeta(block, meta), mesh);
return mesh;
}
private static BlockMesh lookupBlock(Block block, int meta) {
blockKey.block = block;
blockKey.meta = meta;
return blocks.get(blockKey);
}
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;
}
private static final class IconMesh {
TemplateBuffer template;
}
private record BlockMesh(TemplateBuffer template, float red, float green, float blue, float alpha) {}
}
@@ -0,0 +1,113 @@
package com.gtnewhorizons.angelica.rendering.items;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.minecraft.client.Minecraft;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
public final class ItemPropCache<V> {
private static final int EXPIRY_TICKS = 1_200;
private final Object2ObjectLinkedOpenHashMap<ItemProp, Slot<V>> cache = new Object2ObjectLinkedOpenHashMap<>(64);
private final ItemProp key = new ItemProp();
private final IntSupplier capacity;
private final Supplier<V> factory;
private final Consumer<V> disposer;
private int smallestExpiry;
public ItemPropCache(IntSupplier capacity, Supplier<V> factory, Consumer<V> disposer) {
this.capacity = capacity;
this.factory = factory;
this.disposer = disposer;
}
public V get(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
key.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness);
if (cache.isEmpty()) return null;
final Slot<V> slot = cache.getAndMoveToLast(key);
if (slot == null) return null;
final int time = elapsedTicks();
slot.expiry = time + EXPIRY_TICKS;
if (time > smallestExpiry && time > (smallestExpiry = cache.get(cache.firstKey()).expiry + 20)) {
dispose(cache.removeFirst());
if (!cache.isEmpty()) {
smallestExpiry = cache.get(cache.firstKey()).expiry + 20;
}
}
return slot.value;
}
public V insert() {
final Slot<V> slot;
if (cache.size() >= capacity.getAsInt()) {
final ItemProp oldest = cache.firstKey();
slot = cache.removeFirst();
oldest.set(key);
cache.put(oldest, slot);
} else {
slot = new Slot<>();
slot.value = factory.get();
cache.put(new ItemProp(key), slot);
}
slot.expiry = elapsedTicks() + EXPIRY_TICKS;
return slot.value;
}
public void clear() {
for (Slot<V> slot : cache.values()) {
dispose(slot);
}
cache.clear();
smallestExpiry = 0;
}
private void dispose(Slot<V> slot) {
if (disposer != null && slot.value != null) {
disposer.accept(slot.value);
}
}
private static int elapsedTicks() {
return Minecraft.getMinecraft().thePlayer.ticksExisted;
}
private static final class Slot<V> {
private V value;
private int expiry;
}
@NoArgsConstructor
@Data
static final class ItemProp {
private float minU;
private float minV;
private float maxU;
private float maxV;
private int widthSubdivisions;
private int heightSubdivisions;
private float thickness;
ItemProp(ItemProp old) {
set(old);
}
void set(ItemProp other) {
set(other.minU, other.minV, other.maxU, other.maxV, other.widthSubdivisions, other.heightSubdivisions, other.thickness);
}
void set(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
this.minU = minU;
this.minV = minV;
this.maxU = maxU;
this.maxV = maxV;
this.widthSubdivisions = widthSubdivisions;
this.heightSubdivisions = heightSubdivisions;
this.thickness = thickness;
}
}
}
@@ -37,9 +37,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IReloadableResourceManager;
import org.lwjgl.opengl.GL11;
@@ -52,52 +49,16 @@ import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCalloc;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
public class ItemRenderListManager {
// Least used element is at position 0. This is in theory slightly faster.
private static final Object2ObjectLinkedOpenHashMap<ItemProp, CachedVBO> vboCache = new Object2ObjectLinkedOpenHashMap<>(64);
// 1 minute
private static final int EXPIRY_TICKS = 1_200;
private static int smallestExpiry;
private static final ItemProp prop = new ItemProp();
private static final ItemPropCache<CachedVBO> vboCache = new ItemPropCache<>(() -> AngelicaConfig.itemRendererCacheSize, CachedVBO::new, CachedVBO::delete);
public static CachedVBO pre(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
prop.set(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness);
if (!vboCache.isEmpty()) {
final CachedVBO vbo = vboCache.getAndMoveToLast(prop);
if (vbo != null) {
final int time = getElapsedTicks();
vbo.render(time);
// Prevent constant map lookups by only storing the expiry of the least recently used entry
if (time > smallestExpiry && time > (smallestExpiry = (vboCache.get(vboCache.firstKey()).expiry + 20))) {
vboCache.removeFirst().delete();
if (!vboCache.isEmpty()) {
smallestExpiry = vboCache.get(vboCache.firstKey()).expiry + 20;
}
}
return null;
}
final CachedVBO hit = vboCache.get(minU, minV, maxU, maxV, widthSubdivisions, heightSubdivisions, thickness);
if (hit != null) {
hit.render();
return null;
}
final CachedVBO vbo;
if (vboCache.size() >= AngelicaConfig.itemRendererCacheSize) {
final ItemProp oldestProp = vboCache.firstKey();
vbo = vboCache.removeFirst();
oldestProp.set(prop);
vboCache.put(oldestProp, vbo);
} else {
vbo = new CachedVBO();
vboCache.put(new ItemProp(prop), vbo);
}
vbo.expiry = getElapsedTicks() + EXPIRY_TICKS;
return vbo;
return vboCache.insert();
}
public static void post(DirectTessellator tessellator, CachedVBO vbo) {
@@ -106,10 +67,6 @@ public class ItemRenderListManager {
vbo.vertexBuffer.render();
}
private static int getElapsedTicks() {
return Minecraft.getMinecraft().thePlayer.ticksExisted;
}
public static void registerReloadListener(){
IReloadableResourceManager resourceManager = (IReloadableResourceManager) Minecraft.getMinecraft()
.getResourceManager();
@@ -117,16 +74,12 @@ public class ItemRenderListManager {
}
public static void clearCache() {
for (CachedVBO value : vboCache.values()) {
value.delete();
}
vboCache.clear();
}
public static final class CachedVBO {
private final IVertexArrayObject vertexBuffer;
private final IndexBuffer ebo;
private int expiry;
private int extVbo = 0;
public CachedVBO() {
@@ -195,9 +148,8 @@ public class ItemRenderListManager {
extVbo = 0;
}
private void render(int elapsedTicks) {
private void render() {
vertexBuffer.render();
expiry = elapsedTicks + EXPIRY_TICKS;
}
private void delete() {
@@ -210,43 +162,4 @@ public class ItemRenderListManager {
}
}
@NoArgsConstructor
@Data
private static final class ItemProp {
private float minU;
private float minV;
private float maxU;
private float maxV;
private int widthSubdivisions;
private int heightSubdivisions;
private float thickness;
public ItemProp(ItemProp old) {
set(
old.minU, old.minV,
old.maxU, old.maxV,
old.widthSubdivisions, old.heightSubdivisions,
old.thickness
);
}
public void set(ItemProp other) {
set(
other.minU, other.minV,
other.maxU, other.maxV,
other.widthSubdivisions, other.heightSubdivisions,
other.thickness
);
}
public void set(float minU, float minV, float maxU, float maxV, int widthSubdivisions, int heightSubdivisions, float thickness) {
this.minU = minU;
this.minV = minV;
this.maxU = maxU;
this.maxV = maxV;
this.widthSubdivisions = widthSubdivisions;
this.heightSubdivisions = heightSubdivisions;
this.thickness = thickness;
}
}
}
@@ -0,0 +1,68 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL11;
public final class BopParticleDescriptors {
private static final Logger LOG = LogManager.getLogger("Angelica");
private static final String PIXIE_TRAIL_CLASS = "biomesoplenty.client.particles.EntityPixieTrailFX";
private static final ResourceLocation PIXIE_TRAIL_TEXTURE = new ResourceLocation("biomesoplenty:textures/particles/pixietrail.png");
private static final int UNRESOLVED = -1;
private static int pixieTrailTexture = UNRESOLVED;
public static final ParticleDescriptor PIXIE_TRAIL = (fx, partialTicks, out, state) -> {
final int texture = pixieTrailTexture();
if (texture == 0) return false;
fx.particleScale = fx.particleScale * ParticleQuads.ramp(fx.particleAge, fx.particleMaxAge, partialTicks);
ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out);
out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, 1.0F);
out.brightness = 175;
state.texture = texture;
state.blend = true;
state.blendSrc = GL11.GL_SRC_ALPHA;
state.blendDst = GL11.GL_ONE;
state.blendSrcAlpha = GL11.GL_SRC_ALPHA;
state.blendDstAlpha = GL11.GL_ONE;
state.depthMask = false;
return true;
};
private BopParticleDescriptors() {}
public static void registerAll() {
ParticleDescriptorRegistry.register(PIXIE_TRAIL_CLASS, PIXIE_TRAIL);
}
public static void invalidate() {
pixieTrailTexture = UNRESOLVED;
}
private static int pixieTrailTexture() {
int id = pixieTrailTexture;
if (id != UNRESOLVED) return id;
final TextureManager manager = Minecraft.getMinecraft().getTextureManager();
ITextureObject texture = manager.getTexture(PIXIE_TRAIL_TEXTURE);
if (texture == null) {
final int previous = GLStateManager.getBoundTextureForServerState();
manager.bindTexture(PIXIE_TRAIL_TEXTURE);
texture = manager.getTexture(PIXIE_TRAIL_TEXTURE);
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previous);
}
id = texture == null ? 0 : texture.getGlTextureId();
if (id == 0) LOG.warn("Pixie trail texture {} is unavailable; those particles will not draw", PIXIE_TRAIL_TEXTURE);
pixieTrailTexture = id;
return id;
}
}
@@ -0,0 +1,231 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import net.minecraft.client.renderer.Tessellator;
import org.joml.Matrix4fc;
import org.lwjgl.opengl.GL11;
public final class ParticleCaptureTessellator extends Tessellator {
public static final int MAX_VERTICES = 4;
private final float[] verts = new float[MAX_VERTICES * 5];
private final ParticleRenderState state = new ParticleRenderState();
private final ParticleRenderState scratch = new ParticleRenderState();
private int captured;
private boolean spilled;
private boolean uvSet;
private float pendingU;
private float pendingV;
private boolean closed;
private Matrix4fc layerModelView;
private Tessellator run;
public void begin(int startBrightness, Tessellator runTessellator, Matrix4fc layerModelView) {
this.layerModelView = layerModelView;
this.run = runTessellator;
this.captured = 0;
this.spilled = false;
this.closed = false;
this.uvSet = false;
this.pendingU = 0.0f;
this.pendingV = 0.0f;
this.brightness = startBrightness;
this.hasBrightness = true;
this.color = runTessellator.hasColor ? runTessellator.color : 0xFFFFFFFF;
this.hasColor = runTessellator.hasColor;
this.hasTexture = false;
this.hasNormals = false;
this.isColorDisabled = false;
this.xOffset = 0.0D;
this.yOffset = 0.0D;
this.zOffset = 0.0D;
}
public void release() {
run = null;
layerModelView = null;
captured = 0;
}
public boolean spilled() {
return spilled;
}
public void propagateColor() {
if (spilled || closed || !hasColor || run == null) return;
run.color = color;
run.hasColor = true;
}
public int captured() {
return captured;
}
public float[] vertices() {
return verts;
}
public int capturedBrightness() {
return brightness;
}
public ParticleRenderState state() {
return state;
}
public int capturedColor() {
return color;
}
public void replayInto(Tessellator t) {
t.setBrightness(brightness);
if (hasColor) {
t.setColorRGBA(color & 255, (color >> 8) & 255, (color >> 16) & 255, (color >>> 24) & 255);
}
if (uvSet) {
t.setTextureUV(pendingU, pendingV);
}
for (int i = 0, o = 0; i < captured; i++, o += 5) {
t.addVertexWithUV(verts[o], verts[o + 1], verts[o + 2], verts[o + 3], verts[o + 4]);
}
}
private void spill() {
if (spilled) return;
spilled = true;
if (closed) {
scratch.sample();
state.apply();
final boolean wasDrawing = run.isDrawing;
if (!wasDrawing) run.startDrawingQuads();
replayInto(run);
run.draw();
if (wasDrawing) run.startDrawingQuads();
scratch.apply();
} else {
replayInto(run);
}
captured = 0;
}
@Override
public void setTextureUV(double u, double v) {
if (spilled) {
run.setTextureUV(u, v);
return;
}
if (closed) {
run.setTextureUV(u, v);
pendingU = (float) u;
pendingV = (float) v;
return;
}
hasTexture = true;
uvSet = true;
pendingU = (float) u;
pendingV = (float) v;
}
@Override
public void addVertexWithUV(double x, double y, double z, double u, double v) {
setTextureUV(u, v);
addVertex(x, y, z);
}
@Override
public void addVertex(double x, double y, double z) {
if (spilled) {
run.addVertex(x, y, z);
return;
}
boolean overflow = !uvSet || closed || captured == MAX_VERTICES;
if (!overflow && captured == 0) {
if (GLStateManager.getModelViewMatrix().equals(layerModelView)) state.sample();
else overflow = true;
}
if (overflow) {
spill();
if (uvSet) run.addVertexWithUV(x, y, z, pendingU, pendingV);
else run.addVertex(x, y, z);
return;
}
final int o = captured * 5;
verts[o] = (float) (x + xOffset);
verts[o + 1] = (float) (y + yOffset);
verts[o + 2] = (float) (z + zOffset);
verts[o + 3] = pendingU;
verts[o + 4] = pendingV;
captured++;
}
@Override
public void setColorRGBA(int red, int green, int blue, int alpha) {
if (spilled || closed) {
run.setColorRGBA(red, green, blue, alpha);
return;
}
final int r = Math.clamp(red, 0, 255);
final int g = Math.clamp(green, 0, 255);
final int b = Math.clamp(blue, 0, 255);
final int a = Math.clamp(alpha, 0, 255);
final int packed = (a << 24) | (b << 16) | (g << 8) | r;
if (hasColor && packed != color && captured > 0) {
spill();
run.setColorRGBA(red, green, blue, alpha);
return;
}
hasColor = true;
color = packed;
}
@Override
public void setBrightness(int value) {
if (spilled || closed) {
run.setBrightness(value);
return;
}
hasBrightness = true;
brightness = value;
}
@Override
public void setNormal(float x, float y, float z) {
if (!closed) spill();
run.setNormal(x, y, z);
}
@Override
public void disableColor() {
if (!closed) spill();
run.disableColor();
}
@Override
public void startDrawingQuads() {
if (!spilled && !closed && captured != 0) spill();
run.startDrawingQuads();
}
@Override
public void startDrawing(int mode) {
if (mode == GL11.GL_QUADS) {
startDrawingQuads();
return;
}
spill();
run.startDrawing(mode);
}
@Override
public int draw() {
if (!spilled && !closed) {
if (captured == MAX_VERTICES) {
closed = true;
} else if (captured != 0) {
spill();
}
}
return run.draw();
}
}
@@ -0,0 +1,12 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
public final class ParticleCulling {
private ParticleCulling() {}
public static boolean visible(CeleritasWorldRenderer renderer, double x, double y, double z) {
return renderer == null || renderer.isPointVisible(x, y, z);
}
}
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.rendering.particles;
import net.minecraft.client.particle.EntityFX;
public interface ParticleDescriptor {
boolean describe(EntityFX fx, float partialTicks, ParticleParams out, ParticleRenderState state);
}
@@ -0,0 +1,80 @@
package com.gtnewhorizons.angelica.rendering.particles;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.Tessellator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Method;
public final class ParticleDescriptorRegistry {
private static final Logger LOGGER = LogManager.getLogger("Angelica/Particles");
private static final String[] RENDER_PARTICLE_NAMES = { "renderParticle", "func_70539_a" };
public static final ParticleDescriptor CAPTURE = (fx, partialTicks, out, state) -> false;
public static final ParticleDescriptor VANILLA = (fx, partialTicks, out, state) -> {
ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out);
return true;
};
private static final Object2ObjectOpenHashMap<String, ParticleDescriptor> BY_NAME = new Object2ObjectOpenHashMap<>();
private static final Reference2ObjectOpenHashMap<Class<?>, ParticleDescriptor> BY_CLASS = new Reference2ObjectOpenHashMap<>();
private static Class<?> lastClass;
private static ParticleDescriptor lastDescriptor;
static {
VanillaParticleDescriptors.registerAll();
BopParticleDescriptors.registerAll();
}
private ParticleDescriptorRegistry() {}
public static void register(String className, ParticleDescriptor descriptor) {
BY_NAME.put(className, descriptor);
clearCache();
}
public static ParticleDescriptor forClass(Class<?> cls) {
if (cls == lastClass) return lastDescriptor;
ParticleDescriptor d = BY_CLASS.get(cls);
if (d == null) {
d = resolve(cls);
BY_CLASS.put(cls, d);
}
lastClass = cls;
lastDescriptor = d;
return d;
}
public static void clearCache() {
BY_CLASS.clear();
lastClass = null;
lastDescriptor = null;
}
private static ParticleDescriptor resolve(Class<?> cls) {
final ParticleDescriptor registered = BY_NAME.get(cls.getName());
if (registered != null) return registered;
final Method render = renderParticleMethod(cls);
if (render == null) {
LOGGER.warn("Could not locate renderParticle on particle class {}, using the capture path", cls.getName());
return CAPTURE;
}
return render.getDeclaringClass() == EntityFX.class ? VANILLA : CAPTURE;
}
private static Method renderParticleMethod(Class<?> cls) {
for (String name : RENDER_PARTICLE_NAMES) {
try {
return cls.getMethod(name, Tessellator.class, float.class, float.class, float.class, float.class, float.class, float.class);
} catch (NoSuchMethodException ignored) {}
}
return null;
}
}
@@ -0,0 +1,357 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.ParticleInstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.ParticleQuadMesh;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.profiling.BailClassCounts;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.OperationArgs;
import com.gtnewhorizons.angelica.rendering.ParticleRunSplitter;
import com.gtnewhorizons.angelica.rendering.tesr.InstanceRing;
import com.gtnewhorizons.angelica.rendering.tesr.MeshBuffer;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.renderer.Tessellator;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.nio.ByteBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
public final class ParticleInstancer {
private static final int STRIDE = ParticleInstancedAttribs.STRIDE;
private static final int INITIAL_BYTES = 256 * STRIDE;
private static final ParticleCaptureTessellator CAPTURE = new ParticleCaptureTessellator();
private static final ParticleParams SCRATCH = new ParticleParams();
private static final ParticleRenderState STATE = new ParticleRenderState();
private static final ParticleRenderState RESTORE = new ParticleRenderState();
private static final Matrix4f LAYER_MV = new Matrix4f();
private static final Object[] ORIGINAL_ARGS = new Object[8];
private static final ObjectArrayList<Group> GROUP_POOL = new ObjectArrayList<>();
private static int groupCount;
private static final class Group {
final ParticleRenderState state = new ParticleRenderState();
ByteBuffer list;
boolean translucent;
}
private static boolean layerActive;
private static boolean layerStarted;
private static DeferredWorldRenderingPipeline unavailableFor;
private static DeferredWorldRenderingPipeline deferred;
private static Tessellator run;
private static float rotX;
private static float rotXZ;
private static float rotZ;
private static float rotYZ;
private static float rotXY;
private static long direct;
private static long captured;
private static long spilled;
private static long undecodable;
private static long draws;
private ParticleInstancer() {}
public static long getDirect() {
return direct;
}
public static long getCaptured() {
return captured;
}
public static long getDraws() {
return draws;
}
public static long getSpilled() {
return spilled;
}
public static long getUndecodable() {
return undecodable;
}
private static void beginLayer() {
layerActive = false;
layerStarted = true;
final SodiumGameOptions options = ClientProxy.options();
if (options == null || !options.advanced.enableDeferredBatching) return;
deferred = pipeline();
if (available()) {
layerActive = true;
groupCount = 0;
LAYER_MV.set(GLStateManager.getModelViewMatrix());
} else {
deferred = null;
DeferredDrawBatcher.enter();
}
}
public static void renderParticle(EntityFX fx, Tessellator runTessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation<Void> original) {
if (!layerStarted) beginLayer();
if (!layerActive) {
call(fx, runTessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original);
return;
}
renderActive(fx, runTessellator, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original);
}
private static void renderActive(EntityFX fx, Tessellator runTessellator, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation<Void> original) {
run = runTessellator;
rotX = rotationX;
rotXZ = rotationXZ;
rotZ = rotationZ;
rotYZ = rotationYZ;
rotXY = rotationXY;
final ParticleDescriptor descriptor = ParticleDescriptorRegistry.forClass(fx.getClass());
if (descriptor != ParticleDescriptorRegistry.CAPTURE) {
STATE.sample();
SCRATCH.brightness = runTessellator.brightness;
if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return;
runTessellator.color = SCRATCH.colorABGR;
runTessellator.hasColor = true;
emit(groupFor(STATE, deferred != null && ParticleRunSplitter.currentRunTranslucent()));
direct++;
return;
}
CAPTURE.begin(runTessellator.brightness, runTessellator, LAYER_MV);
call(fx, CAPTURE, partialTicks, rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, original);
CAPTURE.propagateColor();
if (CAPTURE.spilled()) {
spilled++;
if (Tracy.ENABLED) BailClassCounts.PARTICLE_SPILL.add(fx.getClass());
return;
}
if (CAPTURE.captured() == 0) return;
if (!ParticleQuadDecoder.decode(CAPTURE.vertices(), CAPTURE.captured(), rotationX, rotationXZ, rotationZ, rotationYZ, rotationXY, SCRATCH)) {
CAPTURE.replayInto(runTessellator);
undecodable++;
return;
}
SCRATCH.colorABGR = CAPTURE.capturedColor();
SCRATCH.brightness = CAPTURE.capturedBrightness();
emit(groupFor(CAPTURE.state(), deferred != null && ParticleRunSplitter.currentRunTranslucent()));
captured++;
}
private static void emit(Group group) {
final ByteBuffer list = MeshBuffer.ensureCapacity(group.list, STRIDE, true);
group.list = list;
ParticleInstancedAttribs.writeInstance(memAddress0(list) + list.position(), SCRATCH.centerX, SCRATCH.centerY, SCRATCH.centerZ, SCRATCH.half, SCRATCH.u0, SCRATCH.v0, SCRATCH.u1, SCRATCH.v1, SCRATCH.colorABGR, SCRATCH.brightness);
list.position(list.position() + STRIDE);
}
public static void endLayer() {
layerStarted = false;
if (!layerActive) {
if (DeferredDrawBatcher.isActive()) DeferredDrawBatcher.exitAndFlush();
return;
}
layerActive = false;
if (groupCount > 0) {
RESTORE.sample();
for (int i = 0; i < groupCount; i++) {
final Group group = GROUP_POOL.get(i);
if (!group.translucent) flush(group);
}
for (int i = 0; i < groupCount; i++) {
final Group group = GROUP_POOL.get(i);
if (group.translucent) flush(group);
}
RESTORE.apply();
if (deferred != null) {
GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent());
}
ring().postDraw();
groupCount = 0;
}
deferred = null;
run = null;
}
private static Group groupFor(ParticleRenderState state, boolean translucent) {
for (int i = 0; i < groupCount; i++) {
final Group g = GROUP_POOL.get(i);
if (g.translucent == translucent && g.state.matches(state)) return g;
}
if (groupCount == GROUP_POOL.size()) GROUP_POOL.add(new Group());
final Group g = GROUP_POOL.get(groupCount++);
g.state.set(state);
g.translucent = translucent;
if (g.list != null) g.list.clear();
g.list = MeshBuffer.ensureCapacity(g.list, INITIAL_BYTES, true);
return g;
}
public static void clear() {
layerActive = false;
layerStarted = false;
deferred = null;
run = null;
unavailableFor = null;
groupCount = 0;
for (int i = 0; i < GROUP_POOL.size(); i++) {
GROUP_POOL.get(i).list = null;
}
GROUP_POOL.clear();
CAPTURE.release();
ParticleQuadMesh.delete();
ParticleDescriptorRegistry.clearCache();
}
private static void call(EntityFX fx, Tessellator target, float partialTicks, float rotationX, float rotationXZ, float rotationZ, float rotationYZ, float rotationXY, Operation<Void> original) {
final Object[] args = ORIGINAL_ARGS;
args[0] = fx;
args[1] = target;
args[2] = OperationArgs.boxed(args[2], partialTicks);
args[3] = OperationArgs.boxed(args[3], rotationX);
args[4] = OperationArgs.boxed(args[4], rotationXZ);
args[5] = OperationArgs.boxed(args[5], rotationZ);
args[6] = OperationArgs.boxed(args[6], rotationYZ);
args[7] = OperationArgs.boxed(args[7], rotationXY);
try {
original.call(args);
} finally {
args[0] = null;
args[1] = null;
}
}
private static boolean available() {
if (deferred != null && deferred == unavailableFor) return false;
if (!ShaderManager.getInstance().isEnabled()) return false;
return deferred == null || deferred.supportsInstancing(Instancing.PARTICLE);
}
private static DeferredWorldRenderingPipeline pipeline() {
if (!Iris.enabled) return null;
return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline pipeline ? pipeline : null;
}
private static InstanceRing ring() {
return TesrBatchRenderer.INSTANCE.instanceRing();
}
private static void flush(Group group) {
final ByteBuffer list = group.list;
final boolean listTranslucent = group.translucent;
final int count = list.position() / STRIDE;
if (count == 0) return;
group.state.apply();
list.flip();
if (deferred != null) {
GbufferPrograms.setTranslucencyDeclaration(listTranslucent);
deferred.rebindCurrentPass();
if (!deferred.hasInstancedVariant(Instancing.PARTICLE)) {
unavailableFor = deferred;
drawInstancesCpu(group.state, list, count, listTranslucent);
list.clear();
return;
}
}
final long base = ring().upload(list, STRIDE);
list.clear();
if (deferred != null) {
deferred.bindInstancedVariant(Instancing.PARTICLE);
issueDraw(base, count, false);
deferred.rebindCurrentPass();
} else {
issueDraw(base, count, true);
}
}
private static void issueDraw(long base, int count, boolean ffp) {
ParticleQuadMesh.update(rotX, rotXZ, rotZ, rotYZ, rotXY);
final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler;
if (extHandler != null && extHandler.wantsExtended()) {
FfpExtendedAttribs.setNeutralCurrentValues();
}
GLStateManager.glBindVertexArray(ParticleQuadMesh.vao());
VAOManager.setCurrentVertexFlags(ParticleQuadMesh.VERTEX_FLAGS);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ring().bufferId());
ParticleInstancedAttribs.pointInstanceAttribs(base);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
if (ffp) GLStateManager.ffpInstancing = Instancing.PARTICLE;
GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, ParticleQuadMesh.VERTEX_COUNT, count);
GLStateManager.ffpInstancing = Instancing.NONE;
GLStateManager.glBindVertexArray(0);
draws++;
}
private static void drawInstancesCpu(ParticleRenderState state, ByteBuffer list, int count, boolean listTranslucent) {
final Tessellator t = run;
RESTORE.apply();
GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent());
t.draw();
t.startDrawingQuads();
GbufferPrograms.setTranslucencyDeclaration(listTranslucent);
state.apply();
for (int i = 0; i < count; i++) {
final int base = i * STRIDE;
final float cx = list.getFloat(base);
final float cy = list.getFloat(base + 4);
final float cz = list.getFloat(base + 8);
final float half = list.getFloat(base + 12);
final float u0 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV);
final float v0 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 4);
final float u1 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 8);
final float v1 = list.getFloat(base + ParticleInstancedAttribs.OFFSET_UV + 12);
final int color = list.getInt(base + ParticleInstancedAttribs.OFFSET_COLOR);
final int light = (int) list.getFloat(base + ParticleInstancedAttribs.OFFSET_LIGHTMAP) | ((int) list.getFloat(base + ParticleInstancedAttribs.OFFSET_LIGHTMAP + 4) << 16);
t.setBrightness(light);
t.setColorRGBA(color & 255, (color >> 8) & 255, (color >> 16) & 255, (color >>> 24) & 255);
for (int c = 0; c < ParticleQuadMesh.VERTEX_COUNT; c++) {
final float a = ParticleQuadMesh.cornerA(c);
final float b = ParticleQuadMesh.cornerB(c);
emitCorner(t, cx, cy, cz, half, a, b, a < 0.0f ? u0 : u1, b < 0.0f ? v0 : v1);
}
}
t.draw();
t.startDrawingQuads();
}
private static void emitCorner(Tessellator t, float cx, float cy, float cz, float half, float a, float b, float u, float v) {
final float ah = a * half;
final float bh = b * half;
t.addVertexWithUV(cx + ParticleQuadMesh.offsetX(ah, bh, rotX, rotYZ), cy + ParticleQuadMesh.offsetY(bh, rotXZ), cz + ParticleQuadMesh.offsetZ(ah, bh, rotZ, rotXY), u, v);
}
}
@@ -0,0 +1,15 @@
package com.gtnewhorizons.angelica.rendering.particles;
public final class ParticleParams {
public float centerX;
public float centerY;
public float centerZ;
public float half;
public float u0;
public float v0;
public float u1;
public float v1;
public int colorABGR;
public int brightness;
}
@@ -0,0 +1,50 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.glsm.ffp.ParticleQuadMesh;
public final class ParticleQuadDecoder {
private ParticleQuadDecoder() {}
public static boolean decode(float[] verts, int count, float rotX, float rotXZ, float rotZ, float rotYZ, float rotXY, ParticleParams out) {
if (count != 4) return false;
final float sx = rotX + rotYZ;
final float sy = rotXZ;
final float sz = rotZ + rotXY;
final float denom = sx * sx + sy * sy + sz * sz;
if (denom <= 1.0e-12f) return false;
final float cx = (verts[0] + verts[10]) * 0.5f;
final float cy = (verts[1] + verts[11]) * 0.5f;
final float cz = (verts[2] + verts[12]) * 0.5f;
final float dx = verts[10] - verts[0];
final float dy = verts[11] - verts[1];
final float dz = verts[12] - verts[2];
final float half = (dx * sx + dy * sy + dz * sz) / (2.0f * denom);
final float scale = Math.max(Math.abs(cx), Math.max(Math.abs(cy), Math.abs(cz)));
final float tol = 1.0e-5f * (1.0f + Math.abs(half) + scale);
for (int i = 0, o = 0; i < ParticleQuadMesh.VERTEX_COUNT; i++, o += 5) {
final float a = ParticleQuadMesh.cornerA(i) * half;
final float b = ParticleQuadMesh.cornerB(i) * half;
if (Math.abs(verts[o] - (cx + ParticleQuadMesh.offsetX(a, b, rotX, rotYZ))) > tol) return false;
if (Math.abs(verts[o + 1] - (cy + ParticleQuadMesh.offsetY(b, rotXZ))) > tol) return false;
if (Math.abs(verts[o + 2] - (cz + ParticleQuadMesh.offsetZ(a, b, rotZ, rotXY))) > tol) return false;
}
if (verts[3] != verts[8] || verts[9] != verts[14] || verts[18] != verts[13] || verts[19] != verts[4]) {
return false;
}
out.centerX = cx;
out.centerY = cy;
out.centerZ = cz;
out.half = half;
out.u0 = verts[3];
out.v0 = verts[4];
out.u1 = verts[13];
out.v1 = verts[14];
return true;
}
}
@@ -0,0 +1,46 @@
package com.gtnewhorizons.angelica.rendering.particles;
import net.minecraft.client.particle.EntityFX;
public final class ParticleQuads {
private ParticleQuads() {}
public static void vanillaQuad(EntityFX fx, float partialTicks, float scale, ParticleParams out) {
out.half = 0.1F * scale;
center(fx, partialTicks, out);
iconUv(fx, out);
out.colorABGR = packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, fx.particleAlpha);
}
static void center(EntityFX fx, float partialTicks, ParticleParams out) {
out.centerX = (float) (fx.prevPosX + (fx.posX - fx.prevPosX) * partialTicks - EntityFX.interpPosX);
out.centerY = (float) (fx.prevPosY + (fx.posY - fx.prevPosY) * partialTicks - EntityFX.interpPosY);
out.centerZ = (float) (fx.prevPosZ + (fx.posZ - fx.prevPosZ) * partialTicks - EntityFX.interpPosZ);
}
static void iconUv(EntityFX fx, ParticleParams out) {
float minU = fx.particleTextureIndexX / 16.0F;
float maxU = minU + 0.0624375F;
float minV = fx.particleTextureIndexY / 16.0F;
float maxV = minV + 0.0624375F;
if (fx.particleIcon != null) {
minU = fx.particleIcon.getMinU();
maxU = fx.particleIcon.getMaxU();
minV = fx.particleIcon.getMinV();
maxV = fx.particleIcon.getMaxV();
}
out.u0 = maxU;
out.v0 = maxV;
out.u1 = minU;
out.v1 = minV;
}
static float ramp(int age, int maxAge, float partialTicks) {
return Math.clamp((age + partialTicks) / maxAge * 32.0F, 0.0F, 1.0F);
}
public static int packColor(float r, float g, float b, float a) {
return (Math.clamp((int) (a * 255.0F), 0, 255) << 24) | (Math.clamp((int) (b * 255.0F), 0, 255) << 16) | (Math.clamp((int) (g * 255.0F), 0, 255) << 8) | Math.clamp((int) (r * 255.0F), 0, 255);
}
}
@@ -0,0 +1,52 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack;
import org.lwjgl.opengl.GL11;
public final class ParticleRenderState {
public int texture;
public boolean blend;
public int blendSrc;
public int blendDst;
public int blendSrcAlpha;
public int blendDstAlpha;
public boolean depthMask;
public void sample() {
texture = GLStateManager.getBoundTextureForServerState();
blend = GLStateManager.getBlendMode().isEnabled();
final BlendStateStack blendState = GLStateManager.getBlendState();
blendSrc = blendState.getSrcRgb();
blendDst = blendState.getDstRgb();
blendSrcAlpha = blendState.getSrcAlpha();
blendDstAlpha = blendState.getDstAlpha();
depthMask = GLStateManager.getDepthState().isEnabled();
}
public void set(ParticleRenderState other) {
texture = other.texture;
blend = other.blend;
blendSrc = other.blendSrc;
blendDst = other.blendDst;
blendSrcAlpha = other.blendSrcAlpha;
blendDstAlpha = other.blendDstAlpha;
depthMask = other.depthMask;
}
public boolean matches(ParticleRenderState other) {
return texture == other.texture && blend == other.blend && blendSrc == other.blendSrc && blendDst == other.blendDst && blendSrcAlpha == other.blendSrcAlpha && blendDstAlpha == other.blendDstAlpha && depthMask == other.depthMask;
}
public void apply() {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
if (blend) {
GLStateManager.glEnable(GL11.GL_BLEND);
GLStateManager.glBlendFuncSeparate(blendSrc, blendDst, blendSrcAlpha, blendDstAlpha);
} else {
GLStateManager.glDisable(GL11.GL_BLEND);
}
GLStateManager.glDepthMask(depthMask);
}
}
@@ -0,0 +1,135 @@
package com.gtnewhorizons.angelica.rendering.particles;
import net.minecraft.client.particle.EntityBlockDustFX;
import net.minecraft.client.particle.EntityBreakingFX;
import net.minecraft.client.particle.EntityCloudFX;
import net.minecraft.client.particle.EntityCrit2FX;
import net.minecraft.client.particle.EntityCritFX;
import net.minecraft.client.particle.EntityDiggingFX;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.client.particle.EntityFireworkOverlayFX;
import net.minecraft.client.particle.EntityFireworkSparkFX;
import net.minecraft.client.particle.EntityFlameFX;
import net.minecraft.client.particle.EntityHeartFX;
import net.minecraft.client.particle.EntityHugeExplodeFX;
import net.minecraft.client.particle.EntityLavaFX;
import net.minecraft.client.particle.EntityNoteFX;
import net.minecraft.client.particle.EntityPortalFX;
import net.minecraft.client.particle.EntityReddustFX;
import net.minecraft.client.particle.EntitySmokeFX;
import net.minecraft.client.particle.EntitySnowShovelFX;
import net.minecraft.client.particle.EntitySpellParticleFX;
import net.minecraft.util.MathHelper;
public final class VanillaParticleDescriptors {
private interface BaseScale {
float of(EntityFX fx);
}
private interface ScaleFactor {
float factor(int age, int maxAge, float partialTicks);
}
private static final ScaleFactor RAMP = ParticleQuads::ramp;
private static final ScaleFactor FLAME = (age, maxAge, partialTicks) -> {
final float f = (age + partialTicks) / maxAge;
return 1.0F - f * f * 0.5F;
};
private static final ScaleFactor LAVA = (age, maxAge, partialTicks) -> {
final float f = (age + partialTicks) / maxAge;
return 1.0F - f * f;
};
private static final ScaleFactor PORTAL = (age, maxAge, partialTicks) -> {
float f = (age + partialTicks) / maxAge;
f = 1.0F - f;
f *= f;
return 1.0F - f;
};
private static final ParticleDescriptor EMPTY = (fx, partialTicks, out, state) -> false;
private static final ParticleDescriptor DIGGING = (fx, partialTicks, out, state) -> {
out.half = 0.1F * fx.particleScale;
ParticleQuads.center(fx, partialTicks, out);
out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, 1.0F);
final float jitterU = fx.particleTextureJitterX;
final float jitterV = fx.particleTextureJitterY;
if (fx.particleIcon != null) {
out.u0 = fx.particleIcon.getInterpolatedU(jitterU / 4.0F * 16.0F);
out.u1 = fx.particleIcon.getInterpolatedU((jitterU + 1.0F) / 4.0F * 16.0F);
out.v1 = fx.particleIcon.getInterpolatedV(jitterV / 4.0F * 16.0F);
out.v0 = fx.particleIcon.getInterpolatedV((jitterV + 1.0F) / 4.0F * 16.0F);
} else {
out.u0 = (fx.particleTextureIndexX + jitterU / 4.0F) / 16.0F;
out.u1 = out.u0 + 0.015609375F;
out.v1 = (fx.particleTextureIndexY + jitterV / 4.0F) / 16.0F;
out.v0 = out.v1 + 0.015609375F;
}
return true;
};
private static final ParticleDescriptor FIREWORK_OVERLAY = (fx, partialTicks, out, state) -> {
final float t = fx.particleAge + partialTicks - 1.0F;
fx.particleAlpha = 0.6F - t * 0.25F * 0.5F;
ParticleQuads.center(fx, partialTicks, out);
out.half = 7.1F * MathHelper.sin(t * 0.25F * (float) Math.PI);
out.u0 = 0.25F + 0.25F;
out.v0 = 0.125F + 0.25F;
out.u1 = 0.25F;
out.v1 = 0.125F;
out.colorABGR = ParticleQuads.packColor(fx.particleRed, fx.particleGreen, fx.particleBlue, fx.particleAlpha);
return true;
};
private record BaseScaled(BaseScale base, ScaleFactor factor) implements ParticleDescriptor {
@Override
public boolean describe(EntityFX fx, float partialTicks, ParticleParams out, ParticleRenderState state) {
fx.particleScale = base.of(fx) * factor.factor(fx.particleAge, fx.particleMaxAge, partialTicks);
ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out);
return true;
}
}
private static final ParticleDescriptor FIREWORK_SPARK = (fx, partialTicks, out, state) -> {
final int age = fx.particleAge;
final int maxAge = fx.particleMaxAge;
if (((EntityFireworkSparkFX) fx).field_92048_ay && age >= maxAge / 3 && (age + maxAge) / 3 % 2 != 0) return false;
ParticleQuads.vanillaQuad(fx, partialTicks, fx.particleScale, out);
return true;
};
private VanillaParticleDescriptors() {}
public static void registerAll() {
registerScaled(EntityFlameFX.class, fx -> ((EntityFlameFX) fx).flameScale, FLAME);
registerScaled(EntityLavaFX.class, fx -> ((EntityLavaFX) fx).lavaParticleScale, LAVA);
registerScaled(EntityPortalFX.class, fx -> ((EntityPortalFX) fx).portalParticleScale, PORTAL);
registerScaled(EntitySmokeFX.class, fx -> ((EntitySmokeFX) fx).smokeParticleScale, RAMP);
registerScaled(EntityCloudFX.class, fx -> ((EntityCloudFX) fx).field_70569_a, RAMP);
registerScaled(EntityCritFX.class, fx -> ((EntityCritFX) fx).initialParticleScale, RAMP);
registerScaled(EntityHeartFX.class, fx -> ((EntityHeartFX) fx).particleScaleOverTime, RAMP);
registerScaled(EntityNoteFX.class, fx -> ((EntityNoteFX) fx).noteParticleScale, RAMP);
registerScaled(EntityReddustFX.class, fx -> ((EntityReddustFX) fx).reddustParticleScale, RAMP);
registerScaled(EntitySnowShovelFX.class, fx -> ((EntitySnowShovelFX) fx).snowDigParticleScale, RAMP);
ParticleDescriptorRegistry.register(EntitySpellParticleFX.class.getName(), ParticleDescriptorRegistry.VANILLA);
ParticleDescriptorRegistry.register(EntityDiggingFX.class.getName(), DIGGING);
ParticleDescriptorRegistry.register(EntityBlockDustFX.class.getName(), DIGGING);
ParticleDescriptorRegistry.register(EntityBreakingFX.class.getName(), DIGGING);
ParticleDescriptorRegistry.register(EntityFireworkOverlayFX.class.getName(), FIREWORK_OVERLAY);
ParticleDescriptorRegistry.register(EntityCrit2FX.class.getName(), EMPTY);
ParticleDescriptorRegistry.register(EntityHugeExplodeFX.class.getName(), EMPTY);
ParticleDescriptorRegistry.register(EntityFireworkSparkFX.class.getName(), FIREWORK_SPARK);
}
private static void registerScaled(Class<? extends EntityFX> cls, BaseScale base, ScaleFactor factor) {
ParticleDescriptorRegistry.register(cls.getName(), new BaseScaled(base, factor));
}
}
@@ -8,9 +8,11 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.rendering.items.DroppedItemInstancer;
import com.gtnewhorizons.angelica.rendering.particles.BopParticleDescriptors;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.gtnewhorizons.angelica.rendering.tesr.VertexTransform;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
@@ -22,13 +24,10 @@ import net.minecraftforge.client.event.TextureStitchEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
public final class AngelicaTesrMeshCache {
@@ -192,6 +191,9 @@ public final class AngelicaTesrMeshCache {
@SubscribeEvent
public void onTextureStitchPost(TextureStitchEvent.Post event) {
INSTANCE.clear();
DroppedItemInstancer.clear();
BopParticleDescriptors.invalidate();
ShaderGlint.invalidate();
}
}
@@ -228,7 +230,7 @@ public final class AngelicaTesrMeshCache {
return entries.containsKey(key);
}
static final class GtnhMeshBackend implements MeshBackend {
public static final class GtnhMeshBackend implements MeshBackend {
private DirectTessellator direct;
@Override
@@ -241,20 +243,10 @@ public final class AngelicaTesrMeshCache {
@Override
public TemplateBuffer endCaptureToTemplate() {
final int vertexCount = direct.getVertexCount();
if (vertexCount == 0) {
TessellatorManager.stopCapturingDirect();
direct = null;
return null;
}
final int drawMode = direct.getDrawMode();
final VertexFormat format = direct.getVertexFormat();
final ByteBuffer copy = direct.allocateBufferCopy();
final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode);
memFree(copy);
final TemplateBuffer template = TemplateCapture.toTemplate(direct);
TessellatorManager.stopCapturingDirect();
direct = null;
return new TemplateBuffer(data, vertexCount, drawMode);
return template;
}
}
}
@@ -0,0 +1,69 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.client.rendering.ModelViewDelta;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import net.minecraft.client.renderer.Tessellator;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector3f;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc;
public final class BakedTransformCapture extends DirectTessellator {
private final ModelViewDelta delta = new ModelViewDelta();
private final Matrix4f deltaMatrix = new Matrix4f();
private final Vector3f scratch = new Vector3f();
private Matrix4fc transform;
private int firstColor;
private boolean sawRun;
private boolean colorUniform = true;
public BakedTransformCapture(int capacity) {
super(memAlloc(capacity));
}
public void begin() {
TessellatorManager.startCapturingDirect(this);
delta.snapshot();
sawRun = false;
colorUniform = true;
}
public TemplateBuffer end() {
final TemplateBuffer template = colorUniform ? TemplateCapture.toTemplate(this) : null;
TessellatorManager.stopCapturingDirect();
return template;
}
@Override
protected int interceptDraw(Tessellator tessellator) {
final Color4 color = GLStateManager.getColor();
final int packed = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
if (!sawRun) {
sawRun = true;
firstColor = packed;
} else if (packed != firstColor) {
colorUniform = false;
}
transform = delta.deltaOrNull(deltaMatrix);
try {
return super.interceptDraw(tessellator);
} finally {
transform = null;
}
}
@Override
protected long writeVertexData(VertexFormat format, int[] rawBuffer, int rawBufferIndex) {
if (transform != null) {
return format.writeToBuffer0(writePtr, rawBuffer, rawBufferIndex, transform, scratch);
}
return super.writeVertexData(format, rawBuffer, rawBufferIndex);
}
}
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
/** Excludes renderers that mix batched model parts with their own draws, which reorders their geometry. */
public final class BatchEligibility {
@@ -13,6 +14,10 @@ public final class BatchEligibility {
private static boolean allowed;
private static long drawsAtStart;
private static long expectedDraws;
private static long foreignDraws;
private static long bracketDrawsAtStart;
private static long bracketExpectedAtStart;
private static int bracketDepth;
private static int parts;
private BatchEligibility() {}
@@ -21,6 +26,7 @@ public final class BatchEligibility {
if (depth++ > 0) return allowed;
drawsAtStart = drawCount;
expectedDraws = 0L;
foreignDraws = 0L;
parts = 0;
allowed = state == SAFE;
return allowed;
@@ -29,9 +35,13 @@ public final class BatchEligibility {
public static byte end(byte state, long drawCount) {
if (--depth > 0) return state;
allowed = false;
GLSMHooks.resolvePendingProgram();
if (parts == 0) return state;
final long foreign = (drawCount - drawsAtStart) - expectedDraws;
if (foreign > 0L) return DENIED;
if (foreign > 0L) {
foreignDraws = foreign;
return DENIED;
}
return state == UNKNOWN ? SAFE : state;
}
@@ -50,9 +60,21 @@ public final class BatchEligibility {
}
}
public static void beginExpectedDraws(long drawCount) {
if (bracketDepth++ > 0) return;
bracketDrawsAtStart = drawCount;
bracketExpectedAtStart = expectedDraws;
}
public static void endExpectedDraws(long drawCount) {
if (--bracketDepth > 0) return;
final long alreadyExpected = expectedDraws - bracketExpectedAtStart;
expectedDraws += (drawCount - bracketDrawsAtStart) - alreadyExpected;
}
public static void onStateChange(Object renderer, byte state) {
if (state != DENIED) return;
final String name = renderer.getClass().getName();
GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts - excluding it from model part batching", name);
GLStateManager.warnOnce("tesr-mixed:" + name, "{} draws its own geometry alongside model parts ({} foreign draws) - excluding it from model part batching", name, foreignDraws);
}
}
@@ -1,8 +1,8 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import org.lwjgl.opengl.GL11;
@@ -17,21 +17,43 @@ public final class EntityMaterials {
static final TesrMaterial ADDITIVE_NO_DEPTH_WRITE = TesrMaterial.builder().additive().noDepthWrite().stream().build();
static final TesrMaterial ADDITIVE_ALPHA = TesrMaterial.builder().additiveAlpha().stream().build();
static final TesrMaterial ADDITIVE_ALPHA_NO_DEPTH_WRITE = TesrMaterial.builder().additiveAlpha().noDepthWrite().stream().build();
static final TesrMaterial SHADOW = TesrMaterial.builder().translucent().cutout(0.1f).noDepthWrite().unlit().stream().build();
public static final TesrMaterial DROPPED_ITEM_CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().unfilteredAtlas().build();
public static final TesrMaterial DROPPED_ITEM_TRANSLUCENT = TesrMaterial.builder().translucent().cutout(0.1f).unfilteredAtlas().stream().build();
public static final TesrMaterial HELD_BLOCK_CUTOUT = TesrMaterial.builder().cutout(0.1f).stream().build();
public static final TesrMaterial HELD_BLOCK_TRANSLUCENT = TesrMaterial.builder().translucent().cutout(0.1f).stream().build();
static final TesrMaterial OVERLAY = TesrMaterial.builder().translucent().depthEqual().stream().build();
static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream()
public static final TesrMaterial GLINT = TesrMaterial.builder().glint().depthEqual().noDepthWrite().unlit().stream()
.special(TesrMaterial.SpecialRender.GLINT).build();
private static final BlendState effectiveBlend = new BlendState();
private static final AlphaState effectiveAlpha = new AlphaState();
private EntityMaterials() {}
static TesrMaterial fromCurrentState() {
static TesrMaterial fromCurrentState(boolean texIdentity) {
final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled();
final boolean texAnimated = textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0));
final BlendState blend = GLStateManager.getBlendState();
return fromState(textured, texAnimated,
GLStateManager.getBlendMode().isEnabled(), blend.getSrcRgb(), blend.getDstRgb(),
GLStateManager.getAlphaTest().isEnabled(),
GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(),
GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled());
final BlendState blend = GLStateManager.getEffectiveBlendState(effectiveBlend);
final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha);
return fromState(textured, textured && !texIdentity, GLStateManager.isEffectiveBlendEnabled(), blend.getSrcRgb(), blend.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alpha.getFunction(), alpha.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled());
}
public static TesrMaterial itemFromCurrentState(boolean unfilteredAtlas) {
final BlendState blend = GLStateManager.getEffectiveBlendState(effectiveBlend);
final AlphaState alpha = GLStateManager.getEffectiveAlphaState(effectiveAlpha);
return itemFromState(unfilteredAtlas, GLStateManager.isEffectiveBlendEnabled(), blend.getSrcRgb(), blend.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alpha.getFunction(), alpha.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled());
}
static TesrMaterial itemFromState(boolean unfilteredAtlas, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) {
if (depthFunc != GL11.GL_LEQUAL && depthFunc != GL11.GL_LESS) return null;
if (!depthMask) return null;
if (!alphaTest) return null;
if (alphaFunc != GL11.GL_GREATER || Math.abs(alphaRef - 0.1f) > 1.0e-4f) return null;
if (blend) {
if (srcRgb != GL11.GL_SRC_ALPHA || dstRgb != GL11.GL_ONE_MINUS_SRC_ALPHA) return null;
return unfilteredAtlas ? DROPPED_ITEM_TRANSLUCENT : HELD_BLOCK_TRANSLUCENT;
}
return unfilteredAtlas ? DROPPED_ITEM_CUTOUT : HELD_BLOCK_CUTOUT;
}
static TesrMaterial fromState(boolean textured, boolean blend, int srcRgb, int dstRgb, boolean alphaTest, int alphaFunc, float alphaRef, int depthFunc, boolean depthMask) {
@@ -0,0 +1,169 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.PassOverride;
import net.coderbot.iris.pipeline.PipelineManager;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.vertices.NormI8;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import java.util.Arrays;
final class EntityShadowBatcher {
private static final ResourceLocation SHADOW_TEXTURE = new ResourceLocation("textures/misc/shadow.png");
private static final int PACKED_UP = NormI8.pack(0f, 1f, 0f, 0f);
private static final int INITIAL_QUADS = 256;
private static final int INITIAL_MVS = 8;
private int[] records = new int[INITIAL_QUADS * ShadowQuadMath.RECORD_SIZE];
private int[] recordMv = new int[INITIAL_QUADS];
private int count;
private Matrix4f[] mvs = new Matrix4f[INITIAL_MVS];
private int mvCount;
private final int[] packedScratch = new int[4 * ModelQuadUtil.VERTEX_SIZE];
private final int[] ijk = new int[6];
private final Matrix4f mvScratch = new Matrix4f();
private final Vector3f scratch = new Vector3f();
private int lastMvGeneration;
private RenderLayer layer;
private long quads;
private long draws;
long statQuads() { return quads; }
long statDraws() { return draws; }
boolean record(World world, Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, float shadowSize) {
if (world == null || !ModelPartBatcher.INSTANCE.entityPassActive()) return false;
if (Iris.enabled) {
final PipelineManager manager = Iris.getPipelineManagerNullable();
if (manager != null) {
final WorldRenderingPipeline pipeline = manager.getPipelineNullable();
if (pipeline != null && pipeline.shouldDisableVanillaEntityShadows()) return false;
}
}
float size = shadowSize;
if (entity instanceof EntityLiving living) {
size *= living.getRenderSizeModifier();
if (living.isChild()) {
size *= 0.5F;
}
}
final double ss = entity.getShadowSize();
final double ex = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks;
final double ey = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks + ss;
final double ez = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks;
final double ox = x - ex;
final double oy = y - ey;
final double oz = z - ez;
final int cells = ShadowQuadMath.box(ex, ey, ez, size, ijk);
ensureCapacity(cells);
final int mvIndex = currentMvIndex();
final int packedLight = GLSMConfig.packedLastBrightness();
final float[] brightnessTable = world.provider.lightBrightnessTable;
final double yParam = y + ss;
final double oyParam = oy + ss;
for (int bx = ijk[0]; bx <= ijk[1]; ++bx) {
for (int by = ijk[2]; by <= ijk[3]; ++by) {
for (int bz = ijk[4]; bz <= ijk[5]; ++bz) {
final Block block = world.getBlock(bx, by - 1, bz);
if (block.getMaterial() == Material.air) continue;
final int light = world.getBlockLightValue(bx, by, bz);
if (light <= 3 || !block.renderAsNormalBlock()) continue;
if (ShadowQuadMath.project(records, count * ShadowQuadMath.RECORD_SIZE, x, yParam, z, bx, by, bz, shadowAlpha, size, ox, oyParam, oz, block.getBlockBoundsMinX(), block.getBlockBoundsMaxX(), block.getBlockBoundsMinY(), block.getBlockBoundsMinZ(), block.getBlockBoundsMaxZ(), brightnessTable[light], packedLight)) {
recordMv[count] = mvIndex;
count++;
}
}
}
}
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GLStateManager.glDisable(GL11.GL_BLEND);
GLStateManager.glDepthMask(true);
return true;
}
void flush(AngelicaBufferSource source) {
if (count == 0) {
mvCount = 0;
return;
}
final SegmentedBufferBuilder builder = source.getBuffer(layer(), 0);
for (int i = 0; i < count; i++) {
ShadowQuadMath.expand(packedScratch, records, i * ShadowQuadMath.RECORD_SIZE, PACKED_UP);
builder.addPackedVertices(packedScratch, 4, mvs[recordMv[i]], scratch);
}
draws++;
quads += count;
count = 0;
mvCount = 0;
}
void reset() {
count = 0;
mvCount = 0;
records = new int[INITIAL_QUADS * ShadowQuadMath.RECORD_SIZE];
recordMv = new int[INITIAL_QUADS];
mvs = new Matrix4f[INITIAL_MVS];
layer = null;
}
private int currentMvIndex() {
final int mvGen = GLStateManager.getMvGeneration();
if (mvCount > 0 && mvGen == lastMvGeneration) return mvCount - 1;
lastMvGeneration = mvGen;
mvScratch.set(GLStateManager.getModelViewMatrix());
if (mvCount > 0 && mvs[mvCount - 1].equals(mvScratch)) return mvCount - 1;
if (mvCount == mvs.length) mvs = Arrays.copyOf(mvs, mvs.length * 2);
Matrix4f slot = mvs[mvCount];
if (slot == null) {
slot = new Matrix4f();
mvs[mvCount] = slot;
}
slot.set(mvScratch);
return mvCount++;
}
private void ensureCapacity(int additionalQuads) {
final int neededQuads = count + additionalQuads;
if (neededQuads * ShadowQuadMath.RECORD_SIZE > records.length) {
records = Arrays.copyOf(records, Math.max(neededQuads * ShadowQuadMath.RECORD_SIZE, records.length * 2));
}
if (neededQuads > recordMv.length) {
recordMv = Arrays.copyOf(recordMv, Math.max(neededQuads, recordMv.length * 2));
}
}
private RenderLayer layer() {
RenderLayer l = layer;
if (l == null) {
l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F);
layer = l;
}
return l;
}
}
@@ -0,0 +1,59 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer;
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
import java.nio.ByteBuffer;
public final class InstanceRing {
private PersistentStreamingBuffer persistentRing;
private OrphanStreamingBuffer orphanRing;
private boolean initialized;
private boolean usedThisFrame;
private int bufferId;
public long upload(ByteBuffer data, int stride) {
if (!initialized) {
initialized = true;
persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY);
}
usedThisFrame = true;
if (persistentRing != null) {
final int index = persistentRing.upload(data, stride);
if (index >= 0) {
bufferId = persistentRing.getBufferId();
return (long) index * stride;
}
}
if (orphanRing == null) orphanRing = new OrphanStreamingBuffer();
orphanRing.upload(data);
bufferId = orphanRing.getBufferId();
return 0;
}
public int bufferId() {
return bufferId;
}
public void postDraw() {
if (usedThisFrame && persistentRing != null) {
persistentRing.postDraw();
}
usedThisFrame = false;
}
public void delete() {
if (persistentRing != null) {
persistentRing.destroy();
persistentRing = null;
}
if (orphanRing != null) {
orphanRing.destroy();
orphanRing = null;
}
initialized = false;
usedThisFrame = false;
bufferId = 0;
}
}
@@ -4,12 +4,15 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.ImmediateExtendedAttribHandler;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.ffp.CubeInstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.UnitCubeMesh;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.streaming.OrphanStreamingBuffer;
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.InstanceColumns;
import com.gtnewhorizons.angelica.rendering.tesr.RetainedTesrGroups.TexRun;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
@@ -26,8 +29,6 @@ import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.CO
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutFloat;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt;
final class InstancedTemplateRenderer {
@@ -36,6 +37,8 @@ final class InstancedTemplateRenderer {
private static final int TEMPLATE_STRIDE = VERTEX_SIZE * 4;
private static final int TEMPLATE_FLAGS = VertexFlags.COLOR_BIT | VertexFlags.TEXTURE_BIT | VertexFlags.NORMAL_BIT;
private static long bucketEpochSource;
private static final class TemplateMesh {
int vao;
int vbo;
@@ -51,69 +54,58 @@ final class InstancedTemplateRenderer {
}
private final Reference2ObjectOpenHashMap<TemplateBuffer, TemplateMesh> meshes = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<TemplateBuffer, Bucket> buckets = new Reference2ObjectOpenHashMap<>();
private final ObjectArrayList<Bucket> bucketPool = new ObjectArrayList<>();
private final ObjectArrayList<Bucket> liveBuckets = new ObjectArrayList<>();
private final float[] matScratch = new float[16];
private PersistentStreamingBuffer persistentRing;
private OrphanStreamingBuffer orphanRing;
private boolean ringInitialized;
private boolean ringUsedThisFrame;
private int uploadBufferId;
private final InstanceRing ring;
private ByteBuffer staging;
int drawGroup(ObjectArrayList<TemplateBuffer> templates, FloatArrayList matrices, IntArrayList lights, IntArrayList colors, int count, long nowMs) {
for (int i = 0; i < count; i++) {
final TemplateBuffer template = templates.get(i);
Bucket bucket = buckets.get(template);
if (bucket == null) {
bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop();
bucket.mesh = meshFor(template, nowMs);
buckets.put(template, bucket);
liveBuckets.add(bucket);
InstancedTemplateRenderer(InstanceRing ring) {
this.ring = ring;
}
int drawTemplates(InstanceColumns cols, TexRun run, long nowMs) {
final long epoch = ++bucketEpochSource;
for (TexRun seg = run; seg != null; seg = seg.next) {
for (int i = seg.start, end = seg.end; i < end; i++) {
final TemplateBuffer template = cols.templates.get(i);
final Bucket bucket;
if (template.bucketEpoch == epoch) {
bucket = liveBuckets.get(template.bucketIndex);
} else {
bucket = bucketPool.isEmpty() ? new Bucket() : bucketPool.pop();
bucket.mesh = meshFor(template, nowMs);
template.bucketEpoch = epoch;
template.bucketIndex = liveBuckets.size();
liveBuckets.add(bucket);
}
bucket.indices.add(i);
}
bucket.indices.add(i);
}
staging = MeshBuffer.ensureCapacity(staging, count * InstancedAttribs.STRIDE, false);
staging = MeshBuffer.ensureCapacity(staging, run.parts * InstancedAttribs.STRIDE, false);
final long base = memAddress0(staging);
long ptr = base;
for (int b = 0, n = liveBuckets.size(); b < n; b++) {
final IntArrayList indices = liveBuckets.get(b).indices;
for (int j = 0, m = indices.size(); j < m; j++) {
final int i = indices.getInt(j);
matrices.getElements(i * 16, matScratch, 0, 16);
for (int k = 0; k < 16; k++) {
memPutFloat(ptr + k * 4L, matScratch[k]);
}
memPutInt(ptr + InstancedAttribs.OFFSET_COLOR, colors.getInt(i));
final int light = lights.getInt(i);
memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP, light & 0xFFFF);
memPutFloat(ptr + InstancedAttribs.OFFSET_LIGHTMAP + 4, (light >>> 16) & 0xFFFF);
InstancedAttribs.writeHead(ptr, cols.matrices, i * 16, cols.colors.getInt(i), cols.overlays.getInt(i), cols.infos.getLong(i));
InstancedAttribs.writeLightmap(ptr + InstancedAttribs.OFFSET_LIGHTMAP, cols.lights.getInt(i));
ptr += InstancedAttribs.STRIDE;
}
}
staging.position(0);
staging.limit((int) (ptr - base));
final long ringBase = uploadInstances(staging);
staging.clear();
final long ringBase = uploadStaging(base, ptr, InstancedAttribs.STRIDE);
int draws = 0;
long recordOffset = ringBase;
final int ringId = uploadBufferId;
final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler;
if (extHandler != null && extHandler.wantsExtended()) {
FfpExtendedAttribs.setNeutralCurrentValues();
}
GLStateManager.instancedFfpDrawActive = true;
neutralizeExtendedAttribs();
GLStateManager.ffpInstancing = Instancing.TEMPLATE;
for (int b = 0, n = liveBuckets.size(); b < n; b++) {
final Bucket bucket = liveBuckets.get(b);
final TemplateMesh mesh = bucket.mesh;
GLStateManager.glBindVertexArray(mesh.vao);
VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ringId);
pointInstanceAttribs(recordOffset);
bindRingTo(mesh.vao, TEMPLATE_FLAGS);
InstancedAttribs.pointTemplate(recordOffset);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLStateManager.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, bucket.indices.size());
draws++;
@@ -122,41 +114,66 @@ final class InstancedTemplateRenderer {
bucket.mesh = null;
bucketPool.add(bucket);
}
GLStateManager.instancedFfpDrawActive = false;
GLStateManager.ffpInstancing = Instancing.NONE;
GLStateManager.glBindVertexArray(0);
liveBuckets.clear();
buckets.clear();
return draws;
}
private static void pointInstanceAttribs(long base) {
for (int c = 0; c < 4; c++) {
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_MATRIX_COL0 + c, 4, GL11.GL_FLOAT, false,
InstancedAttribs.STRIDE, base + c * 16L);
}
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_COLOR, 4, GL11.GL_UNSIGNED_BYTE, true,
InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_COLOR);
GLStateManager.glVertexAttribPointer(InstancedAttribs.LOC_LIGHTMAP, 2, GL11.GL_FLOAT, false,
InstancedAttribs.STRIDE, base + InstancedAttribs.OFFSET_LIGHTMAP);
}
private long uploadInstances(ByteBuffer data) {
if (!ringInitialized) {
ringInitialized = true;
persistentRing = PersistentStreamingBuffer.createOrNull(PersistentStreamingBuffer.DEFAULT_CAPACITY);
}
ringUsedThisFrame = true;
if (persistentRing != null) {
final int index = persistentRing.upload(data, InstancedAttribs.STRIDE);
if (index >= 0) {
uploadBufferId = persistentRing.getBufferId();
return (long) index * InstancedAttribs.STRIDE;
void drawCubes(InstanceColumns cols, TexRun run) {
staging = MeshBuffer.ensureCapacity(staging, run.instances * CubeInstancedAttribs.STRIDE, false);
final long base = memAddress0(staging);
long ptr = base;
for (TexRun seg = run; seg != null; seg = seg.next) {
for (int i = seg.start, end = seg.end; i < end; i++) {
final int off = i * 16;
final CubeParams[] partCubes = cols.cubes.get(i);
final float scale = cols.scales.getFloat(i);
final int color = cols.colors.getInt(i);
final int light = cols.lights.getInt(i);
final int overlay = cols.overlays.getInt(i);
final long info = cols.infos.getLong(i);
for (int p = 0, n = partCubes.length; p < n; p++) {
final CubeParams cube = partCubes[p];
cube.writeRows(ptr, cols.matrices, off, scale);
InstancedAttribs.writeTail(ptr, color, overlay, info);
InstancedAttribs.writeLightmap(ptr + CubeInstancedAttribs.OFFSET_LIGHTMAP_SCALE, light);
cube.writeTexture(ptr);
ptr += CubeInstancedAttribs.STRIDE;
}
}
}
if (orphanRing == null) orphanRing = new OrphanStreamingBuffer();
orphanRing.upload(data);
uploadBufferId = orphanRing.getBufferId();
return 0;
final long ringBase = uploadStaging(base, ptr, CubeInstancedAttribs.STRIDE);
neutralizeExtendedAttribs();
bindRingTo(UnitCubeMesh.vao(), UnitCubeMesh.VERTEX_FLAGS);
CubeInstancedAttribs.pointInstanceAttribs(ringBase);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLStateManager.ffpInstancing = Instancing.CUBE;
GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, run.instances);
GLStateManager.ffpInstancing = Instancing.NONE;
GLStateManager.glBindVertexArray(0);
}
private long uploadStaging(long base, long end, int stride) {
staging.position(0);
staging.limit((int) (end - base));
final long ringBase = ring.upload(staging, stride);
staging.clear();
return ringBase;
}
private void bindRingTo(int vao, int vertexFlags) {
GLStateManager.glBindVertexArray(vao);
VAOManager.setCurrentVertexFlags(vertexFlags);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, ring.bufferId());
}
private static void neutralizeExtendedAttribs() {
final ImmediateExtendedAttribHandler extHandler = GLSMHooks.immediateExtendedHandler;
if (extHandler != null && extHandler.wantsExtended()) {
FfpExtendedAttribs.setNeutralCurrentValues();
}
}
private TemplateMesh meshFor(TemplateBuffer template, long nowMs) {
@@ -196,10 +213,7 @@ final class InstancedTemplateRenderer {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
for (int loc = InstancedAttribs.LOC_MATRIX_COL0; loc <= InstancedAttribs.LOC_LIGHTMAP; loc++) {
GLStateManager.glEnableVertexAttribArray(loc);
GLStateManager.glVertexAttribDivisor(loc, 1);
}
InstancedAttribs.enableHeadArrays();
VAOManager.setCurrentVertexFlags(TEMPLATE_FLAGS);
GLStateManager.glBindVertexArray(0);
return mesh;
@@ -225,10 +239,7 @@ final class InstancedTemplateRenderer {
}
void endFrame() {
if (ringUsedThisFrame && persistentRing != null) {
persistentRing.postDraw();
}
ringUsedThisFrame = false;
ring.postDraw();
}
void sweep(long now) {
@@ -247,6 +258,10 @@ final class InstancedTemplateRenderer {
delete(mesh);
}
meshes.clear();
liveBuckets.clear();
bucketPool.clear();
staging = null;
UnitCubeMesh.delete();
}
private static void delete(TemplateMesh mesh) {
@@ -0,0 +1,46 @@
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.PositionTextureVertex;
import net.minecraft.client.model.TexturedQuad;
public final class ModelBoxCapture {
private static final float EPSILON = 1.0e-4f;
private ModelBoxCapture() {}
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);
if (params == null) return null;
final float lowX = mirror ? params.minX() + params.spanX() : params.minX();
final float spanX = mirror ? -params.spanX() : params.spanX();
for (int face = 0; face < UnitCubeMesh.FACE_COUNT; face++) {
final TexturedQuad quad = quads[face];
if (quad == null || quad.vertexPositions == null || quad.vertexPositions.length != 4) return null;
final int[] corners = UnitCubeMesh.FACES[face].corners();
final UnitCubeMesh.Net net = UnitCubeMesh.FACES[face].net();
for (int corner = 0; corner < 4; corner++) {
final PositionTextureVertex vertex = quad.vertexPositions[mirror ? 3 - corner : corner];
if (vertex == null || vertex.vector3D == null) return null;
final float[] unit = UnitCubeMesh.CORNERS[corners[corner]];
if (!near((float) vertex.vector3D.xCoord, lowX + unit[0] * spanX) || !near((float) vertex.vector3D.yCoord, params.minY() + unit[1] * params.spanY()) || !near((float) vertex.vector3D.zCoord, params.minZ() + unit[2] * params.spanZ())) {
return null;
}
final int u = texU + net.u(corner).texels(sizeX, sizeZ);
final int v = texV + net.v(corner).texels(sizeY, sizeZ);
if (!near(vertex.texturePositionX, u / texWidth) || !near(vertex.texturePositionY, v / texHeight)) {
return null;
}
}
}
return params;
}
private static boolean near(float a, float b) {
return Math.abs(a - b) < EPSILON;
}
}
@@ -1,7 +1,6 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.api.tesr.ModelPartMeshBuilder;
@@ -11,12 +10,17 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.DisplayListManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.glsm.states.PolygonState;
import com.gtnewhorizons.angelica.mixins.interfaces.ModelBoxData;
import com.gtnewhorizons.angelica.profiling.BailClassCounts;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
@@ -31,7 +35,9 @@ import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.client.model.ModelBox;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
@@ -50,7 +56,6 @@ public final class ModelPartBatcher {
MATERIAL("tesr.bail.material"),
TEXTURE("tesr.bail.texture"),
TEMPLATE("tesr.bail.template"),
HURT_FLASH("tesr.bail.hurtFlash"),
FOREIGN_PROGRAM("tesr.bail.foreignProgram"),
MIXED_RENDERER("tesr.bail.mixedRenderer");
@@ -64,7 +69,10 @@ public final class ModelPartBatcher {
private static final long SWEEP_INTERVAL_MS = 5_000L;
private static final Tracy.ZoneId Z_ENTITY_LAYER_LOOP = Tracy.zoneId("entityLayerLoop", Tracy.COLOR_CLIENT);
private final AngelicaBufferSource bufferSource = new AngelicaBufferSource();
private final EntityShadowBatcher shadows = new EntityShadowBatcher();
private final RetainedTesrGroups groups = new RetainedTesrGroups(bufferSource);
private final RetainedTesrGroups shadowGroups = new RetainedTesrGroups(bufferSource);
private RetainedTesrGroups activeGroups = groups;
@@ -75,6 +83,9 @@ public final class ModelPartBatcher {
private final Matrix4f texMatrixScratch = new Matrix4f();
private int lastMvGeneration;
private boolean mvCaptured;
private int texGeneration;
private boolean texCaptured;
private boolean texIdentity;
private boolean active;
private Mode mode = Mode.BLOCK_ENTITIES;
private boolean instancedThisCycle;
@@ -88,7 +99,13 @@ public final class ModelPartBatcher {
public long statParts() { return parts; }
public long statLiveFallbacks() { return liveFallbacks; }
public long statInstancedDraws() { return groups.instancedDraws + shadowGroups.instancedDraws; }
public long statInstancedInstances() { return groups.instancedInstances + shadowGroups.instancedInstances; }
public long statCubeInstances() { return groups.cubeInstances + shadowGroups.cubeInstances; }
public long statTexMatrixRuns() { return groups.texMatrixRuns + shadowGroups.texMatrixRuns; }
public long statBail(BailReason reason) { return bails[reason.ordinal()]; }
public long statShadowQuads() { return shadows.statQuads(); }
public long statShadowDraws() { return shadows.statDraws(); }
private void bail(BailReason reason) {
bails[reason.ordinal()]++;
@@ -96,10 +113,10 @@ public final class ModelPartBatcher {
private static final class PartTemplate {
TemplateBuffer template;
CubeParams[] cubes;
float scale;
long lastUsedMs;
boolean emptyVanillaPart;
boolean forceStream;
}
private final Reference2ObjectOpenHashMap<ModelRenderer, PartTemplate> templates = new Reference2ObjectOpenHashMap<>();
@@ -110,13 +127,15 @@ public final class ModelPartBatcher {
PassOverride pass;
float offsetFactor;
float offsetUnits;
int glintSlot;
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
this.texture = texture;
this.material = material;
this.pass = pass;
this.offsetFactor = offsetFactor;
this.offsetUnits = offsetUnits;
this.glintSlot = glintSlot;
return this;
}
@@ -126,7 +145,8 @@ public final class ModelPartBatcher {
return Objects.equals(texture, other.texture) && Objects.equals(material, other.material)
&& Objects.equals(pass, other.pass)
&& Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor)
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits);
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)
&& glintSlot == other.glintSlot;
}
@Override
@@ -134,6 +154,7 @@ public final class ModelPartBatcher {
int h = (Objects.hashCode(texture) * 31 + Objects.hashCode(material)) * 31 + Objects.hashCode(pass);
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
h = h * 31 + glintSlot;
return h;
}
}
@@ -145,16 +166,24 @@ public final class ModelPartBatcher {
private PassOverride lastLayerPass;
private float lastLayerOffsetFactor;
private float lastLayerOffsetUnits;
private int lastLayerGlintSlot;
private RenderLayer lastLayer;
private static ResourceLocation lastBoundLocation;
private static int lastBoundGlId = -1;
private static int lastBoundGlintSlot = ShaderGlint.NO_TINT;
private ModelPartBatcher() {}
public static void onTextureSwap(int glId, int glintSlot) {
lastBoundGlId = glId;
lastBoundGlintSlot = glintSlot;
}
public static void onTextureBind(ResourceLocation location, int glId) {
lastBoundLocation = location;
lastBoundGlId = glId;
lastBoundGlintSlot = ShaderGlint.NO_TINT;
}
public void begin(Mode mode) {
@@ -172,16 +201,17 @@ public final class ModelPartBatcher {
return;
}
active = true;
final long nowMs = System.currentTimeMillis();
mvCaptured = false;
texCaptured = false;
activeGroups = shadow ? shadowGroups : groups;
bufferSource.setIdKind(mode == Mode.ENTITIES ? AngelicaBufferSource.GroupIdKind.ENTITY : AngelicaBufferSource.GroupIdKind.BLOCK_ENTITY);
activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
final long now = System.currentTimeMillis();
if (now - lastSweepMs >= SWEEP_INTERVAL_MS) {
lastSweepMs = now;
groups.sweep(now);
shadowGroups.sweep(now);
sweepTemplates(now);
if (nowMs - lastSweepMs >= SWEEP_INTERVAL_MS) {
lastSweepMs = nowMs;
groups.sweep(nowMs);
shadowGroups.sweep(nowMs);
sweepTemplates(nowMs);
}
}
@@ -189,25 +219,18 @@ public final class ModelPartBatcher {
if (!active) return;
active = false;
if (shadow) {
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
bufferSource.endBatch(activeGroups);
if (instancedThisCycle) {
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
drawBatches();
} else {
final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive();
final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop;
if (wrapEntities) GbufferPrograms.beginEntities();
else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary();
try {
shadows.flush(bufferSource);
drawBatches();
} finally {
if (wrapEntities) GbufferPrograms.endEntities();
}
if (!TesrBatchRenderer.INSTANCE.hasPendingGeometry()) {
BatchingFontRenderer.flushDeferredText();
}
return;
}
final boolean inEntityLoop = mode == Mode.ENTITIES && Iris.enabled && GbufferPrograms.isEntityLoopActive();
final boolean wrapEntities = mode == Mode.ENTITIES && Iris.enabled && !inEntityLoop;
if (wrapEntities) GbufferPrograms.beginEntities();
else if (inEntityLoop) GbufferPrograms.onEntityRenderBoundary();
try {
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
bufferSource.endBatch(activeGroups);
} finally {
if (wrapEntities) GbufferPrograms.endEntities();
}
if (instancedThisCycle) {
TesrBatchRenderer.INSTANCE.instancedRenderer.endFrame();
@@ -217,10 +240,32 @@ public final class ModelPartBatcher {
}
}
private void drawBatches() {
if (Tracy.ENABLED) Tracy.beginZone(Z_ENTITY_LAYER_LOOP);
try {
bufferSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
bufferSource.endBatch(activeGroups);
} finally {
if (Tracy.ENABLED) Tracy.endZone();
}
}
public boolean isActive() {
return active;
}
public boolean entityPassActive() {
return active && mode == Mode.ENTITIES && !shadow;
}
public boolean isShadowPass() {
return active && shadow;
}
public static boolean recordShadow(World world, Entity entity, double x, double y, double z, float shadowAlpha, float partialTicks, float shadowSize) {
return INSTANCE.shadows.record(world, entity, x, y, z, shadowAlpha, partialTicks, shadowSize);
}
public static boolean partDraw(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
final ModelPartBatcher r = INSTANCE;
if (!r.active) {
@@ -244,15 +289,6 @@ public final class ModelPartBatcher {
}
private boolean queuePart(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
if (shaderPipeline != null) {
if (GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) {
bail(BailReason.FOREIGN_PROGRAM);
return false;
}
} else if (GLStateManager.getOverlayA() != 0.0f) {
bail(BailReason.HURT_FLASH);
return false;
}
final PartTemplate entry = templateFor(part, scale, builder);
if (entry.emptyVanillaPart) {
return true;
@@ -260,7 +296,19 @@ public final class ModelPartBatcher {
if (shadow && isDepthEqualDecalState()) {
return true;
}
final TesrMaterial material = EntityMaterials.fromCurrentState();
return queueTemplate(entry.template, entry.cubes, scale, null);
}
public boolean queueTemplate(TemplateBuffer template, TesrMaterial material) {
return queueTemplate(template, null, 1.0f, material);
}
private boolean queueTemplate(TemplateBuffer template, CubeParams[] cubes, float scale, TesrMaterial explicitMaterial) {
if (shaderPipeline != null && GLStateManager.getActiveProgram() != shaderPipeline.getActivePassProgramId()) {
bail(BailReason.FOREIGN_PROGRAM);
return false;
}
final TesrMaterial material = explicitMaterial != null ? explicitMaterial : EntityMaterials.fromCurrentState(unitTexIdentity());
if (material == null) {
bail(BailReason.MATERIAL);
if (Tracy.ENABLED) {
@@ -283,35 +331,26 @@ public final class ModelPartBatcher {
return false;
}
}
final TemplateBuffer template = entry.template;
if (template == null) {
bail(BailReason.TEMPLATE);
if (Tracy.ENABLED) BailClassCounts.TEMPLATE.add(TesrAttribution.currentRenderable);
return false;
}
Matrix4f texMatrix = null;
if (texture != null) {
final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0);
if (!MatrixHelper.isIdentity(unitMatrix)) {
texMatrix = texMatrixScratch.set(unitMatrix);
if (material.isDepthEqual()) {
entry.forceStream = true;
}
}
}
final Matrix4f texMatrix = texture != null && !unitTexIdentity() ? texMatrixScratch : null;
final PassOverride pass = shaderPipeline != null ? PassOverride.capture() : PassOverride.NONE;
final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL);
final PolygonState polygon = GLStateManager.getPolygonState();
final float offsetFactor = offset ? polygon.getOffsetFactor() : 0.0f;
final float offsetUnits = offset ? polygon.getOffsetUnits() : 0.0f;
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits);
final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT;
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot);
// Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id
final int entityId = mode == Mode.ENTITIES || pass.isEntityPhase()
? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity())
: CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
final Color4 color = GLStateManager.getColor();
final int colorABGR = ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
final int colorABGR = AngelicaBufferSource.packAbgr(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
final int overlayABGR = shaderPipeline != null ? AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor()) : AngelicaBufferSource.packAbgr(GLStateManager.getOverlayR(), GLStateManager.getOverlayG(), GLStateManager.getOverlayB(), GLStateManager.getOverlayA());
final long entityInfo = shaderPipeline != null ? InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem()) : 0L;
final int packedLight = GLSMConfig.packedLastBrightness();
final int mvGen = GLStateManager.getMvGeneration();
if (!mvCaptured || mvGen != lastMvGeneration) {
@@ -319,29 +358,43 @@ public final class ModelPartBatcher {
lastMvGeneration = mvGen;
mvCaptured = true;
}
activeGroups.queue(template, layer, material, modelView, packedLight, colorABGR, entityId, texMatrix, entry.forceStream);
activeGroups.queue(template, cubes, scale, layer, material, modelView, packedLight, colorABGR, overlayABGR, entityInfo, entityId, texMatrix);
parts++;
return true;
}
private final ReferenceOpenHashSet<Class<?>> loggedMaterialBails = new ReferenceOpenHashSet<>();
private final BlendState bailBlend = new BlendState();
private final AlphaState bailAlpha = new AlphaState();
private void logMaterialBail() {
final Class<?> cls = TesrAttribution.currentRenderable;
if (cls == null || !loggedMaterialBails.add(cls)) return;
final boolean textured = GLStateManager.getTextures().getTextureUnitStates(0).isEnabled();
final BlendState blendState = GLStateManager.getBlendState();
AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}",
cls.getName(), shadow, textured,
textured && !MatrixHelper.isIdentity(GLStateManager.getTextures().getTextureUnitMatrix(0)),
GLStateManager.getBlendMode().isEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(),
GLStateManager.getAlphaTest().isEnabled(),
GLStateManager.getAlphaState().getFunction(), GLStateManager.getAlphaState().getReference(),
GLStateManager.getDepthState().getFunc(), GLStateManager.getDepthState().isEnabled());
final BlendState blendState = GLStateManager.getEffectiveBlendState(bailBlend);
final AlphaState alphaState = GLStateManager.getEffectiveAlphaState(bailAlpha);
AngelicaMod.LOGGER.info("TESR MATERIAL bail: cls={} shadow={} textured={} texAnimated={} blend={} src={} dst={} alphaTest={} alphaFunc={} alphaRef={} depthFunc={} depthMask={}", cls.getName(), shadow, textured, textured && !unitTexIdentity(), GLStateManager.isEffectiveBlendEnabled(), blendState.getSrcRgb(), blendState.getDstRgb(), GLStateManager.isEffectiveAlphaTestEnabled(), alphaState.getFunction(), alphaState.getReference(), GLStateManager.getDepthState().getFunc(),GLStateManager.isEffectiveDepthMaskEnabled());
}
static int groupId(boolean piped, boolean entityPhase, int entityId, int blockEntityId) {
if (!piped) return 0;
return entityPhase ? entityId : blockEntityId;
}
private boolean unitTexIdentity() {
final int generation = GLStateManager.getTexMatrixGeneration();
if (!texCaptured || generation != texGeneration) {
final Matrix4f unitMatrix = GLStateManager.getTextures().getTextureUnitMatrix(0);
texIdentity = MatrixHelper.isIdentity(unitMatrix);
if (!texIdentity) texMatrixScratch.set(unitMatrix);
texGeneration = generation;
texCaptured = true;
}
return texIdentity;
}
private static boolean isDepthEqualDecalState() {
return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.getDepthState().isEnabled();
return GLStateManager.getDepthState().getFunc() == GL11.GL_EQUAL && !GLStateManager.isEffectiveDepthMaskEnabled();
}
private PartTemplate templateFor(ModelRenderer part, float scale, ModelPartMeshBuilder builder) {
@@ -357,6 +410,7 @@ public final class ModelPartBatcher {
final PartTemplate entry = reuse != null ? reuse : new PartTemplate();
entry.scale = scale;
entry.template = null;
entry.cubes = null;
entry.emptyVanillaPart = false;
final List<ModelBox> boxes = part.cubeList;
if (builder != null) {
@@ -372,6 +426,7 @@ public final class ModelPartBatcher {
boxes.get(i).render(tess, scale);
}
entry.template = captureBackend.endCaptureToTemplate();
captureCubes(entry, boxes);
} else {
entry.emptyVanillaPart = part.getClass() == ModelRenderer.class;
}
@@ -379,21 +434,35 @@ public final class ModelPartBatcher {
return entry;
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
private static void captureCubes(PartTemplate entry, List<ModelBox> boxes) {
final int n = boxes.size();
CubeParams[] cubes = null;
for (int i = 0; i < n; i++) {
if (!(boxes.get(i) instanceof ModelBoxData data)) return;
final CubeParams params = data.angelica$cubeParams();
if (params == null) return;
if (cubes == null) cubes = new CubeParams[n];
cubes[i] = params;
}
entry.cubes = cubes;
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass)
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits) {
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && glintSlot == lastLayerGlintSlot) {
return lastLayer;
}
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits));
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot));
if (layer == null) {
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits), layer);
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot), layer);
}
lastLayerTexture = texture;
lastLayerMaterial = material;
lastLayerPass = pass;
lastLayerOffsetFactor = offsetFactor;
lastLayerOffsetUnits = offsetUnits;
lastLayerGlintSlot = glintSlot;
lastLayer = layer;
return layer;
}
@@ -409,11 +478,21 @@ public final class ModelPartBatcher {
}
public void clear() {
shadows.reset();
groups.clear();
shadowGroups.clear();
templates.clear();
bufferSource.freeBuffers();
active = false;
shaderPipeline = null;
layers.clear();
scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT);
lastLayerTexture = null;
lastLayerMaterial = null;
lastLayerPass = null;
lastLayer = null;
loggedMaterialBails.clear();
lastBoundLocation = null;
}
public String getDebugString() {
@@ -4,21 +4,24 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.CubeParams;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import it.unimi.dsi.fastutil.floats.FloatArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import net.minecraft.util.ResourceLocation;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector3f;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.function.LongSupplier;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
@@ -29,6 +32,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
static final int DEMOTE_AFTER_STABLE_FRAMES = 4;
static final long IDLE_RESET_FRAMES = 100;
static final long GROUP_TTL_MS = AngelicaTesrMeshCache.LRU_TIMEOUT_MS;
static final int MERGE_SCAN = 4;
private static final Tracy.ZoneId Z_TESR_REBUILD = Tracy.zoneId("tesrRebuild", Tracy.COLOR_CLIENT);
@@ -42,6 +46,8 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private final Matrix4f drawMV = new Matrix4f();
private final Matrix4f savedMV = new Matrix4f();
private boolean mvSaved;
private final Matrix4f savedTexMatrix = new Matrix4f();
private boolean texApplied;
private final float[] matScratch = new float[16];
private double camX, camY, camZ;
private long frameMark;
@@ -52,19 +58,75 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
long streamedInstances;
long instancedDraws;
long instancedInstances;
long cubeInstances;
long texMatrixRuns;
private InstancedTemplateRenderer instanced;
private boolean instancedActive;
private DeferredWorldRenderingPipeline deferred;
private TesrInstancingPipeline deferred;
private final MeshBuffer fallbackMesh = new MeshBuffer();
private ByteBuffer fallbackScratch;
static final class TexRun {
final Matrix4f matrix = new Matrix4f();
boolean identity;
int start, end;
int parts, instances;
TexRun next, last;
}
static final class InstanceColumns {
final ObjectArrayList<TemplateBuffer> templates = new ObjectArrayList<>();
final ObjectArrayList<CubeParams[]> cubes = new ObjectArrayList<>();
final FloatArrayList scales = new FloatArrayList();
final IntArrayList lights = new IntArrayList();
final IntArrayList colors = new IntArrayList();
final IntArrayList overlays = new IntArrayList();
final LongArrayList infos = new LongArrayList();
final ObjectArrayList<TexRun> runs = new ObjectArrayList<>();
float[] matrices = new float[16 * 64];
int size;
void add(TemplateBuffer templateOrNull, Matrix4fc mv, int light, int color, int overlay, long info) {
final int base = size * 16;
if (base + 16 > matrices.length) {
matrices = Arrays.copyOf(matrices, matrices.length << 1);
}
mv.get(matrices, base);
if (templateOrNull != null) templates.add(templateOrNull);
lights.add(light);
colors.add(color);
overlays.add(overlay);
infos.add(info);
size++;
}
void addCubes(TemplateBuffer templateOrNull, CubeParams[] cubeParams, float scale, Matrix4fc mv, int light, int color, int overlay, long info) {
cubes.add(cubeParams);
scales.add(scale);
add(templateOrNull, mv, light, color, overlay, info);
}
void clear() {
templates.clear();
cubes.clear();
scales.clear();
lights.clear();
colors.clear();
overlays.clear();
infos.clear();
runs.clear();
size = 0;
}
}
static final class Group {
final RenderLayer layer;
final TesrMaterial material;
final int blockEntityId;
final boolean opaque;
final boolean stream;
final boolean mergeRuns;
Class<?> renderableClass;
int rebuildsWindow;
long anchorX, anchorY, anchorZ;
@@ -73,15 +135,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
long lastUsedMs;
int entityColor;
final ObjectArrayList<TemplateBuffer> instTemplates = new ObjectArrayList<>();
final FloatArrayList instMatrices = new FloatArrayList();
final IntArrayList instLights = new IntArrayList();
final IntArrayList instColors = new IntArrayList();
final InstanceColumns templateColumns = new InstanceColumns();
final InstanceColumns cubeColumns = new InstanceColumns();
final ObjectArrayList<Matrix4f> instTexMatrices = new ObjectArrayList<>();
private final ObjectArrayList<Matrix4f> texMatrixPool = new ObjectArrayList<>();
private int texMatrixPoolUsed;
private final ObjectArrayList<TexRun> runPool = new ObjectArrayList<>();
private int runPoolUsed;
long hashAcc;
int count;
long builtHash;
int builtCount = -1;
@@ -106,13 +167,49 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
instTexMatrices.add(texMatrixPool.get(texMatrixPoolUsed++).set(src));
}
TexRun openOrExtendRun(InstanceColumns cols, Matrix4f texMatrix) {
final ObjectArrayList<TexRun> list = cols.runs;
final int part = cols.size;
final boolean identity = texMatrix == null;
final int size = list.size();
final int floor = Math.max(0, mergeRuns ? size - MERGE_SCAN : size - 1);
for (int i = size - 1; i >= floor; i--) {
final TexRun head = list.get(i);
if (head.identity != identity || (!identity && !head.matrix.equals(texMatrix))) continue;
if (head.last.end != part) {
final TexRun segment = pooledRun(part);
head.last.next = segment;
head.last = segment;
}
return head;
}
final TexRun head = pooledRun(part);
head.identity = identity;
if (!identity) head.matrix.set(texMatrix);
list.add(head);
return head;
}
private TexRun pooledRun(int part) {
if (runPoolUsed == runPool.size()) {
runPool.add(new TexRun());
}
final TexRun run = runPool.get(runPoolUsed++);
run.start = part;
run.end = part;
run.parts = 0;
run.instances = 0;
run.next = null;
run.last = run;
return run;
}
void clearInstances() {
instTemplates.clear();
instMatrices.clear();
instLights.clear();
instColors.clear();
templateColumns.clear();
cubeColumns.clear();
instTexMatrices.clear();
texMatrixPoolUsed = 0;
runPoolUsed = 0;
}
Group(RenderLayer layer, TesrMaterial material, int blockEntityId) {
@@ -121,12 +218,14 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
this.blockEntityId = blockEntityId;
this.opaque = material.transparency() == TesrMaterial.Transparency.OPAQUE;
this.stream = material.isStream();
this.mergeRuns = material.isDepthEqual() && material.isNoDepthWrite();
this.streaming = stream;
}
}
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>>> groups = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>();
private Group lastGroup;
RetainedTesrGroups(AngelicaBufferSource source) {
this(source, System::currentTimeMillis);
@@ -145,7 +244,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
beginPass(base, camX, camY, camZ, instancedRenderer, null);
}
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, DeferredWorldRenderingPipeline deferred) {
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
baseMV.set(base);
baseMVInv.set(base).invert();
this.camX = camX;
@@ -158,23 +257,28 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
nowMs = clock.getAsLong();
}
private Group groupFor(RenderLayer layer, TesrMaterial material, int blockEntityId) {
Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>> byMaterial = groups.get(layer);
if (byMaterial == null) {
byMaterial = new Reference2ObjectOpenHashMap<>();
groups.put(layer, byMaterial);
}
Int2ObjectOpenHashMap<Group> byId = byMaterial.get(material);
if (byId == null) {
byId = new Int2ObjectOpenHashMap<>();
byMaterial.put(material, byId);
}
Group group = byId.get(blockEntityId);
if (group == null) {
group = new Group(layer, material, blockEntityId);
group.lastUsedMs = nowMs;
byId.put(blockEntityId, group);
byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group);
private Group groupFor(RenderLayer layer, TesrMaterial material, int id) {
final int key = instanceableMaterial(material) ? 0 : id;
Group group = lastGroup;
if (group == null || group.layer != layer || group.material != material || group.blockEntityId != key) {
Reference2ObjectOpenHashMap<TesrMaterial, Int2ObjectOpenHashMap<Group>> byMaterial = groups.get(layer);
if (byMaterial == null) {
byMaterial = new Reference2ObjectOpenHashMap<>();
groups.put(layer, byMaterial);
}
Int2ObjectOpenHashMap<Group> byId = byMaterial.get(material);
if (byId == null) {
byId = new Int2ObjectOpenHashMap<>();
byMaterial.put(material, byId);
}
group = byId.get(key);
if (group == null) {
group = new Group(layer, material, key);
group.lastUsedMs = nowMs;
byId.put(key, group);
byLayer.computeIfAbsent(layer, l -> new ObjectArrayList<>()).add(group);
}
lastGroup = group;
}
if (group.renderableClass == null) {
group.renderableClass = TesrAttribution.currentRenderable;
@@ -186,8 +290,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
promote(groupFor(layer, material, blockEntityId));
}
void queue(TemplateBuffer template, RenderLayer layer, TesrMaterial material, Matrix4f currentMV, int packedLight, int colorABGR, int blockEntityId, Matrix4f texMatrix, boolean forceStream) {
final Group group = groupFor(layer, material, blockEntityId);
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);
}
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) {
final Group group = groupFor(layer, material, id);
if (group.frameMark != frameMark) {
if (frameMark - group.frameMark > IDLE_RESET_FRAMES) {
group.streaming = group.stream;
@@ -210,8 +318,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
group.frameMark = frameMark;
group.lastUsedMs = nowMs;
group.entityColor = SegmentedBufferBuilder.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
group.count = 0;
group.entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
group.hashAcc = 0;
group.clearInstances();
if (!group.anchored || TesrAnchorMath.shouldReanchor(camX, camY, camZ, group.anchorX, group.anchorY, group.anchorZ)) {
@@ -224,18 +331,25 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
source.declareUse(layer);
}
if (group.stream) {
final boolean instanceable = !forceStream && instancedActive && (deferred == null || material.shader() == null);
if (instanceable && (texMatrix == null || template.drawMode != layer.getDrawMode())) {
group.count++;
group.instTemplates.add(template);
currentMV.get(matScratch);
group.instMatrices.addElements(group.instMatrices.size(), matScratch);
group.instLights.add(packedLight);
group.instColors.add(colorABGR);
final boolean instanceable = instanceable(group);
if (instanceable && cubes != null) {
final TexRun run = group.openOrExtendRun(group.cubeColumns, texMatrix);
group.cubeColumns.addCubes(deferred != null ? template : null, cubes, scale, currentMV, packedLight, colorABGR, overlayABGR, entityInfo);
run.last.end = group.cubeColumns.size;
run.parts++;
run.instances += cubes.length;
return;
}
if (instanceable) {
final TexRun run = group.openOrExtendRun(group.templateColumns, texMatrix);
group.templateColumns.add(template, currentMV, packedLight, colorABGR, overlayABGR, entityInfo);
run.last.end = group.templateColumns.size;
run.parts++;
run.instances++;
return;
}
if (template.drawMode == layer.getDrawMode()) {
source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
source.getBuffer(layer, id).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
streamedInstances++;
return;
}
@@ -248,17 +362,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
if (group.streaming && template.drawMode == layer.getDrawMode()) {
group.frameHash += hash;
source.getBuffer(layer, blockEntityId).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
source.getBuffer(layer, id).addTemplateInstance(template, currentMV, scratchVec, colorABGR, packedLight, texMatrix);
streamedInstances++;
return;
}
group.hashAcc += hash;
group.count++;
group.instTemplates.add(template);
scratchMat.get(matScratch);
group.instMatrices.addElements(group.instMatrices.size(), matScratch);
group.instLights.add(packedLight);
group.instColors.add(colorABGR);
group.templateColumns.add(template, scratchMat, packedLight, colorABGR, overlayABGR, entityInfo);
group.addTexMatrix(texMatrix);
}
@@ -267,8 +376,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final ObjectArrayList<Group> list = byLayer.get(layer);
if (list == null) return false;
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (group.frameMark == frameMark && group.count > 0) return true;
if (live(list.get(i))) return true;
}
return false;
}
@@ -277,101 +385,222 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
public void drawLayer(RenderLayer layer) {
final ObjectArrayList<Group> list = byLayer.get(layer);
if (list == null) return;
boolean variantResolved = false;
boolean variantAvailable = false;
boolean variantBound = false;
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (group.frameMark != frameMark || group.count == 0) continue;
if (group.stream && instancedActive && (deferred == null || group.material.shader() == null)) {
restoreMV();
if (deferred == null) {
instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs);
instancedInstances += group.count;
continue;
}
if (!variantResolved) {
variantResolved = true;
variantAvailable = deferred.hasTesrInstancedVariant();
}
if (variantAvailable) {
applyGroupRenderState(group);
if (!variantBound) {
variantBound = true;
deferred.rebindCurrentPass();
deferred.bindTesrInstancedVariant();
}
instancedDraws += instanced.drawGroup(group.instTemplates, group.instMatrices, group.instLights, group.instColors, group.count, nowMs);
instancedInstances += group.count;
} else {
drawGroupCpuFallback(group);
}
continue;
}
variantBound = false;
if (group.builtCount != group.count || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) {
if (group.mesh.isUploaded()) {
group.consecutiveRebuilds++;
}
rebuild(group);
} else {
group.consecutiveRebuilds = 0;
}
draw(group);
if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) {
promote(group);
}
boolean matrixAvailable = true;
boolean cubeAvailable = true;
if (deferred != null && anyInstanceable(list)) {
deferred.rebindCurrentPass();
matrixAvailable = deferred.hasInstancedVariant(Instancing.TEMPLATE);
cubeAvailable = deferred.hasInstancedVariant(Instancing.CUBE);
}
final int need = drawUninstanced(list, matrixAvailable, cubeAvailable);
restoreMV();
if (variantBound) {
if ((need & NEED_MATRIX) != 0) {
if (deferred != null) deferred.bindInstancedVariant(Instancing.TEMPLATE);
drawMatrixVariant(list, cubeAvailable);
}
if ((need & NEED_CUBE) != 0) {
if (deferred != null) deferred.bindInstancedVariant(Instancing.CUBE);
drawCubeVariant(list);
}
if (need != 0 && deferred != null) {
deferred.rebindCurrentPass();
}
}
private void applyGroupRenderState(Group group) {
AngelicaBufferSource.setEntityColor(group.entityColor);
source.applyIdNoRebind(group.blockEntityId);
private static final int NEED_MATRIX = 1;
private static final int NEED_CUBE = 2;
private boolean live(Group g) {
return g.frameMark == frameMark && (g.templateColumns.size > 0 || g.cubeColumns.size > 0);
}
private boolean anyInstanceable(ObjectArrayList<Group> list) {
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (live(group) && instanceable(group)) return true;
}
return false;
}
private int drawUninstanced(ObjectArrayList<Group> list, boolean matrixAvailable, boolean cubeAvailable) {
int need = 0;
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (!live(group)) continue;
if (!instanceable(group)) {
drawRetained(group);
continue;
}
if (group.templateColumns.size > 0) {
if (matrixAvailable) {
need |= NEED_MATRIX;
} else {
drawInstancesCpu(group, group.templateColumns);
}
}
if (group.cubeColumns.size > 0) {
if (cubeAvailable) {
need |= NEED_CUBE;
} else if (matrixAvailable) {
need |= NEED_MATRIX;
} else {
drawInstancesCpu(group, group.cubeColumns);
}
}
}
return need;
}
private void drawMatrixVariant(ObjectArrayList<Group> list, boolean cubeAvailable) {
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (!live(group) || !instanceable(group)) continue;
if (group.templateColumns.size > 0) {
drawTemplateRuns(group.templateColumns);
}
if (!cubeAvailable && group.cubeColumns.size > 0) {
drawTemplateRuns(group.cubeColumns);
}
}
restoreTexMatrix();
}
private void drawCubeVariant(ObjectArrayList<Group> list) {
for (int i = 0, n = list.size(); i < n; i++) {
final Group group = list.get(i);
if (!live(group) || !instanceable(group) || group.cubeColumns.size == 0) continue;
drawCubeInstances(group);
}
restoreTexMatrix();
}
private boolean instanceable(Group group) {
return instanceableMaterial(group.material);
}
private boolean instanceableMaterial(TesrMaterial material) {
return material.isStream() && instancedActive && (deferred == null || material.shader() == null);
}
private void drawRetained(Group group) {
if (group.builtCount != group.templateColumns.size || group.builtHash != group.hashAcc || !group.mesh.isUploaded()) {
if (group.mesh.isUploaded()) {
group.consecutiveRebuilds++;
}
rebuild(group);
} else {
group.consecutiveRebuilds = 0;
}
draw(group);
if (group.consecutiveRebuilds >= PROMOTE_AFTER_REBUILDS && !group.streaming && group.opaque) {
promote(group);
}
}
private void drawTemplateRuns(InstanceColumns cols) {
for (int r = 0, n = cols.runs.size(); r < n; r++) {
final TexRun run = cols.runs.get(r);
applyTexMatrix(run);
instancedDraws += instanced.drawTemplates(cols, run, nowMs);
instancedInstances += run.parts;
}
}
private void drawCubeInstances(Group group) {
final InstanceColumns cols = group.cubeColumns;
for (int r = 0, n = cols.runs.size(); r < n; r++) {
final TexRun run = cols.runs.get(r);
applyTexMatrix(run);
instanced.drawCubes(cols, run);
instancedDraws++;
cubeInstances += run.instances;
}
}
private void applyTexMatrix(TexRun run) {
if (run.identity && !texApplied) return;
if (!texApplied) {
texApplied = true;
savedTexMatrix.set(GLStateManager.getTextures().getTextureUnitMatrix(0));
}
GLStateManager.setTextureMatrix(0, run.identity ? IDENTITY : run.matrix);
if (!run.identity) texMatrixRuns++;
}
private void restoreTexMatrix() {
if (!texApplied) return;
texApplied = false;
GLStateManager.setTextureMatrix(0, savedTexMatrix);
}
private static final Matrix4f IDENTITY = new Matrix4f();
private void drawGroupCpuFallback(Group group) {
AngelicaBufferSource.setEntityColor(group.entityColor);
source.applyIdAndRebind(group.blockEntityId);
static int entityFromInfo(long info) {
return (short) info;
}
static int blockEntityFromInfo(long info) {
return (short) (info >>> 16);
}
private int idFromInfo(long info) {
return source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY ? entityFromInfo(info) : blockEntityFromInfo(info);
}
private void drawInstancesCpu(Group group, InstanceColumns cols) {
saveMV();
GLStateManager.setModelViewMatrix(IDENTITY);
final VertexFormat format = group.layer.getVertexFormat();
int start = 0;
while (start < group.count) {
final int drawMode = group.instTemplates.get(start).drawMode;
int end = start;
int totalVerts = 0;
while (end < group.count && group.instTemplates.get(end).drawMode == drawMode) {
totalVerts += group.instTemplates.get(end).vertexCount;
end++;
final ObjectArrayList<TemplateBuffer> templates = cols.templates;
for (int r = 0, rn = cols.runs.size(); r < rn; r++) {
final TexRun head = cols.runs.get(r);
final Matrix4f texMatrix = head.identity ? null : head.matrix;
for (TexRun seg = head; seg != null; seg = seg.next) {
final int runEnd = seg.end;
int sub = seg.start;
while (sub < runEnd) {
final long info = cols.infos.getLong(sub);
final int overlay = cols.overlays.getInt(sub);
int subEnd = sub;
while (subEnd < runEnd && cols.infos.getLong(subEnd) == info && cols.overlays.getInt(subEnd) == overlay) {
subEnd++;
}
AngelicaBufferSource.setEntityColor(overlay);
source.applyIdAndRebind(idFromInfo(info));
int start = sub;
while (start < subEnd) {
final int drawMode = templates.get(start).drawMode;
int end = start;
int totalVerts = 0;
while (end < subEnd && templates.get(end).drawMode == drawMode) {
totalVerts += templates.get(end).vertexCount;
end++;
}
fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false);
fallbackScratch.clear();
final long base = memAddress0(fallbackScratch);
long ptr = base;
for (int i = start; i < end; i++) {
System.arraycopy(cols.matrices, i * 16, matScratch, 0, 16);
scratchMat.set(matScratch);
ptr = VertexTransform.writeInstance(ptr, format, templates.get(i), scratchMat, scratchVec, cols.colors.getInt(i), cols.lights.getInt(i), texMatrix);
}
fallbackScratch.position((int) (ptr - base));
fallbackScratch.flip();
fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts);
fallbackMesh.render();
streamedInstances += end - start;
start = end;
}
sub = subEnd;
}
}
fallbackScratch = MeshBuffer.ensureCapacity(fallbackScratch, format.getVertexSize() * totalVerts, false);
fallbackScratch.clear();
final long base = memAddress0(fallbackScratch);
long ptr = base;
for (int i = start; i < end; i++) {
group.instMatrices.getElements(i * 16, matScratch, 0, 16);
scratchMat.set(matScratch);
ptr = VertexTransform.writeInstance(ptr, format, group.instTemplates.get(i), scratchMat, scratchVec, group.instColors.getInt(i), group.instLights.getInt(i), null);
}
fallbackScratch.position((int) (ptr - base));
fallbackScratch.flip();
fallbackMesh.upload(format, drawMode, fallbackScratch, totalVerts);
fallbackMesh.render();
streamedInstances += end - start;
start = end;
}
}
private void promote(Group group) {
group.streaming = true;
streamPromotions++;
group.count = 0;
group.hashAcc = 0;
group.frameHash = 0;
group.prevFrameHash = 0;
@@ -383,6 +612,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
void sweep(long now) {
lastGroup = null;
for (final ObjectArrayList<Group> list : byLayer.values()) {
for (int i = list.size() - 1; i >= 0; i--) {
final Group group = list.get(i);
@@ -408,8 +638,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
}
byLayer.clear();
groups.clear();
lastGroup = null;
fallbackMesh.delete();
fallbackScratch = null;
texApplied = false;
instanced = null;
instancedActive = false;
deferred = null;
}
int groupCount() {
@@ -483,22 +718,20 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private void rebuildInner(Group group) {
final VertexFormat format = group.layer.getVertexFormat();
final InstanceColumns cols = group.templateColumns;
int totalVerts = 0;
for (int i = 0, n = group.instTemplates.size(); i < n; i++) {
totalVerts += group.instTemplates.get(i).vertexCount;
for (int i = 0, n = cols.templates.size(); i < n; i++) {
totalVerts += cols.templates.get(i).vertexCount;
}
final int bytes = format.getVertexSize() * totalVerts;
group.scratch = MeshBuffer.ensureCapacity(group.scratch, bytes, false);
group.scratch.clear();
final long base = memAddress0(group.scratch);
long ptr = base;
for (int i = 0, n = group.count; i < n; i++) {
group.instMatrices.getElements(i * 16, matScratch, 0, 16);
for (int i = 0, n = cols.size; i < n; i++) {
System.arraycopy(cols.matrices, i * 16, matScratch, 0, 16);
scratchMat.set(matScratch);
final int light = group.instLights.getInt(i);
final int color = group.instColors.getInt(i);
final TemplateBuffer template = group.instTemplates.get(i);
ptr = VertexTransform.writeInstance(ptr, format, template, scratchMat, scratchVec, color, light, group.instTexMatrices.get(i));
ptr = VertexTransform.writeInstance(ptr, format, cols.templates.get(i), scratchMat, scratchVec, cols.colors.getInt(i), cols.lights.getInt(i), group.instTexMatrices.get(i));
}
group.scratch.position((int) (ptr - base));
group.scratch.flip();
@@ -506,7 +739,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
group.mesh.upload(format, group.layer.getDrawMode(), group.scratch, group.builtVertexCount, true);
group.meshBytes = bytes;
group.builtHash = group.hashAcc;
group.builtCount = group.count;
group.builtCount = cols.size;
}
private void draw(Group group) {
@@ -0,0 +1,98 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import net.minecraft.util.MathHelper;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.COLOR_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.LIGHT_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.NORMAL_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_X_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.TEX_Y_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.VERTEX_SIZE;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.X_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Y_INDEX;
import static com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil.Z_INDEX;
public final class ShadowQuadMath {
public static final int RECORD_SIZE = 11;
public static final int MIN_X = 0, Y = 1, MIN_Z = 2, MAX_X = 3, MAX_Z = 4, U_MIN_X = 5, V_MIN_Z = 6, U_MAX_X = 7, V_MAX_Z = 8, COLOR = 9, LIGHT = 10;
private ShadowQuadMath() {}
public static int box(double ex, double ey, double ez, float size, int[] outIJK) {
final int i = MathHelper.floor_double(ex - size);
final int j = MathHelper.floor_double(ex + size);
final int k = MathHelper.floor_double(ey - size);
final int l = MathHelper.floor_double(ey);
final int i1 = MathHelper.floor_double(ez - size);
final int j1 = MathHelper.floor_double(ez + size);
outIJK[0] = i;
outIJK[1] = j;
outIJK[2] = k;
outIJK[3] = l;
outIJK[4] = i1;
outIJK[5] = j1;
return (j - i + 1) * (l - k + 1) * (j1 - i1 + 1);
}
public static boolean project(int[] out, int off, double x, double y, double z, int bx, int by, int bz, float shadowAlpha, float size, double ox, double oy, double oz, double minX, double maxX, double minY, double minZ, double maxZ, float brightness, int packedLight) {
double alpha = ((double) shadowAlpha - (y - ((double) by + oy)) / 2.0D) * 0.5D * (double) brightness;
if (alpha < 0.0D) return false;
if (alpha > 1.0D) alpha = 1.0D;
final double qMinX = (double) bx + minX + ox;
final double qMaxX = (double) bx + maxX + ox;
final double qY = (double) by + minY + oy + 0.015625D;
final double qMinZ = (double) bz + minZ + oz;
final double qMaxZ = (double) bz + maxZ + oz;
final float uMinX = (float) ((x - qMinX) / 2.0D / (double) size + 0.5D);
final float uMaxX = (float) ((x - qMaxX) / 2.0D / (double) size + 0.5D);
final float vMinZ = (float) ((z - qMinZ) / 2.0D / (double) size + 0.5D);
final float vMaxZ = (float) ((z - qMaxZ) / 2.0D / (double) size + 0.5D);
out[off + MIN_X] = Float.floatToRawIntBits((float) qMinX);
out[off + Y] = Float.floatToRawIntBits((float) qY);
out[off + MIN_Z] = Float.floatToRawIntBits((float) qMinZ);
out[off + MAX_X] = Float.floatToRawIntBits((float) qMaxX);
out[off + MAX_Z] = Float.floatToRawIntBits((float) qMaxZ);
out[off + U_MIN_X] = Float.floatToRawIntBits(uMinX);
out[off + V_MIN_Z] = Float.floatToRawIntBits(vMinZ);
out[off + U_MAX_X] = Float.floatToRawIntBits(uMaxX);
out[off + V_MAX_Z] = Float.floatToRawIntBits(vMaxZ);
out[off + COLOR] = 0xFFFFFF | ((int) ((float) alpha * 255.0F)) << 24;
out[off + LIGHT] = packedLight;
return true;
}
public static void expand(int[] packed32, int[] records, int off, int normalPacked) {
final int minX = records[off + MIN_X];
final int y = records[off + Y];
final int minZ = records[off + MIN_Z];
final int maxX = records[off + MAX_X];
final int maxZ = records[off + MAX_Z];
final int uMinX = records[off + U_MIN_X];
final int vMinZ = records[off + V_MIN_Z];
final int uMaxX = records[off + U_MAX_X];
final int vMaxZ = records[off + V_MAX_Z];
final int color = records[off + COLOR];
final int light = records[off + LIGHT];
write(packed32, 0, minX, y, minZ, uMinX, vMinZ, color, light, normalPacked);
write(packed32, 1, minX, y, maxZ, uMinX, vMaxZ, color, light, normalPacked);
write(packed32, 2, maxX, y, maxZ, uMaxX, vMaxZ, color, light, normalPacked);
write(packed32, 3, maxX, y, minZ, uMaxX, vMinZ, color, light, normalPacked);
}
private static void write(int[] packed32, int vertex, int x, int y, int z, int u, int v, int color, int light, int normal) {
final int base = vertex * VERTEX_SIZE;
packed32[base | X_INDEX] = x;
packed32[base | Y_INDEX] = y;
packed32[base | Z_INDEX] = z;
packed32[base | TEX_X_INDEX] = u;
packed32[base | TEX_Y_INDEX] = v;
packed32[base | COLOR_INDEX] = color;
packed32[base | LIGHT_INDEX] = light;
packed32[base | NORMAL_INDEX] = normal;
}
}
@@ -6,6 +6,8 @@ public final class TemplateBuffer {
final int[] work;
public final int vertexCount;
public final int drawMode;
long bucketEpoch;
int bucketIndex;
public TemplateBuffer(int[] data, int vertexCount, int drawMode) {
this.data = data;
@@ -0,0 +1,25 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import java.nio.ByteBuffer;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0;
import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree;
public final class TemplateCapture {
private TemplateCapture() {}
public static TemplateBuffer toTemplate(DirectTessellator direct) {
final int vertexCount = direct.getVertexCount();
if (vertexCount == 0) return null;
final int drawMode = direct.getDrawMode();
final VertexFormat format = direct.getVertexFormat();
final ByteBuffer copy = direct.allocateBufferCopy();
final int[] data = VertexTransform.decode(memAddress0(copy), format, vertexCount, drawMode);
memFree(copy);
return new TemplateBuffer(data, vertexCount, drawMode);
}
}
@@ -1,13 +1,14 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.api.util.ColorABGR;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.api.tesr.TesrShader;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
@@ -60,7 +61,8 @@ public final class TesrBatchRenderer {
private final AngelicaBufferSource bufferSource = new AngelicaBufferSource();
private final RetainedTesrGroups[] retained = new RetainedTesrGroups[PASS_COUNT];
final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer();
final InstanceRing instanceRing = new InstanceRing();
final InstancedTemplateRenderer instancedRenderer = new InstancedTemplateRenderer(instanceRing);
private int activePass = -1;
private long lastSweepMs;
private boolean deferredFlushPending;
@@ -94,12 +96,16 @@ public final class TesrBatchRenderer {
}
}
public InstanceRing instanceRing() {
return instanceRing;
}
static boolean instancedCapable() {
if (!ShaderManager.getInstance().isEnabled()) return false;
if (!Iris.enabled) return true;
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline == null || pipeline instanceof FixedFunctionWorldRenderingPipeline) return true;
return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsTesrInstancing();
return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsInstancing(Instancing.TEMPLATE);
}
static DeferredWorldRenderingPipeline deferredPipeline() {
@@ -121,9 +127,18 @@ public final class TesrBatchRenderer {
retained[i].clear();
}
instancedRenderer.clear();
instanceRing.delete();
immediateMesh.delete();
immediateScratch = null;
bufferSource.freeBuffers();
layers.clear();
lastLayerTexture = null;
lastLayerMaterial = null;
lastLayerPass = null;
lastLayer = null;
lastImmediateTexture = null;
lastImmediateMaterial = null;
lastImmediateLayer = null;
AngelicaTesrMeshCache.INSTANCE.clear();
}
@@ -146,9 +161,10 @@ public final class TesrBatchRenderer {
final RenderLayer layer = layerFor(texture, material, pass,
offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f);
final int blockEntityId = pass.isEntityPhase()
? Math.max(0, CapturedRenderingState.INSTANCE.getCurrentRenderedEntity())
? CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()
: CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, blockEntityId, captureTextureMatrix(), false);
final long entityInfo = InstancedAttribs.packEntityInfo(CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedItem());
retained[activePass].queue(template, layer, material, modelView, packedLight, colorABGR, 0, entityInfo, blockEntityId, captureTextureMatrix());
} else {
drawImmediate(template, texture, material, packedLight, colorABGR);
}
@@ -287,10 +303,10 @@ public final class TesrBatchRenderer {
private static int resolveColor(TesrMaterial material) {
if (material.hasColor()) {
return ColorABGR.pack(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha());
return AngelicaBufferSource.packAbgr(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha());
}
final Color4 color = GLStateManager.getColor();
return ColorABGR.pack(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
return AngelicaBufferSource.packAbgr(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
public void flush() {
@@ -0,0 +1,12 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
public interface TesrInstancingPipeline {
void rebindCurrentPass();
boolean hasInstancedVariant(Instancing kind);
void bindInstancedVariant(Instancing kind);
}
@@ -3,10 +3,12 @@ package com.gtnewhorizons.angelica.shadercompat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.GlintColorHandler;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import it.unimi.dsi.fastutil.ints.Int2IntLinkedOpenHashMap;
import net.coderbot.iris.pipeline.ShadowRenderer;
import net.irisshaders.iris.api.v0.IrisApi;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
@@ -27,7 +29,8 @@ import static org.joml.Math.clamp;
public final class ShaderGlint {
private static final ResourceLocation GLINT_MASK = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private static final int MAX_CACHE = 64;
public static final int TINT_SLOTS = 64;
public static final int NO_TINT = -1;
private static boolean maskLoaded;
private static boolean maskFailed;
@@ -35,10 +38,11 @@ public final class ShaderGlint {
private static int maskH;
private static int[] maskLum;
private static final Int2IntLinkedOpenHashMap colorToTexture = new Int2IntLinkedOpenHashMap();
private static final Int2IntLinkedOpenHashMap colorToSlot = new Int2IntLinkedOpenHashMap();
static {
colorToTexture.defaultReturnValue(0);
colorToSlot.defaultReturnValue(NO_TINT);
}
private static final int[] slotTextures = new int[TINT_SLOTS];
private static final GlintColorHandler COLOR_HANDLER = ShaderGlint::onColorChanged;
@@ -76,6 +80,7 @@ public final class ShaderGlint {
if (swapped) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, prevTexture);
ModelPartBatcher.onTextureSwap(prevTexture, NO_TINT);
}
swapped = false;
injecting = false;
@@ -84,35 +89,61 @@ public final class ShaderGlint {
private static void onColorChanged(float red, float green, float blue, float alpha) {
if (injecting) return;
final int texture = getTintedTexture(red, green, blue);
if (texture <= 0) return;
final int slot = tintSlot(red, green, blue);
if (slot < 0) return;
final int texture = slotTextures[slot];
injecting = true;
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, alpha);
injecting = false;
swapped = true;
ModelPartBatcher.onTextureSwap(texture, slot);
}
private static int getTintedTexture(float r, float g, float b) {
public static void invalidate() {
for (int i = 0; i < slotTextures.length; i++) {
if (slotTextures[i] != 0) {
GLStateManager.glDeleteTextures(slotTextures[i]);
slotTextures[i] = 0;
}
}
colorToSlot.clear();
maskLum = null;
tintBuffer = null;
maskLoaded = false;
maskFailed = false;
}
public static void bindTintedGlint(int slot) {
if (slot < 0 || ShadowRenderer.ACTIVE || !IrisApi.getInstance().isShaderPackInUse()) return;
final ITextureObject mask = Minecraft.getMinecraft().getTextureManager().getTexture(GLINT_MASK);
if (mask == null || GLStateManager.getBoundTextureForServerState() != mask.getGlTextureId()) return;
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, slotTextures[slot]);
}
private static int tintSlot(float r, float g, float b) {
ensureMaskLoaded();
if (!maskLoaded) return -1;
if (!maskLoaded) return NO_TINT;
final int ri = clamp8(r);
final int gi = clamp8(g);
final int bi = clamp8(b);
final int key = (ri << 16) | (gi << 8) | bi;
final int cached = colorToTexture.getAndMoveToLast(key);
if (cached != 0) return cached;
final int cached = colorToSlot.getAndMoveToLast(key);
if (cached != NO_TINT) return cached;
if (colorToTexture.size() >= MAX_CACHE) {
GLStateManager.glDeleteTextures(colorToTexture.remove(colorToTexture.firstIntKey()));
final int slot;
if (colorToSlot.size() >= TINT_SLOTS) {
slot = colorToSlot.remove(colorToSlot.firstIntKey());
GLStateManager.glDeleteTextures(slotTextures[slot]);
} else {
slot = colorToSlot.size();
}
final int texture = uploadTinted(ri / 255.0F, gi / 255.0F, bi / 255.0F);
colorToTexture.putAndMoveToLast(key, texture);
return texture;
slotTextures[slot] = uploadTinted(ri / 255.0F, gi / 255.0F, bi / 255.0F);
colorToSlot.putAndMoveToLast(key, slot);
return slot;
}
private static int uploadTinted(float r, float g, float b) {
@@ -4,12 +4,14 @@ import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.batchedentityrendering.impl.ordering.SimpleRenderOrderManager;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.pipeline.WorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.joml.Vector4fc;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
@@ -37,6 +39,7 @@ public class AngelicaBufferSource implements Groupable {
private final SegmentedBufferBuilder[] builders = new SegmentedBufferBuilder[NUM_BUFFERS];
private final Object2IntLinkedOpenHashMap<RenderLayer> affinities = new Object2IntLinkedOpenHashMap<>(NUM_BUFFERS);
private final Map<RenderLayer, List<BufferSegment>> typeToSegment = new Object2ObjectOpenHashMap<>();
private final ObjectArrayList<List<BufferSegment>> segmentLists = new ObjectArrayList<>();
private boolean prepared;
private final List<RenderLayer> order = new ArrayList<>();
@@ -86,7 +89,13 @@ public class AngelicaBufferSource implements Groupable {
final List<BufferSegment> builderSegments = builder.getSegments();
for (int i = 0, n = builderSegments.size(); i < n; i++) {
final BufferSegment segment = builderSegments.get(i);
typeToSegment.computeIfAbsent(segment.getRenderType(), t -> new ArrayList<>()).add(segment);
List<BufferSegment> segments = typeToSegment.get(segment.getRenderType());
if (segments == null) {
segments = new ArrayList<>();
typeToSegment.put(segment.getRenderType(), segments);
segmentLists.add(segments);
}
segments.add(segment);
}
}
order.clear();
@@ -168,7 +177,7 @@ public class AngelicaBufferSource implements Groupable {
anyIdSet = false;
}
private GroupIdKind effectiveIdKind() {
public GroupIdKind effectiveIdKind() {
return GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.ENTITIES ? GroupIdKind.ENTITY : idKind;
}
@@ -223,8 +232,8 @@ public class AngelicaBufferSource implements Groupable {
}
private void clearSegmentLists() {
for (List<BufferSegment> segments : typeToSegment.values()) {
segments.clear();
for (int i = 0, n = segmentLists.size(); i < n; i++) {
segmentLists.get(i).clear();
}
}
@@ -245,6 +254,7 @@ public class AngelicaBufferSource implements Groupable {
builder.freeAll();
}
typeToSegment.clear();
segmentLists.clear();
order.clear();
affinities.clear();
renderOrderManager.reset();
@@ -283,19 +293,20 @@ public class AngelicaBufferSource implements Groupable {
}
}
public void applyIdNoRebind(int id) {
anyIdSet = true;
if (effectiveIdKind() == GroupIdKind.ENTITY) {
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(id, 0);
} else {
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(id);
}
public static int packEntityColor(Vector4fc c) {
return packAbgr(c.x(), c.y(), c.z(), c.w());
}
public static void setEntityColor(int packed) {
CapturedRenderingState.INSTANCE.setCurrentEntityColor(
((packed >>> 16) & 0xFF) / 255f, ((packed >>> 8) & 0xFF) / 255f,
(packed & 0xFF) / 255f, (packed >>> 24) / 255f);
public static int packAbgr(float r, float g, float b, float a) {
return (unit(a) << 24) | (unit(b) << 16) | (unit(g) << 8) | unit(r);
}
private static int unit(float v) {
return (int) (Math.clamp(v, 0f, 1f) * 255f + 0.5f);
}
public static void setEntityColor(int abgr) {
CapturedRenderingState.INSTANCE.setCurrentEntityColor((abgr & 0xFF) / 255f, ((abgr >>> 8) & 0xFF) / 255f, ((abgr >>> 16) & 0xFF) / 255f, (abgr >>> 24) / 255f);
}
public static void setBlockEntityAndRebind(int blockEntityId) {
@@ -1,6 +1,7 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.model.quad.ModelQuadView;
import com.gtnewhorizon.gtnhlib.client.renderer.cel.util.ModelQuadUtil;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.rendering.tesr.TemplateBuffer;
@@ -10,7 +11,6 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.coderbot.iris.uniforms.CapturedRenderingState;
import org.joml.Matrix4fc;
import org.joml.Vector3f;
import org.joml.Vector4fc;
import org.lwjgl.BufferUtils;
import java.nio.ByteBuffer;
@@ -79,7 +79,7 @@ public class SegmentedBufferBuilder {
private long allocatedBytes;
public void begin(RenderLayer type, int blockEntityId) {
final int entityColor = packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
final int entityColor = AngelicaBufferSource.packEntityColor(CapturedRenderingState.INSTANCE.getCurrentEntityColor());
if (type == currentType && blockEntityId == currentBlockEntityId && entityColor == currentEntityColor && current != null) {
return;
}
@@ -98,10 +98,6 @@ public class SegmentedBufferBuilder {
segmentStartVertex = current.vertexCount;
}
public static int packEntityColor(Vector4fc c) {
return ((int) (c.w() * 255f + 0.5f) << 24) | ((int) (c.x() * 255f + 0.5f) << 16) | ((int) (c.y() * 255f + 0.5f) << 8) | (int) (c.z() * 255f + 0.5f);
}
public void addQuad(ModelQuadView quad) {
if (current == null) {
throw new IllegalStateException("addQuad() without begin()");
@@ -125,6 +121,19 @@ public class SegmentedBufferBuilder {
current.vertexCount += template.vertexCount;
}
public void addPackedVertices(int[] packed, int vertexCount, Matrix4fc mv, Vector3f scratch) {
if (current == null) {
throw new IllegalStateException("addPackedVertices() without begin()");
}
final VertexFormat format = currentType.getVertexFormat();
ensureCurrentCapacity(format.getVertexSize() * vertexCount);
final ByteBuffer buffer = current.buffer;
final long ptr = memAddress0(buffer) + buffer.position();
final long end = format.writeToBuffer0(ptr, packed, vertexCount * ModelQuadUtil.VERTEX_SIZE, mv, scratch);
buffer.position(buffer.position() + (int) (end - ptr));
current.vertexCount += vertexCount;
}
private void ensureCurrentCapacity(int bytes) {
final int before = current.buffer.capacity();
current.ensureCapacity(bytes);
+1 -1
View File
@@ -238,7 +238,7 @@ public class Iris {
try {
submitTracked(() -> {
TransformPatcher.patchComposite(vertexShader, null, fragmentShader);
TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, new InputAvailability(true, true));
TransformPatcher.patchAttributes(vertexShader, null, fragmentShader, InputAvailability.of(true, true));
}).get();
} catch (Exception e) {
logger.warn("Warmup failed", e);
@@ -1,64 +1,28 @@
package net.coderbot.iris.gbuffer_overrides.matching;
public class InputAvailability {
public enum InputAvailability {
NONE(false, false), TEXTURE(true, false), LIGHTMAP(false, true), BOTH(true, true);
public static final int NUM_VALUES = 8;
public static final InputAvailability[] VALUES = values();
public final boolean texture;
public final boolean lightmap;
public InputAvailability(boolean texture, boolean lightmap) {
InputAvailability(boolean texture, boolean lightmap) {
this.texture = texture;
this.lightmap = lightmap;
}
public static InputAvailability of(boolean texture, boolean lightmap) {
return VALUES[(texture ? 1 : 0) | (lightmap ? 2 : 0)];
}
public static InputAvailability unpack(int packed) {
return new InputAvailability((packed & 1) == 1, (packed & 2) == 2);
return VALUES[packed & 3];
}
public int pack() {
int packed = 0;
if (lightmap) {
packed |= 2;
}
if (texture) {
packed |= 1;
}
return packed;
}
@Override
public String toString() {
return "InputAvailability{" +
"texture=" + texture +
", lightmap=" + lightmap +
'}';
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (lightmap ? 1231 : 1237);
result = prime * result + (texture ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InputAvailability other = (InputAvailability) obj;
if (lightmap != other.lightmap)
return false;
if (texture != other.texture)
return false;
return true;
return ordinal();
}
}
@@ -13,6 +13,6 @@ public class StateTracker {
public boolean lightmapSampler;
public InputAvailability getInputs() {
return new InputAvailability(albedoSampler, lightmapSampler);
return InputAvailability.of(albedoSampler, lightmapSampler);
}
}
@@ -25,8 +25,10 @@ public class ProgramCreator {
int program = GLStateManager.glCreateProgram();
// TODO: This is *really* hardcoded, we need to refactor this to support external calls to glBindAttribLocation
RenderSystem.bindAttributeLocation(program, MC_ENTITY, "iris_Entity");
RenderSystem.bindAttributeLocation(program, MC_ENTITY, "mc_Entity");
RenderSystem.bindAttributeLocation(program, MC_MID_TEX_COORD, "mc_midTexCoord");
RenderSystem.bindAttributeLocation(program, AT_TANGENT, "iris_CubeTangent");
RenderSystem.bindAttributeLocation(program, AT_TANGENT, "at_tangent");
RenderSystem.bindAttributeLocation(program, AT_MIDBLOCK, "at_midBlock");
@@ -329,12 +329,20 @@ public class GbufferPrograms {
public static void setupSpecialRenderCondition(SpecialCondition override) {
currentSpecial = override;
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override));
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setSpecialCondition(override);
}
}
public static void teardownSpecialRenderCondition() {
currentSpecial = null;
Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null));
final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable();
if (pipeline != null) {
pipeline.setSpecialCondition(null);
}
}
public static void runPhaseChangeNotifier() {
@@ -3,12 +3,17 @@ package net.coderbot.iris.layer;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.Locale;
import java.util.Objects;
public record PassOverride(SpecialCondition special, Boolean translucent, WorldRenderingPhase phase) {
public static final PassOverride NONE = new PassOverride(null, null, null);
private static final ObjectArrayList<PassOverride> INTERNED = new ObjectArrayList<>();
public PassOverride(SpecialCondition special, Boolean translucent) {
this(special, translucent, null);
}
@@ -17,8 +22,18 @@ public record PassOverride(SpecialCondition special, Boolean translucent, WorldR
final SpecialCondition special = GbufferPrograms.getSpecialCondition();
final Boolean translucent = GbufferPrograms.getDeclaredTranslucency();
final WorldRenderingPhase phase = GbufferPrograms.getOverridePhase();
return special == null && translucent == null && phase == null
? NONE : new PassOverride(special, translucent, phase);
if (special == null && translucent == null && phase == null) {
return NONE;
}
for (int i = 0, n = INTERNED.size(); i < n; i++) {
final PassOverride candidate = INTERNED.get(i);
if (candidate.special == special && candidate.phase == phase && Objects.equals(candidate.translucent, translucent)) {
return candidate;
}
}
final PassOverride created = new PassOverride(special, translucent, phase);
INTERNED.add(created);
return created;
}
public void apply() {
@@ -13,8 +13,13 @@ import org.joml.Matrix4fc;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.PendingProgramSelection;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.tesr.BatchEligibility;
import com.gtnewhorizons.angelica.rendering.tesr.TesrInstancingPipeline;
import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import net.coderbot.iris.Iris;
@@ -111,6 +116,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -127,7 +133,7 @@ import java.util.function.Supplier;
/**
* Encapsulates the compiled shader program objects for the currently loaded shaderpack.
*/
public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener {
public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener, TesrInstancingPipeline, PendingProgramSelection {
private final RenderTargets renderTargets;
@Nullable
@@ -178,8 +184,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private final ShaderStorageBufferHolder ssboHolder;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> attributeTransforms;
private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> instancedAttributeTransforms;
private boolean supportsTesrInstancing = true;
private final EnumMap<Instancing, Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>>> instancedAttributeTransforms = new EnumMap<>(Instancing.class);
private final boolean[] supportsInstancing = initialInstancingSupport();
private final ParityFlipState parityState = new ParityFlipState(AngelicaConfig.shaderParityFlip);
private final Supplier<ImmutableSet<Integer>> flippedGbuffers;
private final Supplier<ImmutableSet<Integer>> flippedShadowGbuffers;
@@ -214,7 +220,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean worldGroupActive = false;
private boolean isBeforeTranslucent;
private boolean isRenderingShadow = false;
private InputAvailability inputs = new InputAvailability(false, false);
private InputAvailability inputs = InputAvailability.of(false, false);
private SpecialCondition special = null;
private boolean shouldBindPBR;
@@ -254,8 +260,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
.orElse(null);
resolver = new ProgramFallbackResolver(programs);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver, ProgramId.values(), false);
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> instancedTransformFutures = submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true);
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver, attributeProgramIds(Instancing.NONE), Instancing.NONE, mvBuiltinsMemo);
final EnumMap<Instancing, Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>> instancedTransformFutures = new EnumMap<>(Instancing.class);
for (Instancing kind : Instancing.VALUES) {
if (kind != Instancing.NONE) {
instancedTransformFutures.put(kind, submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo));
}
}
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> terrainSolidOverride = programs.getGbuffersTerrainSolid();
@@ -506,17 +518,21 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
Iris.logger.info("[Load #{}] DWRP phase=attribute-join elapsed_ms={}", Iris.getShaderPackLoadId(), String.format("%.1f", (System.nanoTime() - _tLast) / 1_000_000.0));
_tLast = System.nanoTime();
this.instancedAttributeTransforms = new HashMap<>();
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : instancedTransformFutures.entrySet()) {
try {
final Map<PatchShaderType, String> transformed = entry.getValue().join();
if (transformed == null) continue;
this.instancedAttributeTransforms.put(entry.getKey(), transformed);
} catch (Exception e) {
Iris.logger.warn("Instanced transform failed for {}; disabling TESR instancing", entry.getKey().getLeft(), e);
supportsTesrInstancing = false;
instancedAttributeTransforms.clear();
break;
for (Map.Entry<Instancing, Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>> kindEntry : instancedTransformFutures.entrySet()) {
final Instancing kind = kindEntry.getKey();
final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> joined = new HashMap<>();
this.instancedAttributeTransforms.put(kind, joined);
for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : kindEntry.getValue().entrySet()) {
try {
final Map<PatchShaderType, String> transformed = entry.getValue().join();
if (transformed == null) continue;
joined.put(entry.getKey(), transformed);
} catch (Exception e) {
Iris.logger.warn("{} instanced transform failed for {}; disabling it", kind, entry.getKey().getLeft(), e);
supportsInstancing[kind.ordinal()] = false;
joined.clear();
break;
}
}
}
@@ -594,10 +610,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null),
programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer,
() -> usesSampler(IrisSamplers.USAGE_SHADOWTEX1));
Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram();
Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, new InputAvailability(true, true)).getProgram();
shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0)
|| (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0));
Program shadowProgram = table.match(RenderCondition.SHADOW, InputAvailability.of(true, true)).getProgram();
Program shadowWaterProgram = table.match(RenderCondition.SHADOW_TRANSLUCENT, InputAvailability.of(true, true)).getProgram();
shadowRenderer.setUsesImages((shadowProgram != null && shadowProgram.getActiveImages() > 0) || (shadowWaterProgram != null && shadowWaterProgram.getActiveImages() > 0));
shadowRenderer.setPlayerReflectionCaptureEnabled((shadowProgram != null && GLStateManager.glGetUniformLocation(shadowProgram.getProgramId(), "playerAtlas_img") != -1) || (shadowWaterProgram != null && GLStateManager.glGetUniformLocation(shadowWaterProgram.getProgramId(), "playerAtlas_img") != -1));
} else {
shadowRenderer = null;
@@ -644,7 +659,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
@@ -679,7 +694,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flippedAfterPrepareResolved, renderTargets, false, this);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
// Bind custom images as samplers (for texture() access to voxel_sampler, floodfill_sampler, etc.)
@@ -926,6 +941,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
current = null;
currentCondition = null;
clearPendingSelection();
}
public void restorePassAfterModProgram(int newProgram) {
@@ -966,7 +982,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
matchingBlend = true;
try {
matchPass();
requestMatch();
} finally {
matchingBlend = false;
}
@@ -974,7 +990,30 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private boolean matchingBlend;
private void requestMatch() {
if (GLStateManager.isForeignDraw() || BatchEligibility.batchingAllowed()) {
GLSMHooks.pendingProgramSelection = this;
return;
}
matchPass();
}
@Override
public void resolvePendingProgram() {
if (GLSMHooks.pendingProgramSelection == this && !GLStateManager.isForeignDraw()) {
matchPass();
}
}
private void clearPendingSelection() {
if (GLSMHooks.pendingProgramSelection == this) {
GLSMHooks.pendingProgramSelection = null;
}
}
private void matchPass() {
clearPendingSelection();
if (!shouldOverrideShaders()) {
return;
}
@@ -989,6 +1028,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void onEntityRenderBoundary() {
GLSMHooks.resolvePendingProgram();
if (!shouldOverrideShaders()) {
return;
}
@@ -1026,6 +1067,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void rebindCurrentPass() {
GLSMHooks.resolvePendingProgram();
final Pass pass = this.current;
if (pass == null) {
if (GLStateManager.getActiveProgram() == 0) {
@@ -1147,11 +1189,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
framebufferAfterTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, programDirectives.getDrawBuffers());
}
builder.bindAttributeLocation(11, "mc_Entity");
builder.bindAttributeLocation(12, "mc_midTexCoord");
builder.bindAttributeLocation(13, "at_tangent");
builder.bindAttributeLocation(14, "at_midBlock");
AlphaTestOverride alphaTestOverride = programDirectives.getAlphaTestOverride()
.orElse(id.getDefaultAlphaTestOverride());
@@ -1186,7 +1223,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor);
}
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(hasTexture, hasLightmap));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(hasTexture, hasLightmap));
if (!isShadowPass) {
recordSamplerUsage(IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets));
}
@@ -1301,8 +1338,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
private String instancingSourceName;
private InputAvailability instancingAvailability;
private boolean instancingShadow;
@Nullable private Program instancedVariant;
private boolean instancedVariantAttempted;
private final Program[] instancedVariants = new Program[Instancing.VALUES.length];
private final boolean[] instancedVariantAttempted = new boolean[Instancing.VALUES.length];
private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents,
@Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List<BufferBlendOverride> bufferBlendOverrides, boolean shadowViewport) {
@@ -1382,64 +1419,77 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
@Nullable
Program getInstancedVariant() {
if (!instancedVariantAttempted) {
instancedVariantAttempted = true;
if (instancingSourceName != null && supportsTesrInstancing) {
instancedVariant = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow);
Program instancedVariant(Instancing kind) {
final int i = kind.ordinal();
if (!instancedVariantAttempted[i]) {
instancedVariantAttempted[i] = true;
if (instancingSourceName != null && supportsInstancing[i]) {
instancedVariants[i] = buildInstancedVariant(instancingSourceName, instancingAvailability, instancingShadow, kind);
}
}
return instancedVariant;
return instancedVariants[i];
}
public void destroy() {
if (this.program != null) {
this.program.destroy();
}
if (this.instancedVariant != null) {
this.instancedVariant.destroy();
this.instancedVariant = null;
for (int i = 0; i < instancedVariants.length; i++) {
if (instancedVariants[i] != null) {
instancedVariants[i].destroy();
instancedVariants[i] = null;
}
}
}
}
@Nullable
private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow) {
final Map<PatchShaderType, String> transformed = instancedAttributeTransforms.get(Pair.of(sourceName, availability));
private Program buildInstancedVariant(String sourceName, InputAvailability availability, boolean shadow, Instancing kind) {
final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> transforms = instancedAttributeTransforms.get(kind);
final Map<PatchShaderType, String> transformed = transforms != null ? transforms.get(Pair.of(sourceName, availability)) : null;
if (transformed == null) {
return null;
}
try {
final ProgramBuilder builder = beginBuilder(sourceName + "_instanced", transformed);
final ProgramBuilder builder = beginBuilder(sourceName + kind.variantSuffix, transformed);
wireGbufferProgram(builder, availability, shadow);
final Program variant = builder.build();
this.customUniforms.mapholderToPass(builder, variant);
return variant;
} catch (Exception e) {
Iris.logger.warn("TESR instanced variant link failed for {}; disabling TESR instancing", sourceName, e);
supportsTesrInstancing = false;
Iris.logger.warn("{} instanced variant link failed for {}; disabling it", kind, sourceName, e);
supportsInstancing[kind.ordinal()] = false;
return null;
}
}
public boolean supportsTesrInstancing() {
return supportsTesrInstancing;
static boolean[] initialInstancingSupport() {
final boolean[] out = new boolean[Instancing.VALUES.length];
out[Instancing.TEMPLATE.ordinal()] = true;
out[Instancing.CUBE.ordinal()] = AngelicaConfig.cubeInstancingEnabled();
out[Instancing.PARTICLE.ordinal()] = true;
return out;
}
public boolean hasTesrInstancedVariant() {
final Pass pass = current;
return pass != null && pass.getInstancedVariant() != null;
public boolean supportsInstancing(Instancing kind) {
return supportsInstancing[kind.ordinal()];
}
public void bindTesrInstancedVariant() {
final Pass pass = current;
final Program variant = pass.getInstancedVariant();
@Override
public boolean hasInstancedVariant(Instancing kind) {
return current != null && current.instancedVariant(kind) != null;
}
@Override
public void bindInstancedVariant(Instancing kind) {
final Program variant = current.instancedVariant(kind);
variant.use();
this.customUniforms.push(variant);
}
@Override
public void destroy() {
clearPendingSelection();
DepthColorStorage.unlockDepthColor();
BlendModeOverride.restore();
AlphaTestOverride.restore();
@@ -1683,7 +1733,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage));
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages);
IrisSamplers.addCustomTextures(customTextureSamplerInterceptor, customTextureManager.getIrisCustomTextures());
@@ -1761,7 +1811,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this);
IrisImages.addRenderTargetImages(builder, flipped, renderTargets);
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true));
IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, InputAvailability.of(true, true));
IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture());
@@ -2141,7 +2191,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
public void setOverridePhase(WorldRenderingPhase phase) {
this.overridePhase = phase;
syncPhaseDebugGroup();
matchPass();
requestMatch();
GbufferPrograms.runPhaseChangeNotifier();
}
@@ -2149,7 +2199,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
public void setPhase(WorldRenderingPhase phase) {
this.phase = phase;
syncPhaseDebugGroup();
matchPass();
requestMatch();
GbufferPrograms.runPhaseChangeNotifier();
}
@@ -2179,19 +2229,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
@Override
public void setInputs(InputAvailability availability) {
this.inputs = availability;
matchPass();
requestMatch();
}
@Override
public void setSpecialCondition(SpecialCondition special) {
this.special = special;
matchPass();
requestMatch();
}
@Override
public void setDeclaredTranslucency(@Nullable Boolean translucent) {
this.declaredTranslucent = translucent;
matchPass();
requestMatch();
}
@Nullable
@@ -2229,12 +2279,6 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
}
private static final InputAvailability INPUT_NONE = new InputAvailability(false, false);
private static final InputAvailability INPUT_LIGHTMAP_ONLY = new InputAvailability(false, true);
private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false);
private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true);
private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_LIGHTMAP_ONLY, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP };
private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source, TextureStage stage,
Object2ObjectMap<Tri<String, TextureType, TextureStage>, String> textureMap) {
return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(
@@ -2264,10 +2308,14 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
private static Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>>
submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, boolean instanced) {
submitAttributeTransforms(ProgramFallbackResolver resolver, ProgramId[] ids, Instancing instancing, Map<String, Boolean> mvBuiltinsMemo) {
if (instancing == Instancing.CUBE && !AngelicaConfig.cubeInstancingEnabled()) {
return Collections.emptyMap();
}
final boolean instanced = instancing != Instancing.NONE;
final boolean matrixInstanced = instancing.hasInstanceHead();
final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>();
final Set<String> processedSourceNames = new HashSet<>();
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
for (ProgramId id : ids) {
if (id.getGroup() == ProgramGroup.Dh) continue;
final ProgramSource source = resolver.resolveNullable(id);
@@ -2276,9 +2324,9 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
}
final String vertexSource = source.getVertexSource().orElse(null);
final boolean scrollGlint = GlintScrollInjector.shouldInject(id, source);
for (InputAvailability avail : INPUT_AVAILABILITIES) {
for (InputAvailability avail : InputAvailability.VALUES) {
futures.put(Pair.of(source.getName(), avail), Iris.ShaderTransformExecutor.submitTracked(() -> {
if (instanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> {
if (matrixInstanced && mvBuiltinsMemo.computeIfAbsent(source.getName(), k -> {
final boolean references = referencesMvBuiltinsOutsideVertex(source);
if (references) {
Iris.logger.info("TESR instancing: {} references MV builtins outside the vertex stage, keeping CPU path", k);
@@ -2291,7 +2339,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
final String tessControl = source.getTessControlSource().orElse(null);
final String tessEval = source.getTessEvalSource().orElse(null);
final String fragment = source.getFragmentSource().orElse(null);
return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint)
return instanced ? TransformPatcher.patchAttributesInstanced(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint, instancing)
: TransformPatcher.patchAttributes(vertexSource, geometry, tessControl, tessEval, fragment, avail, scrollGlint);
}));
}
@@ -2301,9 +2349,21 @@ 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.Shadow, ProgramId.ShadowWater, ProgramId.ArmorGlint
};
private static final ProgramId[] PARTICLE_PROGRAM_IDS = {
ProgramId.Particles, ProgramId.ParticlesTrans
};
private static ProgramId[] attributeProgramIds(Instancing kind) {
return switch (kind) {
case NONE -> ProgramId.values();
case TEMPLATE, CUBE -> INSTANCED_PROGRAM_IDS;
case PARTICLE -> PARTICLE_PROGRAM_IDS;
};
}
private static final String[] MV_BUILTINS = {
"gl_ModelViewMatrix", "gl_ModelViewMatrixInverse",
"gl_ModelViewProjectionMatrix", "gl_ModelViewProjectionMatrixInverse",
@@ -2371,8 +2431,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
.ifPresent(source -> submitCompositeTransform(source, TextureStage.COMPOSITE_AND_FINAL, tm));
final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs);
submitAttributeTransforms(resolver, ProgramId.values(), false);
submitAttributeTransforms(resolver, INSTANCED_PROGRAM_IDS, true);
final Map<String, Boolean> mvBuiltinsMemo = new ConcurrentHashMap<>();
for (Instancing kind : Instancing.VALUES) {
submitAttributeTransforms(resolver, attributeProgramIds(kind), kind, mvBuiltinsMemo);
}
final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic());
final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource);
@@ -1,6 +1,10 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLLexer;
@@ -30,27 +34,37 @@ class AttributeTransformer {
}
private static void transformCore(Transformer transformer, AttributeParameters parameters) {
final boolean instancedVertex = parameters.instanced && parameters.type == ShaderType.VERTEX;
final boolean wantsMvInverse = instancedVertex && transformer.containsCall("gl_ModelViewMatrixInverse");
CoreTransformHelper.injectMatrixUniforms(transformer, instancedVertex);
final boolean vertex = parameters.type == ShaderType.VERTEX;
final boolean instancedVertex = vertex && parameters.instancing != Instancing.NONE;
final boolean cubeVertex = vertex && parameters.instancing == Instancing.CUBE;
final boolean particleVertex = vertex && parameters.instancing == Instancing.PARTICLE;
final boolean matrixVertex = vertex && parameters.instancing.hasInstanceHead();
final boolean wantsMvInverse = matrixVertex && transformer.containsCall("gl_ModelViewMatrixInverse");
CoreTransformHelper.injectMatrixUniforms(transformer, vertex ? parameters.instancing : Instancing.NONE);
aliasIfUsed(transformer, "projectionMatrix", "iris_ProjectionMatrix");
aliasIfUsed(transformer, "modelViewMatrix", "iris_ModelViewMatrix");
aliasIfUsed(transformer, "normalMatrix", "iris_NormalMatrix");
if (parameters.type == ShaderType.VERTEX) {
transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;");
transformer.injectVariable("layout(location = 1) in vec4 iris_Color;");
transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;");
if (instancedVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
} else {
transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;");
if (!particleVertex) {
transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;");
transformer.injectVariable("layout(location = 1) in vec4 iris_Color;");
if (cubeVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord0;");
} else {
transformer.injectVariable("layout(location = " + PRIMARY_UV + ") in vec4 iris_MultiTexCoord0;");
}
if (instancedVertex) {
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
} else {
transformer.injectVariable("layout(location = " + SECONDARY_UV + ") in vec4 iris_MultiTexCoord1;");
}
}
transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;");
transformer.rename("gl_Vertex", "iris_Vertex");
transformer.replaceExpression("gl_Color", instancedVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)");
transformer.replaceExpression("gl_Color", matrixVertex ? "(iris_Color * iris_ColorModulator * iris_InstColor)" : "(iris_Color * iris_ColorModulator)");
transformer.rename("gl_Normal", "iris_Normal");
aliasIfUsed(transformer, "vaNormal", "iris_Normal");
if (transformer.containsCall("vaPosition") && !transformer.hasVariable("vaPosition")) {
@@ -88,18 +102,83 @@ class AttributeTransformer {
if (instancedVertex) {
foldConstantAttribute(transformer, "mc_Entity", "-1.0", "vec2(-1.0, -1.0)", "vec3(-1.0, -1.0, 0.0)", "vec4(-1.0, -1.0, 0.0, 1.0)");
final StringBuilder init = new StringBuilder(256);
init.append("{ iris_ModelViewMatrix = mat4(iris_InstMat0, iris_InstMat1, iris_InstMat2, iris_InstMat3);");
init.append(" iris_NormalMatrix = mat3(normalize(iris_InstMat0.xyz), normalize(iris_InstMat1.xyz), normalize(iris_InstMat2.xyz));");
if (wantsMvInverse) {
init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);");
final StringBuilder init = new StringBuilder(256).append("{ ");
if (particleVertex) {
init.append("iris_Vertex = ").append(InstancedGlslHelpers.particlePos("iris_InstCenterHalf", "iris_ParticleOffset")).append(';');
init.append(" iris_Color = iris_InstColor;");
init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.particleUv("iris_InstUv", "iris_ParticleCorner")).append(';');
init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0);");
assignMidTexCoord(transformer, init, "vec4((iris_InstUv.x + iris_InstUv.z) * 0.5, (iris_InstUv.y + iris_InstUv.w) * 0.5, 0.0, 1.0)");
} else {
init.append("iris_ModelViewMatrix = ").append(InstancedGlslHelpers.mat4FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';');
init.append(" iris_NormalMatrix = ").append(InstancedGlslHelpers.mat3FromRows("iris_InstRow0", "iris_InstRow1", "iris_InstRow2")).append(';');
if (wantsMvInverse) {
init.append(" iris_ModelViewMatrixInverse = inverse(iris_ModelViewMatrix);");
}
init.append(" iris_MultiTexCoord1 = vec4(").append(cubeVertex ? "iris_InstLightmapScale.xy" : "iris_InstLightmap").append(", 0.0, 1.0);");
if (cubeVertex) {
appendCubeTexCoords(transformer, init);
}
}
init.append(" iris_MultiTexCoord1 = vec4(iris_InstLightmap, 0.0, 1.0); }");
init.append(" }");
transformer.prependMain(init.toString());
}
}
}
private static final int PRIMARY_UV = VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation();
private static final int SECONDARY_UV = VertexFormatElement.Usage.SECONDARY_UV.getAttributeLocation();
private static void appendCubeTexCoords(Transformer transformer, StringBuilder init) {
init.append(' ').append(InstancedGlslHelpers.cubePrelude("iris_", "iris_CubeMid", "iris_CubeDelta", "iris_Normal", "iris_CubeTex", " "));
init.append(" iris_MultiTexCoord0 = ").append(InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeU.x", "iris_cubeU.y", "iris_cubeV.x", "iris_cubeV.y")).append(';');
final int tangentType = transformer.findType("at_tangent");
if (tangentType != 0) {
final String name = vecName(tangentType);
if (name == null || tangentType == GLSLLexer.VEC2) {
throw new IllegalStateException("Unsupported at_tangent type token " + tangentType + " for the cube instanced variant");
}
transformer.removeVariable("at_tangent");
transformer.injectVariable("layout(location = " + ProgramCreator.AT_TANGENT + ") in vec4 iris_CubeTangent;");
transformer.injectVariable(name + " at_tangent;");
init.append(" at_tangent = (iris_CubeTangent * (1.0 - 2.0 * iris_cubeMirror))").append(swizzle(tangentType)).append(';');
}
assignMidTexCoord(transformer, init, InstancedGlslHelpers.cubeUv("iris_CubeTex", "iris_InstLightmapScale", "iris_cubeMidU.x", "iris_cubeMidU.y", "iris_CubeMid.z", "iris_CubeMid.w"));
}
private static void assignMidTexCoord(Transformer transformer, StringBuilder init, String midExpression) {
final int midType = transformer.findType("mc_midTexCoord");
if (midType == 0) {
return;
}
final String name = vecName(midType);
if (name == null) {
throw new IllegalStateException("Unsupported mc_midTexCoord type token " + midType + " for the instanced variant");
}
transformer.removeVariable("mc_midTexCoord");
transformer.injectVariable(name + " mc_midTexCoord;");
init.append(" mc_midTexCoord = (").append(midExpression).append(')').append(swizzle(midType)).append(';');
}
private static String vecName(int type) {
return switch (type) {
case GLSLLexer.VEC2 -> "vec2";
case GLSLLexer.VEC3 -> "vec3";
case GLSLLexer.VEC4 -> "vec4";
default -> null;
};
}
private static String swizzle(int type) {
return switch (type) {
case GLSLLexer.VEC2 -> ".xy";
case GLSLLexer.VEC3 -> ".xyz";
default -> "";
};
}
private static void foldConstantAttribute(Transformer transformer, String name, String floatVal, String vec2Val, String vec3Val, String vec4Val) {
final int type = transformer.findType(name);
if (type == 0) {
@@ -1,6 +1,8 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormatElement;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedGlslHelpers;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import org.taumc.glsl.Transformer;
import java.util.HashMap;
@@ -16,24 +18,37 @@ class CoreTransformHelper {
* Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix.
*/
static void injectMatrixUniforms(Transformer transformer) {
injectMatrixUniforms(transformer, false);
injectMatrixUniforms(transformer, Instancing.NONE);
}
static void injectMatrixUniforms(Transformer transformer, boolean instancedVertex) {
if (instancedVertex) {
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL0 + ") in vec4 iris_InstMat0;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL1 + ") in vec4 iris_InstMat1;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL2 + ") in vec4 iris_InstMat2;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_MATRIX_COL3 + ") in vec4 iris_InstMat3;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_COLOR + ") in vec4 iris_InstColor;");
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_LIGHTMAP + ") in vec2 iris_InstLightmap;");
transformer.injectVariable("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
} else {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
static void injectMatrixUniforms(Transformer transformer, Instancing instancing) {
switch (instancing) {
case PARTICLE -> {
transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.POSITION.getAttributeLocation() + ") in vec3 iris_ParticleOffset;");
transformer.injectVariable("layout(location = " + VertexFormatElement.Usage.PRIMARY_UV.getAttributeLocation() + ") in vec2 iris_ParticleCorner;");
injectAttributeDecls(transformer, instancing);
transformer.injectVariable("vec4 iris_Vertex;");
transformer.injectVariable("vec4 iris_Color;");
transformer.injectVariable("vec4 iris_MultiTexCoord0;");
transformer.injectVariable("vec4 iris_MultiTexCoord1;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
}
case TEMPLATE, CUBE -> {
injectAttributeDecls(transformer, instancing);
transformer.injectVariable("mat4 iris_ModelViewMatrix;");
transformer.injectVariable("mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("mat3 iris_NormalMatrix;");
if (!declaresInvariantPosition(transformer)) {
transformer.injectVariable("invariant gl_Position;");
}
}
case NONE -> {
transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;");
transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;");
transformer.injectVariable("uniform mat3 iris_NormalMatrix;");
}
}
transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;");
transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;");
@@ -58,6 +73,25 @@ class CoreTransformHelper {
transformer.replaceExpression("gl_TextureMatrix", "mat4[8](iris_TextureMatrix, iris_LightmapTextureMatrix, mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0))");
}
private static void injectAttributeDecls(Transformer transformer, Instancing instancing) {
for (String decl : InstancedGlslHelpers.attributeDecls("iris_", instancing)) {
transformer.injectVariable(decl);
}
}
private static boolean declaresInvariantPosition(Transformer transformer) {
final boolean[] found = new boolean[1];
transformer.mutateTree(root -> {
for (int i = 0; i < root.getChildCount(); i++) {
if ("invariantgl_Position;".equals(root.getChild(i).getText())) {
found[0] = true;
return;
}
}
});
return found[0];
}
/**
* Inject vertex attributes and ftransform() replacement for composite/depth shaders. Uses locations matching FullScreenQuadRenderer's POSITION_TEXTURE VAO layout.
*/
@@ -1,18 +1,120 @@
package net.coderbot.iris.pipeline.transform;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters;
import org.taumc.glsl.Transformer;
import org.taumc.glsl.grammar.GLSLParser;
class EntityPatcher {
public static void patchEntityId(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
if (!hasInstanceAttributes(parameters)) {
injectUniformIfUndeclared(transformer, "entityId", "uniform int entityId;");
injectUniformIfUndeclared(transformer, "blockEntityId", "uniform int blockEntityId;");
injectUniformIfUndeclared(transformer, "currentRenderedItemId", "uniform int currentRenderedItemId;");
return;
}
removeIfDeclared(transformer, "entityId");
removeIfDeclared(transformer, "blockEntityId");
removeIfDeclared(transformer, "currentRenderedItemId");
final String geometryIn = parameters.hasTesselation ? "iris_entityInfoTES" : "iris_entityInfo";
final String info = switch (parameters.type) {
case GEOMETRY -> geometryIn + "[0]";
case TESSELATION_CONTROL -> "iris_entityInfo[gl_InvocationID]";
case TESSELATION_EVAL -> "iris_entityInfoTCS[0]";
default -> "iris_entityInfo";
};
transformer.replaceExpression("entityId", info + ".x", GLSLParser::postfix_expression);
transformer.replaceExpression("blockEntityId", info + ".y", GLSLParser::postfix_expression);
transformer.replaceExpression("currentRenderedItemId", info + ".z", GLSLParser::postfix_expression);
switch (parameters.type) {
case VERTEX -> {
if (!transformer.hasVariable("iris_Entity")) {
transformer.injectVariable("layout(location = " + InstancedAttribs.LOC_ENTITY + ") in ivec4 iris_Entity;");
}
transformer.injectVariable("flat out ivec3 iris_entityInfo;");
transformer.prependMain("iris_entityInfo = iris_Entity.xyz;");
}
case TESSELATION_CONTROL -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoTCS[];");
transformer.injectVariable("flat in ivec3 iris_entityInfo[];");
transformer.prependMain("iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];");
}
case TESSELATION_EVAL -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoTES;");
transformer.injectVariable("flat in ivec3 iris_entityInfoTCS[];");
transformer.prependMain("iris_entityInfoTES = iris_entityInfoTCS[0];");
}
case GEOMETRY -> {
transformer.injectVariable("flat out ivec3 iris_entityInfoGS;");
transformer.injectVariable("flat in ivec3 " + geometryIn + "[];");
transformer.prependMain("iris_entityInfoGS = " + geometryIn + "[0];");
}
case FRAGMENT -> {
if (transformer.containsCall("iris_entityInfo")) {
transformer.injectVariable("flat in ivec3 iris_entityInfo;");
if (parameters.hasGeometry) {
transformer.rename("iris_entityInfo", "iris_entityInfoGS");
} else if (parameters.hasTesselation) {
transformer.rename("iris_entityInfo", "iris_entityInfoTES");
}
}
}
default -> {}
}
}
public static void patchOverlayColor(Transformer transformer, AttributeParameters parameters) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
if (!hasInstanceAttributes(parameters)) {
injectUniformIfUndeclared(transformer, "entityColor", "uniform vec4 entityColor;");
return;
}
removeIfDeclared(transformer, "entityColor");
switch (parameters.type) {
case VERTEX -> {
transformer.injectVariable("out vec4 entityColor;");
transformer.prependMain("{ entityColor = iris_InstOverlay; entityColor.rgb *= float(entityColor.a != 0.0); }");
}
case TESSELATION_CONTROL -> {
transformer.replaceExpression("entityColor", "entityColor[gl_InvocationID]", GLSLParser::postfix_expression);
transformer.injectVariable("patch out vec4 entityColorTCS;");
transformer.injectVariable("in vec4 entityColor[];");
transformer.prependMain("entityColorTCS = entityColor[gl_InvocationID];");
}
case TESSELATION_EVAL -> {
transformer.replaceExpression("entityColor", "entityColorTCS", GLSLParser::postfix_expression);
transformer.injectVariable("out vec4 entityColorTES;");
transformer.injectVariable("patch in vec4 entityColorTCS;");
transformer.prependMain("entityColorTES = entityColorTCS;");
}
case GEOMETRY -> {
final String geometryIn = parameters.hasTesselation ? "entityColorTES" : "entityColor";
transformer.replaceExpression("entityColor", geometryIn + "[0]", GLSLParser::postfix_expression);
transformer.injectVariable("out vec4 entityColorGS;");
transformer.injectVariable("in vec4 " + geometryIn + "[];");
transformer.prependMain("entityColorGS = " + geometryIn + "[0];");
}
case FRAGMENT -> {
if (transformer.containsCall("entityColor")) {
transformer.injectVariable("in vec4 entityColor;");
if (parameters.hasGeometry) {
transformer.rename("entityColor", "entityColorGS");
} else if (parameters.hasTesselation) {
transformer.rename("entityColor", "entityColorTES");
}
}
}
default -> {}
}
}
private static boolean hasInstanceAttributes(AttributeParameters parameters) {
return parameters.instancing.hasInstanceHead();
}
private static void injectUniformIfUndeclared(Transformer transformer, String name, String declaration) {
@@ -20,4 +122,10 @@ class EntityPatcher {
transformer.injectVariable(declaration);
}
}
private static void removeIfDeclared(Transformer transformer, String name) {
if (transformer.hasVariable(name)) {
transformer.removeVariable(name);
}
}
}
@@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import java.util.EnumMap;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
@@ -138,11 +139,11 @@ public class TransformPatcher {
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint));
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, Instancing.NONE));
}
public static Map<PatchShaderType, String> patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs, scrollGlint, true));
public static Map<PatchShaderType, String> patchAttributesInstanced(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs, boolean scrollGlint, Instancing instancing) {
return transform(vertex, geometry, tessControl, tessEval, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, tessControl != null, inputs, scrollGlint, instancing));
}
public static Map<PatchShaderType, String> patchAttributes(String vertex, String geometry, String tessControl, String tessEval, String fragment, InputAvailability inputs) {
@@ -1,26 +1,25 @@
package net.coderbot.iris.pipeline.transform.parameter;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability;
import net.coderbot.iris.pipeline.transform.Patch;
import net.coderbot.iris.shaderpack.texture.TextureStage;
public class AttributeParameters extends Parameters {
public final boolean hasGeometry;
public final boolean hasTesselation;
public final InputAvailability inputs;
public final boolean scrollGlint;
public final boolean instanced;
public final Instancing instancing;
// WARNING: adding new fields requires updating hashCode and equals methods!
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint) {
this(patch, hasGeometry, inputs, scrollGlint, false);
}
public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs, boolean scrollGlint, boolean instanced) {
public AttributeParameters(Patch patch, boolean hasGeometry, boolean hasTesselation, InputAvailability inputs, boolean scrollGlint, Instancing instancing) {
super(patch, null);
this.hasGeometry = hasGeometry;
this.hasTesselation = hasTesselation;
this.inputs = inputs;
this.scrollGlint = scrollGlint;
this.instanced = instanced;
this.instancing = instancing;
}
@Override
@@ -33,8 +32,9 @@ public class AttributeParameters extends Parameters {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (hasGeometry ? 1231 : 1237);
result = prime * result + (hasTesselation ? 1231 : 1237);
result = prime * result + (scrollGlint ? 1231 : 1237);
result = prime * result + (instanced ? 1231 : 1237);
result = prime * result + instancing.ordinal();
result = prime * result + ((inputs == null) ? 0 : inputs.hashCode());
return result;
}
@@ -50,9 +50,11 @@ public class AttributeParameters extends Parameters {
AttributeParameters other = (AttributeParameters) obj;
if (hasGeometry != other.hasGeometry)
return false;
if (hasTesselation != other.hasTesselation)
return false;
if (scrollGlint != other.scrollGlint)
return false;
if (instanced != other.instanced)
if (instancing != other.instancing)
return false;
if (inputs == null) {
if (other.inputs != null)