Render pass and state stack optimizations (#2124)

This commit is contained in:
Jason Mitchell authored and GitHub committed 2026-09-21 20:52:51 -07:00
1 parent 87c83f0645
commit 9dd60f6a75
151 files changed
+9242 -3156

No files matched your search

@@ -8,10 +8,10 @@ import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.config.FontConfig;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.ffp.FFPVertexLighting;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import com.gtnewhorizons.angelica.glsm.streaming.PersistentStreamingBuffer;
import com.gtnewhorizons.angelica.glsm.streaming.StreamingUploader;
import com.gtnewhorizons.angelica.hudcaching.HUDCaching;
@@ -38,7 +38,6 @@ import org.joml.Vector4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
@@ -184,9 +183,6 @@ public class BatchingFontRenderer {
private int blendSrcRGB = GL11.GL_SRC_ALPHA;
private int blendDstRGB = GL11.GL_ONE_MINUS_SRC_ALPHA;
private final BlendState blendStateBefore = new BlendState();
private static final BlendState deferredBlendStateBefore = new BlendState();
private float lightmapU = 0.0f;
private float lightmapV = 0.0f;
private boolean lightmapActive = false;
@@ -623,73 +619,48 @@ public class BatchingFontRenderer {
private static void flushDeferredThroughPipeline() {
final BatchingFontRenderer first = deferredSegments.getFirst().owner;
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(deferredBlendStateBefore);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
final int prevBlockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
boolean textureChanged = false;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(first.blendSrcRGB, first.blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glDepthMask(false);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
final int d = GLStateManager.pushState(StateSet.FONT_PIPELINE);
try {
boolean curDepthTest = depthTestBefore;
for (final TextSegment segment : deferredSegments) {
final BatchingFontRenderer owner = segment.owner;
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(first.blendSrcRGB, first.blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
GLStateManager.glDepthMask(false);
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
if (segment.depthTest != curDepthTest) {
if (segment.depthTest) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
curDepthTest = segment.depthTest;
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
try {
boolean curDepthTest = GLStateManager.getDepthTest().isEnabled();
for (final TextSegment segment : deferredSegments) {
final BatchingFontRenderer owner = segment.owner;
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
if (segment.depthTest != curDepthTest) {
if (segment.depthTest) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
curDepthTest = segment.depthTest;
}
final FontDrawCmd[] cmdsData = owner.batchCommands.elements();
Arrays.sort(cmdsData, segment.cmdStart, segment.cmdEnd, FontDrawCmd.DRAW_ORDER_COMPARATOR);
emitRangeThroughPipeline(owner, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
}
final FontDrawCmd[] cmdsData = owner.batchCommands.elements();
Arrays.sort(cmdsData, segment.cmdStart, segment.cmdEnd, FontDrawCmd.DRAW_ORDER_COMPARATOR);
textureChanged |= emitRangeThroughPipeline(owner, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
}
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
restoreDepth(depthTestBefore, depthMaskBefore);
if (isTextureEnabledBefore) {
GLStateManager.enableTexture();
} else {
GLStateManager.disableTexture();
}
if (isBlendEnabledBefore) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(deferredBlendStateBefore.getSrcRgb(), deferredBlendStateBefore.getDstRgb(),
deferredBlendStateBefore.getSrcAlpha(), deferredBlendStateBefore.getDstAlpha());
if (isAlphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
if (textureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
GLStateManager.popStateTo(d);
discardDeferredText();
}
}
@@ -697,27 +668,15 @@ public class BatchingFontRenderer {
private static void flushDeferredTextInner() {
uploadVertexData(deferredVertexPos);
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(deferredBlendStateBefore);
final int shadeModelBefore = GLStateManager.glGetInteger(GL11.GL_SHADE_MODEL);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
deferredSegments.get(0).owner.setupFontDrawState();
GLStateManager.glDepthMask(false);
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
final int d = GLStateManager.pushState(StateSet.FONT);
try {
deferredSegments.get(0).owner.setupFontDrawState();
GLStateManager.glDepthMask(false);
flushLastTexture = DUMMY_RESOURCE_LOCATION;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
boolean curDepthTest = depthTestBefore;
boolean curDepthTest = GLStateManager.getDepthTest().isEnabled();
for (final TextSegment segment : deferredSegments) {
mvpBuf.clear();
segment.mvp.get(mvpBuf);
@@ -732,9 +691,9 @@ public class BatchingFontRenderer {
}
}
} finally {
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore,
lightmapBindingBefore, isAlphaTestEnabledBefore, deferredBlendStateBefore, shadeModelBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLStateManager.glBindVertexArray(0);
GLStateManager.popStateTo(d);
discardDeferredText();
}
}
@@ -826,8 +785,6 @@ public class BatchingFontRenderer {
uploadVertexData(vertexDataPos);
final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM);
final FontDrawCmd[] cmds = batchCommands.elements();
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
@@ -835,42 +792,36 @@ public class BatchingFontRenderer {
}
Arrays.sort(cmds, batchSealedEnd, cmdCount, FontDrawCmd.DRAW_ORDER_COMPARATOR);
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(blendStateBefore);
final int shadeModelBefore = GLStateManager.glGetInteger(GL11.GL_SHADE_MODEL);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int lightmapBindingBefore = boundLightmapTexture();
final boolean depthTestBefore = GLStateManager.getDepthTest().isEnabled();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
setupFontDrawState();
flushLastTexture = DUMMY_RESOURCE_LOCATION;
flushTextureChanged = false;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture);
drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this);
}
if (batchSealedEnd < cmdCount) {
mvpBuf.clear();
resolveMvp(scratchMvp);
scratchMvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId);
drawCommands(cmds, batchSealedEnd, cmdCount, this);
final int d = GLStateManager.pushState(StateSet.FONT);
try {
setupFontDrawState();
flushLastTexture = DUMMY_RESOURCE_LOCATION;
resetFlushLightmap();
try (MemoryStack stack = stackPush()) {
final FloatBuffer mvpBuf = stack.mallocFloat(16);
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
mvpBuf.clear();
segment.mvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, segment.lightmapActive, segment.lightmapU, segment.lightmapV, segment.lightmapTexture);
drawCommands(cmds, segment.cmdStart, segment.cmdEnd, this);
}
if (batchSealedEnd < cmdCount) {
mvpBuf.clear();
resolveMvp(scratchMvp);
scratchMvp.get(mvpBuf);
GLStateManager.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf);
uploadLightmap(lightmapLocation, lightmapActive, lightmapU, lightmapV, lightmapTextureId);
drawCommands(cmds, batchSealedEnd, cmdCount, this);
}
} finally {
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLStateManager.glBindVertexArray(0);
}
} finally {
GLStateManager.popStateTo(d);
}
restoreFontDrawState(prevProgram, isTextureEnabledBefore, isBlendEnabledBefore, boundTextureBefore,
lightmapBindingBefore, isAlphaTestEnabledBefore, blendStateBefore, shadeModelBefore);
restoreDepth(depthTestBefore, depthMaskBefore);
truncateBatchToWatermark();
}
@@ -924,7 +875,6 @@ public class BatchingFontRenderer {
}
private static ResourceLocation flushLastTexture;
private static boolean flushTextureChanged;
private static float flushLastLightmapU;
private static float flushLastLightmapV;
@@ -969,7 +919,6 @@ public class BatchingFontRenderer {
}
if (cmd.texture != null) {
((FontRendererAccessor) owner.underlying).angelica$bindTexture(cmd.texture);
flushTextureChanged = true;
}
flushLastTexture = cmd.texture;
}
@@ -977,38 +926,6 @@ public class BatchingFontRenderer {
}
}
private static void restoreFontDrawState(int prevProgram, boolean textureEnabledBefore, boolean blendEnabledBefore,
int boundTextureBefore, int lightmapBindingBefore, boolean alphaTestEnabledBefore, BlendState blendBefore,
int shadeModelBefore) {
GLStateManager.glUseProgram(prevProgram);
GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
GLStateManager.glBindVertexArray(0);
if (textureEnabledBefore) {
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
}
if (blendEnabledBefore) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(blendBefore.getSrcRgb(), blendBefore.getDstRgb(),
blendBefore.getSrcAlpha(), blendBefore.getDstAlpha());
if (alphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
GLStateManager.glShadeModel(shadeModelBefore);
if (flushTextureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
if (boundLightmapTexture() != lightmapBindingBefore) {
bindLightmapTexture(lightmapBindingBefore);
}
}
private void flushBatchThroughPipeline() {
final int cmdCount = batchCommands.size();
final int segmentCount = batchSegments.size();
@@ -1017,21 +934,7 @@ public class BatchingFontRenderer {
return;
}
final boolean isTextureEnabledBefore = GLStateManager.glIsEnabled(GL11.GL_TEXTURE_2D);
final boolean isBlendEnabledBefore = GLStateManager.isEffectiveBlendEnabled();
final boolean isAlphaTestEnabledBefore = GLStateManager.isEffectiveAlphaTestEnabled();
GLStateManager.getEffectiveBlendState(blendStateBefore);
final int boundTextureBefore = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int prevBlockEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
boolean textureChanged = false;
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
final FontDrawCmd[] cmdsData = batchCommands.elements();
for (int i = 0; i < segmentCount; i++) {
@@ -1043,60 +946,50 @@ public class BatchingFontRenderer {
// The unsealed tail still belongs to the modelview live at flush time; capture it before the segments move it.
resolveModelView(scratchModelView);
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
final int d = GLStateManager.pushState(StateSet.FONT_PIPELINE);
try {
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
textureChanged |= emitRangeThroughPipeline(this, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
}
if (batchSealedEnd < cmdCount) {
GLStateManager.setModelViewMatrix(scratchModelView);
GLStateManager.enableTexture();
GLStateManager.enableAlphaTest();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO);
final Boolean prevTranslucency = GbufferPrograms.beginTranslucencyDeclaration(Boolean.TRUE);
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.glMatrixMode(GL11.GL_MODELVIEW);
GLStateManager.glPushMatrix();
try {
for (int i = 0; i < segmentCount; i++) {
final TextSegment segment = batchSegments.get(i);
if (segment.cmdStart == segment.cmdEnd) continue;
GLStateManager.setModelViewMatrix(segment.modelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(segment.blockEntityId);
emitRangeThroughPipeline(this, cmdsData, segment.cmdStart, segment.cmdEnd,
segment.packedLight, segment.normalX, segment.normalY, segment.normalZ);
}
if (batchSealedEnd < cmdCount) {
GLStateManager.setModelViewMatrix(scratchModelView);
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
final Vector3f normal = ShaderManager.getCurrentNormal();
emitRangeThroughPipeline(this, cmdsData, batchSealedEnd, cmdCount,
GLSMConfig.packedLastBrightness(), normal.x, normal.y, normal.z);
}
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
final Vector3f normal = ShaderManager.getCurrentNormal();
textureChanged |= emitRangeThroughPipeline(this, cmdsData, batchSealedEnd, cmdCount,
GLSMConfig.packedLastBrightness(), normal.x, normal.y, normal.z);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
}
} finally {
GLStateManager.glPopMatrix();
CapturedRenderingState.INSTANCE.setCurrentBlockEntity(prevBlockEntityId);
GbufferPrograms.endTranslucencyDeclaration(prevTranslucency);
if (isTextureEnabledBefore) {
GLStateManager.enableTexture();
} else {
GLStateManager.disableTexture();
}
if (isBlendEnabledBefore) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
GLStateManager.tryBlendFuncSeparate(blendStateBefore.getSrcRgb(), blendStateBefore.getDstRgb(),
blendStateBefore.getSrcAlpha(), blendStateBefore.getDstAlpha());
if (isAlphaTestEnabledBefore) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
if (textureChanged) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, boundTextureBefore);
}
GLStateManager.popStateTo(d);
truncateBatchToWatermark();
}
}
/** Replays one sealed command range through the Tessellator so Iris sees it as ordinary geometry. */
private static boolean emitRangeThroughPipeline(BatchingFontRenderer owner, FontDrawCmd[] cmdsData, int from, int to,
private static void emitRangeThroughPipeline(BatchingFontRenderer owner, FontDrawCmd[] cmdsData, int from, int to,
int packedLight, float normalX, float normalY, float normalZ) {
final Tessellator tessellator = Tessellator.instance;
ResourceLocation lastTexture = DUMMY_RESOURCE_LOCATION;
boolean textureChanged = false;
boolean drawing = false;
try {
for (int i = from; i < to; i++) {
@@ -1111,7 +1004,6 @@ public class BatchingFontRenderer {
} else {
GLStateManager.enableTexture();
((FontRendererAccessor) owner.underlying).angelica$bindTexture(cmd.texture);
textureChanged = true;
}
lastTexture = cmd.texture;
}
@@ -1128,7 +1020,6 @@ public class BatchingFontRenderer {
tessellator.draw();
}
}
return textureChanged;
}
private void emitCommand(Tessellator tessellator, FontDrawCmd cmd) {
@@ -1154,15 +1045,6 @@ public class BatchingFontRenderer {
memGetFloat(ptr + 8), memGetFloat(ptr + 12));
}
private static void restoreDepth(boolean testBefore, boolean maskBefore) {
if (testBefore != GLStateManager.getDepthTest().isEnabled()) {
if (testBefore) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
}
if (maskBefore != GLStateManager.isEffectiveDepthMaskEnabled()) {
GLStateManager.glDepthMask(maskBefore);
}
}
private void truncateBatchToWatermark() {
recycleBatchSegments();
for (int i = batchCommands.size() - 1; i >= deferredCmdWatermark; i--) {
@@ -6,11 +6,14 @@ import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.debug.ChunkDebugMinimap;
import com.gtnewhorizons.angelica.debug.flyby.FlybyRoute;
import com.gtnewhorizons.angelica.debug.flyby.FlybyRunner;
import com.gtnewhorizons.angelica.debug.profiling.AsprofRecorder;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasDebugScreenHandler;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
@@ -20,7 +23,7 @@ import java.util.List;
public class AngelicaCommand extends CommandBase {
private static final List<String> SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "flyby", "help");
private static final List<String> SUBCOMMANDS = Arrays.asList("wireframe", "fog", "minimap", "flyby", "profile", "help");
@Override
public String getCommandName() {
@@ -29,12 +32,29 @@ public class AngelicaCommand extends CommandBase {
@Override
public String getCommandUsage(ICommandSender sender) {
return "/angelica <wireframe|fog|minimap|flyby|help>";
return "/angelica <wireframe|fog|minimap|flyby|profile|help>";
}
@Override
public int getRequiredPermissionLevel() {
return 2; // op
return 0;
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender sender) {
return true;
}
static boolean requiresCheats(String subcommand) {
return "wireframe".equals(subcommand) || "flyby".equals(subcommand);
}
private static boolean cheatsAllowed() {
if (SystemProperties.debugTooling()) return true;
final Minecraft mc = Minecraft.getMinecraft();
final IntegratedServer server = mc.getIntegratedServer();
if (server == null || mc.thePlayer == null) return false;
return server.getConfigurationManager().func_152596_g(mc.thePlayer.getGameProfile());
}
@Override
@@ -50,6 +70,9 @@ public class AngelicaCommand extends CommandBase {
options.add("cancel");
return getListOfStringsMatchingLastWord(args, options.toArray(new String[0]));
}
if (args.length == 2 && "profile".equalsIgnoreCase(args[0])) {
return getListOfStringsMatchingLastWord(args, new String[] { "start", "stop", "status" });
}
return new ArrayList<>();
}
@@ -60,11 +83,18 @@ public class AngelicaCommand extends CommandBase {
return;
}
switch (args[0].toLowerCase()) {
final String subcommand = args[0].toLowerCase();
if (requiresCheats(subcommand) && !cheatsAllowed()) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] " + subcommand + " needs cheats enabled on a world you host"));
return;
}
switch (subcommand) {
case "wireframe" -> handleWireframe(sender);
case "fog" -> handleFog(sender);
case "minimap" -> handleMinimap(sender);
case "flyby" -> handleFlyby(sender, args);
case "profile" -> handleProfile(sender, args);
default -> sendHelp(sender);
}
}
@@ -139,12 +169,58 @@ public class AngelicaCommand extends CommandBase {
+ " (" + route.toTicks(used, speed) + " ticks)"));
}
private void handleProfile(ICommandSender sender, String[] args) {
if (args.length < 2) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Usage: /angelica profile <start|stop|status>"));
return;
}
switch (args[1].toLowerCase()) {
case "start" -> {
final String opts;
if (args.length > 2) {
final StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
if (i > 2) sb.append(',');
sb.append(args[i]);
}
opts = sb.toString();
} else {
opts = SystemProperties.PROFILE_OPTS;
}
final String error = AsprofRecorder.start("manual", opts);
if (error != null) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] " + error));
} else {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Profiling started: " + AsprofRecorder.outputPath()));
}
}
case "stop" -> {
final String path = AsprofRecorder.outputPath();
final String error = AsprofRecorder.stop();
if (error != null) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] " + error));
} else {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Profile written to " + path));
}
}
case "status" -> {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + AsprofRecorder.status()));
if (AsprofRecorder.isRecording()) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " " + AsprofRecorder.outputPath()));
}
}
default -> sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + "Usage: /angelica profile <start|stop|status>"));
}
}
private void sendHelp(ICommandSender sender) {
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] Debug Commands:"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica wireframe" + EnumChatFormatting.WHITE + " - Toggle wireframe rendering"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica fog" + EnumChatFormatting.WHITE + " - Toggle fog debug on F3"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica minimap" + EnumChatFormatting.WHITE + " - Toggle chunk debug overlay"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica flyby <" + FlybyRoute.ids() + ">" + EnumChatFormatting.WHITE + " - Run a deterministic benchmark route"));
sender.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY + " /angelica profile <start|stop|status>" + EnumChatFormatting.WHITE + " - Control async-profiler (JFR) recording"));
}
@Override
@@ -1,28 +1,19 @@
package com.gtnewhorizons.angelica.compat.bop;
import net.minecraft.world.World;
public final class BopFogBlend {
public static final int NO_FOG = -1;
@FunctionalInterface
public interface ColorSource {
/** Packed 0xRRGGBB, or {@link #NO_FOG}. */
int fogColour(int x, int y, int z);
}
private static Object cachedWorld;
private static int cachedGeneration;
private static int cachedX, cachedY, cachedZ, cachedDistance;
private static float interiorR, interiorG, interiorB, interiorWeight;
private BopFogBlend() {}
public static void invalidate() {
cachedWorld = null;
FogBiomeCache.invalidate();
}
public static void accumulate(Object world, int generation, ColorSource source, double posX, double posZ,
int playerX, int playerY, int playerZ, int distance, float[] out) {
public static void accumulate(World world, double posX, double posZ, int playerX, int playerY, int playerZ,
int distance, float[] out) {
out[0] = 0;
out[1] = 0;
@@ -35,63 +26,31 @@ public final class BopFogBlend {
final double zDiffHigh = posZ - playerZ;
if (distance <= 0) {
cell(source, 0, 0, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(world, 0, 0, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
return;
}
if (world != cachedWorld || generation != cachedGeneration || playerX != cachedX || playerY != cachedY
|| playerZ != cachedZ || distance != cachedDistance) {
recomputeInterior(source, playerX, playerY, playerZ, distance);
cachedWorld = world;
cachedGeneration = generation;
cachedX = playerX;
cachedY = playerY;
cachedZ = playerZ;
cachedDistance = distance;
}
out[0] = interiorR;
out[1] = interiorG;
out[2] = interiorB;
out[3] = interiorWeight;
FogColourGrid.accumulateInterior(world, playerX, playerY, playerZ, distance, out);
for (int z = -distance; z <= distance; ++z) {
cell(source, -distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(source, distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(world, -distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(world, distance, z, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
}
for (int x = -distance + 1; x <= distance - 1; ++x) {
cell(source, x, -distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(source, x, distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(world, x, -distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
cell(world, x, distance, xDiffLow, xDiffHigh, zDiffLow, zDiffHigh, playerX, playerY, playerZ, distance, out);
}
}
private static void recomputeInterior(ColorSource source, int playerX, int playerY, int playerZ, int distance) {
float r = 0, g = 0, b = 0, weight = 0;
for (int x = -distance + 1; x <= distance - 1; ++x) {
for (int z = -distance + 1; z <= distance - 1; ++z) {
final int colour = source.fogColour(playerX + x, playerY, playerZ + z);
if (colour == NO_FOG) continue;
r += (colour & 0xFF0000) >> 16;
g += (colour & 0x00FF00) >> 8;
b += colour & 0x0000FF;
weight += 1;
}
}
interiorR = r;
interiorG = g;
interiorB = b;
interiorWeight = weight;
}
private static void cell(ColorSource source, int x, int z, double xDiffLow, double xDiffHigh, double zDiffLow,
private static void cell(World world, int x, int z, double xDiffLow, double xDiffHigh, double zDiffLow,
double zDiffHigh, int playerX, int playerY, int playerZ, int distance, float[] out) {
final int colour = source.fogColour(playerX + x, playerY, playerZ + z);
if (colour == NO_FOG) return;
final int color = FogColourGrid.colour(world, playerX + x, playerY, playerZ + z);
if (color == NO_FOG) return;
float rPart = (colour & 0xFF0000) >> 16;
float gPart = (colour & 0x00FF00) >> 8;
float bPart = colour & 0x0000FF;
float rPart = (color & 0xFF0000) >> 16;
float gPart = (color & 0x00FF00) >> 8;
float bPart = color & 0x0000FF;
float weightPart = 1;
if (x == -distance) {
@@ -1,30 +0,0 @@
package com.gtnewhorizons.angelica.compat.bop;
import biomesoplenty.client.fog.IBiomeFog;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
public final class BopFogColorSource implements BopFogBlend.ColorSource {
public static final BopFogColorSource INSTANCE = new BopFogColorSource();
private World world;
private BopFogColorSource() {}
public BopFogColorSource forWorld(World world) {
this.world = world;
return this;
}
public void freeWorld() {
this.world = null;
}
@Override
public int fogColour(int x, int y, int z) {
final BiomeGenBase biome = FogBiomeCache.get(world, x, z);
if (!(biome instanceof IBiomeFog fog)) return BopFogBlend.NO_FOG;
return fog.getFogColour(x, y, z) & 0xFFFFFF;
}
}
@@ -10,33 +10,42 @@ public final class FogBiomeCache {
private static final Long2ObjectOpenHashMap<BiomeGenBase> CACHE = new Long2ObjectOpenHashMap<>();
private static World cachedWorld;
private static int generation;
private static boolean lastCacheable;
private FogBiomeCache() {}
public static int generation() {
return generation;
public static boolean lastWasCacheable() {
return lastCacheable;
}
public static void invalidate() {
CACHE.clear();
cachedWorld = null;
lastCacheable = false;
FogColourGrid.invalidate();
}
public static BiomeGenBase get(World world, int x, int z) {
static void useWorld(World world) {
if (world != cachedWorld) {
CACHE.clear();
cachedWorld = world;
generation++;
FogColourGrid.invalidate();
}
}
public static BiomeGenBase get(World world, int x, int z) {
useWorld(world);
final long key = ((long) x << 32) | (z & 0xFFFFFFFFL);
BiomeGenBase biome = CACHE.get(key);
if (biome == null) {
biome = world.getBiomeGenForCoords(x, z);
if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) {
lastCacheable = world.getChunkProvider().chunkExists(x >> 4, z >> 4);
if (lastCacheable) {
if (CACHE.size() >= MAX_ENTRIES) CACHE.clear();
CACHE.put(key, biome);
generation++;
}
} else {
lastCacheable = true;
}
return biome;
}
@@ -0,0 +1,116 @@
package com.gtnewhorizons.angelica.compat.bop;
import biomesoplenty.client.fog.IBiomeFog;
import java.util.Arrays;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
public final class FogColourGrid {
public static final int NO_FOG = BopFogBlend.NO_FOG;
private static final int SIZE = 128;
private static final int MASK = SIZE - 1;
private static final long EMPTY = Long.MIN_VALUE;
private static final FogColourGrid INSTANCE = new FogColourGrid();
private final long[] keys = new long[SIZE * SIZE];
private final int[] colours = new int[SIZE * SIZE];
private World gridWorld;
private boolean lastCacheable;
private boolean interiorValid;
private int interiorX;
private int interiorY;
private int interiorZ;
private int interiorDistance;
private float interiorR;
private float interiorG;
private float interiorB;
private float interiorWeight;
private FogColourGrid() {
reset();
}
public static void invalidate() {
INSTANCE.reset();
}
private void reset() {
Arrays.fill(keys, EMPTY);
gridWorld = null;
lastCacheable = false;
interiorValid = false;
}
private void useWorld(World world) {
FogBiomeCache.useWorld(world);
if (world != gridWorld) {
reset();
gridWorld = world;
}
}
public static int colour(World world, int x, int y, int z) {
INSTANCE.useWorld(world);
return INSTANCE.lookup(world, x, y, z);
}
static void accumulateInterior(World world, int x, int y, int z, int distance, float[] out) {
INSTANCE.useWorld(world);
if (!INSTANCE.interiorValid || INSTANCE.interiorX != x || INSTANCE.interiorY != y || INSTANCE.interiorZ != z || INSTANCE.interiorDistance != distance) {
INSTANCE.rebuildInterior(world, x, y, z, distance);
}
out[0] = INSTANCE.interiorR;
out[1] = INSTANCE.interiorG;
out[2] = INSTANCE.interiorB;
out[3] = INSTANCE.interiorWeight;
}
private void rebuildInterior(World world, int playerX, int playerY, int playerZ, int distance) {
float r = 0, g = 0, b = 0, weight = 0;
boolean cacheable = true;
interiorValid = false;
for (int x = -distance + 1; x <= distance - 1; ++x) {
for (int z = -distance + 1; z <= distance - 1; ++z) {
final int color = lookup(world, playerX + x, playerY, playerZ + z);
cacheable &= lastCacheable;
if (color == NO_FOG) continue;
r += (color & 0xFF0000) >> 16;
g += (color & 0x00FF00) >> 8;
b += color & 0x0000FF;
weight += 1;
}
}
interiorR = r;
interiorG = g;
interiorB = b;
interiorWeight = weight;
interiorX = playerX;
interiorY = playerY;
interiorZ = playerZ;
interiorDistance = distance;
interiorValid = cacheable;
}
private int lookup(World world, int x, int y, int z) {
final long key = ((long) (x & 0x3FFFFFF) << 35) | ((long) (z & 0x3FFFFFF) << 9) | (y & 0x1FF);
final int idx = ((x & MASK) << 7) | (z & MASK);
if (keys[idx] == key) {
lastCacheable = true;
return colours[idx];
}
final BiomeGenBase biome = FogBiomeCache.get(world, x, z);
final int result = (biome instanceof IBiomeFog fog) ? (fog.getFogColour(x, y, z) & 0xFFFFFF) : NO_FOG;
lastCacheable = FogBiomeCache.lastWasCacheable();
if (lastCacheable) {
keys[idx] = key;
colours[idx] = result;
}
return result;
}
}
@@ -1,434 +1,284 @@
package com.gtnewhorizons.angelica.compat.mojang;
import com.google.common.collect.ImmutableList;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
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.glsm.GLStateManager;
import com.gtnewhorizons.angelica.rendering.tesr.DrawState;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import it.unimi.dsi.fastutil.Hash;
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import lombok.Getter;
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.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
public abstract class RenderLayer extends RenderPhase { // Aka: RenderType (Iris)
private static final RenderLayer SOLID = of("solid", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 2097152, true, false, RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(MIPMAP_BLOCK_ATLAS_TEXTURE).build(true));
private static final RenderLayer CUTOUT = of("cutout", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 131072, true, false, RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(BLOCK_ATLAS_TEXTURE).alpha(HALF_ALPHA).build(true));
private static final RenderLayer TRANSLUCENT = of("translucent", DefaultVertexFormat.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 262144, true, true, createTranslucentPhaseData());
public final class RenderLayer implements BlendingStateHolder {
@Getter
private final VertexFormat vertexFormat;
@Getter
private final int drawMode;
@Getter
private final int expectedBufferSize;
private static final int TESR_BUFFER_SIZE = 65536;
public RenderLayer(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, Runnable startAction, Runnable endAction) {
super(name, startAction, endAction);
private static final ObjectOpenCustomHashSet<RenderLayer> CACHE = new ObjectOpenCustomHashSet<>(HashStrategy.INSTANCE);
static final class Hook {
final Runnable begin;
final Runnable end;
Hook(Runnable begin, Runnable end) {
this.begin = begin;
this.end = end;
}
}
private static final Hook[] GLINT_HOOKS = new Hook[ShaderGlint.TINT_SLOTS + 1];
private static final Hook BEACON_BEAM_HOOK = new Hook(
() -> GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM),
GbufferPrograms::teardownSpecialRenderCondition);
private static final Reference2ObjectOpenHashMap<TesrShader, Hook> SHADER_HOOKS = new Reference2ObjectOpenHashMap<>();
private static final Reference2ObjectOpenHashMap<PassOverride, Hook> PASS_HOOKS = new Reference2ObjectOpenHashMap<>();
private String name;
@Getter private final VertexFormat vertexFormat;
@Getter private final int drawMode;
@Getter private final int expectedBufferSize;
@Getter private final DrawState state;
@Getter private final ResourceLocation textureId;
@Getter private final boolean unfilteredAtlas;
private final TransparencyType transparencyType;
private final Hook hook;
private final boolean noPass;
private final int hash;
private RenderLayer(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, DrawState state,
ResourceLocation textureId, boolean unfilteredAtlas, TransparencyType transparencyType, Hook hook,
boolean noPass) {
this.name = name;
this.vertexFormat = vertexFormat;
this.drawMode = drawMode;
this.expectedBufferSize = expectedBufferSize;
this.state = state;
this.textureId = textureId;
this.unfilteredAtlas = unfilteredAtlas;
this.transparencyType = transparencyType;
this.hook = hook;
this.noPass = noPass;
int h = System.identityHashCode(vertexFormat);
h = h * 31 + drawMode;
h = h * 31 + expectedBufferSize;
h = h * 31 + System.identityHashCode(state);
h = h * 31 + Objects.hashCode(textureId);
h = h * 31 + (unfilteredAtlas ? 1 : 0);
h = h * 31 + transparencyType.ordinal();
h = h * 31 + System.identityHashCode(hook);
h = h * 31 + (noPass ? 1 : 0);
this.hash = h;
}
public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, MultiPhaseParameters phaseData) {
return of(name, vertexFormat, drawMode, expectedBufferSize, false, false, phaseData);
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) {
return build(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cull, lit, false);
}
public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) {
return RenderLayer.MultiPhase.of(name, vertexFormat, drawMode, expectedBufferSize, hasCrumbling, translucent, phases);
public static RenderLayer tesrNoPass(ResourceLocation texture, TesrMaterial material, int cull, boolean lit) {
return build(texture, material, PassOverride.NONE, 0.0f, 0.0f, ShaderGlint.NO_TINT, cull, lit, true);
}
public static RenderLayer solid() {
return SOLID;
}
public static RenderLayer cutout() {
return CUTOUT;
}
private static MultiPhaseParameters createTranslucentPhaseData() {
return RenderLayer.MultiPhaseParameters.builder().shadeModel(SMOOTH_SHADE_MODEL).lightmap(ENABLE_LIGHTMAP).texture(MIPMAP_BLOCK_ATLAS_TEXTURE).transparency(TRANSLUCENT_TRANSPARENCY).target(TRANSLUCENT_TARGET).build(true);
}
public static RenderLayer translucent() {
return TRANSLUCENT;
}
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, material.isUnfilteredAtlas()) : NO_TEXTURE);
if (material.isNoCull()) {
b.cull(DISABLE_CULLING);
private static RenderLayer build(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit, boolean noPass) {
final DrawState state = DrawState.forMaterial(material, cull, lit, offsetFactor, offsetUnits);
final Hook hook = hookFor(material, noPass ? PassOverride.NONE : pass, glintSlot);
final TransparencyType transparency = transparencyFor(state.getBlend());
final RenderLayer candidate = new RenderLayer(null, BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL,
GL11.GL_QUADS, TESR_BUFFER_SIZE, state, texture, material.isUnfilteredAtlas(), transparency, hook,
noPass);
final RenderLayer retained = intern(candidate);
if (retained == candidate) {
retained.name = "angelica_tesr_" + (noPass ? "nopass_" : "")
+ material.transparency().name().toLowerCase(Locale.ROOT) + (noPass ? "" : pass.nameSuffix())
+ (offsetFactor == 0.0f && offsetUnits == 0.0f ? "" : "_offset" + offsetFactor + "_" + offsetUnits)
+ "_cull" + state.getCull() + (state.isLit() ? "_lit" : "")
+ (glintSlot == ShaderGlint.NO_TINT ? "" : "_tint" + glintSlot);
}
if (material.isUnlit()) {
b.texturing(NO_FFP_LIGHTING);
return retained;
}
private static RenderLayer intern(RenderLayer layer) {
return CACHE.addOrGet(layer);
}
public static void clearInterningAndHooks() {
CACHE.clear();
SHADER_HOOKS.clear();
PASS_HOOKS.clear();
for (int i = 0; i < GLINT_HOOKS.length; i++) {
GLINT_HOOKS[i] = null;
}
if (material.isNoDepthWrite()) {
b.writeMaskState(COLOR_MASK);
}
if (material.isDepthOnly()) {
b.writeMaskState(DEPTH_MASK);
}
b.alpha(material.cutoutAlpha() > 0 ? new RenderPhase.Alpha(material.cutoutAlpha()) : ZERO_ALPHA);
b.depthTest(material.isDepthEqual() ? EQUAL_DEPTH_TEST : LEQUAL_DEPTH_TEST);
switch (material.transparency()) {
case TRANSLUCENT -> b.transparency(TRANSLUCENT_TRANSPARENCY);
case ADDITIVE -> b.transparency(ADDITIVE_TRANSPARENCY);
case ADDITIVE_ALPHA -> b.transparency(LIGHTNING_TRANSPARENCY);
case GLINT -> b.transparency(GLINT_TRANSPARENCY);
case OPAQUE -> b.transparency(NO_TRANSPARENCY);
}
boolean shaderPhaseTaken = true;
}
public static int cacheSize() {
return CACHE.size();
}
private static TransparencyType transparencyFor(int blend) {
return switch (blend) {
case DrawState.OPAQUE -> TransparencyType.OPAQUE;
case DrawState.GLINT -> TransparencyType.DECAL;
default -> TransparencyType.GENERAL_TRANSPARENT;
};
}
private static Hook hookFor(TesrMaterial material, PassOverride pass, int glintSlot) {
switch (material.special()) {
case GLINT -> b.shader(glintShader(glintSlot));
case BEACON_BEAM -> b.shader(SPECIAL_BEACON_BEAM);
case GLINT -> {
return glintHook(glintSlot);
}
case BEACON_BEAM -> {
return BEACON_BEAM_HOOK;
}
case NONE -> {
final TesrShader shader = material.shader();
if (shader != null) {
b.shader(new RenderPhase.Shader("angelica_tesr_shader_" + shader.name(), shader.bind(), shader.release()));
} else {
shaderPhaseTaken = false;
return shaderHook(shader);
}
}
}
if (!shaderPhaseTaken && pass != PassOverride.NONE) {
b.shader(new RenderPhase.Shader("angelica_tesr_pass" + pass.nameSuffix(), pass::apply, pass::clear));
return pass == PassOverride.NONE ? null : passHook(pass);
}
private static Hook glintHook(int slot) {
Hook hook = GLINT_HOOKS[slot + 1];
if (hook == null) {
hook = new Hook(() -> {
GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT);
ShaderGlint.bindTintedGlint(slot);
}, GbufferPrograms::teardownSpecialRenderCondition);
GLINT_HOOKS[slot + 1] = hook;
}
b.layering(polygonOffset(offsetFactor, offsetUnits));
return b;
return hook;
}
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;
private static Hook shaderHook(TesrShader shader) {
Hook hook = SHADER_HOOKS.get(shader);
if (hook == null) {
hook = new Hook(shader.bind(), shader.release());
SHADER_HOOKS.put(shader, hook);
}
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, ShaderGlint.NO_TINT);
return hook;
}
public static RenderLayer tesr(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
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),
BatchVertexFormats.POSITION_COLOR_TEXTURE_LIGHTF_NORMAL, GL11.GL_QUADS, 65536, true, sortsTranslucent, b.build(false));
}
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, ShaderGlint.NO_TINT).build(false));
}
public static RenderLayer getOutline(ResourceLocation texture, RenderPhase.Cull cull) {
return of("outline", DefaultVertexFormat.POSITION_COLOR_TEXTURE, 7, 256, RenderLayer.MultiPhaseParameters.builder().texture(new RenderPhase.Texture(texture, false, false)).cull(cull).depthTest(ALWAYS_DEPTH_TEST).alpha(ONE_TENTH_ALPHA).fog(NO_FOG).target(OUTLINE_TARGET).build(RenderLayer.OutlineMode.IS_OUTLINE));
}
public int mode() {
return this.drawMode;
}
public ResourceLocation getTextureId() {
return null;
}
static final class MultiPhase extends RenderLayer implements BlendingStateHolder {
private static final ObjectOpenCustomHashSet<MultiPhase> CACHE;
private final MultiPhaseParameters phases;
private final int hash;
private final Optional<RenderLayer> affectedOutline;
@Override
public TransparencyType getTransparencyType() {
return phases.transparency == null ? TransparencyType.OPAQUE : phases.transparency.getTransparencyType();
private static Hook passHook(PassOverride pass) {
Hook hook = PASS_HOOKS.get(pass);
if (hook == null) {
hook = new Hook(pass::apply, pass::clear);
PASS_HOOKS.put(pass, hook);
}
return hook;
}
private MultiPhase(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent, MultiPhaseParameters phases) {
super(name, vertexFormat, drawMode, expectedBufferSize, () -> {
final ImmutableList<RenderPhase> p = phases.phases;
for (int i = 0, n = p.size(); i < n; i++) {
p.get(i).startDrawing();
@Override
public TransparencyType getTransparencyType() {
return transparencyType;
}
public void startDrawing() {
boolean filtering = false;
boolean hookActive = false;
try {
state.apply();
if (textureId != null) {
GLStateManager.enableTexture();
Minecraft.getMinecraft().getTextureManager().bindTexture(textureId);
if (unfilteredAtlas) {
filtering = true;
TextureUtil.func_152777_a(false, false, 1.0F);
}
}, () -> {
final ImmutableList<RenderPhase> p = phases.phases;
for (int i = 0, n = p.size(); i < n; i++) {
p.get(i).endDrawing();
}
});
this.phases = phases;
this.affectedOutline = phases.outlineMode == RenderLayer.OutlineMode.AFFECTS_OUTLINE && phases.texture != null ? phases.texture.getId().map((arg2) -> {
return getOutline(arg2, phases.cull);
}) : Optional.empty();
this.hash = Objects.hash(new Object[]{super.hashCode(), phases});
}
public static MultiPhase of(String name, VertexFormat vertexFormat, int drawMode, int expectedBufferSize, boolean hasCrumbling, boolean translucent,
MultiPhaseParameters phases) {
return (MultiPhase)CACHE.addOrGet(new MultiPhase(name, vertexFormat, drawMode, expectedBufferSize, hasCrumbling, translucent, phases));
}
public Optional<RenderLayer> getAffectedOutline() {
return this.affectedOutline;
}
@Override
public ResourceLocation getTextureId() {
return phases.texture == null ? null : phases.texture.getId().orElse(null);
}
@Override
public boolean equals(@Nullable Object object) {
return this == object;
}
@Override
public int hashCode() {
return this.hash;
}
@Override
public String toString() {
return "RenderType[" + this.phases + ']';
}
static {
CACHE = new ObjectOpenCustomHashSet<>(RenderLayer.MultiPhase.HashStrategy.INSTANCE);
}
static enum HashStrategy implements Hash.Strategy<MultiPhase> {
INSTANCE;
private HashStrategy() {
}
public int hashCode(@Nullable MultiPhase arg) {
return arg == null ? 0 : arg.hash;
}
public boolean equals(@Nullable MultiPhase arg, @Nullable MultiPhase arg2) {
if (arg == arg2) {
return true;
} else {
return arg != null && arg2 != null && arg.name.equals(arg2.name)
&& arg.getVertexFormat() == arg2.getVertexFormat() && arg.getDrawMode() == arg2.getDrawMode()
&& Objects.equals(arg.phases, arg2.phases);
}
}
}
}
public static final class MultiPhaseParameters {
private final RenderPhase.Texture texture;
private final RenderPhase.Transparency transparency;
private final RenderPhase.DiffuseLighting diffuseLighting;
private final RenderPhase.ShadeModel shadeModel;
private final RenderPhase.Alpha alpha;
private final RenderPhase.DepthTest depthTest;
private final RenderPhase.Cull cull;
private final RenderPhase.Lightmap lightmap;
private final RenderPhase.Fog fog;
private final RenderPhase.Layering layering;
private final RenderPhase.Target target;
private final RenderPhase.Texturing texturing;
private final RenderPhase.WriteMaskState writeMaskState;
private final RenderPhase.Shader shader;
private final OutlineMode outlineMode;
private final ImmutableList<RenderPhase> phases;
private MultiPhaseParameters(RenderPhase.Texture texture, RenderPhase.Transparency transparency, RenderPhase.DiffuseLighting diffuseLighting, RenderPhase.ShadeModel shadeModel, RenderPhase.Alpha alpha, RenderPhase.DepthTest depthTest, RenderPhase.Cull cull, RenderPhase.Lightmap lightmap, RenderPhase.Fog fog, RenderPhase.Layering layering, RenderPhase.Target target, RenderPhase.Texturing texturing, RenderPhase.WriteMaskState writeMaskState, RenderPhase.Shader shader, OutlineMode outlineMode) {
this.texture = texture;
this.transparency = transparency;
this.diffuseLighting = diffuseLighting;
this.shadeModel = shadeModel;
this.alpha = alpha;
this.depthTest = depthTest;
this.cull = cull;
this.lightmap = lightmap;
this.fog = fog;
this.layering = layering;
this.target = target;
this.texturing = texturing;
this.writeMaskState = writeMaskState;
this.shader = shader;
this.outlineMode = outlineMode;
final ImmutableList.Builder<RenderPhase> declared = ImmutableList.builder();
for (RenderPhase phase : new RenderPhase[] { this.texture, this.transparency, this.diffuseLighting,
this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering,
this.target, this.texturing, this.writeMaskState, this.shader }) {
if (phase != null) declared.add(phase);
}
this.phases = declared.build();
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
MultiPhaseParameters rendertype$state = (MultiPhaseParameters)object;
return this.outlineMode == rendertype$state.outlineMode && this.phases.equals(rendertype$state.phases);
} else {
return false;
GLStateManager.disableTexture();
}
}
@Override
public int hashCode() {
return Objects.hash(new Object[]{this.phases, this.outlineMode});
}
@Override
public String toString() {
return "CompositeState[" + this.phases + ", outlineProperty=" + this.outlineMode + ']';
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private RenderPhase.Texture texture;
private RenderPhase.Transparency transparency;
private RenderPhase.DiffuseLighting diffuseLighting;
private RenderPhase.ShadeModel shadeModel;
private RenderPhase.Alpha alpha;
private RenderPhase.DepthTest depthTest;
private RenderPhase.Cull cull;
private RenderPhase.Lightmap lightmap;
private RenderPhase.Fog fog;
private RenderPhase.Layering layering;
private RenderPhase.Target target;
private RenderPhase.Texturing texturing;
private RenderPhase.WriteMaskState writeMaskState;
private RenderPhase.Shader shader;
private Builder() {}
public Builder texture(RenderPhase.Texture texture) {
this.texture = texture;
return this;
if (hook != null) {
hookActive = true;
hook.begin.run();
}
public Builder transparency(RenderPhase.Transparency transparency) {
this.transparency = transparency;
return this;
} catch (Throwable failure) {
if (hookActive) {
try {
hook.end.run();
} catch (Throwable cleanup) {
RenderFailures.suppress(failure, cleanup);
}
}
public void layering(Layering layering) {
this.layering = layering;
}
public Builder shadeModel(RenderPhase.ShadeModel shadeModel) {
this.shadeModel = shadeModel;
return this;
}
public Builder alpha(RenderPhase.Alpha alpha) {
this.alpha = alpha;
return this;
}
public Builder depthTest(RenderPhase.DepthTest depthTest) {
this.depthTest = depthTest;
return this;
}
public Builder cull(RenderPhase.Cull cull) {
this.cull = cull;
return this;
}
public Builder lightmap(RenderPhase.Lightmap lightmap) {
this.lightmap = lightmap;
return this;
}
public Builder fog(RenderPhase.Fog fog) {
this.fog = fog;
return this;
}
public Builder target(RenderPhase.Target target) {
this.target = target;
return this;
}
public Builder texturing(RenderPhase.Texturing texturing) {
this.texturing = texturing;
return this;
}
public Builder writeMaskState(RenderPhase.WriteMaskState writeMaskState) {
this.writeMaskState = writeMaskState;
return this;
}
public Builder shader(RenderPhase.Shader shader) {
this.shader = shader;
return this;
}
public MultiPhaseParameters build(boolean affectsOutline) {
return this.build(affectsOutline ? RenderLayer.OutlineMode.AFFECTS_OUTLINE : RenderLayer.OutlineMode.NONE);
}
public MultiPhaseParameters build(OutlineMode outlineMode) {
return new MultiPhaseParameters(this.texture, this.transparency, this.diffuseLighting, this.shadeModel, this.alpha, this.depthTest, this.cull, this.lightmap, this.fog, this.layering, this.target, this.texturing, this.writeMaskState, this.shader, outlineMode);
if (filtering) {
try {
TextureUtil.func_147945_b();
} catch (Throwable cleanup) {
RenderFailures.suppress(failure, cleanup);
}
}
throw failure;
}
}
enum OutlineMode {
NONE("none"),
IS_OUTLINE("is_outline"),
AFFECTS_OUTLINE("affects_outline");
private final String name;
OutlineMode(String name) {
this.name = name;
public void endDrawing() {
Throwable failure = null;
try {
if (hook != null) hook.end.run();
} catch (Throwable t) {
failure = t;
} finally {
if (textureId != null && unfilteredAtlas) {
try {
TextureUtil.func_147945_b();
} catch (Throwable cleanup) {
failure = RenderFailures.suppress(failure, cleanup);
}
}
}
if (failure != null) RenderFailures.rethrow(failure);
}
@Override
public String toString() {
return this.name;
}
@Override
public boolean equals(@Nullable Object object) {
return this == object;
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return "RenderLayer[" + name + ", " + state + ", texture=" + textureId + ']';
}
private enum HashStrategy implements Hash.Strategy<RenderLayer> {
INSTANCE;
@Override
public int hashCode(@Nullable RenderLayer layer) {
return layer == null ? 0 : layer.hash;
}
@Override
public boolean equals(@Nullable RenderLayer a, @Nullable RenderLayer b) {
if (a == b) return true;
if (a == null || b == null) return false;
return a.vertexFormat == b.vertexFormat && a.drawMode == b.drawMode
&& a.expectedBufferSize == b.expectedBufferSize && a.state == b.state
&& Objects.equals(a.textureId, b.textureId) && a.unfilteredAtlas == b.unfilteredAtlas
&& a.transparencyType == b.transparencyType && a.hook == b.hook
&& a.noPass == b.noPass;
}
}
}
@@ -1,569 +0,0 @@
package com.gtnewhorizons.angelica.compat.mojang;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
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;
import javax.annotation.Nullable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Optional;
public abstract class RenderPhase {
protected final String name;
protected Runnable beginAction;
private final Runnable endAction;
protected static final Transparency NO_TRANSPARENCY = new Transparency("no_transparency", TransparencyType.OPAQUE, GLStateManager::disableBlend, () -> {
});
protected static final Transparency ADDITIVE_TRANSPARENCY = new Transparency("additive_transparency", () -> {
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
}, () -> {
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
});
protected static final Transparency LIGHTNING_TRANSPARENCY = new Transparency("lightning_transparency", () -> {
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
}, () -> {
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
});
protected static final Transparency GLINT_TRANSPARENCY = new Transparency("glint_transparency", TransparencyType.DECAL, () -> {
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE);
}, () -> {
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
});
protected static final Transparency CRUMBLING_TRANSPARENCY = new Transparency("crumbling_transparency", TransparencyType.DECAL, () -> {
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
}, () -> {
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
});
protected static final Transparency TRANSLUCENT_TRANSPARENCY = new Transparency("translucent_transparency", () -> {
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
}, () -> {
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
});
protected static final Alpha ZERO_ALPHA = new Alpha(0.0F);
protected static final Alpha ONE_TENTH_ALPHA = new Alpha(0.003921569F);
protected static final Alpha HALF_ALPHA = new Alpha(0.5F);
protected static final ShadeModel SHADE_MODEL = new ShadeModel(false);
protected static final ShadeModel SMOOTH_SHADE_MODEL = new ShadeModel(true);
protected static final Texture MIPMAP_BLOCK_ATLAS_TEXTURE;
protected static final Texture BLOCK_ATLAS_TEXTURE;
protected static final Texture NO_TEXTURE;
protected static final Texturing DEFAULT_TEXTURING;
protected static final Texturing NO_FFP_LIGHTING;
protected static final Lightmap ENABLE_LIGHTMAP;
protected static final Lightmap DISABLE_LIGHTMAP;
protected static final DiffuseLighting ENABLE_DIFFUSE_LIGHTING;
protected static final DiffuseLighting DISABLE_DIFFUSE_LIGHTING;
protected static final Cull ENABLE_CULLING;
protected static final Cull DISABLE_CULLING;
protected static final DepthTest ALWAYS_DEPTH_TEST;
protected static final DepthTest EQUAL_DEPTH_TEST;
protected static final DepthTest LEQUAL_DEPTH_TEST;
protected static final WriteMaskState ALL_MASK;
protected static final WriteMaskState COLOR_MASK;
protected static final WriteMaskState DEPTH_MASK;
protected static final Layering NO_LAYERING;
protected static final Fog NO_FOG;
protected static final Fog FOG;
protected static final Fog BLACK_FOG;
protected static final Target MAIN_TARGET;
protected static final Target OUTLINE_TARGET;
protected static final Target TRANSLUCENT_TARGET;
protected static final Shader NO_SHADER = new Shader("no_shader", () -> {}, () -> {});
private static final Map<Long, Layering> POLYGON_OFFSET_LAYERINGS = new ConcurrentHashMap<>();
public static Layering polygonOffset(float factor, float units) {
if (factor == 0.0f && units == 0.0f) {
return NO_LAYERING;
}
final long key = ((long) Float.floatToIntBits(factor) << 32) | (Float.floatToIntBits(units) & 0xFFFFFFFFL);
return POLYGON_OFFSET_LAYERINGS.computeIfAbsent(key, k -> new Layering("polygon_offset_" + factor + "_" + units, () -> {
GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(factor, units);
}, () -> {
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(0.0f, 0.0f);
}));
}
public RenderPhase(String name, Runnable beginAction, Runnable endAction) {
this.name = name;
this.beginAction = beginAction;
this.endAction = endAction;
}
public void startDrawing() {
this.beginAction.run();
}
public void endDrawing() {
this.endAction.run();
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
RenderPhase lv = (RenderPhase)object;
return this.name.equals(lv.name);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public String toString() {
return this.name;
}
private static ResourceLocation ATLAS = TextureMap.locationBlocksTexture;
static {
// TODO: Sodium - SpriteAtlasTexture
MIPMAP_BLOCK_ATLAS_TEXTURE = new Texture(ATLAS, false, true);
BLOCK_ATLAS_TEXTURE = new Texture(ATLAS, false, false);
NO_TEXTURE = new Texture();
DEFAULT_TEXTURING = new Texturing("default_texturing", () -> {
}, () -> {
});
NO_FFP_LIGHTING = new Texturing("no_ffp_lighting", GLStateManager::disableLighting, GLStateManager::enableLighting);
ENABLE_LIGHTMAP = new Lightmap(true);
DISABLE_LIGHTMAP = new Lightmap(false);
ENABLE_DIFFUSE_LIGHTING = new DiffuseLighting(true);
DISABLE_DIFFUSE_LIGHTING = new DiffuseLighting(false);
ENABLE_CULLING = new Cull(true);
DISABLE_CULLING = new Cull(false);
ALWAYS_DEPTH_TEST = new DepthTest("always", GL11.GL_ALWAYS);
EQUAL_DEPTH_TEST = new DepthTest("==", GL11.GL_EQUAL);
LEQUAL_DEPTH_TEST = new DepthTest("<=", GL11.GL_LEQUAL);
ALL_MASK = new WriteMaskState(true, true);
COLOR_MASK = new WriteMaskState(true, false);
DEPTH_MASK = new WriteMaskState(false, true);
NO_LAYERING = new Layering("no_layering", () -> {}, () -> {});
NO_FOG = new Fog("no_fog", () -> {
}, () -> {
});
FOG = new Fog("fog", GLStateManager::enableFog, GLStateManager::disableFog);
BLACK_FOG = new Fog("black_fog", () -> {
GLStateManager.fogColor(0.0F, 0.0F, 0.0F, 1.0F);
GLStateManager.enableFog();
}, GLStateManager::disableFog);
MAIN_TARGET = new Target("main_target", () -> {
}, () -> {
});
OUTLINE_TARGET = new Target("outline_target", () -> {
// TODO: Sodium - entity outline framebuffer
//MinecraftClient.getInstance().worldRenderer.getEntityOutlinesFramebuffer().beginWrite(false);
}, () -> {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
});
TRANSLUCENT_TARGET = new Target("translucent_target", () -> {
if (Minecraft.isFancyGraphicsEnabled()) {
// TODO: Sodium - translucent framebuffer
// MinecraftClient.getInstance().worldRenderer.getTranslucentFramebuffer().beginWrite(false);
}
}, () -> {
if (Minecraft.isFancyGraphicsEnabled()) {
Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(false);
}
});
}
public static class Target extends RenderPhase {
public Target(String string, Runnable runnable, Runnable runnable2) {
super(string, runnable, runnable2);
}
}
public static class Fog extends RenderPhase {
public Fog(String string, Runnable runnable, Runnable runnable2) {
super(string, runnable, runnable2);
}
}
public static class Layering extends RenderPhase {
public Layering(String string, Runnable runnable, Runnable runnable2) {
super(string, runnable, runnable2);
}
}
public static class WriteMaskState extends RenderPhase {
private final boolean color;
private final boolean depth;
public WriteMaskState(boolean color, boolean depth) {
super("write_mask_state", () -> {
if (!depth) {
GLStateManager.glDepthMask(depth);
}
if (!color) {
GLStateManager.glColorMask(color, color, color, color);
}
}, () -> {
if (!depth) {
GLStateManager.glDepthMask(true);
}
if (!color) {
GLStateManager.glColorMask(true, true, true, true);
}
});
this.color = color;
this.depth = depth;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
WriteMaskState lv = (WriteMaskState)object;
return this.color == lv.color && this.depth == lv.depth;
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(this.color, this.depth);
}
@Override
public String toString() {
return this.name + "[writeColor=" + this.color + ", writeDepth=" + this.depth + ']';
}
}
public static class DepthTest extends RenderPhase {
private final String depthFunction;
private final int func;
public DepthTest(String string, int i) {
super("depth_test", () -> {
if (i != GL11.GL_ALWAYS) {
GLStateManager.enableDepthTest();
GLStateManager.glDepthFunc(i);
}
}, () -> {
if (i != GL11.GL_ALWAYS) {
GLStateManager.disableDepthTest();
GLStateManager.glDepthFunc(GL11.GL_LEQUAL);
}
});
this.depthFunction = string;
this.func = i;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
DepthTest lv = (DepthTest)object;
return this.func == lv.func;
} else {
return false;
}
}
@Override
public int hashCode() {
return Integer.hashCode(this.func);
}
@Override
public String toString() {
return this.name + '[' + this.depthFunction + ']';
}
}
public static class Cull extends Toggleable {
public Cull(boolean culling) {
super("cull", () -> {
if (!culling) {
GLStateManager.disableCull();
}
}, () -> {
if (!culling) {
GLStateManager.enableCull();
}
}, culling);
}
}
public static class DiffuseLighting extends Toggleable {
public DiffuseLighting(boolean guiLighting) {
super("diffuse_lighting", () -> {
if (guiLighting) {
throw new RuntimeException("Not Implemented Yet");
// net.minecraft.client.drawScreen.DiffuseLighting.enable();
}
}, () -> {
if (guiLighting) {
throw new RuntimeException("Not Implemented Yet");
// net.minecraft.client.drawScreen.DiffuseLighting.disable();
}
}, guiLighting);
}
}
public static class Lightmap extends Toggleable {
public Lightmap(boolean lightmap) {
super("lightmap", () -> {}, () -> {}, lightmap);
}
}
static class Toggleable extends RenderPhase {
private final boolean enabled;
public Toggleable(String string, Runnable runnable, Runnable runnable2, boolean bl) {
super(string, runnable, runnable2);
this.enabled = bl;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
Toggleable lv = (Toggleable)object;
return this.enabled == lv.enabled;
} else {
return false;
}
}
@Override
public int hashCode() {
return Boolean.hashCode(this.enabled);
}
@Override
public String toString() {
return this.name + '[' + this.enabled + ']';
}
}
public static class Shader extends RenderPhase {
public Shader(String name, Runnable bind, Runnable release) {
super(name, bind, release);
}
}
public static class Texturing extends RenderPhase {
public Texturing(String string, Runnable runnable, Runnable runnable2) {
super(string, runnable, runnable2);
}
}
public static class Texture extends 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() {
super("texture", GLStateManager::disableTexture, GLStateManager::enableTexture);
this.id = Optional.empty();
this.bilinear = false;
this.mipmap = false;
this.unfilteredAtlas = false;
}
@Override
public boolean equals(Object object) {
if (this == object) {
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 && this.unfilteredAtlas == lv.unfilteredAtlas;
} else {
return false;
}
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public String toString() {
return this.name + '[' + this.id + "(blur=" + this.bilinear + ", mipmap=" + this.mipmap + ", unfilteredAtlas=" + this.unfilteredAtlas + ")]";
}
protected Optional<ResourceLocation> getId() {
return this.id;
}
}
public static class ShadeModel extends RenderPhase {
private final boolean smooth;
public ShadeModel(boolean smooth) {
super("shade_model",
() -> GLStateManager.glShadeModel(smooth ? GL11.GL_SMOOTH : GL11.GL_FLAT),
() -> GLStateManager.glShadeModel(GL11.GL_FLAT));
this.smooth = smooth;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
ShadeModel lv = (ShadeModel)object;
return this.smooth == lv.smooth;
} else {
return false;
}
}
@Override
public int hashCode() {
return Boolean.hashCode(this.smooth);
}
@Override
public String toString() {
return this.name + '[' + (this.smooth ? "smooth" : "flat") + ']';
}
}
public static class Alpha extends RenderPhase {
private final float alpha;
public Alpha(float alpha) {
super("alpha", () -> {
if (alpha > 0.0F) {
GLStateManager.enableAlphaTest();
GLStateManager.glAlphaFunc(GL11.GL_GREATER, alpha);
} else {
GLStateManager.disableAlphaTest();
}
}, () -> {
GLStateManager.disableAlphaTest();
GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F);
});
this.alpha = alpha;
}
@Override
public boolean equals(@Nullable Object object) {
if (this == object) {
return true;
} else if (object != null && this.getClass() == object.getClass()) {
if (!super.equals(object)) {
return false;
} else {
return this.alpha == ((Alpha)object).alpha;
}
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), this.alpha);
}
@Override
public String toString() {
return this.name + '[' + this.alpha + ']';
}
}
public static class Transparency extends RenderPhase {
private final TransparencyType transparencyType;
public Transparency(String string, Runnable runnable, Runnable runnable2) {
this(string, TransparencyType.GENERAL_TRANSPARENT, runnable, runnable2);
}
public Transparency(String string, TransparencyType transparencyType, Runnable runnable, Runnable runnable2) {
super(string, runnable, runnable2);
this.transparencyType = transparencyType;
}
public TransparencyType getTransparencyType() {
return transparencyType;
}
}
}
@@ -87,36 +87,33 @@ public class ChunkDebugMinimap {
// Save GL state
GLStateManager.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GLStateManager.glPushMatrix();
try {
// Setup rendering
GLStateManager.glScaled(2, 2, 1);
GLStateManager.glTranslated(32, 32, 0);
// Setup rendering
GLStateManager.glScaled(2, 2, 1);
GLStateManager.glTranslated(32, 32, 0);
GLStateManager.disableLighting();
GLStateManager.disableTexture();
GLStateManager.disableDepthTest();
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLStateManager.disableLighting();
GLStateManager.disableTexture();
GLStateManager.disableDepthTest();
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
final Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
final Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
final ChunkProviderClient chunkProvider = (ChunkProviderClient) mc.theWorld.getChunkProvider();
final ChunkProviderClient chunkProvider = (ChunkProviderClient) mc.theWorld.getChunkProvider();
for (int x = playerChunkX - RANGE; x < playerChunkX + RANGE; x++) {
for (int z = playerChunkZ - RANGE; z < playerChunkZ + RANGE; z++) {
drawChunk(tess, x, z, playerChunkX, playerChunkZ, manager, chunkProvider);
for (int x = playerChunkX - RANGE; x < playerChunkX + RANGE; x++) {
for (int z = playerChunkZ - RANGE; z < playerChunkZ + RANGE; z++) {
drawChunk(tess, x, z, playerChunkX, playerChunkZ, manager, chunkProvider);
}
}
tess.draw();
} finally {
GLStateManager.glPopMatrix();
GLStateManager.glPopAttrib();
}
tess.draw();
// Restore GL state
GLStateManager.enableLighting();
GLStateManager.enableDepthTest();
GLStateManager.disableBlend();
GLStateManager.glPopMatrix();
GLStateManager.glPopAttrib();
}
private void drawChunk(Tessellator tess, int chunkX, int chunkZ, int playerChunkX, int playerChunkZ, AngelicaRenderSectionManager manager, ChunkProviderClient chunkProvider) {
@@ -2,6 +2,9 @@ package com.gtnewhorizons.angelica.debug.flyby;
import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.config.SystemProperties.FlybyPacing;
import com.gtnewhorizons.angelica.debug.profiling.AsprofRecorder;
import com.gtnewhorizons.angelica.debug.profiling.AsprofRecorder.StopResult;
import com.gtnewhorizons.angelica.debug.profiling.AsprofRecorder.StopStatus;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.backend.VSyncMode;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
@@ -58,6 +61,10 @@ public final class FlybyRunner {
private boolean waitForFocus;
private boolean exitWhenDone;
private boolean startedFromProperties;
private boolean armed;
private int waitTicks;
private boolean jfr;
private long recordingId;
private final AtomicReference<FlybyRequest> pendingRequest = new AtomicReference<>();
private FlybyRequest activeRequest;
private String[] sceneCommands = NO_COMMANDS;
@@ -133,15 +140,20 @@ public final class FlybyRunner {
this.start(configured, SystemProperties.FLYBY_LENGTH, SystemProperties.FLYBY_WARMUP_TICKS, SystemProperties.FLYBY_SPEED);
this.fixedOrigin = origin;
this.waitForTracy = SystemProperties.FLYBY_WAIT_FOR_TRACY;
if (this.waitForTracy && !Tracy.ENABLED) {
LOGGER.warn("Flyby: waitForTracy requested but Tracy is disabled in this build");
this.waitForTracy = false;
}
this.waitForFocus = SystemProperties.FLYBY_WAIT_FOR_FOCUS;
this.exitWhenDone = SystemProperties.FLYBY_EXIT_WHEN_DONE;
this.jfr = SystemProperties.FLYBY_JFR;
if (!SystemProperties.FLYBY_COMMANDS.isEmpty()) {
this.sceneCommands = FlybyScene.load(SystemProperties.FLYBY_COMMANDS);
LOGGER.info("Flyby scene '{}': {} commands", SystemProperties.FLYBY_COMMANDS, this.sceneCommands.length);
}
LOGGER.info("Flyby started from properties: route={} warmup={} length={} {} ({} ticks) waitForTracy={} waitForFocus={} exitWhenDone={}",
LOGGER.info("Flyby started from properties: route={} warmup={} length={} {} ({} ticks) waitForTracy={} waitForFocus={} exitWhenDone={} jfr={}",
configured.id(), this.warmupTicks, this.runLength, configured.lengthUnit(), this.runTicks,
this.waitForTracy, this.waitForFocus, this.exitWhenDone);
this.waitForTracy, this.waitForFocus, this.exitWhenDone, this.jfr);
}
public void start(FlybyRoute route, int length, int warmupTicks, double speed) {
@@ -156,6 +168,8 @@ public final class FlybyRunner {
this.waitForTracy = false;
this.waitForFocus = false;
this.exitWhenDone = false;
this.jfr = false;
this.armed = false;
this.fixedOrigin = null;
sceneGuarded = false;
this.state = State.WAITING;
@@ -185,6 +199,11 @@ public final class FlybyRunner {
return;
}
if (mc.theWorld == null && this.armed) {
this.restorePauseOnLostFocus(mc);
this.armed = false;
}
if (this.state == State.EXITING) {
if (++this.tick >= EXIT_TICKS) {
this.state = State.DONE;
@@ -198,8 +217,21 @@ public final class FlybyRunner {
switch (this.state) {
case WAITING -> {
if (this.waitForTracy && !Tracy.isConnected()) return;
if (this.waitForFocus && !Display.isActive()) return;
if (!this.armed) {
this.armed = true;
this.waitTicks = 0;
this.overridePauseOnLostFocus(mc);
}
if (mc.currentScreen != null) mc.displayGuiScreen(null);
if (this.waitForTracy && !Tracy.isConnected()) {
if (this.waitTicks++ % 100 == 0) LOGGER.info("Flyby waiting for Tracy connection");
return;
}
if (this.waitForFocus && !Display.isActive()) {
if (this.waitTicks++ % 100 == 0) LOGGER.info("Flyby waiting for window focus");
return;
}
this.begin(mc, player);
}
case PREPARING -> {
@@ -210,6 +242,17 @@ public final class FlybyRunner {
}
case WARMUP -> {
this.applyPosition(player, 0);
if (this.jfr && this.tick == Math.max(0, this.warmupTicks - 40)) {
final String error;
synchronized (AsprofRecorder.class) {
error = AsprofRecorder.start(this.route.id(), SystemProperties.PROFILE_OPTS);
if (error == null) this.recordingId = AsprofRecorder.recordingId();
}
if (error != null) {
LOGGER.warn("Flyby: failed to start async-profiler: {}", error);
player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[Angelica] Flyby: failed to start async-profiler: " + error));
}
}
if (++this.tick >= this.warmupTicks) {
this.tick = 0;
this.beginMeasuring(mc);
@@ -247,15 +290,18 @@ public final class FlybyRunner {
this.lastFrameNs = now;
}
private void overridePauseOnLostFocus(Minecraft mc) {
if (this.pauseOnLostFocusOverridden) return;
this.pauseOnLostFocusSaved = mc.gameSettings.pauseOnLostFocus;
this.pauseOnLostFocusOverridden = true;
mc.gameSettings.pauseOnLostFocus = false;
}
private void begin(Minecraft mc, EntityClientPlayerMP player) {
if (mc.currentScreen != null) {
mc.displayGuiScreen(null);
}
if (!this.pauseOnLostFocusOverridden) {
this.pauseOnLostFocusSaved = mc.gameSettings.pauseOnLostFocus;
this.pauseOnLostFocusOverridden = true;
mc.gameSettings.pauseOnLostFocus = false;
}
this.overridePauseOnLostFocus(mc);
this.parkedX = player.posX;
this.parkedY = player.posY;
@@ -638,6 +684,24 @@ public final class FlybyRunner {
mc.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.AQUA + "[Angelica] " + EnumChatFormatting.WHITE + summary));
}
this.stopRecording(mc);
}
private void stopRecording(Minecraft mc) {
final long ownedId = this.recordingId;
this.recordingId = 0;
final StopResult result = AsprofRecorder.stopIfRecording(ownedId);
if (result.status() == StopStatus.NO_MATCH) return;
final boolean failed = result.status() == StopStatus.FAILED;
final String message = failed ? "Flyby: failed to stop async-profiler: " + result.error()
: "Flyby: profile written to " + result.path();
if (failed) LOGGER.warn(message);
else LOGGER.info(message);
if (mc.thePlayer != null) {
mc.thePlayer.addChatMessage(new ChatComponentText((failed ? EnumChatFormatting.RED : EnumChatFormatting.AQUA)
+ "[Angelica] " + message));
}
if (Tracy.ENABLED) Tracy.message(message);
}
private void teardown(Minecraft mc, EntityClientPlayerMP player) {
@@ -645,6 +709,7 @@ public final class FlybyRunner {
this.returnToOrigin(player);
this.restorePauseOnLostFocus(mc);
this.armed = false;
sceneGuarded = false;
this.sceneClearRequested = this.sceneCommands.length > 0;
this.restorePacing(mc);
@@ -654,6 +719,7 @@ public final class FlybyRunner {
}
private void exitGame(Minecraft mc) {
this.stopRecording(mc);
LOGGER.info("Flyby complete, shutting down.");
if (mc.theWorld != null) {
mc.theWorld.sendQuittingDisconnectingPacket();
@@ -727,6 +793,8 @@ public final class FlybyRunner {
FramePacer.endStats();
final Minecraft mc = Minecraft.getMinecraft();
this.restorePauseOnLostFocus(mc);
this.armed = false;
this.stopRecording(mc);
this.pendingRequest.set(null);
this.activeRequest = null;
sceneGuarded = false;
@@ -0,0 +1,206 @@
package com.gtnewhorizons.angelica.debug.profiling;
import com.gtnewhorizons.angelica.config.SystemProperties;
import one.profiler.AsyncProfiler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public final class AsprofRecorder {
private static final Logger LOGGER = LogManager.getLogger("Angelica/Asprof");
private static boolean availabilityChecked;
private static boolean availabilityValue;
private static final Session SESSION = new Session(Asprof::execute);
private static boolean shutdownHookRegistered;
private AsprofRecorder() {}
public static synchronized boolean available() {
if (!availabilityChecked) {
availabilityChecked = true;
availabilityValue = computeAvailable();
}
return availabilityValue;
}
private static boolean computeAvailable() {
if (!SystemProperties.debugTooling()) return false;
final String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
if (!(os.contains("mac") || os.contains("linux"))) return false;
return AsprofRecorder.class.getResource("/one/profiler/AsyncProfiler.class") != null;
}
public static synchronized String start(String tag, String opts) {
if (!available()) return "async-profiler is not available on this platform/build";
if (SESSION.recordingId() != 0) return "already recording to " + SESSION.outputPath();
File file = SystemProperties.PROFILE_OUTPUT.isEmpty() ? new File(SystemProperties.PROFILE_DIR, fileName(tag, System.currentTimeMillis())) : new File(SystemProperties.PROFILE_OUTPUT);
file = file.getAbsoluteFile();
if (file.exists()) return "output file already exists: " + file.getPath();
final File parent = file.getParentFile();
if (parent != null) parent.mkdirs();
final String command = command(opts, file.getPath());
LOGGER.info("async-profiler: {}", command);
try {
SESSION.start(file.getPath(), command);
} catch (Throwable t) {
return handleFailure(t);
}
ensureShutdownHook();
return null;
}
public static synchronized String stop() {
final StopResult result = completeStop(SESSION.stop());
if (result.status() == StopStatus.NO_MATCH) return "not recording";
return result.error();
}
public static synchronized long recordingId() {
return SESSION.recordingId();
}
public static synchronized StopResult stopIfRecording(long expectedId) {
return completeStop(SESSION.stopIfRecording(expectedId));
}
private static StopResult completeStop(StopResult result) {
if (result.status() == StopStatus.FAILED) {
handleFailure(result.failure());
} else if (result.status() == StopStatus.STOPPED) {
LOGGER.info("Profile written: {} ({} bytes)", result.path(), new File(result.path()).length());
}
return result;
}
public static synchronized String status() {
if (!available()) return "async-profiler is not available on this platform/build";
try {
return SESSION.status();
} catch (Throwable t) {
return handleFailure(t);
}
}
public static synchronized boolean isRecording() {
return SESSION.recordingId() != 0;
}
public static synchronized String outputPath() {
return SESSION.outputPath();
}
private static void ensureShutdownHook() {
if (shutdownHookRegistered) return;
shutdownHookRegistered = true;
Runtime.getRuntime().addShutdownHook(new Thread(AsprofRecorder::shutdownStop, "Asprof-Shutdown"));
}
private static synchronized void shutdownStop() {
completeStop(SESSION.stop());
}
private static String handleFailure(Throwable t) {
LOGGER.warn("async-profiler command failed", t);
if (t instanceof LinkageError || t instanceof UnsupportedOperationException) {
availabilityChecked = true;
availabilityValue = false;
}
return firstLine(String.valueOf(t.getMessage()));
}
static String command(String opts, String file) {
return opts.isEmpty() ? "start,jfr,file=" + file : "start,jfr," + opts + ",file=" + file;
}
static String fileName(String tag, long nowMillis) {
final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ROOT);
return "angelica-" + tag + "-" + format.format(new Date(nowMillis)) + ".jfr";
}
static String firstLine(String s) {
if (s == null || s.isEmpty()) return "";
final int newline = s.indexOf('\n');
final String line = newline < 0 ? s : s.substring(0, newline);
return line.trim();
}
public enum StopStatus { NO_MATCH, STOPPED, FAILED }
public record StopResult(StopStatus status, String path, Throwable failure) {
private static final StopResult NO_MATCH = new StopResult(StopStatus.NO_MATCH, null, null);
public String error() {
return failure == null ? null : AsprofRecorder.firstLine(String.valueOf(failure.getMessage()));
}
}
static final class Session {
@FunctionalInterface
interface CommandExecutor {
String execute(String command) throws Throwable;
}
private final CommandExecutor executor;
private long lastId;
private long recordingId;
private String path;
Session(CommandExecutor executor) {
this.executor = executor;
}
synchronized long start(String path, String command) throws Throwable {
if (recordingId != 0) throw new IllegalStateException("already recording to " + this.path);
if (lastId == Long.MAX_VALUE) throw new IllegalStateException("recording identity exhausted");
executor.execute(command);
this.path = path;
recordingId = ++lastId;
return recordingId;
}
synchronized long recordingId() {
return recordingId;
}
synchronized String outputPath() {
return path;
}
synchronized String status() throws Throwable {
return executor.execute("status");
}
synchronized StopResult stop() {
return stopIfRecording(recordingId);
}
synchronized StopResult stopIfRecording(long expectedId) {
if (expectedId == 0 || recordingId != expectedId) return StopResult.NO_MATCH;
final String stoppedPath = path;
Throwable failure = null;
try {
executor.execute("stop");
} catch (Throwable t) {
failure = t;
}
recordingId = 0;
path = null;
return new StopResult(failure == null ? StopStatus.STOPPED : StopStatus.FAILED, stoppedPath, failure);
}
}
private static final class Asprof {
static String execute(String cmd) throws Throwable {
return AsyncProfiler.getInstance().execute(cmd);
}
}
}
@@ -5,7 +5,7 @@ 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;
import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import net.coderbot.iris.Iris;
import net.minecraft.client.Minecraft;
@@ -70,7 +70,7 @@ public final class ImmediateExtendedAttribs implements ImmediateExtendedAttribHa
programWantsExtCache.clear();
ItemRenderListManager.clearCache();
FfpExtendedAttribs.reset();
TesrBatchRenderer.INSTANCE.clearRetained();
TesrLifecycle.reset();
}
private final Vector3f normal = new Vector3f();
@@ -10,8 +10,6 @@ import com.gtnewhorizons.angelica.glsm.hooks.ShaderTransformPostProcessor;
import com.gtnewhorizons.angelica.glsm.shader.ShaderType;
import org.taumc.glsl.grammar.GLSLParser;
import com.gtnewhorizons.angelica.glsm.hooks.ShaderWorkSubmitter;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaBooleanLayer;
import com.gtnewhorizons.angelica.glsm.hooks.VanillaStateLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.sdlgpu.SDLGPUGate;
import net.coderbot.iris.Iris;
@@ -89,44 +87,6 @@ public class IrisGLSMBridge {
};
}
private static VanillaBooleanLayer gated(VanillaBooleanLayer layer) {
return new VanillaBooleanLayer() {
@Override
public boolean isOverrideHeld() {
return Iris.enabled && layer.isOverrideHeld();
}
@Override
public boolean getVanilla() {
return layer.getVanilla();
}
@Override
public void setVanilla(boolean enabled) {
layer.setVanilla(enabled);
}
};
}
private static <T> VanillaStateLayer<T> gated(VanillaStateLayer<T> layer) {
return new VanillaStateLayer<>() {
@Override
public boolean isOverrideHeld() {
return Iris.enabled && layer.isOverrideHeld();
}
@Override
public void readVanilla(T into) {
layer.readVanilla(into);
}
@Override
public void writeVanilla(T from) {
layer.writeVanilla(from);
}
};
}
public static void register() {
GLSMConfig.expandVertexFormats = Iris.enabled;
IrisSamplers.initRenderer();
@@ -164,12 +124,12 @@ public class IrisGLSMBridge {
}
};
GLStateManager.getBlendMode().setVanillaLayer(gated(BlendModeStorage.ENABLE_LAYER));
GLStateManager.getBlendState().setVanillaLayer(gated(BlendModeStorage.FUNC_LAYER));
GLStateManager.getAlphaTest().setVanillaLayer(gated(AlphaTestStorage.ENABLE_LAYER));
GLStateManager.getAlphaState().setVanillaLayer(gated(AlphaTestStorage.FUNC_LAYER));
GLStateManager.getDepthState().setVanillaLayer(gated(DepthColorStorage.DEPTH_LAYER));
GLStateManager.getColorMask().setVanillaLayer(gated(DepthColorStorage.COLOR_LAYER));
GLStateManager.getBlendMode().setVanillaLayer(BlendModeStorage.ENABLE_LAYER);
GLStateManager.getBlendState().setVanillaLayer(BlendModeStorage.FUNC_LAYER);
GLStateManager.getAlphaTest().setVanillaLayer(AlphaTestStorage.ENABLE_LAYER);
GLStateManager.getAlphaState().setVanillaLayer(AlphaTestStorage.FUNC_LAYER);
GLStateManager.getDepthState().setVanillaLayer(DepthColorStorage.DEPTH_LAYER);
GLStateManager.getColorMask().setVanillaLayer(DepthColorStorage.COLOR_LAYER);
GLSMHooks.alphaHandler = new DeferredAlphaHandler() {
@Override
@@ -178,13 +138,13 @@ public class IrisGLSMBridge {
}
@Override
public void deferAlphaTestToggle(boolean enabled) {
AlphaTestStorage.deferAlphaTestToggle(enabled);
public boolean deferAlphaTestToggle(boolean enabled) {
return AlphaTestStorage.deferAlphaTestToggle(enabled);
}
@Override
public void deferAlphaFunc(int function, float reference) {
AlphaTestStorage.deferAlphaFunc(function, reference);
public boolean deferAlphaFunc(int function, float reference) {
return AlphaTestStorage.deferAlphaFunc(function, reference);
}
};
@@ -91,7 +91,7 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix
if (SDLGPUGate.isSDLGPUAvailable()) {
LOGGER.info("SDL GPU window mode enabled");
} else {
LOGGER.warn("angelica.sdlgpu.enable=true but SDL GPU dependencies not available, falling back to GL");
LOGGER.warn("SDL GPU disabled, running on OpenGL: {}", SDLGPUGate.missingRequirement());
}
}
@@ -35,6 +35,11 @@ public final class TracyFramePlots {
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_GLSM_BRACKETS = new PlotDelta("glsm.brackets");
private static final PlotDelta P_GLSM_COW_SLOTS = new PlotDelta("glsm.cowSlots");
private static final PlotDelta P_GLSM_POP_RESTORES = new PlotDelta("glsm.popRestores");
private static final PlotDelta P_GLSM_POP_GL_CALLS = new PlotDelta("glsm.popGLCalls");
private static final PlotDelta P_GLSM_POP_DISCARDS = new PlotDelta("glsm.popDiscards");
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");
@@ -176,6 +181,11 @@ public final class TracyFramePlots {
P_GL_DRAW_CALLS.plot(GLStateManager.drawCalls);
P_GL_TEX_BIND_MISSES.plot(GLStateManager.texBindMisses);
P_GL_PROGRAM_SWITCHES.plot(GLStateManager.programSwitches);
P_GLSM_BRACKETS.plot(GLStateManager.attribPushes);
P_GLSM_COW_SLOTS.plot(GLStateManager.attribSlotsSaved);
P_GLSM_POP_RESTORES.plot(GLStateManager.attribValueRestores);
P_GLSM_POP_GL_CALLS.plot(GLStateManager.attribBackendCalls);
P_GLSM_POP_DISCARDS.plot(GLStateManager.attribDiscards);
P_GL_LIST_PLAYBACKS.plot(DisplayListManager.listPlaybacks);
P_GL_STREAMED_BYTES.plot(TessellatorStreamingDrawer.streamedBytes);
P_GL_STREAM_DRAWS.plot(TessellatorStreamingDrawer.streamDraws);
@@ -74,6 +74,7 @@ import com.gtnewhorizons.angelica.rendering.celeritas.threading.DefaultChunkTask
import com.gtnewhorizons.angelica.rendering.celeritas.threading.ThreadedChunkTaskProvider;
import com.gtnewhorizons.angelica.rendering.items.BlockRenderListManager;
import com.gtnewhorizons.angelica.rendering.items.ItemRenderListManager;
import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle;
import com.gtnewhorizons.angelica.utils.AnimationMode;
import com.gtnewhorizons.angelica.utils.ManagedEnum;
import com.gtnewhorizons.angelica.zoom.Zoom;
@@ -253,6 +254,7 @@ public final class ClientProxy extends CommonProxy {
Tracy.sectionLeave(this.worldSection);
this.worldSection = 0L;
DynamicLights.get().removeAllLightSources();
TesrLifecycle.reset();
GpuCulling.onWorldUnload();
}
@@ -5,15 +5,14 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.QuadConverter;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.states.ColorMask;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfo;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.mixins.interfaces.ModelBoxQuads;
import com.gtnewhorizons.angelica.rendering.tesr.PassRebindGate;
import lombok.Getter;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.blending.DepthColorStorage;
import net.coderbot.iris.gl.image.GlImage;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.uniforms.CapturedRenderingState;
@@ -324,28 +323,19 @@ public final class PlayerReflectionCapture {
if (skin64Valid) GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, skin64Tex);
}
final boolean maskable = !DepthColorStorage.isDepthColorLocked();
final ColorMask prevColor = GLStateManager.getColorMask();
final boolean pr = prevColor.red, pg = prevColor.green, pb = prevColor.blue, pa = prevColor.alpha;
final boolean prevDepthWrite = GLStateManager.getDepthState().isEnabled();
final int prevEntityId = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity();
final int prevItemId = CapturedRenderingState.INSTANCE.getCurrentRenderedItem();
savedModelView.set(GLStateManager.getModelViewMatrix());
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(pendingEntityId, pendingItemId);
GLStateManager.setModelViewMatrix(pendingModelView);
if (maskable) {
GLStateManager.glColorMask(false, false, false, false);
GLStateManager.glDepthMask(false);
}
final int maskStateDepth = GLStateManager.pushState(StateSet.MASKS);
GLStateManager.glColorMask(false, false, false, false);
GLStateManager.glDepthMask(false);
try {
QuadConverter.drawQuadsAsTriangles(0, VERTEX_COUNT);
} finally {
if (maskable) {
GLStateManager.glDepthMask(prevDepthWrite);
GLStateManager.glColorMask(pr, pg, pb, pa);
}
GLStateManager.popStateTo(maskStateDepth);
GLStateManager.setModelViewMatrix(savedModelView);
CapturedRenderingState.INSTANCE.setCurrentEntityAndItem(prevEntityId, prevItemId);
@@ -0,0 +1,22 @@
package com.gtnewhorizons.angelica.rendering;
public final class RenderFailures {
private RenderFailures() {}
public static Throwable suppress(Throwable failure, Throwable cleanup) {
if (failure == null) return cleanup;
if (failure != cleanup) failure.addSuppressed(cleanup);
return failure;
}
public static <T extends Throwable> void rethrow(Throwable failure) throws T {
if (failure != null) throw (T) failure;
}
public static void rethrowWrapped(Throwable failure) {
if (failure == null) return;
if (failure instanceof RuntimeException runtime) throw runtime;
if (failure instanceof Error error) throw error;
throw new RuntimeException(failure);
}
}
@@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas;
import com.google.common.collect.ImmutableListMultimap;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.utils.SpritePadding;
import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap;
import lombok.Getter;
@@ -95,8 +96,7 @@ public class AngelicaRenderPassConfiguration {
private static final class AngelicaPipelineState implements TerrainRenderPass.PipelineState {
private final int pass;
private final boolean disableAlphaTest;
private int savedAlphaFunction;
private float savedAlphaReference;
private int alphaStateDepth = -1;
private AngelicaPipelineState(int pass, boolean disableAlphaTest) {
this.pass = pass;
@@ -108,9 +108,11 @@ public class AngelicaRenderPassConfiguration {
GLStateManager.glDepthMask(true);
if (pass == 0) {
final var alphaState = GLStateManager.getAlphaState();
savedAlphaFunction = alphaState.getFunction();
savedAlphaReference = alphaState.getReference();
if (alphaStateDepth >= 0) {
GLStateManager.popStateTo(alphaStateDepth);
alphaStateDepth = -1;
}
alphaStateDepth = GLStateManager.pushState(StateSet.ALPHA);
GLStateManager.glAlphaFunc(GL11.GL_GREATER, AlphaCutoffParameter.HALF.cutoff());
}
if (disableAlphaTest) {
@@ -120,8 +122,9 @@ public class AngelicaRenderPassConfiguration {
@Override
public void clear() {
if (pass == 0) {
GLStateManager.glAlphaFunc(savedAlphaFunction, savedAlphaReference);
if (alphaStateDepth >= 0) {
GLStateManager.popStateTo(alphaStateDepth);
alphaStateDepth = -1;
}
if (disableAlphaTest) {
GLStateManager.enableAlphaTest();
@@ -6,7 +6,6 @@ import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.gtnewhorizons.angelica.compat.bop.BopFogBlend;
import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient;
@@ -54,13 +53,14 @@ 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.culling.GpuTerrainCuller;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle;
import net.coderbot.iris.pipeline.ShadowRenderer;
public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, AngelicaRenderSectionManager, BlockRenderLayer, TileEntity, CeleritasWorldRenderer.TileEntityRenderContext> implements IDynamicLightWorldRenderer {
@@ -167,12 +167,9 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
this.sortedTileEntities.clear();
ShadowRenderer.visibleTileEntities.clear();
ShadowRenderer.globalTileEntities.clear();
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
ParticleInstancer.clear();
TesrLifecycle.reset();
GpuCulling.onWorldUnload();
FfpExtendedAttribs.reset();
BopFogBlend.invalidate();
FogBiomeCache.invalidate();
super.unloadWorld();
}
@@ -289,6 +286,15 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
super.setupTerrain(viewport, cameraState, frame, spectator, updateChunksImmediately);
if (!renderSectionManager.isInShadowPass()) {
final GpuTerrainCuller terrainCuller = GpuTerrainCuller.activeInstance();
if (terrainCuller != null) {
terrainCuller.prepareAllPasses(createChunkRenderMatrices(), renderSectionManager.getRenderLists(),
viewport.getTransform(), cameraTransform(cameraState.x(), cameraState.y(), cameraState.z()),
IrisShaderProviderHolder.shouldUseFaceCulling());
}
}
// Process deferred dynamic light chunk rebuilds with frustum culling
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(viewport);
@@ -357,6 +363,17 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
private CameraTransform cachedCameraTransform;
private double cachedCamX, cachedCamY, cachedCamZ;
private CameraTransform cameraTransform(double x, double y, double z) {
CameraTransform camera = cachedCameraTransform;
if (camera == null || cachedCamX != x || cachedCamY != y || cachedCamZ != z) {
camera = cachedCameraTransform = new CameraTransform(x, y, z);
cachedCamX = x;
cachedCamY = y;
cachedCamZ = z;
}
return camera;
}
@Override
public void drawChunkLayer(BlockRenderLayer renderLayer, double x, double y, double z) {
if (DEBUG_WIREFRAME_MODE) {
@@ -366,13 +383,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
final ChunkRenderMatrices matrices = createChunkRenderMatrices();
final Collection<TerrainRenderPass> passes = this.renderSectionManager.getRenderPassConfiguration().vanillaRenderStages().get(renderLayer);
if (passes != null && !passes.isEmpty()) {
CameraTransform realCamera = cachedCameraTransform;
if (realCamera == null || cachedCamX != x || cachedCamY != y || cachedCamZ != z) {
realCamera = cachedCameraTransform = new CameraTransform(x, y, z);
cachedCamX = x;
cachedCamY = y;
cachedCamZ = z;
}
final CameraTransform realCamera = cameraTransform(x, y, z);
final CameraTransform occlusionCamera = this.getLastViewport().getTransform();
for (final TerrainRenderPass pass : passes) {
this.renderSectionManager.renderLayer(matrices, pass, occlusionCamera, realCamera);
@@ -105,12 +105,23 @@ public final class GpuTerrainCuller {
private final PassState primaryPass = new PassState();
private final PassState secondPass = new PassState();
private final PassState sortedPass = new PassState();
private PassState buildPass = primaryPass;
private PassState current = primaryPass;
private boolean secondPrepared;
private boolean primaryReady;
private TerrainRenderPass preparedPrimaryPass;
private boolean translucentReady;
private ChunkRenderListIterable preparedRenderLists;
private int totalAppendedEntries;
@Getter private boolean computeActiveThisPass;
private static GpuTerrainCuller activeInstance;
public static GpuTerrainCuller activeInstance() {
return activeInstance;
}
private int currentDrawStart;
private int currentDrawCount;
private boolean indirectBufferBound;
@@ -136,9 +147,20 @@ public final class GpuTerrainCuller {
if (Tracy.ENABLED) TerrainDrawStats.recordSectionMetaBytes(bytes);
return true;
};
activeInstance = this;
}
private void invalidatePreparedPasses() {
preparedRenderLists = null;
preparedPrimaryPass = null;
primaryReady = false;
secondPrepared = false;
translucentReady = false;
computeActiveThisPass = false;
}
void beginCullPass(int indexPointerMask) {
invalidatePreparedPasses();
this.computeActiveThisPass = GpuCulling.mode().computeEnabled();
this.totalAppendedEntries = 0;
this.secondPrepared = false;
@@ -222,11 +244,14 @@ public final class GpuTerrainCuller {
currentDrawStart = 0;
currentDrawCount = 0;
if (current == secondPass) secondPrepared = false;
else if (current == primaryPass) primaryReady = false;
else if (current == sortedPass) translucentReady = false;
}
private void dispatchPreparedPasses() {
if (!computeActiveThisPass || totalAppendedEntries == 0) return;
if (!needsDispatch(primaryPass) && (!secondPrepared || !needsDispatch(secondPass))) return;
if (!needsDispatch(primaryPass) && (!secondPrepared || !needsDispatch(secondPass))
&& (!translucentReady || !needsDispatch(sortedPass))) return;
if (!culler.ensureReady()) return;
if (frustumUboBytes == null) {
LOG.warn("GpuTerrainCuller: frustum UBO not set before dispatch; skipping cull");
@@ -242,6 +267,7 @@ public final class GpuTerrainCuller {
try {
dispatchPass(primaryPass);
if (secondPrepared) dispatchPass(secondPass);
if (translucentReady) dispatchPass(sortedPass);
} finally {
BackendManager.RENDER_BACKEND.endComputeDispatchBatch();
}
@@ -289,12 +315,54 @@ public final class GpuTerrainCuller {
}
public void beginRenderPass(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, boolean useBlockFaceCulling) {
if (renderPass == AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS && renderLists.hasPass(renderPass)
&& selectPreparedSecondPass()) {
if (renderLists == preparedRenderLists && renderLists.hasPass(renderPass)) {
if (renderPass == preparedPrimaryPass && selectPreparedPrimaryPass()) return;
if (renderPass == AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS && selectPreparedSecondPass()) return;
if (renderPass == AngelicaRenderPassConfiguration.TRANSLUCENT_PASS && selectPreparedSortedPass()) return;
}
if (!renderLists.hasPass(renderPass)) {
if (renderLists != preparedRenderLists) invalidatePreparedPasses();
current = null;
return;
}
if (!renderLists.hasPass(renderPass)) return;
walkPrimaryGroup(matrices, renderLists, renderPass, occlusionCamera, camera, useBlockFaceCulling);
preparedRenderLists = renderLists;
preparedPrimaryPass = renderPass;
primaryReady = true;
}
boolean selectPreparedPrimaryPass() {
if (!primaryReady || !computeActiveThisPass) return false;
this.current = primaryPass;
this.currentDrawStart = 0;
this.currentDrawCount = 0;
return true;
}
boolean selectPreparedSortedPass() {
if (!translucentReady || !computeActiveThisPass) return false;
this.current = sortedPass;
this.currentDrawStart = 0;
this.currentDrawCount = 0;
return true;
}
void startSortedPass(int mask) {
if (!secondPrepared) primaryPass.entryCount = totalAppendedEntries - primaryPass.entryBase;
sortedPass.reset(mask, totalAppendedEntries);
this.buildPass = sortedPass;
this.current = sortedPass;
}
void finishSortedPass() {
sortedPass.entryCount = totalAppendedEntries - sortedPass.entryBase;
this.translucentReady = true;
this.buildPass = primaryPass;
this.current = primaryPass;
}
private void walkPrimaryGroup(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, CameraTransform camera, boolean useBlockFaceCulling) {
final boolean combined = renderPass == AngelicaRenderPassConfiguration.SOLID_PASS && AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS);
final int indexPointerMask = renderPass.isSorted() ? 0xFFFFFFFF : 0;
@@ -310,6 +378,23 @@ public final class GpuTerrainCuller {
return;
}
prepareFrustumUbo(matrices, camera);
syncSectionMetaIfDirty();
walkPass(renderLists, renderPass, occlusionCamera, useBlockFaceCulling);
if (combined) {
startSecondPass();
walkPass(renderLists, AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS, occlusionCamera, useBlockFaceCulling);
finishCombinedBuild();
}
if (walkPrimitiveType != null) {
FrustumExtractor.patchPrimitiveRatio(walkPrimitiveType.getVerticesPerPrimitive(), walkPrimitiveType.getIndexBufferElementsPerPrimitive(), uboBytes);
}
}
private void prepareFrustumUbo(ChunkRenderMatrices matrices, CameraTransform camera) {
if (uboBytes == null) {
uboBytes = FrustumExtractor.allocateUboByteBuffer();
}
@@ -328,19 +413,61 @@ public final class GpuTerrainCuller {
FrustumExtractor.patchBypassFrustum(shadow, uboBytes);
frustumUboBytes = uboBytes;
}
syncSectionMetaIfDirty();
public void prepareAllPasses(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, CameraTransform occlusionCamera, CameraTransform camera, boolean useBlockFaceCulling) {
invalidatePreparedPasses();
walkPass(renderLists, renderPass, occlusionCamera, useBlockFaceCulling);
if (combined) {
startSecondPass();
walkPass(renderLists, AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS, occlusionCamera, useBlockFaceCulling);
finishCombinedBuild();
final boolean hasSolid = AngelicaRenderPassConfiguration.SOLID_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.SOLID_PASS);
final boolean hasCutout = AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS);
final boolean hasTranslucent = AngelicaRenderPassConfiguration.TRANSLUCENT_PASS != null && renderLists.hasPass(AngelicaRenderPassConfiguration.TRANSLUCENT_PASS);
final TerrainRenderPass primary = hasSolid ? AngelicaRenderPassConfiguration.SOLID_PASS : hasCutout ? AngelicaRenderPassConfiguration.CUTOUT_MIPPED_PASS : null;
if (primary == null && !hasTranslucent) return;
try {
if (primary != null) {
walkPrimaryGroup(matrices, renderLists, primary, occlusionCamera, camera, useBlockFaceCulling);
}
if (hasTranslucent) {
walkSortedGroup(matrices, renderLists, occlusionCamera, camera, useBlockFaceCulling, primary != null);
}
dispatchPreparedPasses();
preparedRenderLists = renderLists;
preparedPrimaryPass = primary;
primaryReady = primary != null;
} catch (RuntimeException | Error failure) {
invalidatePreparedPasses();
throw failure;
}
}
private void walkSortedGroup(ChunkRenderMatrices matrices, ChunkRenderListIterable renderLists, CameraTransform occlusionCamera, CameraTransform camera, boolean useBlockFaceCulling, boolean chained) {
if (chained) {
startSortedPass(0xFFFFFFFF);
} else {
invalidatePreparedPasses();
computeActiveThisPass = GpuCulling.mode().computeEnabled();
totalAppendedEntries = 0;
secondPrepared = false;
passOutputBase = 0;
walkPrimitiveType = null;
primaryPass.reset(0, 0);
sortedPass.reset(0xFFFFFFFF, 0);
buildPass = sortedPass;
current = sortedPass;
}
if (walkPrimitiveType != null) {
FrustumExtractor.patchPrimitiveRatio(walkPrimitiveType.getVerticesPerPrimitive(), walkPrimitiveType.getIndexBufferElementsPerPrimitive(), uboBytes);
if (computeActiveThisPass) {
prepareFrustumUbo(matrices, camera);
syncSectionMetaIfDirty();
walkPass(renderLists, AngelicaRenderPassConfiguration.TRANSLUCENT_PASS, occlusionCamera, useBlockFaceCulling);
if (walkPrimitiveType != null) {
FrustumExtractor.patchPrimitiveRatio(walkPrimitiveType.getVerticesPerPrimitive(), walkPrimitiveType.getIndexBufferElementsPerPrimitive(), uboBytes);
}
}
finishSortedPass();
}
private void walkPass(ChunkRenderListIterable renderLists, TerrainRenderPass renderPass, CameraTransform occlusionCamera, boolean useBlockFaceCulling) {
@@ -497,7 +624,7 @@ public final class GpuTerrainCuller {
void drawRegionRange(CommandList commandList, GlTessellation tessellation, GlPrimitiveType primitiveType, int drawStart, int drawCount) {
if (drawCount == 0) return;
dispatchPreparedPasses();
if (!current.dispatched) dispatchPreparedPasses();
if (!current.dispatched) return;
if (Tracy.ENABLED) {
@@ -539,5 +666,8 @@ public final class GpuTerrainCuller {
uboBytes = null;
primaryPass.releaseRanges();
secondPass.releaseRanges();
sortedPass.releaseRanges();
invalidatePreparedPasses();
if (activeInstance == this) activeInstance = null;
}
}
@@ -1,7 +1,9 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.ParticleInstancedAttribs;
@@ -43,7 +45,7 @@ public final class ParticleInstancer {
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 int restoreDepth = -1;
private static final Matrix4f LAYER_MV = new Matrix4f();
private static final Object[] ORIGINAL_ARGS = new Object[8];
@@ -61,6 +63,7 @@ public final class ParticleInstancer {
private static DeferredWorldRenderingPipeline unavailableFor;
private static DeferredWorldRenderingPipeline deferred;
private static Tessellator run;
private static boolean ringUsedThisLayer;
private static float rotX;
private static float rotXZ;
@@ -175,33 +178,63 @@ public final class ParticleInstancer {
}
public static void endLayer() {
layerStarted = false;
if (!layerActive) {
layerStarted = false;
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);
Throwable failure = null;
ringUsedThisLayer = false;
try {
if (groupCount > 0) {
restoreDepth = GLStateManager.pushState(StateSet.BATCH);
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);
}
}
} catch (Throwable t) {
failure = t;
} finally {
if (restoreDepth >= 0) {
try {
GLStateManager.popStateTo(restoreDepth);
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
} finally {
restoreDepth = -1;
}
if (deferred != null) {
try {
GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent());
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
}
}
if (ringUsedThisLayer) {
try {
ring().postDraw();
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
}
for (int i = 0; i < groupCount; i++) {
final Group group = GROUP_POOL.get(i);
if (group.translucent) flush(group);
final ByteBuffer list = GROUP_POOL.get(i).list;
if (list != null) list.clear();
}
RESTORE.apply();
if (deferred != null) {
GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent());
}
ring().postDraw();
groupCount = 0;
deferred = null;
run = null;
layerStarted = false;
ringUsedThisLayer = false;
}
deferred = null;
run = null;
RenderFailures.rethrowWrapped(failure);
}
private static Group groupFor(ParticleRenderState state, boolean translucent) {
@@ -225,6 +258,7 @@ public final class ParticleInstancer {
run = null;
unavailableFor = null;
groupCount = 0;
ringUsedThisLayer = false;
for (int i = 0; i < GROUP_POOL.size(); i++) {
GROUP_POOL.get(i).list = null;
}
@@ -286,6 +320,7 @@ public final class ParticleInstancer {
}
}
ringUsedThisLayer = true;
final long base = ring().upload(list, STRIDE);
list.clear();
@@ -309,19 +344,23 @@ public final class ParticleInstancer {
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++;
try {
if (ffp) GLStateManager.ffpInstancing = Instancing.PARTICLE;
GLStateManager.glDrawArraysInstanced(GL11.GL_QUADS, 0, ParticleQuadMesh.VERTEX_COUNT, count);
draws++;
} finally {
GLStateManager.ffpInstancing = Instancing.NONE;
GLStateManager.glBindVertexArray(0);
}
}
private static void drawInstancesCpu(ParticleRenderState state, ByteBuffer list, int count, boolean listTranslucent) {
final Tessellator t = run;
RESTORE.apply();
GLStateManager.popStateTo(restoreDepth);
GbufferPrograms.setTranslucencyDeclaration(ParticleRunSplitter.currentRunTranslucent());
t.draw();
t.startDrawingQuads();
restoreDepth = GLStateManager.pushState(StateSet.BATCH);
GbufferPrograms.setTranslucencyDeclaration(listTranslucent);
state.apply();
for (int i = 0; i < count; i++) {
@@ -1,11 +1,13 @@
package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import org.lwjgl.opengl.GL11;
public final class ParticleRenderState {
private final BlendState scratch = new BlendState();
public int texture;
public boolean blend;
public int blendSrc;
@@ -16,13 +18,13 @@ public final class ParticleRenderState {
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();
blend = GLStateManager.isEffectiveBlendEnabled();
GLStateManager.getEffectiveBlendState(scratch);
blendSrc = scratch.getSrcRgb();
blendDst = scratch.getDstRgb();
blendSrcAlpha = scratch.getSrcAlpha();
blendDstAlpha = scratch.getDstAlpha();
depthMask = GLStateManager.isEffectiveDepthMaskEnabled();
}
public void set(ParticleRenderState other) {
@@ -0,0 +1,204 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import it.unimi.dsi.fastutil.Hash;
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet;
import lombok.Getter;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
public final class DrawState {
public static final int DISABLED = 0;
public static final int CULL_BACK = 1;
public static final int CULL_FRONT = 2;
public static final int CULL_BOTH = 3;
public static final int OPAQUE = 0;
public static final int TRANSLUCENT = 1;
public static final int ADDITIVE = 2;
public static final int ADDITIVE_ALPHA = 3;
public static final int GLINT = 4;
private static final ObjectOpenCustomHashSet<DrawState> CACHE = new ObjectOpenCustomHashSet<>(HashStrategy.INSTANCE);
static void clearInterning() {
CACHE.clear();
}
static int internedStateCount() {
return CACHE.size();
}
@Getter private final int cull;
@Getter private final int blend;
@Getter private final boolean depthEqual;
@Getter private final boolean depthWrite;
@Getter private final boolean colorWrite;
@Getter private final float alphaCutoff;
@Getter private final boolean lit;
@Getter private final float offsetFactor;
@Getter private final float offsetUnits;
private final int hash;
private DrawState(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, float offsetFactor, float offsetUnits) {
this.cull = cull;
this.blend = blend;
this.depthEqual = depthEqual;
this.depthWrite = depthWrite;
this.colorWrite = colorWrite;
this.alphaCutoff = alphaCutoff;
this.lit = lit;
this.offsetFactor = offsetFactor;
this.offsetUnits = offsetUnits;
int h = cull;
h = h * 31 + blend;
h = h * 31 + (depthEqual ? 1 : 0);
h = h * 31 + (depthWrite ? 1 : 0);
h = h * 31 + (colorWrite ? 1 : 0);
h = h * 31 + Float.floatToIntBits(alphaCutoff);
h = h * 31 + (lit ? 1 : 0);
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
this.hash = h;
}
public static DrawState of(int cull, int blend, boolean depthEqual, boolean depthWrite, boolean colorWrite, float alphaCutoff, boolean lit, float offsetFactor, float offsetUnits) {
return CACHE.addOrGet(new DrawState(cull, blend, depthEqual, depthWrite, colorWrite, alphaCutoff, lit, offsetFactor, offsetUnits));
}
public static DrawState forMaterial(TesrMaterial material, int cull, boolean lit, float offsetFactor, float offsetUnits) {
return of(material.isNoCull() ? DISABLED : cull,
blendFor(material.transparency()),
material.isDepthEqual(),
!material.isNoDepthWrite(),
!material.isDepthOnly(),
material.cutoutAlpha(),
lit && !material.isUnlit(),
offsetFactor, offsetUnits);
}
public static int blendFor(TesrMaterial.Transparency transparency) {
return switch (transparency) {
case TRANSLUCENT -> TRANSLUCENT;
case ADDITIVE -> ADDITIVE;
case ADDITIVE_ALPHA -> ADDITIVE_ALPHA;
case GLINT -> GLINT;
case OPAQUE -> OPAQUE;
};
}
public static int packCull(boolean enabled, int faceMode) {
if (!enabled) return DISABLED;
return switch (faceMode) {
case GL11.GL_FRONT -> CULL_FRONT;
case GL11.GL_FRONT_AND_BACK -> CULL_BOTH;
default -> CULL_BACK;
};
}
public static int liveCull() {
return packCull(GLStateManager.getCullState().isEnabled(), GLStateManager.getPolygonState().getCullFaceMode());
}
public static boolean liveLit(TesrMaterial material) {
return GLStateManager.getLightingState().isEnabled() && !material.isUnlit();
}
public void apply() {
switch (blend) {
case TRANSLUCENT -> {
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
case ADDITIVE -> {
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
}
case ADDITIVE_ALPHA -> {
GLStateManager.enableBlend();
GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
}
case GLINT -> {
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE);
}
default -> GLStateManager.disableBlend();
}
GLStateManager.enableDepthTest();
GLStateManager.glDepthFunc(depthEqual ? GL11.GL_EQUAL : GL11.GL_LEQUAL);
GLStateManager.glDepthMask(depthWrite);
GLStateManager.glColorMask(colorWrite, colorWrite, colorWrite, colorWrite);
if (alphaCutoff > 0.0f) {
GLStateManager.enableAlphaTest();
GLStateManager.glAlphaFunc(GL11.GL_GREATER, alphaCutoff);
} else {
GLStateManager.disableAlphaTest();
}
if (lit) {
GLStateManager.enableLighting();
} else {
GLStateManager.disableLighting();
}
switch (cull) {
case CULL_BACK -> {
GLStateManager.enableCull();
GLStateManager.glCullFace(GL11.GL_BACK);
}
case CULL_FRONT -> {
GLStateManager.enableCull();
GLStateManager.glCullFace(GL11.GL_FRONT);
}
case CULL_BOTH -> {
GLStateManager.enableCull();
GLStateManager.glCullFace(GL11.GL_FRONT_AND_BACK);
}
default -> GLStateManager.disableCull();
}
if (offsetFactor != 0.0f || offsetUnits != 0.0f) {
GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(offsetFactor, offsetUnits);
} else {
GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
GLStateManager.glPolygonOffset(0.0f, 0.0f);
}
}
@Override
public boolean equals(@Nullable Object o) {
return this == o;
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return "DrawState[cull=" + cull + ", blend=" + blend + ", depthEqual=" + depthEqual + ", depthWrite=" + depthWrite + ", colorWrite=" + colorWrite + ", alphaCutoff=" + alphaCutoff + ", lit=" + lit + ", offset=" + offsetFactor + '/' + offsetUnits + ']';
}
private enum HashStrategy implements Hash.Strategy<DrawState> {
INSTANCE;
@Override
public int hashCode(@Nullable DrawState state) {
return state == null ? 0 : state.hash;
}
@Override
public boolean equals(@Nullable DrawState a, @Nullable DrawState b) {
if (a == b) return true;
if (a == null || b == null) return false;
return a.cull == b.cull && a.blend == b.blend && a.depthEqual == b.depthEqual && a.depthWrite == b.depthWrite && a.colorWrite == b.colorWrite && Float.floatToIntBits(a.alphaCutoff) == Float.floatToIntBits(b.alphaCutoff) && a.lit == b.lit && Float.floatToIntBits(a.offsetFactor) == Float.floatToIntBits(b.offsetFactor) && Float.floatToIntBits(a.offsetUnits) == Float.floatToIntBits(b.offsetUnits);
}
}
}
@@ -4,6 +4,7 @@ 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 com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
import net.coderbot.batchedentityrendering.impl.SegmentedBufferBuilder;
import net.coderbot.iris.Iris;
@@ -161,7 +162,7 @@ final class EntityShadowBatcher {
private RenderLayer layer() {
RenderLayer l = layer;
if (l == null) {
l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F);
l = RenderLayer.tesr(SHADOW_TEXTURE, EntityMaterials.SHADOW, PassOverride.NONE, 0.0F, 0.0F, ShaderGlint.NO_TINT, DrawState.CULL_BACK, false);
layer = l;
}
return l;
@@ -128,14 +128,18 @@ public final class ModelPartBatcher {
float offsetFactor;
float offsetUnits;
int glintSlot;
int cull;
boolean lit;
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
LayerKey set(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cull, boolean lit) {
this.texture = texture;
this.material = material;
this.pass = pass;
this.offsetFactor = offsetFactor;
this.offsetUnits = offsetUnits;
this.glintSlot = glintSlot;
this.cull = cull;
this.lit = lit;
return this;
}
@@ -146,7 +150,7 @@ public final class ModelPartBatcher {
&& Objects.equals(pass, other.pass)
&& Float.floatToIntBits(offsetFactor) == Float.floatToIntBits(other.offsetFactor)
&& Float.floatToIntBits(offsetUnits) == Float.floatToIntBits(other.offsetUnits)
&& glintSlot == other.glintSlot;
&& glintSlot == other.glintSlot && cull == other.cull && lit == other.lit;
}
@Override
@@ -155,6 +159,8 @@ public final class ModelPartBatcher {
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
h = h * 31 + glintSlot;
h = h * 31 + cull;
h = h * 31 + (lit ? 1 : 0);
return h;
}
}
@@ -167,6 +173,8 @@ public final class ModelPartBatcher {
private float lastLayerOffsetFactor;
private float lastLayerOffsetUnits;
private int lastLayerGlintSlot;
private int lastLayerCull;
private boolean lastLayerLit;
private RenderLayer lastLayer;
private static ResourceLocation lastBoundLocation;
@@ -344,7 +352,9 @@ public final class ModelPartBatcher {
final float offsetFactor = offset ? polygon.getOffsetFactor() : 0.0f;
final float offsetUnits = offset ? polygon.getOffsetUnits() : 0.0f;
final int glintSlot = material.special() == TesrMaterial.SpecialRender.GLINT ? lastBoundGlintSlot : ShaderGlint.NO_TINT;
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot);
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final boolean lit = DrawState.liveLit(material);
final RenderLayer layer = layerFor(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit);
// Entities nested inside a TESR (mob spawner, OpenBlocks trophy) run in the block entity pass but carry an entity id
final int entityId = groupId(shaderPipeline != null, mode == Mode.ENTITIES || pass.isEntityPhase(), CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity());
final Color4 color = GLStateManager.getColor();
@@ -447,15 +457,16 @@ public final class ModelPartBatcher {
entry.cubes = cubes;
}
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot) {
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int glintSlot, int cullCode, boolean lit) {
if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass)
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && glintSlot == lastLayerGlintSlot) {
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && glintSlot == lastLayerGlintSlot
&& cullCode == lastLayerCull && lit == lastLayerLit) {
return lastLayer;
}
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot));
RenderLayer layer = layers.get(scratchKey.set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit));
if (layer == null) {
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot), layer);
layer = RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit);
layers.put(new LayerKey().set(texture, material, pass, offsetFactor, offsetUnits, glintSlot, cullCode, lit), layer);
}
lastLayerTexture = texture;
lastLayerMaterial = material;
@@ -463,6 +474,8 @@ public final class ModelPartBatcher {
lastLayerOffsetFactor = offsetFactor;
lastLayerOffsetUnits = offsetUnits;
lastLayerGlintSlot = glintSlot;
lastLayerCull = cullCode;
lastLayerLit = lit;
lastLayer = layer;
return layer;
}
@@ -486,10 +499,13 @@ public final class ModelPartBatcher {
active = false;
shaderPipeline = null;
layers.clear();
scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT);
scratchKey.set(null, null, null, 0.0f, 0.0f, ShaderGlint.NO_TINT, DrawState.DISABLED, false);
lastLayerTexture = null;
lastLayerMaterial = null;
lastLayerPass = null;
lastLayerGlintSlot = ShaderGlint.NO_TINT;
lastLayerCull = DrawState.DISABLED;
lastLayerLit = false;
lastLayer = null;
loggedMaterialBails.clear();
lastBoundLocation = null;
@@ -1,5 +1,6 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizon.gtnhlib.client.renderer.MatrixHelper;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
@@ -7,6 +8,7 @@ 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.StateSet;
import com.gtnewhorizons.angelica.glsm.ffp.InstancedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.Instancing;
import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager;
@@ -14,6 +16,7 @@ import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.states.Color4;
import com.gtnewhorizons.angelica.glsm.states.PolygonState;
import com.gtnewhorizons.angelica.shadercompat.ShaderGlint;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.coderbot.batchedentityrendering.impl.AngelicaBufferSource;
@@ -108,7 +111,7 @@ public final class TesrBatchRenderer {
return pipeline instanceof DeferredWorldRenderingPipeline deferred && deferred.supportsInstancing(Instancing.TEMPLATE);
}
static DeferredWorldRenderingPipeline deferredPipeline() {
public static DeferredWorldRenderingPipeline deferredPipeline() {
if (!Iris.enabled) return null;
return Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline deferred
? deferred : null;
@@ -135,9 +138,13 @@ public final class TesrBatchRenderer {
lastLayerTexture = null;
lastLayerMaterial = null;
lastLayerPass = null;
lastLayerCull = DrawState.DISABLED;
lastLayerLit = false;
lastLayer = null;
lastImmediateTexture = null;
lastImmediateMaterial = null;
lastImmediateCull = DrawState.DISABLED;
lastImmediateLit = false;
lastImmediateLayer = null;
AngelicaTesrMeshCache.INSTANCE.clear();
}
@@ -158,8 +165,10 @@ public final class TesrBatchRenderer {
final boolean offset = GLStateManager.glIsEnabled(GL11.GL_POLYGON_OFFSET_FILL);
final PolygonState polygon = GLStateManager.getPolygonState();
final PassOverride pass = PassOverride.capture();
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final boolean lit = DrawState.liveLit(material);
final RenderLayer layer = layerFor(texture, material, pass,
offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f);
offset ? polygon.getOffsetFactor() : 0.0f, offset ? polygon.getOffsetUnits() : 0.0f, cullCode, lit);
final int blockEntityId = pass.isEntityPhase()
? CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()
: CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity();
@@ -190,8 +199,10 @@ public final class TesrBatchRenderer {
PassOverride pass;
float offsetFactor;
float offsetUnits;
int cull;
boolean lit;
LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits) {
LayerKey set(ResourceLocation texture, TesrMaterial.Transparency transparency, boolean noCull, boolean unlit, boolean noDepthWrite, boolean depthOnly, float cutoutAlpha, boolean depthEqual, TesrMaterial.SpecialRender special, TesrShader shader, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cull, boolean lit) {
this.texture = texture;
this.transparency = transparency;
this.noCull = noCull;
@@ -206,11 +217,13 @@ public final class TesrBatchRenderer {
this.pass = pass;
this.offsetFactor = offsetFactor;
this.offsetUnits = offsetUnits;
this.cull = cull;
this.lit = lit;
return this;
}
LayerKey copy() {
return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass, pass, offsetFactor, offsetUnits);
return new LayerKey().set(texture, transparency, noCull, unlit, noDepthWrite, depthOnly, cutoutAlpha, depthEqual, special, shader, noPass, pass, offsetFactor, offsetUnits, cull, lit);
}
@Override
@@ -223,7 +236,8 @@ public final class TesrBatchRenderer {
&& depthEqual == other.depthEqual && special == other.special && shader == other.shader && noPass == other.noPass
&& 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)
&& cull == other.cull && lit == other.lit;
}
@Override
@@ -242,6 +256,8 @@ public final class TesrBatchRenderer {
h = h * 31 + Objects.hashCode(pass);
h = h * 31 + Float.floatToIntBits(offsetFactor);
h = h * 31 + Float.floatToIntBits(offsetUnits);
h = h * 31 + cull;
h = h * 31 + (lit ? 1 : 0);
return h;
}
}
@@ -253,42 +269,52 @@ public final class TesrBatchRenderer {
private PassOverride lastLayerPass;
private float lastLayerOffsetFactor;
private float lastLayerOffsetUnits;
private int lastLayerCull;
private boolean lastLayerLit;
private RenderLayer lastLayer;
private ResourceLocation lastImmediateTexture;
private TesrMaterial lastImmediateMaterial;
private int lastImmediateCull;
private boolean lastImmediateLit;
private RenderLayer lastImmediateLayer;
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits) {
private RenderLayer layerFor(ResourceLocation texture, TesrMaterial material, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit) {
if (texture == lastLayerTexture && material == lastLayerMaterial && pass.equals(lastLayerPass)
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits) {
&& offsetFactor == lastLayerOffsetFactor && offsetUnits == lastLayerOffsetUnits && cullCode == lastLayerCull && lit == lastLayerLit) {
return lastLayer;
}
final RenderLayer layer = layerLookup(texture, material, false, pass, offsetFactor, offsetUnits);
final RenderLayer layer = layerLookup(texture, material, false, pass, offsetFactor, offsetUnits, cullCode, lit);
lastLayerTexture = texture;
lastLayerMaterial = material;
lastLayerPass = pass;
lastLayerOffsetFactor = offsetFactor;
lastLayerOffsetUnits = offsetUnits;
lastLayerCull = cullCode;
lastLayerLit = lit;
lastLayer = layer;
return layer;
}
private RenderLayer noPassLayerFor(ResourceLocation texture, TesrMaterial material) {
if (texture == lastImmediateTexture && material == lastImmediateMaterial) {
final int cullCode = material.isNoCull() ? DrawState.DISABLED : DrawState.liveCull();
final boolean lit = DrawState.liveLit(material);
if (texture == lastImmediateTexture && material == lastImmediateMaterial && cullCode == lastImmediateCull && lit == lastImmediateLit) {
return lastImmediateLayer;
}
final RenderLayer layer = layerLookup(texture, material, true, PassOverride.NONE, 0.0f, 0.0f);
final RenderLayer layer = layerLookup(texture, material, true, PassOverride.NONE, 0.0f, 0.0f, cullCode, lit);
lastImmediateTexture = texture;
lastImmediateMaterial = material;
lastImmediateCull = cullCode;
lastImmediateLit = lit;
lastImmediateLayer = layer;
return layer;
}
private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits) {
final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass, pass, offsetFactor, offsetUnits);
private RenderLayer layerLookup(ResourceLocation texture, TesrMaterial material, boolean noPass, PassOverride pass, float offsetFactor, float offsetUnits, int cullCode, boolean lit) {
final LayerKey key = scratchKey.set(texture, material.transparency(), material.isNoCull(), material.isUnlit(), material.isNoDepthWrite(), material.isDepthOnly(), material.cutoutAlpha(), material.isDepthEqual(), material.special(), material.shader(), noPass, pass, offsetFactor, offsetUnits, cullCode, lit);
RenderLayer layer = layers.get(key);
if (layer == null) {
layer = noPass ? RenderLayer.tesrNoPass(texture, material) : RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits);
layer = noPass ? RenderLayer.tesrNoPass(texture, material, cullCode, lit) : RenderLayer.tesr(texture, material, pass, offsetFactor, offsetUnits, ShaderGlint.NO_TINT, cullCode, lit);
layers.put(key.copy(), layer);
}
return layer;
@@ -353,40 +379,32 @@ public final class TesrBatchRenderer {
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DEFERRED);
try {
final EntityRenderer entityRenderer = Minecraft.getMinecraft().entityRenderer;
final boolean savedDepthMask = GLStateManager.getDepthState().isEnabled();
final boolean savedDepthTest = GLStateManager.getDepthTest().isEnabled();
final boolean savedBlend = GLStateManager.getBlendMode().isEnabled();
final int savedSrcRgb = GLStateManager.getBlendState().getSrcRgb();
final int savedDstRgb = GLStateManager.getBlendState().getDstRgb();
final int savedSrcAlpha = GLStateManager.getBlendState().getSrcAlpha();
final int savedDstAlpha = GLStateManager.getBlendState().getDstAlpha();
final boolean savedAlphaTest = GLStateManager.getAlphaTest().isEnabled();
final int savedAlphaFunc = GLStateManager.getAlphaState().getFunction();
final float savedAlphaRef = GLStateManager.getAlphaState().getReference();
GLStateManager.glDepthMask(true);
GLStateManager.enableDepthTest();
GLStateManager.enableBlend();
GLStateManager.defaultBlendFunc();
entityRenderer.enableLightmap(0);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
final boolean wrap = Iris.enabled && GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.NONE;
if (wrap) GbufferPrograms.beginBlockEntities();
final int deferredDepth = GLStateManager.pushState(StateSet.BATCH);
try {
bufferSource.endBatch(hook);
instancedRenderer.endFrame();
AngelicaBufferSource.rebindPass();
BatchingFontRenderer.flushDeferredText();
GLStateManager.glDepthMask(true);
GLStateManager.enableDepthTest();
GLStateManager.enableBlend();
GLStateManager.defaultBlendFunc();
entityRenderer.enableLightmap(0);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
GLStateManager.glEnable(GL11.GL_TEXTURE_2D);
final boolean wrap = Iris.enabled && GbufferPrograms.getCurrentPhase() == WorldRenderingPhase.NONE;
boolean blockEntitiesBegun = false;
if (wrap) {
GbufferPrograms.beginBlockEntities();
blockEntitiesBegun = true;
}
try {
bufferSource.endBatch(hook);
instancedRenderer.endFrame();
AngelicaBufferSource.rebindPass();
BatchingFontRenderer.flushDeferredText();
} finally {
if (blockEntitiesBegun) GbufferPrograms.endBlockEntities();
entityRenderer.disableLightmap(0);
}
} finally {
if (wrap) GbufferPrograms.endBlockEntities();
entityRenderer.disableLightmap(0);
GLStateManager.glDepthMask(savedDepthMask);
if (savedDepthTest) GLStateManager.enableDepthTest(); else GLStateManager.disableDepthTest();
if (savedBlend) GLStateManager.enableBlend(); else GLStateManager.disableBlend();
GLStateManager.tryBlendFuncSeparate(savedSrcRgb, savedDstRgb, savedSrcAlpha, savedDstAlpha);
if (savedAlphaTest) GLStateManager.enableAlphaTest(); else GLStateManager.disableAlphaTest();
GLStateManager.glAlphaFunc(savedAlphaFunc, savedAlphaRef);
GLStateManager.popStateTo(deferredDepth);
}
} finally {
if (Tracy.ENABLED) Tracy.endZone();
@@ -519,12 +537,30 @@ public final class TesrBatchRenderer {
immediateScratch.position((int) (end - addr));
immediateScratch.flip();
final RenderLayer layer = noPassLayerFor(texture, material);
GLStateManager.glPushAttrib(AngelicaBufferSource.SAVED_STATE_BITS);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
layer.startDrawing();
immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount);
immediateMesh.render();
layer.endDrawing();
GLStateManager.glPopAttrib();
final int d = GLStateManager.pushState(StateSet.BATCH);
try {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
boolean layerStarted = false;
Throwable failure = null;
try {
layer.startDrawing();
layerStarted = true;
immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount);
immediateMesh.render();
} catch (Throwable t) {
failure = t;
} finally {
if (layerStarted) {
try {
layer.endDrawing();
} catch (Throwable cleanup) {
failure = RenderFailures.suppress(failure, cleanup);
}
}
}
if (failure != null) RenderFailures.rethrow(failure);
} finally {
GLStateManager.popStateTo(d);
}
}
}
@@ -0,0 +1,18 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.rendering.particles.ParticleInstancer;
public final class TesrLifecycle {
private TesrLifecycle() {}
public static void reset() {
TesrBatchRenderer.INSTANCE.clearRetained();
ModelPartBatcher.INSTANCE.clear();
ParticleInstancer.clear();
RenderLayer.clearInterningAndHooks();
DrawState.clearInterning();
}
}
@@ -91,7 +91,7 @@ public class FancyDial {
logger.config("fbo: supported=%s", fboSupported);
logger.config("GL13: supported=%s, enabled=%s", gl13Supported, useGL13);
int bits = GL11.GL_VIEWPORT_BIT | GL11.GL_SCISSOR_BIT | GL11.GL_DEPTH_BITS | GL11.GL_LIGHTING_BIT;
int bits = GL11.GL_VIEWPORT_BIT | GL11.GL_SCISSOR_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT;
if (useGL13) {
bits |= GL13.GL_MULTISAMPLE_BIT;
}
@@ -422,8 +422,11 @@ public class FancyDial {
private void renderToFB(double angle, FBO fbo) {
if (fbo != null) {
fbo.bind();
renderImpl(angle);
fbo.unbind();
try {
renderImpl(angle);
} finally {
fbo.unbind();
}
}
}
@@ -1,7 +1,9 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -12,7 +14,6 @@ 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;
import java.util.ArrayList;
@@ -22,8 +23,6 @@ import java.util.Map;
/** Collects geometry into per-RenderLayer buffers during a pass and draws it all at endBatch, one state bracket per layer. Based on Iris's FullyBufferedMultiBufferSource */
public class AngelicaBufferSource implements Groupable {
public static final int SAVED_STATE_BITS = GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_CURRENT_BIT | GL11.GL_LIGHTING_BIT | GL11.GL_TEXTURE_BIT;
private static final int NUM_BUFFERS = 32;
public enum GroupIdKind { BLOCK_ENTITY, ENTITY }
@@ -43,7 +42,7 @@ public class AngelicaBufferSource implements Groupable {
private boolean prepared;
private final List<RenderLayer> order = new ArrayList<>();
private boolean stateSaved;
private int drawStateDepth = -1;
private boolean anyIdSet;
private GroupIdKind idKind = GroupIdKind.BLOCK_ENTITY;
@@ -113,7 +112,6 @@ public class AngelicaBufferSource implements Groupable {
}
}
affinities.clear();
stateSaved = false;
anyIdSet = false;
}
@@ -129,13 +127,18 @@ public class AngelicaBufferSource implements Groupable {
public void endBatchWithType(TransparencyType type, LayerDrawHook hook) {
ensurePrepared();
int keep = 0;
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != type) {
order.set(keep++, layer);
continue;
try {
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != type) {
order.set(keep++, layer);
continue;
}
drawLayer(layer, hook);
}
drawLayer(layer, hook);
} catch (Throwable t) {
discardAfterFailure(t);
throw t;
}
for (int i = order.size() - 1; i >= keep; i--) {
order.remove(i);
@@ -144,15 +147,20 @@ public class AngelicaBufferSource implements Groupable {
public void endBatch(LayerDrawHook hook) {
ensurePrepared();
for (int i = 0, n = order.size(); i < n; i++) {
drawLayer(order.get(i), hook);
try {
for (int i = 0, n = order.size(); i < n; i++) {
drawLayer(order.get(i), hook);
}
} catch (Throwable t) {
discardAfterFailure(t);
throw t;
}
order.clear();
finish();
}
public void pauseBatch() {
releaseAttribState();
restoreDrawState();
clearCurrentId();
}
@@ -161,10 +169,10 @@ public class AngelicaBufferSource implements Groupable {
finish();
}
private void releaseAttribState() {
if (stateSaved) {
GLStateManager.glPopAttrib();
stateSaved = false;
private void restoreDrawState() {
if (drawStateDepth >= 0) {
GLStateManager.popStateTo(drawStateDepth);
drawStateDepth = -1;
}
}
@@ -186,17 +194,42 @@ public class AngelicaBufferSource implements Groupable {
final boolean hasDynamic = segments != null && !segments.isEmpty();
final boolean hasRetained = hook != null && hook.hasDraws(layer);
if (!hasDynamic && !hasRetained) return;
if (!stateSaved) {
stateSaved = true;
GLStateManager.glPushAttrib(SAVED_STATE_BITS);
if (drawStateDepth < 0) {
drawStateDepth = GLStateManager.pushState(StateSet.BATCH);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
}
layer.startDrawing();
if (hasDynamic) {
anyIdSet = true;
Throwable failure = null;
try {
if (hasDynamic) {
drawDynamic(segments);
}
if (hasRetained) {
anyIdSet = true;
hook.drawLayer(layer);
}
} catch (Throwable t) {
failure = t;
} finally {
try {
layer.endDrawing();
} catch (Throwable cleanup) {
failure = RenderFailures.suppress(failure, cleanup);
}
}
if (failure != null) RenderFailures.rethrow(failure);
}
private void drawDynamic(List<BufferSegment> segments) {
anyIdSet = true;
boolean matrixPushed = false;
SegmentedBufferBuilder.LayerBuffer bound = null;
boolean boundSetup = false;
Throwable failure = null;
try {
GLStateManager.glPushMatrix();
matrixPushed = true;
GLStateManager.glLoadIdentity();
SegmentedBufferBuilder.LayerBuffer bound = null;
final boolean entityKind = effectiveIdKind() == GroupIdKind.ENTITY;
int currentId = Integer.MIN_VALUE;
int currentColor = 0;
@@ -214,21 +247,37 @@ public class AngelicaBufferSource implements Groupable {
}
final SegmentedBufferBuilder.LayerBuffer owner = segment.getOwner();
if (owner != bound) {
if (bound != null) bound.finishDraw();
if (boundSetup) {
bound.finishDraw();
boundSetup = false;
}
bound = null;
owner.uploadForDraw();
owner.setupDraw();
bound = owner;
bound.uploadForDraw();
bound.setupDraw();
boundSetup = true;
}
bound.draw(segment.getFirstVertex(), segment.getVertexCount());
}
if (bound != null) bound.finishDraw();
GLStateManager.glPopMatrix();
} catch (Throwable t) {
failure = t;
} finally {
if (boundSetup) {
try {
bound.finishDraw();
} catch (Throwable cleanup) {
failure = RenderFailures.suppress(failure, cleanup);
}
}
if (matrixPushed) {
try {
GLStateManager.glPopMatrix();
} catch (Throwable cleanup) {
failure = RenderFailures.suppress(failure, cleanup);
}
}
}
if (hasRetained) {
anyIdSet = true;
hook.drawLayer(layer);
}
layer.endDrawing();
if (failure != null) RenderFailures.rethrow(failure);
}
private void clearSegmentLists() {
@@ -238,15 +287,44 @@ public class AngelicaBufferSource implements Groupable {
}
private void finish() {
releaseAttribState();
clearCurrentId();
clearSegmentLists();
final Throwable failure = cleanupAfterBatch(null);
if (failure != null) RenderFailures.rethrow(failure);
}
private Throwable cleanupAfterBatch(Throwable failure) {
try {
restoreDrawState();
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
try {
clearCurrentId();
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
try {
clearSegmentLists();
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
final long now = System.currentTimeMillis();
final long maxIdle = getTargetClearTime();
for (SegmentedBufferBuilder builder : builders) {
builder.resetAndReclaim(now, maxIdle);
for (int i = 0; i < builders.length; i++) {
try {
builders[i].resetAndReclaim(now, maxIdle);
} catch (Throwable t) {
failure = RenderFailures.suppress(failure, t);
}
}
affinities.clear();
renderOrderManager.reset();
prepared = false;
return failure;
}
private void discardAfterFailure(Throwable failure) {
order.clear();
cleanupAfterBatch(failure);
}
public void freeBuffers() {
@@ -324,13 +402,7 @@ public class AngelicaBufferSource implements Groupable {
}
static TransparencyType getTransparencyType(RenderLayer type) {
while (type instanceof WrappableRenderType wrappable) {
type = wrappable.unwrap();
}
if (type instanceof BlendingStateHolder holder) {
return holder.getTransparencyType();
}
return TransparencyType.GENERAL_TRANSPARENT;
return type.getTransparencyType();
}
@Override
@@ -1,10 +0,0 @@
package net.coderbot.batchedentityrendering.impl;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
public interface WrappableRenderType {
/**
* Returns the underlying wrapped RenderType. Might return itself if this RenderType doesn't wrap anything.
*/
RenderLayer unwrap();
}
@@ -7,9 +7,7 @@ import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSet;
import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetPolicy;
import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetProvider;
import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider;
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.batchedentityrendering.impl.WrappableRenderType;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.ArrayList;
@@ -33,21 +31,8 @@ public class GraphTranslucencyRenderOrderManager implements RenderOrderManager {
}
}
private static TransparencyType getTransparencyType(RenderLayer type) {
while (type instanceof WrappableRenderType) {
type = ((WrappableRenderType) type).unwrap();
}
if (type instanceof BlendingStateHolder blendingState) {
return blendingState.getTransparencyType();
}
// Default to "generally transparent" if we can't figure it out.
return TransparencyType.GENERAL_TRANSPARENT;
}
public void begin(RenderLayer renderType) {
TransparencyType transparencyType = getTransparencyType(renderType);
TransparencyType transparencyType = renderType.getTransparencyType();
Digraph<RenderLayer> graph = types.get(transparencyType);
graph.add(renderType);
@@ -1,8 +1,6 @@
package net.coderbot.batchedentityrendering.impl.ordering;
import net.coderbot.batchedentityrendering.impl.BlendingStateHolder;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.batchedentityrendering.impl.WrappableRenderType;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.ArrayList;
@@ -21,21 +19,8 @@ public class TranslucencyRenderOrderManager implements RenderOrderManager {
}
}
private static TransparencyType getTransparencyType(RenderLayer type) {
while (type instanceof WrappableRenderType) {
type = ((WrappableRenderType) type).unwrap();
}
if (type instanceof BlendingStateHolder) {
return ((BlendingStateHolder) type).getTransparencyType();
}
// Default to "generally transparent" if we can't figure it out.
return TransparencyType.GENERAL_TRANSPARENT;
}
public void begin(RenderLayer type) {
renderTypes.get(getTransparencyType(type)).add(type);
renderTypes.get(type.getTransparencyType()).add(type);
}
public void startGroup() {
@@ -1,10 +0,0 @@
package net.coderbot.iris.fantastic;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import java.util.function.Function;
public interface WrappingMultiBufferSource {
void pushWrappingFunction(Function<RenderLayer, RenderLayer> wrappingFunction);
void popWrappingFunction();
void assertWrapStackEmpty();
}
@@ -52,13 +52,17 @@ public class AlphaTestStorage {
}
}
public static void deferAlphaTestToggle(boolean enabled) {
public static boolean deferAlphaTestToggle(boolean enabled) {
if (enabled == vanillaEnabled) return false;
vanillaEnabled = enabled;
return true;
}
public static void deferAlphaFunc(int function, float reference) {
public static boolean deferAlphaFunc(int function, float reference) {
if (function == vanillaFunction && Float.compare(reference, vanillaReference) == 0) return false;
vanillaFunction = function;
vanillaReference = reference;
return true;
}
public static void restoreAlphaTest() {
@@ -116,82 +116,83 @@ public class ShaderPackScreen extends GuiScreen implements HudHideable {
@Override
public void drawScreen(int mouseX, int mouseY, float delta) {
GLStateManager.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT);
if(dirty) {
dirty = false;
this.initGui();
}
handleDroppedFiles();
if (this.mc.theWorld == null) {
super.drawDefaultBackground();
} else if (!this.guiHidden) {
this.drawGradientRect(0, 0, width, height, 0x4F232323, 0x4F232323);
}
if (!this.guiHidden) {
if (optionMenuOpen && this.shaderOptionList != null) {
this.shaderOptionList.drawScreen(mouseX, mouseY, delta);
this.shaderOptionList.drawSearchBox();
} else {
this.shaderPackList.drawScreen(mouseX, mouseY, delta);
try {
if(dirty) {
dirty = false;
this.initGui();
}
}
if (hoveredElement != null) {
hoveredElementCommentTimer++;
} else {
hoveredElementCommentTimer = 0;
}
handleDroppedFiles();
super.drawScreen(mouseX, mouseY, delta);
if (this.mc.theWorld == null) {
super.drawDefaultBackground();
} else if (!this.guiHidden) {
this.drawGradientRect(0, 0, width, height, 0x4F232323, 0x4F232323);
}
if (!this.guiHidden) {
drawCenteredString(this.fontRendererObj, this.title, (int) (this.width * 0.5), 8, 0xFFFFFF);
if (notificationDialog != null && notificationDialogTimer > 0) {
drawCenteredString(this.fontRendererObj, notificationDialog, (int) (this.width * 0.5), 21, 0xFFFFFF);
} else {
if (optionMenuOpen) {
drawCenteredString(this.fontRendererObj, configureTitle(), (int) (this.width * 0.5), 21, 0xFFFFFF);
if (!this.guiHidden) {
if (optionMenuOpen && this.shaderOptionList != null) {
this.shaderOptionList.drawScreen(mouseX, mouseY, delta);
this.shaderOptionList.drawSearchBox();
} else {
drawCenteredString(this.fontRendererObj, selectTitle(), (int) (this.width * 0.5), 21, 0xFFFFFF);
this.shaderPackList.drawScreen(mouseX, mouseY, delta);
}
}
// Draw the comment panel
if (this.isDisplayingComment()) {
final int panelHeight = Math.max(50, 18 + (this.hoveredElementCommentBody.size() * 10));
final int x = (int) (0.5 * this.width) - 157;
final int y = this.height - (panelHeight + 4);
// Draw panel
GuiUtil.drawPanel(x, y, COMMENT_PANEL_WIDTH, panelHeight);
// Draw text
this.fontRendererObj.drawStringWithShadow(this.hoveredElementCommentTitle.orElse(""), x + 4, y + 4, 0xFFFFFF);
for (int i = 0; i < this.hoveredElementCommentBody.size(); i++) {
this.fontRendererObj.drawStringWithShadow(this.hoveredElementCommentBody.get(i), x + 4, (y + 16) + (i * 10), 0xFFFFFF);
if (hoveredElement != null) {
hoveredElementCommentTimer++;
} else {
hoveredElementCommentTimer = 0;
}
super.drawScreen(mouseX, mouseY, delta);
if (!this.guiHidden) {
drawCenteredString(this.fontRendererObj, this.title, (int) (this.width * 0.5), 8, 0xFFFFFF);
if (notificationDialog != null && notificationDialogTimer > 0) {
drawCenteredString(this.fontRendererObj, notificationDialog, (int) (this.width * 0.5), 21, 0xFFFFFF);
} else {
if (optionMenuOpen) {
drawCenteredString(this.fontRendererObj, configureTitle(), (int) (this.width * 0.5), 21, 0xFFFFFF);
} else {
drawCenteredString(this.fontRendererObj, selectTitle(), (int) (this.width * 0.5), 21, 0xFFFFFF);
}
}
// Draw the comment panel
if (this.isDisplayingComment()) {
final int panelHeight = Math.max(50, 18 + (this.hoveredElementCommentBody.size() * 10));
final int x = (int) (0.5 * this.width) - 157;
final int y = this.height - (panelHeight + 4);
// Draw panel
GuiUtil.drawPanel(x, y, COMMENT_PANEL_WIDTH, panelHeight);
// Draw text
this.fontRendererObj.drawStringWithShadow(this.hoveredElementCommentTitle.orElse(""), x + 4, y + 4, 0xFFFFFF);
for (int i = 0; i < this.hoveredElementCommentBody.size(); i++) {
this.fontRendererObj.drawStringWithShadow(this.hoveredElementCommentBody.get(i), x + 4, (y + 16) + (i * 10), 0xFFFFFF);
}
}
}
}
// Render everything queued to drawScreen last
for (Runnable render : TOP_LAYER_RENDER_QUEUE) {
render.run();
}
TOP_LAYER_RENDER_QUEUE.clear();
// Render everything queued to drawScreen last
for (Runnable render : TOP_LAYER_RENDER_QUEUE) {
render.run();
}
TOP_LAYER_RENDER_QUEUE.clear();
if (this.developmentComponent != null) {
this.fontRendererObj.drawStringWithShadow(developmentComponent, 2, this.height - 10, 0xFFFFFF);
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 20, 0xFFFFFF);
} else if (this.updateComponent != null) {
this.fontRendererObj.drawStringWithShadow(updateComponent, 2, this.height - 10, 0xFFFFFF);
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 20, 0xFFFFFF);
} else {
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 10, 0xFFFFFF);
if (this.developmentComponent != null) {
this.fontRendererObj.drawStringWithShadow(developmentComponent, 2, this.height - 10, 0xFFFFFF);
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 20, 0xFFFFFF);
} else if (this.updateComponent != null) {
this.fontRendererObj.drawStringWithShadow(updateComponent, 2, this.height - 10, 0xFFFFFF);
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 20, 0xFFFFFF);
} else {
this.fontRendererObj.drawStringWithShadow(irisTextComponent, 2, this.height - 10, 0xFFFFFF);
}
} finally {
GLStateManager.glPopAttrib();
}
GLStateManager.glPopAttrib();
}
@Override
@@ -5,8 +5,6 @@ import net.coderbot.iris.Iris;
import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.states.AlphaState;
import com.gtnewhorizons.angelica.glsm.states.BlendState;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.gl.state.StateUpdateNotifiers;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
@@ -156,89 +154,6 @@ public class GbufferPrograms {
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + previousUnit);
}
public static long pushCutoutDefaults() {
final long saved = packCutoutState();
setCutoutDefaults();
return saved;
}
public static void popCutoutDefaults(long saved) {
if ((saved & ALPHA_ENABLED_BIT) != 0) {
GLStateManager.enableAlphaTest();
} else {
GLStateManager.disableAlphaTest();
}
GLStateManager.glAlphaFunc((int) ((saved >>> 32) & 0xFFFF), Float.intBitsToFloat((int) saved));
if ((saved & LIGHTMAP_ENABLED_BIT) == 0) {
final int previousUnit = GLStateManager.getActiveTextureUnitForServerState();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE1);
GLStateManager.disableTexture();
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + previousUnit);
}
}
public static int pushBlendState() {
if (blendDepth == blendSaves.length) {
blendSaves = Arrays.copyOf(blendSaves, blendDepth * 2);
blendEnabledSaves = Arrays.copyOf(blendEnabledSaves, blendDepth * 2);
}
BlendState saved = blendSaves[blendDepth];
if (saved == null) {
saved = new BlendState();
blendSaves[blendDepth] = saved;
}
GLStateManager.getEffectiveBlendState(saved);
blendEnabledSaves[blendDepth] = GLStateManager.isEffectiveBlendEnabled();
return blendDepth++;
}
public static void popBlendState(int depth) {
blendDepth = depth;
final boolean enabled = blendEnabledSaves[depth];
if (enabled != GLStateManager.isEffectiveBlendEnabled()) {
if (enabled) {
GLStateManager.enableBlend();
} else {
GLStateManager.disableBlend();
}
}
final BlendState saved = blendSaves[depth];
GLStateManager.getEffectiveBlendState(blendScratch);
if (blendScratch.getSrcRgb() != saved.getSrcRgb() || blendScratch.getDstRgb() != saved.getDstRgb()
|| blendScratch.getSrcAlpha() != saved.getSrcAlpha() || blendScratch.getDstAlpha() != saved.getDstAlpha()) {
GLStateManager.tryBlendFuncSeparate(saved.getSrcRgb(), saved.getDstRgb(), saved.getSrcAlpha(), saved.getDstAlpha());
}
}
public static void popBlendStateTop() {
if (blendDepth > 0) {
popBlendState(blendDepth - 1);
}
}
private static BlendState[] blendSaves = new BlendState[4];
private static boolean[] blendEnabledSaves = new boolean[4];
private static int blendDepth;
private static final BlendState blendScratch = new BlendState();
private static final long ALPHA_ENABLED_BIT = 1L << 48;
private static final long LIGHTMAP_ENABLED_BIT = 1L << 49;
private static final AlphaState alphaScratch = new AlphaState();
private static long packCutoutState() {
GLStateManager.getEffectiveAlphaState(alphaScratch);
return (Float.floatToRawIntBits(alphaScratch.getReference()) & 0xFFFFFFFFL)
| ((long) (alphaScratch.getFunction() & 0xFFFF) << 32)
| (GLStateManager.isEffectiveAlphaTestEnabled() ? ALPHA_ENABLED_BIT : 0L)
| (GLStateManager.getTextures().getTextureUnitStates(1).isEnabled() ? LIGHTMAP_ENABLED_BIT : 0L);
}
public static void setBlockEntityDefaults() {
GLStateManager.glVertexAttrib2s(ProgramCreator.MC_ENTITY, (short)-1, (short)-1);
FfpExtendedAttribs.setNeutralCurrentValues();
@@ -6,6 +6,7 @@ import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.compat.mojang.InteractionHand;
import com.gtnewhorizons.angelica.event.RenderHandEvent;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.mixins.interfaces.ItemRendererAccessor;
import com.gtnewhorizons.angelica.rendering.RenderingState;
import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer;
@@ -128,40 +129,47 @@ public class HandRenderer {
ACTIVE = true;
final int blendSave = GbufferPrograms.pushBlendState();
final long cutoutSave = GbufferPrograms.pushCutoutDefaults();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
pipeline.setPhase(WorldRenderingPhase.HAND_SOLID);
GLStateManager.glPushMatrix();
GLStateManager.glDepthMask(true); // actually write to the depth buffer, it's normally disabled at this point
mc.mcProfiler.startSection("iris_hand");
final int stateDepth = GLStateManager.pushState(StateSet.HAND);
try {
setupGlState(gameRenderer, camera, tickDelta);
GbufferPrograms.setCutoutDefaults();
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.disableBlend();
GLStateManager.defaultBlendFunc();
renderingSolid = true;
pipeline.setPhase(WorldRenderingPhase.HAND_SOLID);
mc.entityRenderer.enableLightmap(tickDelta);
mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta);
mc.entityRenderer.disableLightmap(tickDelta);
boolean matrixPushed = false;
boolean profilerSectionStarted = false;
try {
GLStateManager.glPushMatrix();
matrixPushed = true;
GLStateManager.glDepthMask(true); // actually write to the depth buffer, it's normally disabled at this point
mc.mcProfiler.startSection("iris_hand");
profilerSectionStarted = true;
try {
setupGlState(gameRenderer, camera, tickDelta);
GbufferPrograms.setBlockEntityDefaults();
renderingSolid = true;
mc.entityRenderer.enableLightmap(tickDelta);
mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta);
mc.entityRenderer.disableLightmap(tickDelta);
} finally {
renderingSolid = false;
if (profilerSectionStarted) mc.mcProfiler.endSection();
}
} finally {
if (matrixPushed) {
GLStateManager.glPopMatrix();
resetProjectionMatrix();
}
}
} finally {
renderingSolid = false;
mc.mcProfiler.endSection();
GLStateManager.glPopMatrix();
resetProjectionMatrix();
GLStateManager.glDepthMask(depthMaskBefore);
GbufferPrograms.popCutoutDefaults(cutoutSave);
GbufferPrograms.popBlendState(blendSave);
GLStateManager.popStateTo(stateDepth);
pipeline.setPhase(WorldRenderingPhase.NONE);
@@ -177,36 +185,43 @@ public class HandRenderer {
ACTIVE = true;
final int blendSave = GbufferPrograms.pushBlendState();
final long cutoutSave = GbufferPrograms.pushCutoutDefaults();
final boolean depthMaskBefore = GLStateManager.isEffectiveDepthMaskEnabled();
GLStateManager.enableBlend();
GLStateManager.defaultBlendFunc();
pipeline.setPhase(WorldRenderingPhase.HAND_TRANSLUCENT);
GLStateManager.glPushMatrix();
GLStateManager.glDepthMask(false);
mc.mcProfiler.startSection("iris_hand_translucent");
final int stateDepth = GLStateManager.pushState(StateSet.HAND);
try {
setupGlState(gameRenderer, camera, tickDelta);
GbufferPrograms.setCutoutDefaults();
GbufferPrograms.setBlockEntityDefaults();
GLStateManager.enableBlend();
GLStateManager.defaultBlendFunc();
mc.entityRenderer.enableLightmap(tickDelta);
mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta);
mc.entityRenderer.disableLightmap(tickDelta);
pipeline.setPhase(WorldRenderingPhase.HAND_TRANSLUCENT);
boolean matrixPushed = false;
boolean profilerSectionStarted = false;
try {
GLStateManager.glPushMatrix();
matrixPushed = true;
GLStateManager.glDepthMask(false);
mc.mcProfiler.startSection("iris_hand_translucent");
profilerSectionStarted = true;
try {
setupGlState(gameRenderer, camera, tickDelta);
GbufferPrograms.setBlockEntityDefaults();
mc.entityRenderer.enableLightmap(tickDelta);
mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta);
mc.entityRenderer.disableLightmap(tickDelta);
} finally {
if (profilerSectionStarted) mc.mcProfiler.endSection();
}
} finally {
if (matrixPushed) {
GLStateManager.glPopMatrix();
resetProjectionMatrix();
}
}
} finally {
mc.mcProfiler.endSection();
GLStateManager.glPopMatrix();
resetProjectionMatrix();
GLStateManager.glDepthMask(depthMaskBefore);
GbufferPrograms.popCutoutDefaults(cutoutSave);
GbufferPrograms.popBlendState(blendSave);
GLStateManager.popStateTo(stateDepth);
pipeline.setPhase(WorldRenderingPhase.NONE);
@@ -681,16 +681,10 @@ public class ShadowRenderer {
/** Flushes deferred shadow-pass geometry while GL_POLYGON_OFFSET_FILL is still enabled. */
private static void flushShadowModelParts() {
if (Tracy.ENABLED) Tracy.beginZone(Z_SHADOW_MODEL_PARTS);
final boolean alphaEnabled = GLStateManager.getAlphaTest().isEnabled();
final int alphaFunc = GLStateManager.getAlphaState().getFunction();
final float alphaRef = GLStateManager.getAlphaState().getReference();
try {
ModelPartBatcher.INSTANCE.flush();
PlayerReflectionCapture.flush();
} finally {
if (alphaEnabled) GLStateManager.enableAlphaTest();
else GLStateManager.disableAlphaTest();
GLStateManager.glAlphaFunc(alphaFunc, alphaRef);
if (Tracy.ENABLED) Tracy.endZone();
}
}