Compare commits

..
Author SHA1 Message Date
Connor Colenso 8c8d346560 Add a particle API for mods that size or draw particles themselves
A render scale per particle for the ones the instancer batches straight from their fields, and the pack's
particle program for particles drawn outside the effect renderer. Any number of mods can add a scale source,
the factors multiply.
2026-11-16 16:21:20 +00:00
Connor Colenso e59e4662f2 Let a terrain draw use its own model space as the pack's block grid
Packs pick parts of some blocks by where a pixel sits inside its world block (cauldron water, end portal
frame eyes, brewing stands), which goes wrong for geometry drawn turned or off the grid. While a local grid
is on, the camera and matrix uniforms describe a world where the draw's model space is the block grid. View
space, clip space and the shadow map come out the same. Not on the SDL GPU backend.

The remapping is one table in LocalGridFrame, applied where the custom uniform inputs are built, so the Iris
uniform classes stay as they are. Custom uniforms the pack builds from remapped ones get evaluated again too,
and smooth() smooths from the frame's starting value when it's called twice in one frame so it doesn't step
twice.

beginLocalGrid hands back a LocalGrid to close, and warns once if the modelview was left changed. Also adds the
at_midBlock location to TerrainRendering for packs that don't need the grid.
2026-11-16 16:21:20 +00:00
Connor Colenso 6dda240a34 Add positional dynamic lights for things that aren't entities
Mods can make a light at any position, move it and change it, and it lights terrain and entities like a held
torch. Also a way to look up lights near a point and Angelica's falloff.

A light can be set to show under a shaderpack without the shader force option (setLitUnderShaderpacks), for
lights that stand in for real blocks a pack can't light itself. Entity and held item lights still need shader
force, and dynamic lights turned off still means off.

A light can also reach further than a held torch, or less far (setReach, 0-15). It falls off like block light
then, so 15 is what a real block of that luminance gives. Fractions work, for a lamp in something drawn smaller
than life. The default stays the old 7.75 block torch falloff. A positional light only tracks the chunk sections
its light gets into, up to 27 at reach 15, so a longer reach rebuilds more when it moves. A change in reach
under 0.1 doesn't rebuild anything, like a move under 0.1 blocks.

Switching dynamic lights, shader force or the pack now rebuilds the sections the lights were in. Before that a
light that went dark stayed in the terrain until something else rebuilt it, and with a pack on that would leave
entity lights behind next to the ones that stay lit. A light that sat still also never came back.

The per section source filter now counts the cells a block outside the section too (14.8 from the middle
instead of 13.9), the same cells the section tracking rebuilds for.
2026-11-16 16:21:20 +00:00
Connor Colenso 9aea999a86 Add shadow casters so mod geometry can draw into the shadow map
Casters run in the shadow pass with the solid shadows and again after translucent terrain, so geometry drawn
from a TESR or the world draw stage can shadow like terrain.
2026-11-15 22:21:54 +00:00
Connor Colenso 72657e5cfb Add a world draw stage for mod geometry inside the world pass
RenderWorldLastEvent comes after the pack's composite passes, so anything drawn there misses its lighting,
fog and shadows. Drawers registered here run right after block entities, once per Forge pass.
2026-11-15 22:21:54 +00:00
Connor Colenso 30a0291cca Add a terrain API for mods that bake blocks outside the chunk mesher
TerrainRendering lets geometry drawn outside the chunk renderer (moving structures, previews) use the
pack's terrain programs, materials, layer overrides and AO and shading settings, and bake the same way the
mesher does. TerrainLighter runs the mesher's smooth and flat light pipelines over any block access.
Vanilla AO can be turned off per thread while baking.
2026-11-15 22:21:54 +00:00
130 changed files with 2300 additions and 4676 deletions

No files matched your search

+1 -3
View File
@@ -17,7 +17,7 @@
* HUD caching * HUD caching
* Custom fonts and text effects * Custom fonts and text effects
* MCPatcher - connected textures, custom item textures, custom colors, random mobs, better skies * MCPatcher - connected textures, custom item textures, custom colors, random mobs, better skies
* Bundled NotFine, zoom, FPS reducer, menu blur * Bundled NotFine, zoom, FPS reducer
## Status ## Status
* OpenGL + Celeritas terrain - Default * OpenGL + Celeritas terrain - Default
@@ -129,7 +129,5 @@ Targets GL 3.3+ core profile
* FFP vertex shader generation inspired by ffvertex_prog.c (Copyright 2007 VMware, Inc.) * FFP vertex shader generation inspired by ffvertex_prog.c (Copyright 2007 VMware, Inc.)
* FFP fragment shader generation inspired by ff_fragment_shader.c (Copyright 2007, 2009 VMware, Inc. / 2010-2011 Intel Corporation) * FFP fragment shader generation inspired by ff_fragment_shader.c (Copyright 2007, 2009 VMware, Inc. / 2010-2011 Intel Corporation)
* Fog parameter optimization inspired by st_nir_lower_fog.c (Copyright 2023 Google LLC) and prog_statevars.c (Copyright 1999-2007 Brian Paul) * Fog parameter optimization inspired by st_nir_lower_fog.c (Copyright 2023 Google LLC) and prog_statevars.c (Copyright 1999-2007 Brian Paul)
* Blur
* tterrag for [Blur](https://github.com/tterrag1098/Blur) - Menu blur based on Blur under the MIT license
* RGSS Terrain Texture Filtering * RGSS Terrain Texture Filtering
* Indiesoft for [defold-sharp-sprite](https://github.com/indiesoftby/defold-sharp-sprite), used as the reference implementation under the MIT license * Indiesoft for [defold-sharp-sprite](https://github.com/indiesoftby/defold-sharp-sprite), used as the reference implementation under the MIT license
@@ -1,43 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.stacks.BlendStateStack;
import org.lwjgl.opengl.GL11;
/// Discards fragments that would not change the target under the draw's blend, so the depth [DepthEcho] keeps for a
/// glow covers only what the glow shows and transparent texels do not take a [DepthPeel] peel. A fragment it drops
/// changes the draw's own color by less than one 8-bit step.
public final class CoverageDiscard {
private static final int OFF = 0;
private static final int ALPHA = 1;
private static final int RGB = 2;
private static final int RGB_ALPHA = 3;
public static final String GLSL = "#define COVER_OFF " + OFF + "\n"
+ "#define COVER_RGB " + RGB + "\n"
+ "#define COVER_RGB_ALPHA " + RGB_ALPHA + "\n"
+ "#define COVER_MIN 0.004\n"
+ """
uniform int u_CoverMode;
void coverageTest(vec4 c) {
if (u_CoverMode == COVER_OFF) return;
float rgb = max(c.r, max(c.g, c.b));
float coverage = u_CoverMode == COVER_RGB ? rgb : u_CoverMode == COVER_RGB_ALPHA ? rgb * c.a : c.a;
if (coverage < COVER_MIN) discard;
}
""";
private CoverageDiscard() {}
public static boolean active() {
return GLSMConfig.depthPeel || DepthEcho.discardsCoverage();
}
public static int mode() {
if (!GLSMBlend.getBlendMode().isEnabled()) return OFF;
final BlendStateStack blend = GLStateManager.ctx().blendState;
if (blend.getDstRgb() != GL11.GL_ONE) return ALPHA;
return blend.getSrcRgb() == GL11.GL_SRC_ALPHA ? RGB_ALPHA : RGB;
}
}
@@ -1,140 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.stacks.ColorMaskStack;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND;
/// A draw between [#beginTracking] and [#endTracking] is left to the caller's replay instead of repeated. A replay
/// ignores the depth mask, which a previous renderer may leak differently into the pass and the replay, and repeats
/// set GL state through the backend, never the GLSM cache.
public final class DepthEcho {
private static int framebuffer;
private static int source;
private static boolean echoed;
private static boolean tracking;
private static boolean hit;
private static int immediate;
private static boolean replaying;
private static boolean replayDepthWrite;
private DepthEcho() {}
public static void arm(int framebuffer, int source) {
DepthEcho.framebuffer = framebuffer;
DepthEcho.source = source;
}
public static void disarm() {
framebuffer = 0;
tracking = false;
hit = false;
endReplay();
}
public static boolean armed() {
return framebuffer != 0;
}
public static void beginTracking() {
tracking = framebuffer != 0;
hit = false;
}
public static boolean endTracking() {
tracking = false;
final boolean was = hit;
hit = false;
return was;
}
public static void beginImmediate() {
immediate++;
}
public static void endImmediate() {
immediate--;
}
public static void beginReplay() {
replaying = true;
}
public static void endReplay() {
replaying = false;
restoreReplayDepthMask();
}
public static boolean replaying() {
return replaying;
}
public static boolean takeEchoed() {
final boolean was = echoed;
echoed = false;
return was;
}
public static boolean skipsCall() {
return replaySkips() && !DisplayListManager.isRecording();
}
public static boolean skipsDraw() {
if (!replaying) return false;
if (replaySkips()) return true;
if (!GLSMDepthStencilAlpha.getDepthState().isEnabled()) {
RENDER_BACKEND.depthMask(true);
replayDepthWrite = true;
}
return false;
}
private static boolean replaySkips() {
return replaying && !(blendsVisibly() && GLSMFramebuffer.getDrawFramebuffer() == framebuffer);
}
public static boolean discardsCoverage() {
return replaying || echoes();
}
public static boolean begin() {
if (replayDepthWrite) {
restoreReplayDepthMask();
return false;
}
if (!echoes()) return false;
echoed = true;
if (tracking && immediate == 0 && !BatchStateGuard.isSuspended()) {
hit = true;
return false;
}
RENDER_BACKEND.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, framebuffer);
RENDER_BACKEND.depthMask(true);
return true;
}
public static void end() {
RENDER_BACKEND.depthMask(false);
RENDER_BACKEND.bindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, source);
}
private static void restoreReplayDepthMask() {
if (!replayDepthWrite) return;
replayDepthWrite = false;
RENDER_BACKEND.depthMask(GLSMDepthStencilAlpha.getDepthState().isEnabled());
}
private static boolean echoes() {
return framebuffer != 0 && !GLSMDepthStencilAlpha.getDepthState().isEnabled() && blendsVisibly() && GLSMFramebuffer.getDrawFramebuffer() == source;
}
private static boolean blendsVisibly() {
if (!GLSMDepthStencilAlpha.getDepthTest().isEnabled() || !GLSMBlend.getBlendMode().isEnabled()) return false;
if (GLSMDepthStencilAlpha.getDepthState().getFunc() == GL11.GL_EQUAL) return false;
final ColorMaskStack mask = GLSMBlend.getColorMask();
return mask.red || mask.green || mask.blue || mask.alpha;
}
}
@@ -1,105 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.stacks.ColorMaskStack;
import com.gtnewhorizons.angelica.glsm.stacks.DepthStateStack;
import org.lwjgl.opengl.GL11;
import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND;
/// Per-draw state for depth peeling. Color passes skip the depth test but keep the draw's depth writes, so the target
/// ends with the nearest peeled depth and the rest pass's own test keeps only what is in front of it. Draws with an
/// application program cannot run [#GLSL], so they skip the peels and draw unsorted afterwards.
public final class DepthPeel {
public static final int TEXTURE_UNIT = 15;
public static final int SCENE_TEXTURE_UNIT = 14;
private static final int PASS_DEPTH = 0;
private static final int PASS_COLOR = 1;
private static final int PASS_REST = 2;
private static final int UNBOUNDED = 4;
public static final String GLSL = "#define PEEL_PASS_COLOR " + PASS_COLOR + "\n"
+ "#define PEEL_UNBOUNDED " + UNBOUNDED + "\n"
+ "#define PEEL_SCENE_TOLERANCE 6.0e-8\n"
+ "#define PEEL_WINDOW 2.4e-7\n"
+ """
uniform sampler2D u_PeelDepth;
uniform sampler2D u_PeelScene;
uniform int u_PeelMode;
void peelTest() {
ivec2 texel = ivec2(gl_FragCoord.xy);
float z = gl_FragCoord.z;
if (z > texelFetch(u_PeelScene, texel, 0).r + PEEL_SCENE_TOLERANCE) discard;
float bound = texelFetch(u_PeelDepth, texel, 0).r;
if ((u_PeelMode & 3) == PEEL_PASS_COLOR) {
if (z > bound || z < bound - PEEL_WINDOW) discard;
} else if ((u_PeelMode & PEEL_UNBOUNDED) == 0 && z >= bound - PEEL_WINDOW) {
discard;
}
}
""";
public enum Pass { OFF, DEPTH, COLOR, REST, APPLICATION }
private static Pass pass = Pass.OFF;
private static boolean unbounded;
private static boolean overridden;
private static boolean skippedApplicationDraws;
private DepthPeel() {}
public static void setPass(Pass next, boolean unbounded) {
if (pass == Pass.OFF) skippedApplicationDraws = false;
pass = next;
DepthPeel.unbounded = unbounded;
GLSMConfig.depthPeel = next == Pass.DEPTH || next == Pass.COLOR || next == Pass.REST;
}
public static boolean active() {
return pass != Pass.OFF;
}
public static boolean skippedApplicationDraws() {
return skippedApplicationDraws;
}
public static int shaderMode() {
return switch (pass) {
case DEPTH -> PASS_DEPTH | (unbounded ? UNBOUNDED : 0);
case COLOR -> PASS_COLOR;
default -> PASS_REST;
};
}
public static boolean begin() {
if (pass == Pass.OFF) return true;
final boolean fixedFunction = GLSMPrograms.getActiveProgram() == 0;
if (pass == Pass.APPLICATION) return !fixedFunction;
if (!fixedFunction) {
skippedApplicationDraws = true;
return false;
}
if (pass == Pass.DEPTH) {
RENDER_BACKEND.colorMask(false, false, false, false);
RENDER_BACKEND.depthMask(true);
RENDER_BACKEND.depthFunc(GL11.GL_GREATER);
overridden = true;
} else if (pass == Pass.COLOR) {
RENDER_BACKEND.depthFunc(GL11.GL_ALWAYS);
overridden = true;
}
return true;
}
public static void end() {
if (!overridden) return;
overridden = false;
final ColorMaskStack mask = GLSMBlend.getColorMask();
final DepthStateStack depth = GLSMDepthStencilAlpha.getDepthState();
RENDER_BACKEND.colorMask(mask.red, mask.green, mask.blue, mask.alpha);
RENDER_BACKEND.depthMask(depth.isEnabled());
RENDER_BACKEND.depthFunc(depth.getFunc());
}
}
@@ -149,46 +149,19 @@ public final class GLSMBlend {
} }
static void issueBlendFunc(BlendStateStack blend) { static void issueBlendFunc(BlendStateStack blend) {
RENDER_BACKEND.blendFuncSeparate(blend.getSrcRgb(), blend.getDstRgb(), emittedSrcAlpha(blend), emittedDstAlpha(blend)); if (GLSMConfig.hudCacheOverride) {
} RENDER_BACKEND.blendFuncSeparate(blend.getSrcRgb(), blend.getDstRgb(), GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
} else {
private static boolean addsWithoutCoverage(BlendStateStack blend) { RENDER_BACKEND.blendFuncSeparate(blend.getSrcRgb(), blend.getDstRgb(), blend.getSrcAlpha(), blend.getDstAlpha());
return blend.getDstRgb() == GL11.GL_ONE; }
}
private static int emittedSrcAlpha(BlendStateStack blend) {
if (GLSMConfig.layerBlending) return addsWithoutCoverage(blend) ? GL11.GL_ZERO : GL11.GL_ONE;
return GLSMConfig.hudCacheOverride ? GL11.GL_ONE : blend.getSrcAlpha();
}
private static int emittedDstAlpha(BlendStateStack blend) {
if (GLSMConfig.layerBlending) return addsWithoutCoverage(blend) ? GL11.GL_ONE : GL11.GL_ONE_MINUS_SRC_ALPHA;
return GLSMConfig.hudCacheOverride ? GL11.GL_ONE_MINUS_SRC_ALPHA : blend.getDstAlpha();
} }
public static void setHudCacheOverride(boolean enabled) { public static void setHudCacheOverride(boolean enabled) {
if (GLSMConfig.hudCacheOverride == enabled) return; if (GLSMConfig.hudCacheOverride == enabled) return;
GLSMConfig.hudCacheOverride = enabled; GLSMConfig.hudCacheOverride = enabled;
reissueBlendFunc();
}
public static void setLayerBlending(boolean enabled) {
if (GLSMConfig.layerBlending == enabled) return;
GLSMConfig.layerBlending = enabled;
reissueBlendFunc();
}
public static boolean isLayerBlending() {
return GLSMConfig.layerBlending;
}
private static void reissueBlendFunc() {
final BlendStateStack blend = ctx().blendState;
final DeferredBlendHandler bh = GLSMHooks.blendHandler; final DeferredBlendHandler bh = GLSMHooks.blendHandler;
if (bh != null && bh.isOverrideHeld()) { if (bh != null && bh.isOverrideHeld()) return;
blend.setFuncUnknownState(); final BlendStateStack blend = ctx().blendState;
return;
}
issueBlendFunc(blend); issueBlendFunc(blend);
blend.clearFuncUnknownState(); blend.clearFuncUnknownState();
} }
@@ -253,10 +226,11 @@ public final class GLSMBlend {
glCtx.blendState.clearFuncUnknownState(); glCtx.blendState.clearFuncUnknownState();
issueBlendFunc(glCtx.blendState); issueBlendFunc(glCtx.blendState);
if (GLSMHooks.BLEND_FUNC_CHANGE.hasListeners()) { if (GLSMHooks.BLEND_FUNC_CHANGE.hasListeners()) {
final boolean hudCache = GLSMConfig.hudCacheOverride;
GLSMHooks.blendFuncChangeEvent.srcRgb = srcRgb; GLSMHooks.blendFuncChangeEvent.srcRgb = srcRgb;
GLSMHooks.blendFuncChangeEvent.dstRgb = dstRgb; GLSMHooks.blendFuncChangeEvent.dstRgb = dstRgb;
GLSMHooks.blendFuncChangeEvent.srcAlpha = emittedSrcAlpha(glCtx.blendState); GLSMHooks.blendFuncChangeEvent.srcAlpha = hudCache ? GL11.GL_ONE : srcAlpha;
GLSMHooks.blendFuncChangeEvent.dstAlpha = emittedDstAlpha(glCtx.blendState); GLSMHooks.blendFuncChangeEvent.dstAlpha = hudCache ? GL11.GL_ONE_MINUS_SRC_ALPHA : dstAlpha;
GLSMHooks.BLEND_FUNC_CHANGE.post(GLSMHooks.blendFuncChangeEvent); GLSMHooks.BLEND_FUNC_CHANGE.post(GLSMHooks.blendFuncChangeEvent);
} }
} }
@@ -6,7 +6,6 @@ import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode;
import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener; import com.gtnewhorizons.angelica.glsm.backend.GLDebugMessageListener;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.ffp.VAOManager; import com.gtnewhorizons.angelica.glsm.ffp.VAOManager;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList;
import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder;
@@ -77,7 +76,6 @@ public final class GLSMDraws {
ImmediateModeRecorder.begin(mode); ImmediateModeRecorder.begin(mode);
return; return;
} }
BatchStateGuard.beforeDraw();
ImmediateModeRecorder.beginLive(mode); ImmediateModeRecorder.beginLive(mode);
} }
@@ -143,7 +141,6 @@ public final class GLSMDraws {
} }
public static void glDrawElements(int mode, ByteBuffer indices) { public static void glDrawElements(int mode, ByteBuffer indices) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
CommandRecorder savedRecorder = null; CommandRecorder savedRecorder = null;
@@ -177,7 +174,6 @@ public final class GLSMDraws {
} }
public static void glDrawElements(int mode, IntBuffer indices) { public static void glDrawElements(int mode, IntBuffer indices) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
CommandRecorder savedRecorder = null; CommandRecorder savedRecorder = null;
@@ -211,7 +207,6 @@ public final class GLSMDraws {
} }
public static void glDrawElements(int mode, ShortBuffer indices) { public static void glDrawElements(int mode, ShortBuffer indices) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
CommandRecorder savedRecorder = null; CommandRecorder savedRecorder = null;
@@ -245,7 +240,6 @@ public final class GLSMDraws {
} }
public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) { public static void glDrawElements(int mode, int count, int type, ByteBuffer indices) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
CommandRecorder savedRecorder = null; CommandRecorder savedRecorder = null;
@@ -279,7 +273,6 @@ public final class GLSMDraws {
} }
public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) { public static void glDrawElements(int mode, int indices_count, int type, long indices_buffer_offset) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
final GLContextState glCtx = ctx(); final GLContextState glCtx = ctx();
drawCalls++; drawCalls++;
@@ -336,14 +329,12 @@ public final class GLSMDraws {
} }
public static void glDrawElementsBaseVertex(int mode, int count, int type, long indices, int basevertex) { public static void glDrawElementsBaseVertex(int mode, int count, int type, long indices, int basevertex) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
RENDER_BACKEND.drawElementsBaseVertex(mode, count, type, indices, basevertex); RENDER_BACKEND.drawElementsBaseVertex(mode, count, type, indices, basevertex);
} }
public static void glDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) { public static void glDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
final GLContextState glCtx = ctx(); final GLContextState glCtx = ctx();
@@ -362,7 +353,6 @@ public final class GLSMDraws {
} }
public static void glDrawArraysInstanced(int mode, int first, int count, int primcount) { public static void glDrawArraysInstanced(int mode, int first, int count, int primcount) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
final GLContextState glCtx = ctx(); final GLContextState glCtx = ctx();
@@ -387,7 +377,6 @@ public final class GLSMDraws {
} }
public static void glDrawRangeElements(int mode, int start, int end, int count, int type, long indices) { public static void glDrawRangeElements(int mode, int start, int end, int count, int type, long indices) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
final GLContextState glCtx = ctx(); final GLContextState glCtx = ctx();
final boolean locked = acquireDrawLock(); final boolean locked = acquireDrawLock();
@@ -404,13 +393,11 @@ public final class GLSMDraws {
} }
public static void glDrawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) { public static void glDrawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
RENDER_BACKEND.drawRangeElementsBaseVertex(mode, start, end, count, type, indices, baseVertex); RENDER_BACKEND.drawRangeElementsBaseVertex(mode, start, end, count, type, indices, baseVertex);
} }
public static void glMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { public static void glMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
final GLContextState glCtx = ctx(); final GLContextState glCtx = ctx();
final boolean locked = acquireDrawLock(); final boolean locked = acquireDrawLock();
@@ -436,7 +423,6 @@ public final class GLSMDraws {
} }
public static void glDrawArrays(int mode, int first, int count) { public static void glDrawArrays(int mode, int first, int count) {
if (DepthEcho.skipsCall()) return;
rejectExitCapture(); rejectExitCapture();
drawCalls++; drawCalls++;
CommandRecorder savedRecorder = null; CommandRecorder savedRecorder = null;
@@ -535,7 +521,6 @@ public final class GLSMDraws {
public static void glCallList(int list) { public static void glCallList(int list) {
rejectExitCapture(); rejectExitCapture();
if (!DisplayListManager.isRecording()) BatchStateGuard.beforeDraw();
if (!GLDebug.isActive()) { if (!GLDebug.isActive()) {
DisplayListManager.glCallList(list); DisplayListManager.glCallList(list);
return; return;
@@ -64,7 +64,6 @@ public final class GLSMFramebuffer {
private static long firstClearBlockNanos; private static long firstClearBlockNanos;
public static void glClear(int mask) { public static void glClear(int mask) {
if (DepthEcho.replaying() && !DisplayListManager.isRecording()) return;
rejectExitCapture(); rejectExitCapture();
final RecordMode mode = DisplayListManager.getRecordMode(); final RecordMode mode = DisplayListManager.getRecordMode();
if (mode != RecordMode.NONE) { if (mode != RecordMode.NONE) {
@@ -316,7 +315,6 @@ public final class GLSMFramebuffer {
} }
public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) { public static void glBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, int mask, int filter) {
if (DepthEcho.replaying() && !DisplayListManager.isRecording()) return;
rejectExitCapture(); rejectExitCapture();
RENDER_BACKEND.blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); RENDER_BACKEND.blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
} }
@@ -503,8 +503,8 @@ public final class GLSMQueries {
return RENDER_BACKEND.genQueries(); return RENDER_BACKEND.genQueries();
} }
public static void glDeleteQueries(int id) { rejectExitCapture(); RENDER_BACKEND.deleteQueries(id); } public static void glDeleteQueries(int id) { rejectExitCapture(); RENDER_BACKEND.deleteQueries(id); }
public static void glBeginQuery(int target, int id) { rejectExitCapture(); if (!DepthEcho.replaying()) RENDER_BACKEND.beginQuery(target, id); } public static void glBeginQuery(int target, int id) { rejectExitCapture(); RENDER_BACKEND.beginQuery(target, id); }
public static void glEndQuery(int target) { rejectExitCapture(); if (!DepthEcho.replaying()) RENDER_BACKEND.endQuery(target); } public static void glEndQuery(int target) { rejectExitCapture(); RENDER_BACKEND.endQuery(target); }
public static void glGetQueryObjectui(int id, int pname, IntBuffer params) { rejectExitCapture(); RENDER_BACKEND.getQueryObjectui(id, pname, params); } public static void glGetQueryObjectui(int id, int pname, IntBuffer params) { rejectExitCapture(); RENDER_BACKEND.getQueryObjectui(id, pname, params); }
public static int glGetQueryObjecti(int id, int pname) { rejectExitCapture(); return RENDER_BACKEND.getQueryObjecti(id, pname); } public static int glGetQueryObjecti(int id, int pname) { rejectExitCapture(); return RENDER_BACKEND.getQueryObjecti(id, pname); }
public static void glQueryCounter(int id, int target) { rejectExitCapture(); RENDER_BACKEND.queryCounter(id, target); } public static void glQueryCounter(int id, int target) { rejectExitCapture(); RENDER_BACKEND.queryCounter(id, target); }
@@ -6,8 +6,6 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import java.util.Arrays;
public final class StateSet { public final class StateSet {
public static final int R_DEPTH = 1; public static final int R_DEPTH = 1;
@@ -81,47 +79,28 @@ public final class StateSet {
public static final StateSet CUTOUT = buildCutout(); public static final StateSet CUTOUT = buildCutout();
public static final StateSet MASKS = buildMasks(); public static final StateSet MASKS = buildMasks();
public static final StateSet CULL = buildCull(); public static final StateSet CULL = buildCull();
public static final StateSet BLOCK_ENTITY_PASS = buildBlockEntityPass();
private static CowStateStack<?>[] batchMembers() {
return new CowStateStack<?>[] {
GLSMBlend.getBlendState(), GLSMDepthStencilAlpha.getAlphaState(), GLSMDepthStencilAlpha.getDepthState(),
GLSMBlend.getColorMask(), GLSMRasterizer.getPolygonState(),
GLSMTextures.getTextures().getTextureUnitBindings(0), GLSMTextures.getTextures().getTextureUnitBindings(1),
GLSMTextures.getActiveTextureUnitStack(),
GLSMBlend.getBlendMode(), GLSMDepthStencilAlpha.getAlphaTest(), GLSMDepthStencilAlpha.getDepthTest(),
GLSMLighting.getLightingState(), GLSMRasterizer.getCullState(), GLSMRasterizer.getPolygonOffsetFillState(),
GLSMTextures.getTextures().getTextureUnitStates(0), GLSMTextures.getTextures().getTextureUnitStates(1),
GLSMLighting.getLightStates()[0], GLSMLighting.getLightStates()[1],
GLSMLighting.getLightDataStates()[0], GLSMLighting.getLightDataStates()[1],
GLSMLighting.getColorMaterial(), GLSMLighting.getColorMaterialFace(), GLSMLighting.getColorMaterialParameter(),
GLSMLighting.getLightModel(), GLSMLighting.getFrontMaterial(), GLSMLighting.getBackMaterial(),
GLSMLighting.getNormalizeState(), GLSMLighting.getRescaleNormalState()
};
}
private static StateSet buildBatch() { private static StateSet buildBatch() {
return new StateSet(0, return new StateSet(0,
ids(batchMembers()), ids(
GLSMBlend.getBlendState(), GLSMDepthStencilAlpha.getAlphaState(), GLSMDepthStencilAlpha.getDepthState(),
GLSMBlend.getColorMask(), GLSMRasterizer.getPolygonState(),
GLSMTextures.getTextures().getTextureUnitBindings(0), GLSMTextures.getTextures().getTextureUnitBindings(1),
GLSMTextures.getActiveTextureUnitStack(),
GLSMBlend.getBlendMode(), GLSMDepthStencilAlpha.getAlphaTest(), GLSMDepthStencilAlpha.getDepthTest(),
GLSMLighting.getLightingState(), GLSMRasterizer.getCullState(), GLSMRasterizer.getPolygonOffsetFillState(),
GLSMTextures.getTextures().getTextureUnitStates(0), GLSMTextures.getTextures().getTextureUnitStates(1),
GLSMLighting.getLightStates()[0], GLSMLighting.getLightStates()[1],
GLSMLighting.getLightDataStates()[0], GLSMLighting.getLightDataStates()[1],
GLSMLighting.getColorMaterial(), GLSMLighting.getColorMaterialFace(), GLSMLighting.getColorMaterialParameter(),
GLSMLighting.getLightModel(), GLSMLighting.getFrontMaterial(), GLSMLighting.getBackMaterial(),
GLSMLighting.getNormalizeState(), GLSMLighting.getRescaleNormalState()
),
R_BLEND | R_DEPTH | R_COLOR_MASK | R_POLYGON | R_TEXTURE | R_ACTIVE_UNIT, R_BLEND | R_DEPTH | R_COLOR_MASK | R_POLYGON | R_TEXTURE | R_ACTIVE_UNIT,
B_FRAG_COLORBUF | B_LIGHTING, B_FRAG_COLORBUF | B_LIGHTING,
true); true);
} }
private static StateSet buildBlockEntityPass() {
final CowStateStack<?>[] batch = batchMembers();
final CowStateStack<?>[] all = Arrays.copyOf(batch, batch.length + 4);
all[batch.length] = GLSMCurrentAttribs.getColor();
all[batch.length + 1] = GLSMFog.getFogState();
all[batch.length + 2] = GLSMFog.getFogMode();
all[batch.length + 3] = GLSMRasterizer.getShadeModelState();
return new StateSet(0,
ids(all),
R_BLEND | R_DEPTH | R_COLOR_MASK | R_POLYGON | R_TEXTURE | R_ACTIVE_UNIT,
B_FRAG_COLORBUF | B_LIGHTING | B_CURRENT | B_FRAG_FOG,
true);
}
private static StateSet buildFont() { private static StateSet buildFont() {
return new StateSet(0, return new StateSet(0,
ids( ids(
@@ -323,42 +323,42 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueDrawArrays(int mode, int first, int count) { public void drawArrays(int mode, int first, int count) {
GL11.glDrawArrays(mode, first, count); GL11.glDrawArrays(mode, first, count);
} }
@Override @Override
protected void issueDrawElements(int mode, int count, int type, long indices) { public void drawElements(int mode, int count, int type, long indices) {
GL11.glDrawElements(mode, count, type, indices); GL11.glDrawElements(mode, count, type, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, ByteBuffer indices) { public void drawElements(int mode, ByteBuffer indices) {
GL11.glDrawElements(mode, indices); GL11.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, IntBuffer indices) { public void drawElements(int mode, IntBuffer indices) {
GL11.glDrawElements(mode, indices); GL11.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, ShortBuffer indices) { public void drawElements(int mode, ShortBuffer indices) {
GL11.glDrawElements(mode, indices); GL11.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, int count, int type, ByteBuffer indices) { public void drawElements(int mode, int count, int type, ByteBuffer indices) {
GL11.glDrawElements(mode, count, type, indices); GL11.glDrawElements(mode, count, type, indices);
} }
@Override @Override
protected void issueDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) { public void drawElementsInstanced(int mode, int count, int type, long indices, int primcount) {
GL31.glDrawElementsInstanced(mode, count, type, indices, primcount); GL31.glDrawElementsInstanced(mode, count, type, indices, primcount);
} }
@Override @Override
protected void issueDrawArraysInstanced(int mode, int first, int count, int primcount) { public void drawArraysInstanced(int mode, int first, int count, int primcount) {
GL31.glDrawArraysInstanced(mode, first, count, primcount); GL31.glDrawArraysInstanced(mode, first, count, primcount);
} }
@@ -368,7 +368,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { public void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) {
GL43.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride); GL43.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride);
} }
@@ -378,12 +378,12 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueDrawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) { public void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) {
GL32.glDrawElementsBaseVertex(mode, count, type, indices, baseVertex); GL32.glDrawElementsBaseVertex(mode, count, type, indices, baseVertex);
} }
@Override @Override
protected void issueMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) {
for (int i = 0; i < drawcount; i++) { for (int i = 0; i < drawcount; i++) {
GL32.glDrawElementsBaseVertex(mode, memGetInt(pCount + 4L * i), type, memGetAddress(pIndices + (long) i * POINTER_SIZE), memGetInt(pBaseVertex + 4L * i)); GL32.glDrawElementsBaseVertex(mode, memGetInt(pCount + 4L * i), type, memGetAddress(pIndices + (long) i * POINTER_SIZE), memGetInt(pBaseVertex + 4L * i));
} }
@@ -1715,7 +1715,7 @@ public final class Lwjgl2GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) {
GL14.glMultiDrawArrays(mode, firsts, counts); GL14.glMultiDrawArrays(mode, firsts, counts);
} }
@@ -1,8 +1,6 @@
package com.gtnewhorizons.angelica.glsm.backend; package com.gtnewhorizons.angelica.glsm.backend;
import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
import com.gtnewhorizons.angelica.glsm.DepthEcho;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import com.gtnewhorizons.angelica.glsm.GLESFormatRemap; import com.gtnewhorizons.angelica.glsm.GLESFormatRemap;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack; import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.GLStateManager;
@@ -323,221 +321,28 @@ public abstract class RenderBackend {
public abstract void logicOp(int opcode); public abstract void logicOp(int opcode);
public abstract void hint(int target, int mode); public abstract void hint(int target, int mode);
public abstract void drawArrays(int mode, int first, int count);
public abstract void drawElements(int mode, int count, int type, long indices);
public void drawElements(int mode, ByteBuffer indices) {}
public void drawElements(int mode, IntBuffer indices) {}
public void drawElements(int mode, ShortBuffer indices) {}
public void drawElements(int mode, int count, int type, ByteBuffer indices) {}
public abstract void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride);
public void multiDrawArraysIndirectCount(int mode, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); } public void multiDrawArraysIndirectCount(int mode, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); }
public void multiDrawElementsIndirectCount(int mode, int type, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); } public void multiDrawElementsIndirectCount(int mode, int type, long indirect, long drawcount, int maxdrawcount, int stride) { throw new UnsupportedOperationException(getName() + ": indirect draw-count buffers unsupported"); }
public abstract void copyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size); public abstract void copyBufferSubData(int readTarget, int writeTarget, long readOffset, long writeOffset, long size);
public abstract void drawElementsInstanced(int mode, int count, int type, long indices, int primcount);
public abstract void drawArraysInstanced(int mode, int first, int count, int primcount);
public void provokingVertex(int provokeMode) {} public void provokingVertex(int provokeMode) {}
public abstract void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex);
public final void drawArrays(int mode, int first, int count) { public abstract void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex);
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawArrays(mode, first, count);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawArrays(mode, first, count);
} finally {
DepthEcho.end();
}
}
}
public final void drawElements(int mode, int count, int type, long indices) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElements(mode, count, type, indices);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElements(mode, count, type, indices);
} finally {
DepthEcho.end();
}
}
}
public final void drawElements(int mode, ByteBuffer indices) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElements(mode, indices);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElements(mode, indices);
} finally {
DepthEcho.end();
}
}
}
public final void drawElements(int mode, IntBuffer indices) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElements(mode, indices);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElements(mode, indices);
} finally {
DepthEcho.end();
}
}
}
public final void drawElements(int mode, ShortBuffer indices) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElements(mode, indices);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElements(mode, indices);
} finally {
DepthEcho.end();
}
}
}
public final void drawElements(int mode, int count, int type, ByteBuffer indices) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElements(mode, count, type, indices);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElements(mode, count, type, indices);
} finally {
DepthEcho.end();
}
}
}
public final void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride);
} finally {
DepthEcho.end();
}
}
}
public final void drawElementsInstanced(int mode, int count, int type, long indices, int primcount) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElementsInstanced(mode, count, type, indices, primcount);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElementsInstanced(mode, count, type, indices, primcount);
} finally {
DepthEcho.end();
}
}
}
public final void drawArraysInstanced(int mode, int first, int count, int primcount) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawArraysInstanced(mode, first, count, primcount);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawArraysInstanced(mode, first, count, primcount);
} finally {
DepthEcho.end();
}
}
}
public final void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueDrawElementsBaseVertex(mode, count, type, indices, baseVertex);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueDrawElementsBaseVertex(mode, count, type, indices, baseVertex);
} finally {
DepthEcho.end();
}
}
}
public final void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueMultiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueMultiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex);
} finally {
DepthEcho.end();
}
}
}
public final void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) {
if (DepthEcho.skipsDraw() || !DepthPeel.begin()) return;
try {
issueMultiDrawArrays(mode, firsts, counts);
} finally {
DepthPeel.end();
}
if (DepthEcho.begin()) {
try {
issueMultiDrawArrays(mode, firsts, counts);
} finally {
DepthEcho.end();
}
}
}
protected abstract void issueDrawArrays(int mode, int first, int count);
protected abstract void issueDrawElements(int mode, int count, int type, long indices);
protected void issueDrawElements(int mode, ByteBuffer indices) {}
protected void issueDrawElements(int mode, IntBuffer indices) {}
protected void issueDrawElements(int mode, ShortBuffer indices) {}
protected void issueDrawElements(int mode, int count, int type, ByteBuffer indices) {}
protected abstract void issueMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride);
protected abstract void issueDrawElementsInstanced(int mode, int count, int type, long indices, int primcount);
protected abstract void issueDrawArraysInstanced(int mode, int first, int count, int primcount);
protected abstract void issueDrawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex);
protected abstract void issueMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex);
protected abstract void issueMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts);
public void drawRangeElements(int mode, int start, int end, int count, int type, long indices) { public void drawRangeElements(int mode, int start, int end, int count, int type, long indices) {
drawElements(mode, count, type, indices); drawElements(mode, count, type, indices);
} }
public void drawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) { public void drawRangeElementsBaseVertex(int mode, int start, int end, int count, int type, long indices, int baseVertex) {
drawElementsBaseVertex(mode, count, type, indices, baseVertex); drawElementsBaseVertex(mode, count, type, indices, baseVertex);
} }
public abstract void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts);
public abstract void primitiveRestartIndex(int index); public abstract void primitiveRestartIndex(int index);
public abstract void pointParameterf(int pname, float param); public abstract void pointParameterf(int pname, float param);
public abstract void pointParameteri(int pname, int param); public abstract void pointParameteri(int pname, int param);
@@ -2,11 +2,9 @@ package com.gtnewhorizons.angelica.glsm.ffp;
import java.util.Arrays; import java.util.Arrays;
import com.gtnewhorizons.angelica.glsm.CoverageDiscard;
import com.gtnewhorizons.angelica.glsm.GLContextState; import com.gtnewhorizons.angelica.glsm.GLContextState;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer; import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.GLStateManager;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMConfig;
import com.gtnewhorizons.angelica.glsm.states.TexEnvState; import com.gtnewhorizons.angelica.glsm.states.TexEnvState;
import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray; import com.gtnewhorizons.angelica.glsm.states.TextureUnitArray;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
@@ -18,24 +16,24 @@ import org.lwjgl.opengl.GL13;
* Packed-long fragment shader permutation key for FFP emulation. * Packed-long fragment shader permutation key for FFP emulation.
* *
* Layout: * Layout:
* long[0]: global bits (14) + unit 0 (45 bits at offset 14), depth peel (59), coverage discard (60), combined glint (61), glint alpha (62), clip discard (63) * long[0]: global bits (14) + unit 0 (47 bits at offset 14)
* long[1..3]: unit 1..3 (45 bits each, low-aligned) * long[1..3]: unit 1..3 (47 bits each, low-aligned)
* Only max(1, nrEnabledUnits) longs are significant. * Only max(1, nrEnabledUnits) longs are significant.
* *
* Per-unit packing (45 bits): * Per-unit packing (47 bits):
* 0: enabled * 0: enabled
* 1-3: mode (MODULATE=0..COMBINE=5) * 1-3: mode (MODULATE=0..COMBINE=5)
* 4: needsEnvColor * 4: needsEnvColor
* 5-7: combineRgb (encoded 0-7) * 5-8: combineRgb (encoded 0-7)
* 8-10: combineAlpha (encoded 0-7) * 9-12: combineAlpha (encoded 0-7)
* 11-12: scaleShiftRgb * 13-14: scaleShiftRgb
* 13-14: scaleShiftAlpha * 15-16: scaleShiftAlpha
* 15-19: arg0 RGB (source:3 + operand:2) * 17-21: arg0 RGB (source:3 + operand:2)
* 20-24: arg1 RGB * 22-26: arg1 RGB
* 25-29: arg2 RGB * 27-31: arg2 RGB
* 30-34: arg0 Alpha * 32-36: arg0 Alpha
* 35-39: arg1 Alpha * 37-41: arg1 Alpha
* 40-44: arg2 Alpha * 42-46: arg2 Alpha
*/ */
public final class FragmentKey { public final class FragmentKey {
public static final int TEX_ENV_MODULATE = 0; public static final int TEX_ENV_MODULATE = 0;
@@ -80,8 +78,6 @@ public final class FragmentKey {
} }
private static final int GLOBAL_BITS = 14; private static final int GLOBAL_BITS = 14;
private static final int BIT_DEPTH_PEEL = 59;
private static final int BIT_COVERAGE_DISCARD = 60;
private static final int BIT_COMBINED_GLINT = 61; private static final int BIT_COMBINED_GLINT = 61;
private static final int BIT_GLINT_REPLACE_ALPHA = 62; private static final int BIT_GLINT_REPLACE_ALPHA = 62;
private static final int BIT_CLIP_DISCARD = 63; private static final int BIT_CLIP_DISCARD = 63;
@@ -98,16 +94,16 @@ public final class FragmentKey {
private static final int U_ENABLED = 0; private static final int U_ENABLED = 0;
private static final int U_MODE = 1; // 3 bits private static final int U_MODE = 1; // 3 bits
private static final int U_NEEDS_ENV_COLOR = 4; // 1 bit private static final int U_NEEDS_ENV_COLOR = 4; // 1 bit
private static final int U_COMBINE_RGB = 5; // 3 bits private static final int U_COMBINE_RGB = 5; // 4 bits
private static final int U_COMBINE_ALPHA = 8; // 3 bits private static final int U_COMBINE_ALPHA = 9; // 4 bits
private static final int U_SCALE_RGB = 11; // 2 bits private static final int U_SCALE_RGB = 13; // 2 bits
private static final int U_SCALE_ALPHA = 13; // 2 bits private static final int U_SCALE_ALPHA = 15; // 2 bits
private static final int U_ARG0_RGB = 15; // 5 bits (source:3 + operand:2) private static final int U_ARG0_RGB = 17; // 5 bits (source:3 + operand:2)
private static final int U_ARG1_RGB = 20; // 5 bits private static final int U_ARG1_RGB = 22; // 5 bits
private static final int U_ARG2_RGB = 25; // 5 bits private static final int U_ARG2_RGB = 27; // 5 bits
private static final int U_ARG0_ALPHA = 30; // 5 bits private static final int U_ARG0_ALPHA = 32; // 5 bits
private static final int U_ARG1_ALPHA = 35; // 5 bits private static final int U_ARG1_ALPHA = 37; // 5 bits
private static final int U_ARG2_ALPHA = 40; // 5 bits private static final int U_ARG2_ALPHA = 42; // 5 bits
static final int MAX_UNITS = 4; static final int MAX_UNITS = 4;
@@ -131,8 +127,6 @@ public final class FragmentKey {
public static int packFromState(long[] out, GLContextState glCtx) { public static int packFromState(long[] out, GLContextState glCtx) {
long global = 0; long global = 0;
if (CombinedGlint.isActive()) global |= 1L << BIT_COMBINED_GLINT; if (CombinedGlint.isActive()) global |= 1L << BIT_COMBINED_GLINT;
if (CoverageDiscard.active()) global |= 1L << BIT_COVERAGE_DISCARD;
if (GLSMConfig.depthPeel) global |= 1L << BIT_DEPTH_PEEL;
if (CombinedGlint.replacesAlpha()) global |= 1L << BIT_GLINT_REPLACE_ALPHA; if (CombinedGlint.replacesAlpha()) global |= 1L << BIT_GLINT_REPLACE_ALPHA;
if (GLSMRasterizer.clipEmulationActive(glCtx)) global |= 1L << BIT_CLIP_DISCARD; if (GLSMRasterizer.clipEmulationActive(glCtx)) global |= 1L << BIT_CLIP_DISCARD;
@@ -206,8 +200,8 @@ public final class FragmentKey {
if (mode == TEX_ENV_COMBINE) { if (mode == TEX_ENV_COMBINE) {
final int combRgb = encodeCombineFunc(envState.combineRgb); final int combRgb = encodeCombineFunc(envState.combineRgb);
final int combAlpha = encodeCombineFunc(envState.combineAlpha); final int combAlpha = encodeCombineFunc(envState.combineAlpha);
bits |= ((long) (combRgb & 0x7)) << U_COMBINE_RGB; bits |= ((long) (combRgb & 0xF)) << U_COMBINE_RGB;
bits |= ((long) (combAlpha & 0x7)) << U_COMBINE_ALPHA; bits |= ((long) (combAlpha & 0xF)) << U_COMBINE_ALPHA;
bits |= ((long) (encodeScale(envState.scaleRgb) & 0x3)) << U_SCALE_RGB; bits |= ((long) (encodeScale(envState.scaleRgb) & 0x3)) << U_SCALE_RGB;
bits |= ((long) (encodeScale(envState.scaleAlpha) & 0x3)) << U_SCALE_ALPHA; bits |= ((long) (encodeScale(envState.scaleAlpha) & 0x3)) << U_SCALE_ALPHA;
@@ -270,8 +264,6 @@ public final class FragmentKey {
public boolean combinedGlint() { return (packed[0] & (1L << BIT_COMBINED_GLINT)) != 0; } public boolean combinedGlint() { return (packed[0] & (1L << BIT_COMBINED_GLINT)) != 0; }
public boolean clipDiscard() { return (packed[0] & (1L << BIT_CLIP_DISCARD)) != 0; } public boolean clipDiscard() { return (packed[0] & (1L << BIT_CLIP_DISCARD)) != 0; }
public boolean glintReplaceAlpha() { return (packed[0] & (1L << BIT_GLINT_REPLACE_ALPHA)) != 0; } public boolean glintReplaceAlpha() { return (packed[0] & (1L << BIT_GLINT_REPLACE_ALPHA)) != 0; }
public boolean coverageDiscard() { return (packed[0] & (1L << BIT_COVERAGE_DISCARD)) != 0; }
public boolean depthPeel() { return (packed[0] & (1L << BIT_DEPTH_PEEL)) != 0; }
public int textureSupersamplingSamples() { return 1 << (int) ((packed[0] >> BIT_TEXTURE_SUPERSAMPLING) & 0x7); } public int textureSupersamplingSamples() { return 1 << (int) ((packed[0] >> BIT_TEXTURE_SUPERSAMPLING) & 0x7); }
public boolean alphaTestEnabled() { return ((packed[0] >> BIT_ALPHA_TEST) & 1) != 0; } public boolean alphaTestEnabled() { return ((packed[0] >> BIT_ALPHA_TEST) & 1) != 0; }
public int alphaTestFunc() { return (int) ((packed[0] >> BIT_ALPHA_FUNC) & 0x7); } public int alphaTestFunc() { return (int) ((packed[0] >> BIT_ALPHA_FUNC) & 0x7); }
@@ -289,8 +281,8 @@ public final class FragmentKey {
public boolean unitEnabled(int i) { return (unitBits(i) & 1) != 0; } public boolean unitEnabled(int i) { return (unitBits(i) & 1) != 0; }
public int unitMode(int i) { return (int) ((unitBits(i) >> U_MODE) & 0x7); } public int unitMode(int i) { return (int) ((unitBits(i) >> U_MODE) & 0x7); }
public boolean unitNeedsEnvColor(int i) { return ((unitBits(i) >> U_NEEDS_ENV_COLOR) & 1) != 0; } public boolean unitNeedsEnvColor(int i) { return ((unitBits(i) >> U_NEEDS_ENV_COLOR) & 1) != 0; }
public int unitCombineRgb(int i) { return (int) ((unitBits(i) >> U_COMBINE_RGB) & 0x7); } public int unitCombineRgb(int i) { return (int) ((unitBits(i) >> U_COMBINE_RGB) & 0xF); }
public int unitCombineAlpha(int i) { return (int) ((unitBits(i) >> U_COMBINE_ALPHA) & 0x7); } public int unitCombineAlpha(int i) { return (int) ((unitBits(i) >> U_COMBINE_ALPHA) & 0xF); }
public int unitScaleShiftRgb(int i) { return (int) ((unitBits(i) >> U_SCALE_RGB) & 0x3); } public int unitScaleShiftRgb(int i) { return (int) ((unitBits(i) >> U_SCALE_RGB) & 0x3); }
public int unitScaleShiftAlpha(int i) { return (int) ((unitBits(i) >> U_SCALE_ALPHA) & 0x3); } public int unitScaleShiftAlpha(int i) { return (int) ((unitBits(i) >> U_SCALE_ALPHA) & 0x3); }
@@ -1,7 +1,5 @@
package com.gtnewhorizons.angelica.glsm.ffp; package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.glsm.CoverageDiscard;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader;
@@ -26,8 +24,6 @@ public final class FragmentShaderGenerator {
sb.append("#define GLINT_ALPHA_FUNC ").append(key.alphaTestEnabled() ? key.alphaTestFunc() : 7).append('\n'); sb.append("#define GLINT_ALPHA_FUNC ").append(key.alphaTestEnabled() ? key.alphaTestFunc() : 7).append('\n');
sb.append("#define GLINT_OVERLAY ").append(key.overlayInstanced() ? 2 : key.overlayEnabled() ? 1 : 0).append('\n'); sb.append("#define GLINT_OVERLAY ").append(key.overlayInstanced() ? 2 : key.overlayEnabled() ? 1 : 0).append('\n');
sb.append("#define GLINT_LIGHTMAP ").append(key.nrEnabledUnits() > 1 && key.unitEnabled(1) ? 1 : 0).append('\n'); sb.append("#define GLINT_LIGHTMAP ").append(key.nrEnabledUnits() > 1 && key.unitEnabled(1) ? 1 : 0).append('\n');
if (key.depthPeel()) sb.append("#define DEPTH_PEEL 1\n");
if (key.coverageDiscard()) sb.append("#define COVERAGE_DISCARD 1\n");
sb.append(ShaderLoader.getShaderSource("angelica:combined_glint.frag.glsl")); sb.append(ShaderLoader.getShaderSource("angelica:combined_glint.frag.glsl"));
return sb.toString(); return sb.toString();
} }
@@ -47,8 +43,6 @@ public final class FragmentShaderGenerator {
emitSpecularAdd(sb, key); emitSpecularAdd(sb, key);
emitAlphaTest(sb, key); emitAlphaTest(sb, key);
emitFog(sb, key); emitFog(sb, key);
if (key.depthPeel()) sb.append(" peelTest();\n");
if (key.coverageDiscard()) sb.append(" coverageTest(color);\n");
sb.append(" fragColor = color;\n"); sb.append(" fragColor = color;\n");
sb.append("}\n"); sb.append("}\n");
@@ -95,8 +89,6 @@ public final class FragmentShaderGenerator {
sb.append("uniform sampler2D u_Sampler").append(i).append(";\n"); sb.append("uniform sampler2D u_Sampler").append(i).append(";\n");
} }
} }
if (key.depthPeel()) sb.append(DepthPeel.GLSL);
if (key.coverageDiscard()) sb.append(CoverageDiscard.GLSL);
sb.append(FFPUniformBlock.GLSL_DECL); sb.append(FFPUniformBlock.GLSL_DECL);
sb.append('\n'); sb.append('\n');
} }
@@ -2,7 +2,6 @@ package com.gtnewhorizons.angelica.glsm.ffp;
import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer; import com.gtnewhorizons.angelica.glsm.CompatShaderTransformer;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import com.gtnewhorizons.angelica.glsm.GLDebug; import com.gtnewhorizons.angelica.glsm.GLDebug;
import com.gtnewhorizons.angelica.glsm.GLSMPrograms; import com.gtnewhorizons.angelica.glsm.GLSMPrograms;
import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.GLStateManager;
@@ -36,12 +35,6 @@ public class Program {
@Getter private final FragmentKey fragmentKey; @Getter private final FragmentKey fragmentKey;
public final int[] locSampler = { -1, -1, -1, -1 }; public final int[] locSampler = { -1, -1, -1, -1 };
public final int locPeelDepth;
public final int locPeelScene;
private final int locPeelMode;
private int peelMode = -1;
private final int locCoverMode;
private int coverMode = -1;
Program(int programId, VertexKey vertexKey, FragmentKey fragmentKey) { Program(int programId, VertexKey vertexKey, FragmentKey fragmentKey) {
this.programId = programId; this.programId = programId;
@@ -50,26 +43,6 @@ public class Program {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
locSampler[i] = RENDER_BACKEND.getUniformLocation(programId, "u_Sampler" + i); locSampler[i] = RENDER_BACKEND.getUniformLocation(programId, "u_Sampler" + i);
} }
locPeelDepth = RENDER_BACKEND.getUniformLocation(programId, "u_PeelDepth");
locPeelScene = RENDER_BACKEND.getUniformLocation(programId, "u_PeelScene");
locPeelMode = RENDER_BACKEND.getUniformLocation(programId, "u_PeelMode");
locCoverMode = RENDER_BACKEND.getUniformLocation(programId, "u_CoverMode");
}
boolean peels() {
return locPeelMode != -1;
}
void syncPeelMode(int mode) {
if (peelMode == mode) return;
RENDER_BACKEND.uniform1i(locPeelMode, mode);
peelMode = mode;
}
void syncCoverMode(int mode) {
if (locCoverMode == -1 || coverMode == mode) return;
RENDER_BACKEND.uniform1i(locCoverMode, mode);
coverMode = mode;
} }
public void destroy() { public void destroy() {
@@ -126,8 +99,6 @@ public class Program {
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
if (ffpProgram.locSampler[i] != -1) backend.uniform1i(ffpProgram.locSampler[i], i); if (ffpProgram.locSampler[i] != -1) backend.uniform1i(ffpProgram.locSampler[i], i);
} }
if (ffpProgram.locPeelDepth != -1) backend.uniform1i(ffpProgram.locPeelDepth, DepthPeel.TEXTURE_UNIT);
if (ffpProgram.locPeelScene != -1) backend.uniform1i(ffpProgram.locPeelScene, DepthPeel.SCENE_TEXTURE_UNIT);
if (previousProgram != 0) { if (previousProgram != 0) {
backend.useProgram(previousProgram); backend.useProgram(previousProgram);
} else { } else {
@@ -4,8 +4,6 @@ import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat;
import com.gtnewhorizons.angelica.config.SystemProperties; import com.gtnewhorizons.angelica.config.SystemProperties;
import com.gtnewhorizons.angelica.glsm.CompatUniformManager; import com.gtnewhorizons.angelica.glsm.CompatUniformManager;
import com.gtnewhorizons.angelica.glsm.CoverageDiscard;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import com.gtnewhorizons.angelica.glsm.GLContextState; import com.gtnewhorizons.angelica.glsm.GLContextState;
import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs; import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs;
import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.GLStateManager;
@@ -190,8 +188,6 @@ public final class ShaderManager {
private void uploadUniforms(GLContextState glCtx) { private void uploadUniforms(GLContextState glCtx) {
if (currentProgram != null) { if (currentProgram != null) {
uniforms.upload(glCtx); uniforms.upload(glCtx);
if (currentProgram.peels()) currentProgram.syncPeelMode(DepthPeel.shaderMode());
if (currentProgram.getFragmentKey().coverageDiscard()) currentProgram.syncCoverMode(CoverageDiscard.mode());
} }
} }
@@ -7,7 +7,6 @@ import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder;
/** Drains deferred geometry before changing state that is not stored with each batch. */ /** Drains deferred geometry before changing state that is not stored with each batch. */
public final class BatchStateGuard { public final class BatchStateGuard {
public static Runnable flush; public static Runnable flush;
public static Runnable drawFlush;
private static int suspended; private static int suspended;
private BatchStateGuard() {} private BatchStateGuard() {}
@@ -17,20 +16,12 @@ public final class BatchStateGuard {
public static boolean isSuspended() { return suspended != 0; } public static boolean isSuspended() { return suspended != 0; }
public static void beforeChange() { public static void beforeChange() {
run(flush); if (flush == null || suspended != 0 || !GLStateManager.isMainThread()
}
public static void beforeDraw() {
run(drawFlush);
}
private static void run(Runnable action) {
if (action == null || suspended != 0 || !GLStateManager.isMainThread()
|| DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.COMPILE) return; || DisplayListManager.getRecordMode() == DisplayListManager.RecordMode.COMPILE) return;
final CommandRecorder recorder = DisplayListManager.isRecording() ? DisplayListManager.pauseRecording() : null; final CommandRecorder recorder = DisplayListManager.isRecording() ? DisplayListManager.pauseRecording() : null;
suspend(); suspend();
try { try {
action.run(); flush.run();
} finally { } finally {
resume(); resume();
if (recorder != null) DisplayListManager.resumeRecording(recorder); if (recorder != null) DisplayListManager.resumeRecording(recorder);
@@ -15,8 +15,6 @@ public final class GLSMConfig {
} }
public static boolean hudCacheOverride; public static boolean hudCacheOverride;
public static boolean layerBlending;
public static boolean depthPeel;
public static boolean extendedAttribsExpected; public static boolean extendedAttribsExpected;
public static volatile boolean expandVertexFormats; public static volatile boolean expandVertexFormats;
@@ -12,8 +12,7 @@ final class GLSMOwners {
"getColorLogicOpState", "getColorMask", "getEffectiveBlendState", "getEffectiveColorMask", "getColorLogicOpState", "getColorMask", "getEffectiveBlendState", "getEffectiveColorMask",
"getIndexLogicOpState", "getLogicOpMode", "glBlendColor", "glBlendEquation", "glBlendEquationSeparate", "getIndexLogicOpState", "getLogicOpMode", "glBlendColor", "glBlendEquation", "glBlendEquationSeparate",
"glBlendFunc", "glBlendFuncSeparate", "glBlendFuncSeparatei", "glClearColor", "glColorMask", "glLogicOp", "glBlendFunc", "glBlendFuncSeparate", "glBlendFuncSeparatei", "glClearColor", "glColorMask", "glLogicOp",
"isEffectiveBlendEnabled", "isLayerBlending", "setHudCacheOverride", "setLayerBlending", "isEffectiveBlendEnabled", "setHudCacheOverride", "tryBlendFuncSeparate"},
"tryBlendFuncSeparate"},
{"com/gtnewhorizons/angelica/glsm/GLSMBuffers", {"com/gtnewhorizons/angelica/glsm/GLSMBuffers",
"getBoundCopyReadBuffer", "getBoundCopyWriteBuffer", "getBoundVBO", "getIndexedBufferBinding", "getBoundCopyReadBuffer", "getBoundCopyWriteBuffer", "getBoundVBO", "getIndexedBufferBinding",
"glBindBuffer", "glBindBufferBase", "glBindBufferRange", "glBufferData", "glBufferStorage", "glBindBuffer", "glBindBufferBase", "glBindBufferRange", "glBufferData", "glBufferStorage",
@@ -53,10 +53,4 @@ void main() {
#if GLINT_REPLACE_ALPHA #if GLINT_REPLACE_ALPHA
fragColor.a = visible1 ? b.a : a.a; fragColor.a = visible1 ? b.a : a.a;
#endif #endif
#ifdef DEPTH_PEEL
peelTest();
#endif
#ifdef COVERAGE_DISCARD
coverageTest(fragColor);
#endif
} }
@@ -1,119 +0,0 @@
package com.gtnewhorizons.angelica.glsm;
import com.gtnewhorizons.angelica.glsm.hooks.DeferredBlendHandler;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
@GLCoreTest
public class GLSM_BlendAlphaOverride_GLTest {
private static void assertDriverFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
assertEquals(srcRgb, GL11.glGetInteger(GL14.GL_BLEND_SRC_RGB));
assertEquals(dstRgb, GL11.glGetInteger(GL14.GL_BLEND_DST_RGB));
assertEquals(srcAlpha, GL11.glGetInteger(GL14.GL_BLEND_SRC_ALPHA));
assertEquals(dstAlpha, GL11.glGetInteger(GL14.GL_BLEND_DST_ALPHA));
}
private static void assertCachedFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
assertEquals(srcRgb, GLSMQueries.glGetInteger(GL14.GL_BLEND_SRC_RGB));
assertEquals(dstRgb, GLSMQueries.glGetInteger(GL14.GL_BLEND_DST_RGB));
assertEquals(srcAlpha, GLSMQueries.glGetInteger(GL14.GL_BLEND_SRC_ALPHA));
assertEquals(dstAlpha, GLSMQueries.glGetInteger(GL14.GL_BLEND_DST_ALPHA));
}
@AfterEach
void resetOverrides() {
GLSMHooks.blendHandler = null;
GLSMBlend.setHudCacheOverride(false);
GLSMBlend.setLayerBlending(false);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
@Test
void overrideChangesTheDriverFuncButNotTheCache() {
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLSMBlend.setHudCacheOverride(true);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_SRC_ALPHA, GL11.GL_ONE);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertCachedFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertDriverFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.setHudCacheOverride(false);
assertCachedFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertDriverFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
}
@Test
void popUnderOverrideKeepsTheOverriddenAlphaOnTheDriver() {
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
final int d = GLSMAttribStack.pushState(StateSet.BLEND);
GLSMBlend.setHudCacheOverride(true);
GLSMBlend.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
GLSMAttribStack.popStateTo(d);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.setHudCacheOverride(false);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
@Test
void separateAlphaIsForcedEvenWhenDstAlphaAlreadyMatches() {
GLSMBlend.setHudCacheOverride(true);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_ALPHA);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_ALPHA);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
static Stream<Arguments> layerBlendRows() {
return Stream.of(
Arguments.of("translucent over", GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA),
Arguments.of("alpha additive", GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE));
}
@ParameterizedTest(name = "{0}")
@MethodSource("layerBlendRows")
void layerBlendingAccumulatesCoverageAndKeepsAdditiveCoverageFree(String name, int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
GLSMBlend.setLayerBlending(true);
GLSMBlend.glBlendFunc(srcRgb, dstRgb);
assertCachedFunc(srcRgb, dstRgb, srcRgb, dstRgb);
assertDriverFunc(srcRgb, dstRgb, srcAlpha, dstAlpha);
GLSMBlend.setLayerBlending(false);
assertDriverFunc(srcRgb, dstRgb, srcRgb, dstRgb);
}
@Test
void togglingWhileABlendOverrideIsHeldReemitsOnTheNextUnchangedFunc() {
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMHooks.blendHandler = new HeldOverride();
GLSMBlend.setLayerBlending(true);
GLSMHooks.blendHandler = null;
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
private static final class HeldOverride implements DeferredBlendHandler {
@Override public boolean isBlendLocked() { return false; }
@Override public boolean isOverrideHeld() { return true; }
@Override public void deferBlendModeToggle(boolean enabled) {}
@Override public void deferBlendFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {}
@Override public void flushDeferredBlend() {}
}
}
@@ -0,0 +1,83 @@
package com.gtnewhorizons.angelica.glsm;
import org.junit.jupiter.api.Test;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL14;
import static org.junit.jupiter.api.Assertions.assertEquals;
@GLCoreTest
public class GLSM_HudCacheBlendOverride_GLTest {
private static void assertDriverFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
assertEquals(srcRgb, GL11.glGetInteger(GL14.GL_BLEND_SRC_RGB));
assertEquals(dstRgb, GL11.glGetInteger(GL14.GL_BLEND_DST_RGB));
assertEquals(srcAlpha, GL11.glGetInteger(GL14.GL_BLEND_SRC_ALPHA));
assertEquals(dstAlpha, GL11.glGetInteger(GL14.GL_BLEND_DST_ALPHA));
}
private static void assertCachedFunc(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) {
assertEquals(srcRgb, GLSMQueries.glGetInteger(GL14.GL_BLEND_SRC_RGB));
assertEquals(dstRgb, GLSMQueries.glGetInteger(GL14.GL_BLEND_DST_RGB));
assertEquals(srcAlpha, GLSMQueries.glGetInteger(GL14.GL_BLEND_SRC_ALPHA));
assertEquals(dstAlpha, GLSMQueries.glGetInteger(GL14.GL_BLEND_DST_ALPHA));
}
@Test
void overrideChangesTheDriverFuncButNotTheCache() {
try {
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
GLSMBlend.setHudCacheOverride(true);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_SRC_ALPHA, GL11.GL_ONE);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertCachedFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertDriverFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.setHudCacheOverride(false);
assertCachedFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
assertDriverFunc(GL11.GL_DST_COLOR, GL11.GL_ZERO, GL11.GL_ZERO, GL11.GL_ONE);
} finally {
GLSMBlend.setHudCacheOverride(false);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
}
@Test
void popUnderOverrideKeepsTheOverriddenAlphaOnTheDriver() {
try {
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
final int d = GLSMAttribStack.pushState(StateSet.BLEND);
GLSMBlend.setHudCacheOverride(true);
GLSMBlend.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
GLSMAttribStack.popStateTo(d);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMBlend.setHudCacheOverride(false);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
} finally {
GLSMBlend.setHudCacheOverride(false);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
}
@Test
void separateAlphaIsForcedEvenWhenDstAlphaAlreadyMatches() {
try {
GLSMBlend.setHudCacheOverride(true);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_ALPHA);
assertCachedFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE_MINUS_SRC_ALPHA);
assertDriverFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA);
} finally {
GLSMBlend.setHudCacheOverride(false);
GLSMBlend.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
}
}
}
@@ -167,33 +167,6 @@ public class GLSM_StateSet_GLTest {
|| GLSMBlend.getColorMask().blue || GLSMBlend.getColorMask().alpha, "cache color mask - not a HAND member, must stay toggled"); || GLSMBlend.getColorMask().blue || GLSMBlend.getColorMask().alpha, "cache color mask - not a HAND member, must stay toggled");
} }
@Test
void blockEntityPassRestoresColorFogAndShadeModelOnTopOfBatchButNotStencil() {
GLSMCurrentAttribs.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GLSMFog.disableFog();
GLSMFog.glFogf(GL11.GL_FOG_END, 64.0f);
GLSMRasterizer.glShadeModel(GL11.GL_SMOOTH);
GLSMDepthStencilAlpha.glDepthMask(true);
GLSMEnable.glDisable(GL11.GL_STENCIL_TEST);
final int d = GLSMAttribStack.pushState(StateSet.BLOCK_ENTITY_PASS);
GLSMCurrentAttribs.glColor4f(0.2f, 0.4f, 0.6f, 0.8f);
GLSMFog.enableFog();
GLSMFog.glFogf(GL11.GL_FOG_END, 8.0f);
GLSMRasterizer.glShadeModel(GL11.GL_FLAT);
GLSMDepthStencilAlpha.glDepthMask(false);
GLSMEnable.glEnable(GL11.GL_STENCIL_TEST);
GLSMAttribStack.popStateTo(d);
assertEquals(1.0f, GLSMCurrentAttribs.getColor().getRed(), "cache color red");
assertEquals(1.0f, GLSMCurrentAttribs.getColor().getAlpha(), "cache color alpha");
assertFalse(GLSMFog.getFogMode().isEnabled(), "fog enable restored by BLOCK_ENTITY_PASS pop");
assertEquals(64.0f, GLSMFog.getFogState().getEnd(), "cache fog end");
assertEquals(GL11.GL_SMOOTH, GLSMRasterizer.getShadeModelState().getValue(), "cache shade model");
assertTrue(GLSMDepthStencilAlpha.getDepthState().isEnabled(), "depth mask restored, as in BATCH");
verifyIsEnabled(GL11.GL_STENCIL_TEST, true, "Stencil test - not a BLOCK_ENTITY_PASS member, must stay toggled");
}
@Test @Test
void masksRestoresDepthMaskAndColorMaskButNotDepthTestEnable() { void masksRestoresDepthMaskAndColorMaskButNotDepthTestEnable() {
GLSMDepthStencilAlpha.glDepthMask(true); GLSMDepthStencilAlpha.glDepthMask(true);
@@ -493,42 +493,42 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueDrawArrays(int mode, int first, int count) { public void drawArrays(int mode, int first, int count) {
GL11C.glDrawArrays(mode, first, count); GL11C.glDrawArrays(mode, first, count);
} }
@Override @Override
protected void issueDrawElements(int mode, int count, int type, long indices) { public void drawElements(int mode, int count, int type, long indices) {
GL11C.glDrawElements(mode, count, type, indices); GL11C.glDrawElements(mode, count, type, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, ByteBuffer indices) { public void drawElements(int mode, ByteBuffer indices) {
GL11C.glDrawElements(mode, indices); GL11C.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, IntBuffer indices) { public void drawElements(int mode, IntBuffer indices) {
GL11C.glDrawElements(mode, indices); GL11C.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, ShortBuffer indices) { public void drawElements(int mode, ShortBuffer indices) {
GL11C.glDrawElements(mode, indices); GL11C.glDrawElements(mode, indices);
} }
@Override @Override
protected void issueDrawElements(int mode, int count, int type, ByteBuffer indices) { public void drawElements(int mode, int count, int type, ByteBuffer indices) {
GL11C.glDrawElements(mode, count, type, MemoryUtil.memAddress(indices)); GL11C.glDrawElements(mode, count, type, MemoryUtil.memAddress(indices));
} }
@Override @Override
protected void issueDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) { public void drawElementsInstanced(int mode, int count, int type, long indices, int primcount) {
GL31C.glDrawElementsInstanced(mode, count, type, indices, primcount); GL31C.glDrawElementsInstanced(mode, count, type, indices, primcount);
} }
@Override @Override
protected void issueDrawArraysInstanced(int mode, int first, int count, int primcount) { public void drawArraysInstanced(int mode, int first, int count, int primcount) {
GL31C.glDrawArraysInstanced(mode, first, count, primcount); GL31C.glDrawArraysInstanced(mode, first, count, primcount);
} }
@@ -539,7 +539,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { public void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) {
GL43C.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride); GL43C.glMultiDrawElementsIndirect(mode, type, indirect, drawcount, stride);
} }
@@ -549,12 +549,12 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueDrawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) { public void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) {
GL32C.glDrawElementsBaseVertex(mode, count, type, indices, baseVertex); GL32C.glDrawElementsBaseVertex(mode, count, type, indices, baseVertex);
} }
@Override @Override
protected void issueMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) {
GL32C.nglMultiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex); GL32C.nglMultiDrawElementsBaseVertex(mode, pCount, type, pIndices, drawcount, pBaseVertex);
} }
@@ -1884,7 +1884,7 @@ public final class Lwjgl3GLRenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) {
GL14C.glMultiDrawArrays(mode, firsts, counts); GL14C.glMultiDrawArrays(mode, firsts, counts);
} }
@@ -1,83 +0,0 @@
# Translucent TESR ordering scene for a generated superflat (windows-flyby-kit/make_world.py). Needs
# -Dangelica.debug.testBlocks=true. $x $y $z is the flight start; ground-standing level is $y-2. Start facing south (yaw 0),
# pitch 15. Blocks: test_tesr_provider (0 translucent red, 1 additive purple), test_tesr_model (0 box pane,
# 1 Tessellator pane, 2 stacked A/B/A panes), test_tesr_decal, test_tesr_glow; metadata + 8 draws in the solid pass.
gamerule doMobSpawning false
# translucent pass: three rows, materials shifted per row so every column stacks three different ones
setblock $x-2 $y $z+6 angelica:test_tesr_provider 0 replace
setblock $x-1 $y $z+6 angelica:test_tesr_provider 1 replace
setblock $x+0 $y $z+6 angelica:test_tesr_model 0 replace
setblock $x+1 $y $z+6 angelica:test_tesr_model 1 replace
setblock $x-2 $y $z+8 angelica:test_tesr_provider 1 replace
setblock $x-1 $y $z+8 angelica:test_tesr_model 0 replace
setblock $x+0 $y $z+8 angelica:test_tesr_model 1 replace
setblock $x+1 $y $z+8 angelica:test_tesr_provider 0 replace
setblock $x-2 $y $z+10 angelica:test_tesr_model 0 replace
setblock $x-1 $y $z+10 angelica:test_tesr_model 1 replace
setblock $x+0 $y $z+10 angelica:test_tesr_provider 0 replace
setblock $x+1 $y $z+10 angelica:test_tesr_provider 1 replace
# solid pass: the same rows two blocks higher
setblock $x-2 $y+2 $z+6 angelica:test_tesr_provider 8 replace
setblock $x-1 $y+2 $z+6 angelica:test_tesr_provider 9 replace
setblock $x+0 $y+2 $z+6 angelica:test_tesr_model 8 replace
setblock $x+1 $y+2 $z+6 angelica:test_tesr_model 9 replace
setblock $x-2 $y+2 $z+8 angelica:test_tesr_provider 9 replace
setblock $x-1 $y+2 $z+8 angelica:test_tesr_model 8 replace
setblock $x+0 $y+2 $z+8 angelica:test_tesr_model 9 replace
setblock $x+1 $y+2 $z+8 angelica:test_tesr_provider 8 replace
setblock $x-2 $y+2 $z+10 angelica:test_tesr_model 8 replace
setblock $x-1 $y+2 $z+10 angelica:test_tesr_model 9 replace
setblock $x+0 $y+2 $z+10 angelica:test_tesr_provider 8 replace
setblock $x+1 $y+2 $z+10 angelica:test_tesr_provider 9 replace
# one tile entity submitting translucent A, additive B, translucent A; a depth-equal decal
setblock $x-7 $y $z+8 angelica:test_tesr_model 2 replace
setblock $x-7 $y+1 $z+8 angelica:test_tesr_decal 0 replace
# light blue glass wall: glow and provider panes in front, a provider pane behind. The panes behind the wall and
# under the water show only when block entities draw before translucent terrain.
setblock $x+5 $y-1 $z+14 stained_glass 3 replace
setblock $x+5 $y $z+14 stained_glass 3 replace
setblock $x+5 $y+1 $z+14 stained_glass 3 replace
setblock $x+6 $y-1 $z+14 stained_glass 3 replace
setblock $x+6 $y $z+14 stained_glass 3 replace
setblock $x+6 $y+1 $z+14 stained_glass 3 replace
setblock $x+7 $y-1 $z+14 stained_glass 3 replace
setblock $x+7 $y $z+14 stained_glass 3 replace
setblock $x+7 $y+1 $z+14 stained_glass 3 replace
setblock $x+8 $y-1 $z+14 stained_glass 3 replace
setblock $x+8 $y $z+14 stained_glass 3 replace
setblock $x+8 $y+1 $z+14 stained_glass 3 replace
setblock $x+9 $y-1 $z+14 stained_glass 3 replace
setblock $x+9 $y $z+14 stained_glass 3 replace
setblock $x+9 $y+1 $z+14 stained_glass 3 replace
setblock $x+6 $y $z+13 angelica:test_tesr_glow 0 replace
setblock $x+8 $y $z+13 angelica:test_tesr_provider 0 replace
setblock $x+7 $y $z+15 angelica:test_tesr_provider 0 replace
# water pool with a provider pane under the surface
setblock $x-10 $y-4 $z+12 water 0 replace
setblock $x-10 $y-3 $z+12 water 0 replace
setblock $x-10 $y-4 $z+13 water 0 replace
setblock $x-10 $y-3 $z+13 water 0 replace
setblock $x-10 $y-4 $z+14 water 0 replace
setblock $x-10 $y-3 $z+14 water 0 replace
setblock $x-9 $y-4 $z+12 water 0 replace
setblock $x-9 $y-3 $z+12 water 0 replace
setblock $x-9 $y-4 $z+13 water 0 replace
setblock $x-9 $y-3 $z+13 water 0 replace
setblock $x-9 $y-4 $z+14 water 0 replace
setblock $x-9 $y-3 $z+14 water 0 replace
setblock $x-8 $y-4 $z+12 water 0 replace
setblock $x-8 $y-3 $z+12 water 0 replace
setblock $x-8 $y-4 $z+13 water 0 replace
setblock $x-8 $y-3 $z+13 water 0 replace
setblock $x-8 $y-4 $z+14 water 0 replace
setblock $x-8 $y-3 $z+14 water 0 replace
setblock $x-9 $y-4 $z+13 angelica:test_tesr_provider 0 replace
# control: a lone pane with sky behind it
setblock $x+5 $y+2 $z+8 angelica:test_tesr_provider 0 replace
@@ -1,58 +0,0 @@
# Translucency layer scene for a generated superflat (windows-flyby-kit/make_world.py). $x $y $z is the flight start;
# ground-standing level is $y-2. Start facing south (yaw 0), pitch 15. Use with -Dangelica.flyby.weather=RAIN. Torch
# flame and smoke and rain fall in front of a light blue glass wall and a water pool; one torch row stands behind the glass.
gamerule doMobSpawning false
# glass wall
setblock $x-1 $y-2 $z+9 stained_glass 3 replace
setblock $x-1 $y-1 $z+9 stained_glass 3 replace
setblock $x-1 $y+0 $z+9 stained_glass 3 replace
setblock $x+0 $y-2 $z+9 stained_glass 3 replace
setblock $x+0 $y-1 $z+9 stained_glass 3 replace
setblock $x+0 $y+0 $z+9 stained_glass 3 replace
setblock $x+1 $y-2 $z+9 stained_glass 3 replace
setblock $x+1 $y-1 $z+9 stained_glass 3 replace
setblock $x+1 $y+0 $z+9 stained_glass 3 replace
setblock $x+2 $y-2 $z+9 stained_glass 3 replace
setblock $x+2 $y-1 $z+9 stained_glass 3 replace
setblock $x+2 $y+0 $z+9 stained_glass 3 replace
setblock $x+3 $y-2 $z+9 stained_glass 3 replace
setblock $x+3 $y-1 $z+9 stained_glass 3 replace
setblock $x+3 $y+0 $z+9 stained_glass 3 replace
# torches in front of and behind the glass
setblock $x-1 $y-2 $z+7 torch 5 replace
setblock $x-1 $y-2 $z+11 torch 5 replace
setblock $x+0 $y-2 $z+7 torch 5 replace
setblock $x+0 $y-2 $z+11 torch 5 replace
setblock $x+1 $y-2 $z+7 torch 5 replace
setblock $x+1 $y-2 $z+11 torch 5 replace
setblock $x+2 $y-2 $z+7 torch 5 replace
setblock $x+2 $y-2 $z+11 torch 5 replace
setblock $x+3 $y-2 $z+7 torch 5 replace
setblock $x+3 $y-2 $z+11 torch 5 replace
# water pool with torches in front of it
setblock $x-6 $y-3 $z+7 water 0 replace
setblock $x-6 $y-3 $z+8 water 0 replace
setblock $x-6 $y-3 $z+9 water 0 replace
setblock $x-6 $y-3 $z+10 water 0 replace
setblock $x-5 $y-3 $z+7 water 0 replace
setblock $x-5 $y-3 $z+8 water 0 replace
setblock $x-5 $y-3 $z+9 water 0 replace
setblock $x-5 $y-3 $z+10 water 0 replace
setblock $x-4 $y-3 $z+7 water 0 replace
setblock $x-4 $y-3 $z+8 water 0 replace
setblock $x-4 $y-3 $z+9 water 0 replace
setblock $x-4 $y-3 $z+10 water 0 replace
setblock $x-3 $y-3 $z+7 water 0 replace
setblock $x-3 $y-3 $z+8 water 0 replace
setblock $x-3 $y-3 $z+9 water 0 replace
setblock $x-3 $y-3 $z+10 water 0 replace
setblock $x-2 $y-3 $z+7 water 0 replace
setblock $x-2 $y-3 $z+8 water 0 replace
setblock $x-2 $y-3 $z+9 water 0 replace
setblock $x-2 $y-3 $z+10 water 0 replace
setblock $x-5 $y-2 $z+6 torch 5 replace
setblock $x-3 $y-2 $z+6 torch 5 replace
@@ -1228,7 +1228,7 @@ public class SDLGPURenderBackend extends RenderBackend {
} }
} }
@Override protected void issueDrawArrays(int mode, int first, int count) { @Override public void drawArrays(int mode, int first, int count) {
if (count <= 0) return; if (count <= 0) return;
final ContextState st = s(); final ContextState st = s();
if (st.rasterizerDiscard) return; if (st.rasterizerDiscard) return;
@@ -1250,7 +1250,7 @@ public class SDLGPURenderBackend extends RenderBackend {
captureVertexWrites(st, first, count, 1, 0, 0, 0); captureVertexWrites(st, first, count, 1, 0, 0, 0);
} }
@Override protected void issueDrawElements(int mode, int count, int type, long indices) { @Override public void drawElements(int mode, int count, int type, long indices) {
final ContextState st = s(); final ContextState st = s();
final long rp = prepareIndexedDrawBind(st, mode, type, "drawElements"); final long rp = prepareIndexedDrawBind(st, mode, type, "drawElements");
if (rp == 0) return; if (rp == 0) return;
@@ -1260,7 +1260,7 @@ public class SDLGPURenderBackend extends RenderBackend {
captureVertexWrites(st, 0, count, 1, type, indices, 0); captureVertexWrites(st, 0, count, 1, type, indices, 0);
} }
@Override protected void issueDrawElementsInstanced(int mode, int count, int type, long indices, int primcount) { @Override public void drawElementsInstanced(int mode, int count, int type, long indices, int primcount) {
final ContextState st = s(); final ContextState st = s();
final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsInstanced"); final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsInstanced");
if (rp == 0) return; if (rp == 0) return;
@@ -1272,7 +1272,7 @@ public class SDLGPURenderBackend extends RenderBackend {
} }
@Override protected void issueDrawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) { @Override public void drawElementsBaseVertex(int mode, int count, int type, long indices, int baseVertex) {
final ContextState st = s(); final ContextState st = s();
final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsBaseVertex"); final long rp = prepareIndexedDrawBind(st, mode, type, "drawElementsBaseVertex");
if (rp == 0) return; if (rp == 0) return;
@@ -1297,7 +1297,7 @@ public class SDLGPURenderBackend extends RenderBackend {
return rp; return rp;
} }
@Override protected void issueMultiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) { @Override public void multiDrawElementsBaseVertex(int mode, long pCount, int type, long pIndices, int drawcount, long pBaseVertex) {
if (drawcount <= 0) return; if (drawcount <= 0) return;
final ContextState st = s(); final ContextState st = s();
final long rp = prepareIndexedDrawBind(st, mode, type, "multiDrawElementsBaseVertex"); final long rp = prepareIndexedDrawBind(st, mode, type, "multiDrawElementsBaseVertex");
@@ -1317,7 +1317,7 @@ public class SDLGPURenderBackend extends RenderBackend {
} }
} }
@Override protected void issueMultiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) { @Override public void multiDrawElementsIndirect(int mode, int type, long indirect, int drawcount, int stride) {
final ContextState cs = s(); final ContextState cs = s();
if (drawcount <= 0) return; if (drawcount <= 0) return;
Tracy.beginZone(Z_SDL_INDIRECT_DRAW); Tracy.beginZone(Z_SDL_INDIRECT_DRAW);
@@ -4670,7 +4670,7 @@ public class SDLGPURenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueDrawArraysInstanced(int mode, int first, int count, int primcount) { public void drawArraysInstanced(int mode, int first, int count, int primcount) {
if (count <= 0 || primcount <= 0) return; if (count <= 0 || primcount <= 0) return;
final ContextState st = s(); final ContextState st = s();
if (st.rasterizerDiscard) return; if (st.rasterizerDiscard) return;
@@ -4688,11 +4688,11 @@ public class SDLGPURenderBackend extends RenderBackend {
} }
@Override @Override
protected void issueMultiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) { public void multiDrawArrays(int mode, IntBuffer firsts, IntBuffer counts) {
if (firsts == null || counts == null) return; if (firsts == null || counts == null) return;
final int n = Math.min(firsts.remaining(), counts.remaining()); final int n = Math.min(firsts.remaining(), counts.remaining());
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
issueDrawArrays(mode, firsts.get(firsts.position() + i), counts.get(counts.position() + i)); drawArrays(mode, firsts.get(firsts.position() + i), counts.get(counts.position() + i));
} }
} }
@@ -8,21 +8,13 @@ import java.util.List;
public final class ClipZRemap { public final class ClipZRemap {
private static final String INJECTION_STD = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;\n"; private static final String INJECTION_STD = "gl_Position.z = gl_Position.z * 0.5 + gl_Position.w * 0.5;\n";
private static final String PRECISE_POSITION = "precise gl_Position;\n";
private ClipZRemap() {} private ClipZRemap() {}
public static boolean collectEdits(GLSLParser.Translation_unitContext root, List<Edit> edits) { public static boolean collectEdits(GLSLParser.Translation_unitContext root, List<Edit> edits) {
boolean preciseInserted = false;
for (GLSLParser.External_declarationContext external : root.external_declaration()) { for (GLSLParser.External_declarationContext external : root.external_declaration()) {
final GLSLParser.Function_definitionContext function = external.function_definition(); final GLSLParser.Function_definitionContext function = external.function_definition();
if (function == null) continue; if (function == null || function.function_prototype().IDENTIFIER() == null) continue;
if (!preciseInserted) {
final int start = external.getStart().getStartIndex();
edits.add(new Edit(start, start - 1, PRECISE_POSITION));
preciseInserted = true;
}
if (function.function_prototype().IDENTIFIER() == null) continue;
if (!"main".equals(function.function_prototype().IDENTIFIER().getText())) continue; if (!"main".equals(function.function_prototype().IDENTIFIER().getText())) continue;
final GLSLParser.Compound_statement_no_new_scopeContext body = function.compound_statement_no_new_scope(); final GLSLParser.Compound_statement_no_new_scopeContext body = function.compound_statement_no_new_scope();
if (body == null || body.RIGHT_BRACE() == null) return false; if (body == null || body.RIGHT_BRACE() == null) return false;
@@ -1,92 +0,0 @@
package com.gtnewhorizons.angelica.sdlgpu;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import org.lwjgl.opengl.GL20;
import org.lwjgl.sdl.SDLError;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Consumer;
import javax.imageio.ImageIO;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERSTAGE_FRAGMENT;
import static org.lwjgl.sdl.SDLGPU.SDL_GPU_SHADERSTAGE_VERTEX;
public final class GpuTestPrograms {
private GpuTestPrograms() {}
public static int link(ShaderManager sm, String vertex, String fragment) {
final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, vertex);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragment);
sm.compileShader(fs);
final int program = sm.createProgram();
sm.attachShader(program, vs);
sm.attachShader(program, fs);
sm.linkProgram(program);
final ShaderManager.ProgramObject po = sm.getProgram(program);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
final ShaderManager.ResourceCounts vr = po.vertexResources;
final ShaderManager.ResourceCounts fr = po.fragmentResources;
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures());
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures());
assertTrue(po.sdlVertexShader != 0 && po.sdlFragmentShader != 0, "SDL shader creation failed: " + SDLError.SDL_GetError());
return program;
}
public static String solidFragment(String rgb) {
return """
#version 460 core
layout(location = 0) out vec4 fragColor;
void main() { fragColor = vec4(%s, 1.0); }
""".formatted(rgb);
}
public static long pipeline(PipelineStore store, ShaderManager sm, int program, int colorFormat, int depthFormat, Consumer<PipelineCache> state) {
final ShaderManager.ProgramObject po = sm.getProgram(program);
final ContextState cs = new ContextState();
final PipelineCache cache = cs.pipeline;
cache.vertexShader = po.sdlVertexShader;
cache.fragmentShader = po.sdlFragmentShader;
cache.programId = program;
cache.maxFragOutputLocation = po.maxFragOutputLocation;
cache.setVertexInputs(po.vertexInputMask, po.vertexInputVecSize, po.vertexInputBaseType, po.vertexInputName, po.vertexInputSetId);
cache.setColorTargetFormats(new int[]{ colorFormat });
cache.setDrawBuffers(new int[]{ 0 });
cache.hasDepthTarget = true;
cache.depthTargetFormat = depthFormat;
state.accept(cache);
cache.markShaderDirty();
cache.markOutputDirty();
final long pipeline = cache.getOrCreatePipeline(store, cs);
assertTrue(pipeline != 0, "pipeline creation failed: " + SDLError.SDL_GetError());
return pipeline;
}
public static Path dumpPng(ByteBuffer rgba, int width, int height, String name) throws IOException {
final Path out = Path.of("build", "test-artifacts");
Files.createDirectories(out);
final BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
final int i = (y * width + x) * 4;
img.setRGB(x, y, ((rgba.get(i) & 0xFF) << 16) | ((rgba.get(i + 1) & 0xFF) << 8) | (rgba.get(i + 2) & 0xFF));
}
}
final Path file = out.resolve(name + ".png").toAbsolutePath();
ImageIO.write(img, "png", file.toFile());
return file;
}
}
@@ -84,7 +84,7 @@ public final class SdlTestRig {
} }
} }
private static SdlTestRig realRig; private static long realSdlDevice;
private static final int SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL; private static final int SHADER_FORMATS = SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL | SDL_GPU_SHADERFORMAT_DXBC | SDL_GPU_SHADERFORMAT_DXIL;
@@ -95,19 +95,19 @@ public final class SdlTestRig {
public static SdlTestRig acquireRealDevice() { public static SdlTestRig acquireRealDevice() {
initSdlVideo(); initSdlVideo();
final long handle = SDL_CreateGPUDevice(SHADER_FORMATS, true, (CharSequence) null); realSdlDevice = SDL_CreateGPUDevice(SHADER_FORMATS, true, (CharSequence) null);
assertTrue(handle != 0, "No SDL GPU device: " + SDLError.SDL_GetError()); assertTrue(realSdlDevice != 0, "No SDL GPU device: " + SDLError.SDL_GetError());
realRig = new SdlTestRig(handle); final SdlTestRig rig = new SdlTestRig(realSdlDevice);
realRig.frameManager.setResourceManager(realRig.resourceManager); rig.frameManager.setResourceManager(rig.resourceManager);
return realRig; return rig;
} }
public static void releaseRealDevice() { public static void releaseRealDevice() {
if (realRig == null) return; if (realSdlDevice != 0) {
SDL_WaitForGPUIdle(realRig.sdlHandle); SDL_WaitForGPUIdle(realSdlDevice);
realRig.resourceManager.shutdown(); SDL_DestroyGPUDevice(realSdlDevice);
SDL_DestroyGPUDevice(realRig.sdlHandle); realSdlDevice = 0;
realRig = null; }
} }
} }
@@ -1,15 +1,16 @@
package com.gtnewhorizons.angelica.sdlgpu.pipeline; package com.gtnewhorizons.angelica.sdlgpu.pipeline;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension; import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.frame.ContextState;
import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig; import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig;
import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager; import com.gtnewhorizons.angelica.sdlgpu.shader.ShaderManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.opengl.GL20;
import org.lwjgl.sdl.SDLError;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo; import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo; import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo;
import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryStack;
@@ -48,7 +49,13 @@ class StencilMaskGpuTest {
"}", "}",
""); "");
private static final String FILL_FRAGMENT = GpuTestPrograms.solidFragment("1.0, 0.0, 0.0"); private static final String FILL_FRAGMENT = String.join("\n",
"#version 460 core",
"layout(location = 0) out vec4 fragColor;",
"void main() {",
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);",
"}",
"");
@BeforeAll @BeforeAll
static void setUp() throws Exception { static void setUp() throws Exception {
@@ -69,28 +76,56 @@ class StencilMaskGpuTest {
fillPipeline = createPipeline(FILL_FRAGMENT, false); fillPipeline = createPipeline(FILL_FRAGMENT, false);
} }
@AfterAll
static void tearDown() {
if (store != null) store.shutdown();
if (sm != null) sm.shutdown();
}
private static long createPipeline(String fragmentSource, boolean writesMask) { private static long createPipeline(String fragmentSource, boolean writesMask) {
final int prog = GpuTestPrograms.link(sm, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX, fragmentSource); final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragmentSource);
sm.compileShader(fs);
final int prog = sm.createProgram();
sm.attachShader(prog, vs);
sm.attachShader(prog, fs);
sm.linkProgram(prog);
final ShaderManager.ProgramObject po = sm.getProgram(prog);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, po.vertexResources.numSamplers(), po.vertexResources.numUBOs(), po.vertexResources.numStorageBuffers(), po.vertexResources.numStorageTextures());
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, po.fragmentResources.numSamplers(), po.fragmentResources.numUBOs(), po.fragmentResources.numStorageBuffers(), po.fragmentResources.numStorageTextures());
assertTrue(po.sdlVertexShader != 0 && po.sdlFragmentShader != 0, "SDL shader creation failed");
final ContextState cs = new ContextState();
final PipelineCache cache = cs.pipeline;
cache.vertexShader = po.sdlVertexShader;
cache.fragmentShader = po.sdlFragmentShader;
cache.programId = prog;
cache.maxFragOutputLocation = po.maxFragOutputLocation;
cache.shaderInputMask = po.vertexInputMask;
cache.shaderInputVecSize = po.vertexInputVecSize;
cache.shaderInputBaseType = po.vertexInputBaseType;
cache.shaderInputName = po.vertexInputName;
cache.setColorTargetFormats(new int[]{ colorFormat });
cache.setDrawBuffers(new int[]{ 0 });
cache.hasDepthTarget = true;
cache.depthTargetFormat = depthFormat;
cache.depthTestEnabled = false;
cache.depthWriteEnabled = false;
cache.stencilTestEnabled = true;
cache.stencilCompareMask = 0xFF;
cache.stencilWriteMask = writesMask ? 0xFF : 0x00;
final int compareOp = writesMask ? SDL_GPU_COMPAREOP_ALWAYS : SDL_GPU_COMPAREOP_EQUAL; final int compareOp = writesMask ? SDL_GPU_COMPAREOP_ALWAYS : SDL_GPU_COMPAREOP_EQUAL;
final int passOp = writesMask ? SDL_GPU_STENCILOP_REPLACE : SDL_GPU_STENCILOP_KEEP; final int passOp = writesMask ? SDL_GPU_STENCILOP_REPLACE : SDL_GPU_STENCILOP_KEEP;
return GpuTestPrograms.pipeline(store, sm, prog, colorFormat, depthFormat, cache -> { cache.stencilFrontCompareOp = compareOp;
cache.depthTestEnabled = false; cache.stencilBackCompareOp = compareOp;
cache.depthWriteEnabled = false; cache.stencilFrontPassOp = passOp;
cache.stencilTestEnabled = true; cache.stencilBackPassOp = passOp;
cache.stencilCompareMask = 0xFF; cache.markShaderDirty();
cache.stencilWriteMask = writesMask ? 0xFF : 0x00; cache.markOutputDirty();
cache.stencilFrontCompareOp = compareOp;
cache.stencilBackCompareOp = compareOp; assertTrue(cache.effectiveStencilTestEnabled(), "stencil must survive the depth-format gate");
cache.stencilFrontPassOp = passOp; final long pipeline = cache.getOrCreatePipeline(store, cs);
cache.stencilBackPassOp = passOp; assertTrue(pipeline != 0, "pipeline creation failed: " + SDLError.SDL_GetError());
assertTrue(cache.effectiveStencilTestEnabled(), "stencil must survive the depth-format gate"); return pipeline;
});
} }
private static void render(int secondPassStencilLoad) { private static void render(int secondPassStencilLoad) {
@@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.sdlgpu.resource;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension; import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.device.Device; import com.gtnewhorizons.angelica.sdlgpu.device.Device;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -29,6 +30,11 @@ class BufferSizeGpuExactnessTest {
resourceManager = rig.resourceManager; resourceManager = rig.resourceManager;
} }
@AfterAll
static void tearDown() {
if (resourceManager != null) resourceManager.shutdown();
}
@ParameterizedTest(name = "{0}") @ParameterizedTest(name = "{0}")
@CsvSource({"sub-bucket,9001,1000", "bucket boundary,9002,4096"}) @CsvSource({"sub-bucket,9001,1000", "bucket boundary,9002,4096"})
void createdBufferReportsRequestedSize(String name, int glId, long size) { void createdBufferReportsRequestedSize(String name, int glId, long size) {
@@ -1,186 +0,0 @@
package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineCache;
import com.gtnewhorizons.angelica.sdlgpu.pipeline.PipelineStore;
import org.joml.Matrix4f;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
import org.lwjgl.sdl.SDL_GPUDepthStencilTargetInfo;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.lwjgl.sdl.SDLGPU.*;
@ExtendWith(RealDeviceExtension.class)
@Tag("sdl-gpu-device")
class CoplanarDepthGpuTest {
private static final int SIZE = 256;
private static final int GRID = 32;
private static final int UBO_BYTES = 4 * 64 + 2 * 16;
private static final double CAM_X = 1475.7192986248613, CAM_Y = 70.62, CAM_Z = -935.8161276616005;
private static final String HEADER = """
#version 460 core
layout(std140) uniform Mats { mat4 proj; mat4 view; mat4 viewInv; mat4 mv; vec4 params; vec4 region; };
vec3 _vert_position;
void _vert_init() {
const ivec2 corner[6] = ivec2[](ivec2(0, 0), ivec2(1, 0), ivec2(1, 1), ivec2(0, 0), ivec2(1, 1), ivec2(0, 1));
int g = int(params.w);
int q = gl_VertexID / 6;
int c = gl_VertexID % 6;
vec2 uv = vec2(float(q % g + corner[c].x), float(q / g + corner[c].y)) / params.w;
vec3 packed = floor(vec3(uv.x * 16.0, 1.37 + uv.y * 3.1, 9.0 + uv.y * 7.0) * 2048.0);
_vert_position = packed * (1.0 / 2048.0) + vec3(params.z);
}
vec4 _celeritas_getVertexPosition() { return vec4(_vert_position + region.xyz, 1.0); }
""";
private static final String TERRAIN_VERTEX = HEADER + """
out vec3 vWorld;
void main() {
_vert_init();
vec4 position = viewInv * (mv * _celeritas_getVertexPosition());
vWorld = position.xyz;
gl_Position = proj * (view * position);
}
""";
private static final String WATER_VERTEX = HEADER + """
out vec3 vWorld;
out vec3 vView;
out float vWave;
out vec3 vNormal;
void main() {
_vert_init();
vec4 position = viewInv * (mv * _celeritas_getVertexPosition());
vWorld = position.xyz;
float wave = sin(position.x * 0.7 + params.y) * cos(position.z * 0.3 + params.y) * params.x;
if (params.x > 0.0) position.y += wave;
vWave = wave;
vView = (view * position).xyz;
vNormal = normalize(mat3(view) * vec3(0.0, 1.0, 0.0) + vec3(wave));
gl_Position = proj * (view * position);
}
""";
private static SdlTestRig rig;
private static ShaderManager sm;
private static PipelineStore store;
private static long colorTexture;
private static int colorFormat;
private static long depthTexture;
private static int depthFormat;
private static long terrainPipeline;
private static long waterPipeline;
@BeforeAll
static void setUp() {
rig = RealDeviceExtension.rig();
sm = new ShaderManager(rig.device);
store = new PipelineStore(rig.device);
final RealDeviceExtension.Target color = RealDeviceExtension.colorTarget(9600, SIZE, SIZE);
colorTexture = color.texture();
colorFormat = color.sdlFormat();
PipelineCache.setSwapchainFormats(new int[]{ colorFormat });
final RealDeviceExtension.Target depth = RealDeviceExtension.depthStencilTarget(9601, SIZE, SIZE);
depthTexture = depth.texture();
depthFormat = depth.sdlFormat();
terrainPipeline = createPipeline(TERRAIN_VERTEX, GpuTestPrograms.solidFragment("1.0, 0.0, 0.0"), SDL_GPU_COMPAREOP_LESS, true);
waterPipeline = createPipeline(WATER_VERTEX, GpuTestPrograms.solidFragment("0.0, 1.0, 0.0"), SDL_GPU_COMPAREOP_EQUAL, false);
}
@AfterAll
static void tearDown() {
if (store != null) store.shutdown();
if (sm != null) sm.shutdown();
}
private static long createPipeline(String vertexSource, String fragmentSource, int compareOp, boolean depthWrite) {
final int prog = GpuTestPrograms.link(sm, vertexSource, fragmentSource);
assertEquals(1, sm.getProgram(prog).vertexResources.numUBOs(), "the matrix block must be the only vertex UBO, pushed at slot 0");
return GpuTestPrograms.pipeline(store, sm, prog, colorFormat, depthFormat, cache -> {
cache.depthTestEnabled = true;
cache.depthWriteEnabled = depthWrite;
cache.depthCompareOp = compareOp;
});
}
private static void writeMats(ByteBuffer ubo) {
final Matrix4f proj = new Matrix4f().perspective((float) Math.toRadians(70.0), 1.0f, 0.05f, 512.0f);
final Matrix4f view = new Matrix4f().rotationX(0.35f).rotateY((float) Math.PI - 0.2f);
proj.get(0, ubo);
view.get(64, ubo);
view.invert(new Matrix4f()).get(128, ubo);
view.get(192, ubo);
ubo.putFloat(256, 0.0f).putFloat(260, 0.25f).putFloat(264, -0.37f).putFloat(268, GRID);
ubo.putFloat(272, (float) (1472.0 - CAM_X)).putFloat(276, (float) (64.0 - CAM_Y));
}
private static void drawAndRead(ByteBuffer ubo, ByteBuffer pixels) {
try (MemoryStack stack = MemoryStack.stackPush()) {
final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice());
assertTrue(cb != 0, "no command buffer");
final SDL_GPUColorTargetInfo.Buffer color = SDL_GPUColorTargetInfo.calloc(1, stack);
color.get(0).texture(colorTexture).load_op(SDL_GPU_LOADOP_CLEAR).store_op(SDL_GPU_STOREOP_STORE);
final SDL_GPUDepthStencilTargetInfo ds = SDL_GPUDepthStencilTargetInfo.calloc(stack)
.texture(depthTexture)
.load_op(SDL_GPU_LOADOP_CLEAR).store_op(SDL_GPU_STOREOP_DONT_CARE).clear_depth(1.0f)
.stencil_load_op(SDL_GPU_LOADOP_CLEAR).stencil_store_op(SDL_GPU_STOREOP_DONT_CARE);
SDL_PushGPUVertexUniformData(cb, 0, ubo);
final long pass = SDL_BeginGPURenderPass(cb, color, ds);
assertTrue(pass != 0, "no render pass");
SDL_BindGPUGraphicsPipeline(pass, terrainPipeline);
SDL_DrawGPUPrimitives(pass, GRID * GRID * 6, 1, 0, 0);
SDL_BindGPUGraphicsPipeline(pass, waterPipeline);
SDL_DrawGPUPrimitives(pass, GRID * GRID * 6, 1, 0, 0);
SDL_EndGPURenderPass(pass);
pixels.clear();
rig.resourceManager.downloadFromTexture(cb, colorTexture, 0, 0, SIZE, SIZE, 0, pixels);
}
}
@Test
void secondProgramMatchesFirstProgramDepthOnCoplanarGeometry() throws IOException {
final ByteBuffer ubo = MemoryUtil.memCalloc(UBO_BYTES);
final ByteBuffer pixels = MemoryUtil.memAlloc(SIZE * SIZE * 4);
try {
int mismatched = 0, covered = 0;
Path firstBad = null;
writeMats(ubo);
for (double chunkZ : new double[]{ 0, 16, 64, 256 }) {
ubo.putFloat(280, (float) (-944.0 + chunkZ - CAM_Z));
drawAndRead(ubo, pixels);
int red = 0;
for (int i = 0; i < SIZE * SIZE * 4; i += 4) {
if ((pixels.get(i) & 0xFF) > 128) red++;
else if ((pixels.get(i + 1) & 0xFF) > 128) covered++;
}
if (red > 0 && firstBad == null) firstBad = GpuTestPrograms.dumpPng(pixels, SIZE, SIZE, "coplanar_depth_dz" + (int) chunkZ);
mismatched += red;
covered += red;
}
assertTrue(covered > 4 * SIZE, "the plane must cover the target, covered=" + covered);
assertEquals(0, mismatched, "depth EQUAL failed on " + mismatched + "/" + covered + " pixels drawn by both programs; first failing view: " + firstBad);
} finally {
MemoryUtil.memFree(ubo);
MemoryUtil.memFree(pixels);
}
}
}
@@ -1,10 +1,8 @@
package com.gtnewhorizons.angelica.sdlgpu.shader; package com.gtnewhorizons.angelica.sdlgpu.shader;
import com.gtnewhorizons.angelica.sdlgpu.GpuTestPrograms;
import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension; import com.gtnewhorizons.angelica.sdlgpu.RealDeviceExtension;
import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig; import com.gtnewhorizons.angelica.sdlgpu.SdlTestRig;
import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig; import com.gtnewhorizons.angelica.sdlgpu.glsm.GlsmSdlHeadlessRig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
@@ -12,6 +10,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource; import org.junit.jupiter.params.provider.ValueSource;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
import org.lwjgl.sdl.SDL_GPUColorTargetDescription; import org.lwjgl.sdl.SDL_GPUColorTargetDescription;
import org.lwjgl.sdl.SDL_GPUColorTargetInfo; import org.lwjgl.sdl.SDL_GPUColorTargetInfo;
@@ -26,6 +25,7 @@ import org.lwjgl.system.MemoryUtil;
import java.io.IOException; import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -48,11 +48,6 @@ class FragmentStorageTextureReadGpuTest {
sm = new ShaderManager(rig.device); sm = new ShaderManager(rig.device);
} }
@AfterAll
static void tearDown() {
if (sm != null) sm.shutdown();
}
private static String fragment(int samplerCount) { private static String fragment(int samplerCount) {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append("#version 460 core\n"); sb.append("#version 460 core\n");
@@ -74,7 +69,8 @@ class FragmentStorageTextureReadGpuTest {
return (x == y) ? 255 - z * 16 : z * 32 + x * 2 + y; return (x == y) ? 255 - z * 16 : z * 32 + x * 2 + y;
} }
private int createVoxelTexture(int glId) { private int createVoxelTexture() {
final int glId = 9001;
final long handle = rig.resourceManager.createTexture(glId, GL12.GL_TEXTURE_3D, GL30.GL_R16UI, VOL, VOL, VOL, 1); final long handle = rig.resourceManager.createTexture(glId, GL12.GL_TEXTURE_3D, GL30.GL_R16UI, VOL, VOL, VOL, 1);
assertTrue(handle != 0, "voxel texture creation failed"); assertTrue(handle != 0, "voxel texture creation failed");
final ByteBuffer data = MemoryUtil.memAlloc(VOL * VOL * VOL * 2); final ByteBuffer data = MemoryUtil.memAlloc(VOL * VOL * VOL * 2);
@@ -99,15 +95,25 @@ class FragmentStorageTextureReadGpuTest {
} }
private int linkProgram(int samplerCount) { private int linkProgram(int samplerCount) {
final int prog = GpuTestPrograms.link(sm, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX, fragment(samplerCount)); final int vs = sm.createShader(GL20.GL_VERTEX_SHADER);
sm.shaderSource(vs, GlsmSdlHeadlessRig.FULLSCREEN_VERTEX);
sm.compileShader(vs);
final int fs = sm.createShader(GL20.GL_FRAGMENT_SHADER);
sm.shaderSource(fs, fragment(samplerCount));
sm.compileShader(fs);
final int prog = sm.createProgram();
sm.attachShader(prog, vs);
sm.attachShader(prog, fs);
sm.linkProgram(prog);
final ShaderManager.ProgramObject po = sm.getProgram(prog); final ShaderManager.ProgramObject po = sm.getProgram(prog);
assertTrue(po != null && po.linked, "link failed: " + (po == null ? "no program" : po.infoLog));
assertEquals(samplerCount, po.fragmentResources.numSamplers(), "production sampler count"); assertEquals(samplerCount, po.fragmentResources.numSamplers(), "production sampler count");
assertEquals(1, po.fragmentResources.numStorageTextures(), "production storage texture count"); assertEquals(1, po.fragmentResources.numStorageTextures(), "production storage texture count");
return prog; return prog;
} }
private void runCase(int samplerCount) throws IOException { private void runCase(int samplerCount) throws IOException {
final int voxelGlId = createVoxelTexture(9000 + samplerCount); final int voxelGlId = createVoxelTexture();
final long voxelHandle = rig.resourceManager.getTextureHandle(voxelGlId); final long voxelHandle = rig.resourceManager.getTextureHandle(voxelGlId);
final int targetGlId = 9100 + samplerCount; final int targetGlId = 9100 + samplerCount;
@@ -126,6 +132,13 @@ class FragmentStorageTextureReadGpuTest {
System.out.println("[GpuReadTest] S=" + samplerCount System.out.println("[GpuReadTest] S=" + samplerCount
+ " VS=" + po.vertexResources + " FS=" + po.fragmentResources); + " VS=" + po.vertexResources + " FS=" + po.fragmentResources);
final ShaderManager.ResourceCounts vr = po.vertexResources;
po.sdlVertexShader = sm.createSDLShader(po.vertexSpirv, SDL_GPU_SHADERSTAGE_VERTEX, vr.numSamplers(), vr.numUBOs(), vr.numStorageBuffers(), vr.numStorageTextures());
final ShaderManager.ResourceCounts fr = po.fragmentResources;
po.sdlFragmentShader = sm.createSDLShader(po.fragmentSpirv, SDL_GPU_SHADERSTAGE_FRAGMENT, fr.numSamplers(), fr.numUBOs(), fr.numStorageBuffers(), fr.numStorageTextures());
assertTrue(po.sdlVertexShader != 0, "SDL vertex shader creation failed");
assertTrue(po.sdlFragmentShader != 0, "SDL fragment shader creation failed");
final long pipeline; final long pipeline;
try (MemoryStack stack = MemoryStack.stackPush()) { try (MemoryStack stack = MemoryStack.stackPush()) {
final SDL_GPUColorTargetDescription.Buffer colorDesc = SDL_GPUColorTargetDescription.calloc(1, stack); final SDL_GPUColorTargetDescription.Buffer colorDesc = SDL_GPUColorTargetDescription.calloc(1, stack);
@@ -176,14 +189,13 @@ class FragmentStorageTextureReadGpuTest {
assertTrue(SDL_SubmitGPUCommandBuffer(cb), "draw submit failed"); assertTrue(SDL_SubmitGPUCommandBuffer(cb), "draw submit failed");
SDL_WaitForGPUIdle(rig.device.getDevice()); SDL_WaitForGPUIdle(rig.device.getDevice());
} }
SDL_ReleaseGPUGraphicsPipeline(rig.device.getDevice(), pipeline);
final ByteBuffer pixels = MemoryUtil.memAlloc(TARGET * TARGET * 4); final ByteBuffer pixels = MemoryUtil.memAlloc(TARGET * TARGET * 4);
try { try {
final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice()); final long cb = SDL_AcquireGPUCommandBuffer(rig.device.getDevice());
assertTrue(cb != 0, "no readback command buffer"); assertTrue(cb != 0, "no readback command buffer");
rig.resourceManager.downloadFromTexture(cb, targetHandle, 0, 0, TARGET, TARGET, 0, pixels); rig.resourceManager.downloadFromTexture(cb, targetHandle, 0, 0, TARGET, TARGET, 0, pixels);
final Path png = GpuTestPrograms.dumpPng(pixels, TARGET, TARGET, "storage_read_s" + samplerCount); final Path png = dumpPng(pixels, samplerCount);
// SDL's Y-flip means the readback may be row-inverted vs gl_FragCoord; either orientation // SDL's Y-flip means the readback may be row-inverted vs gl_FragCoord; either orientation
// is a fixed convention, not this bug - accept whichever matches. // is a fixed convention, not this bug - accept whichever matches.
final int direct = countMismatches(pixels, false, null); final int direct = countMismatches(pixels, false, null);
@@ -217,6 +229,22 @@ class FragmentStorageTextureReadGpuTest {
return mismatches; return mismatches;
} }
private static Path dumpPng(ByteBuffer rgba, int samplerCount) throws IOException {
final Path out = Path.of("build", "test-artifacts");
Files.createDirectories(out);
final java.awt.image.BufferedImage img = new java.awt.image.BufferedImage(TARGET, TARGET, java.awt.image.BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < TARGET; y++) {
for (int x = 0; x < TARGET; x++) {
final int i = (y * TARGET + x) * 4;
img.setRGB(x, y, ((rgba.get(i) & 0xFF) << 16) | ((rgba.get(i + 1) & 0xFF) << 8) | (rgba.get(i + 2) & 0xFF));
}
}
final Path file = out.resolve("storage_read_s" + samplerCount + ".png").toAbsolutePath();
javax.imageio.ImageIO.write(img, "png", file.toFile());
System.out.println("[GpuReadTest] wrote " + file);
return file;
}
@ParameterizedTest(name = "{0} samplers") @ParameterizedTest(name = "{0} samplers")
@ValueSource(ints = {0, 2}) @ValueSource(ints = {0, 2})
void fragmentImageLoadReadsCorrectTexels(int samplerCount) throws IOException { void fragmentImageLoadReadsCorrectTexels(int samplerCount) throws IOException {
@@ -291,55 +291,6 @@ class MslCrossCompileTest {
assertUniqueBufferSlots(msl); assertUniqueBufferSlots(msl);
} }
private static final String POSITION_HEAD = """
#version 460 core
layout(std140) uniform Mats { mat4 proj; mat4 view; mat4 viewInv; mat4 mv; vec4 ab; };
in vec3 a_Position;
out float vOut;
""";
static Stream<Arguments> positionVertexShapes() {
return Stream.of(
Arguments.of("chain through a temporary", "proj|view|viewInv|mv", POSITION_HEAD + """
void main() {
vec4 position = viewInv * (mv * vec4(a_Position, 1.0));
vOut = ab.x * ab.y;
gl_Position = proj * (view * position);
}
"""),
Arguments.of("declared invariant", "proj|view", POSITION_HEAD + """
invariant gl_Position;
void main() {
vOut = ab.x * ab.y;
gl_Position = proj * (view * vec4(a_Position, 1.0));
}
"""),
Arguments.of("already precise", "proj|view", POSITION_HEAD + """
precise gl_Position;
void main() {
vOut = ab.x * ab.y;
gl_Position = proj * (view * vec4(a_Position, 1.0));
}
"""),
Arguments.of("helper writes gl_Position", "proj|view", POSITION_HEAD + """
void place(vec4 p) { gl_Position = proj * (view * p); }
void main() {
vOut = ab.x * ab.y;
place(viewInv * (mv * vec4(a_Position, 1.0)));
}
"""));
}
@ParameterizedTest(name = "{0}")
@MethodSource("positionVertexShapes")
void positionMathIsContractionFreeAndOtherMathIsNot(String name, String exactMatrices, String glsl) {
final String transformed = ShaderManager.applyPrewarmTransformsFull(glsl, GL20.GL_VERTEX_SHADER, null, null).source();
final String msl = crossCompile(transformed, Shaderc.shaderc_vertex_shader, GL20.GL_VERTEX_SHADER, false).code();
assertTrue(msl.contains("spvFMulMatrixVector") && msl.contains("[[clang::optnone]]"), "gl_Position math must go through the optnone fma helpers:\n" + msl);
assertFalse(Pattern.compile("\\.(" + exactMatrices + ") \\*").matcher(msl).find(), "a plain multiply by " + exactMatrices + " is left on the gl_Position chain:\n" + msl);
assertTrue(Pattern.compile("\\.ab\\.x \\* \\w+\\.ab\\.y").matcher(msl).find(), "math not feeding gl_Position must stay contractible:\n" + msl);
}
private static void assertUniqueBufferSlots(String msl) { private static void assertUniqueBufferSlots(String msl) {
final Set<Integer> seen = new HashSet<>(); final Set<Integer> seen = new HashSet<>();
int from = 0; int from = 0;
@@ -0,0 +1,61 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.PositionalLightSource;
public final class DynamicLightsApi {
private DynamicLightsApi() {}
/** True when dynamic lights are on (the setting is on, and there's no shaderpack or shader force is on). */
public static boolean isEnabled() {
return DynamicLights.isEnabled();
}
/**
* True when lights made with this {@link PositionalLight#setLitUnderShaderpacks} setting give light right now. With
* true that's whenever dynamic lights are on, shaderpack or not.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return DynamicLights.isEnabled(litUnderShaderpacks);
}
/** A new light, off until it gets a luminance. */
public static PositionalLight createLight() {
return new PositionalLightSource();
}
/**
* Calls the visitor for every dynamic light within radius blocks of the point that gives light right now, entities
* included. Positional lights are passed as themselves, other lights as null. Under a shaderpack without shader
* force that's only the lights lit under shaderpacks.
*/
public static void forEachLightNear(double x, double y, double z, double radius, LightVisitor visitor) {
if (!DynamicLights.isActive()) return;
DynamicLights.get().forEachSourceNear(x, y, z, radius, source -> visitor.visit(
source instanceof PositionalLight light ? light : null,
source.angelica$getDynamicLightX(),
source.angelica$getDynamicLightY(),
source.angelica$getDynamicLightZ(),
source.angelica$getLuminance()));
}
/** How bright a held torch reach dynamic light of this luminance is at this distance, 0 past 7.75 blocks. */
public static double lightLevelAt(int luminance, double distance) {
return DynamicLights.falloff(luminance, distance);
}
/**
* How bright a dynamic light of this luminance and reach (see {@link PositionalLight#setReach}) is at this distance.
* Other lights from {@link #forEachLightNear} come with null and light like {@link PositionalLight#TORCH_REACH}.
*/
public static double lightLevelAt(int luminance, float reach, double distance) {
return DynamicLights.falloff(luminance, reach, distance);
}
@FunctionalInterface
public interface LightVisitor {
void visit(PositionalLight light, double x, double y, double z, int luminance);
}
}
@@ -0,0 +1,54 @@
package com.gtnewhorizons.angelica.api.dynamiclights;
/**
* A dynamic light at a position, for moving things that aren't entities. Make one with
* {@link DynamicLightsApi#createLight}. Lights terrain and entities like a held torch, so only while dynamic lights are
* on (see {@link #setLitUnderShaderpacks} for shaderpacks). Main thread only.
*/
public interface PositionalLight {
/** Moves the light. Cheap enough to call every frame, chunks only rebuild once it's moved a bit. */
void setPosition(double x, double y, double z);
/** Brightness 0-15. 0 switches it off. */
void setLuminance(int luminance);
double getX();
double getY();
double getZ();
int getLuminance();
/**
* Under a shaderpack dynamic lights only show with the player's shader force option, since packs do their own
* held item and entity light. A light that stands in for real blocks (a rendered structure's lamps) has nothing
* else to light the world round it, so set this and it lights things under a pack too, like it does without one.
* Dynamic lights turned off still means off. False by default.
*/
void setLitUnderShaderpacks(boolean lit);
boolean isLitUnderShaderpacks();
/** {@link #setReach} for Angelica's held torch falloff, the default. */
float TORCH_REACH = -1;
/**
* How far it lights at full brightness, 0-15, like block light: a luminance 15 light falls 15 / reach levels a
* block, so 15 lights exactly like a real block of that luminance and smaller reaches fade out sooner. Dimmer lights
* get as far as their luminance allows. {@link #TORCH_REACH} (the default) lights like a held torch instead,
* straight down to nothing at 7.75 blocks whatever the luminance. Fractions are fine, e.g. for a lamp in something
* drawn at an eighth of its size. Like a move under 0.1 blocks, a change under 0.1 doesn't rebuild the terrain it
* lights.
* <p>
* Further costs more: a moving light rebuilds every chunk section its light gets into, up to 27 at reach 15 against
* 8 or so for a torch, and never more than 8 at reach 7 or less.
*/
void setReach(float reach);
float getReach();
/** Switches it off for good and drops it from Angelica's lights. */
void remove();
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|dynamiclights", apiVersion = "1")
package com.gtnewhorizons.angelica.api.dynamiclights;
import cpw.mods.fml.common.API;
@@ -0,0 +1,72 @@
package com.gtnewhorizons.angelica.api.particles;
import net.coderbot.iris.layer.GbufferPrograms;
import net.minecraft.client.particle.EntityFX;
import java.util.Arrays;
/** For mods that draw particles themselves or change their size. */
public final class ParticleRendering {
private ParticleRendering() {}
/** A size factor per particle, 1 for a normal one. */
@FunctionalInterface
public interface RenderScale {
float of(EntityFX fx);
}
private static final RenderScale[] NO_SCALES = new RenderScale[0];
// Swapped for a new array on every change, so the per particle read is one field and a length check
private static volatile RenderScale[] renderScales = NO_SCALES;
/**
* Scales the particles Angelica batches straight from their fields without calling {@code renderParticle}, which
* is the ones that don't override it plus the vanilla and BoP ones it knows. Particles that do go through
* {@code renderParticle} keep whatever size that gives, so scale those there. Every source added gets asked about
* every batched particle and the factors multiply, so return 1 for particles that aren't yours.
*/
public static synchronized void addRenderScale(RenderScale source) {
for (RenderScale existing : renderScales) {
if (existing == source) return;
}
final RenderScale[] next = Arrays.copyOf(renderScales, renderScales.length + 1);
next[next.length - 1] = source;
renderScales = next;
}
public static synchronized void removeRenderScale(RenderScale source) {
final RenderScale[] old = renderScales;
for (int i = 0; i < old.length; i++) {
if (old[i] != source) continue;
final RenderScale[] next = new RenderScale[old.length - 1];
System.arraycopy(old, 0, next, 0, i);
System.arraycopy(old, i + 1, next, i, old.length - i - 1);
renderScales = next.length == 0 ? NO_SCALES : next;
return;
}
}
/** The size factor for this particle from every {@link #addRenderScale} source, 1 without any. */
public static float renderScale(EntityFX fx) {
final RenderScale[] sources = renderScales;
if (sources.length == 0) return 1;
float scale = 1;
for (RenderScale source : sources) scale *= source.of(fx);
return scale;
}
/**
* Particles drawn outside the effect renderer (e.g. a mod's own list) get the pack's particle program between this
* and {@link #endParticleDraw}, like the world's particles. Pass the returned token to the end call. Nests. Without
* a pack nothing changes.
*/
public static int beginParticleDraw() {
return GbufferPrograms.beginParticles();
}
public static void endParticleDraw(int token) {
GbufferPrograms.endParticles(token);
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|particles", apiVersion = "1")
package com.gtnewhorizons.angelica.api.particles;
import cpw.mods.fml.common.API;
@@ -0,0 +1,20 @@
package com.gtnewhorizons.angelica.api.shadows;
/**
* Draws extra geometry into the shaderpack shadow map, for things that should cast shadows but aren't terrain or
* entities. RenderWorldLastEvent geometry never gets there, and TESRs only do when the pack shadows block entities.
* Register with {@link ShadowCasters#register}.
*/
@FunctionalInterface
public interface ShadowCaster {
/**
* Called once per shadow pass for each stage, with the shadow modelview loaded and the block entity shadow program
* bound. Positions are relative to the camera position passed in, so translate by worldX - cameraX etc. Put back
* any GL state you change.
*
* @param stage {@link ShadowStage#SOLID} with the other solid shadows, {@link ShadowStage#TRANSLUCENT} after
* translucent terrain for things the pack should tint light through instead of blocking it
*/
void renderShadow(ShadowStage stage, double cameraX, double cameraY, double cameraZ, float partialTicks);
}
@@ -0,0 +1,44 @@
package com.gtnewhorizons.angelica.api.shadows;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.coderbot.iris.pipeline.ShadowRenderer;
import java.util.concurrent.CopyOnWriteArrayList;
/** Where {@link ShadowCaster}s are registered. Main thread only. */
public final class ShadowCasters {
private static final CopyOnWriteArrayList<ShadowCaster> CASTERS = new CopyOnWriteArrayList<>();
private ShadowCasters() {}
public static void register(ShadowCaster caster) {
CASTERS.addIfAbsent(caster);
}
public static void unregister(ShadowCaster caster) {
CASTERS.remove(caster);
}
/** True while the shaderpack shadow pass is drawing, e.g. to skip work in a TESR that also feeds a caster. */
public static boolean isRenderingShadows() {
return ShadowRenderer.ACTIVE;
}
public static boolean hasCasters() {
return !CASTERS.isEmpty();
}
/** Internal, called by the shadow renderer with its state set up. A caster that throws is dropped. */
public static void renderAll(ShadowStage stage, double cameraX, double cameraY, double cameraZ,
float partialTicks) {
for (ShadowCaster caster : CASTERS) {
try {
caster.renderShadow(stage, cameraX, cameraY, cameraZ, partialTicks);
} catch (Throwable t) {
AngelicaMod.LOGGER.error("Shadow caster {} threw, removing it", caster, t);
CASTERS.remove(caster);
}
}
}
}
@@ -0,0 +1,8 @@
package com.gtnewhorizons.angelica.api.shadows;
public enum ShadowStage {
/** After the shadow pass's entities and tile entities, before translucent depth is split off. */
SOLID,
/** After translucent terrain. Only runs when the pack draws translucent shadows. */
TRANSLUCENT
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|shadows", apiVersion = "1")
package com.gtnewhorizons.angelica.api.shadows;
import cpw.mods.fml.common.API;
@@ -0,0 +1,108 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.rendering.celeritas.VertexArrayQuadView;
import com.gtnewhorizons.angelica.rendering.celeritas.light.LightDataCache;
import com.gtnewhorizons.angelica.rendering.celeritas.light.VanillaDiffuseProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.world.IBlockAccess;
import org.embeddedt.embeddium.impl.model.light.LightPipeline;
import org.embeddedt.embeddium.impl.model.light.data.LightDataAccess;
import org.embeddedt.embeddium.impl.model.light.data.QuadLightData;
import org.embeddedt.embeddium.impl.model.light.flat.FlatLightPipeline;
import org.embeddedt.embeddium.impl.model.light.smooth.SmoothLightPipeline;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFacing;
import org.embeddedt.embeddium.impl.model.quad.properties.ModelQuadFlags;
import org.embeddedt.embeddium.impl.render.chunk.vertex.format.ChunkVertexEncoder;
import org.embeddedt.embeddium.impl.util.QuadUtil;
/**
* Per-vertex AO and lightmap for block quads, worked out like the chunk mesher lights terrain (same light pipeline and
* light data) but over any block access. For mods baking block geometry outside the chunk renderer.
* <p>
* Not thread safe, use one per thread. Light data is cached per 16 block region, so quads from the same region in a
* row are cheapest. The cache doesn't notice world changes, call {@link #reset} before each bake.
*/
public final class TerrainLighter {
private final LightDataCache cache = new LightDataCache();
private final SmoothLightPipeline smooth;
private final FlatLightPipeline flat;
private final ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad();
private final VertexArrayQuadView quad = new VertexArrayQuadView(vertices);
private final QuadLightData out = new QuadLightData();
private int regionX = Integer.MIN_VALUE, regionY, regionZ;
// The last fluid quad, to spot the back face vanilla draws straight after it
private ModelQuadFacing fluidLightFace;
private final float[] fluidXyz = new float[12];
private static final int[] REVERSED = { 0, 3, 2, 1 };
public TerrainLighter(IBlockAccess world) {
cache.setWorld(world);
smooth = new SmoothLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
flat = new FlatLightPipeline(cache, VanillaDiffuseProvider.INSTANCE, true);
}
/** Drops the cached light data so the next quad reads the world again. Call it before each bake. */
public void reset() {
regionX = Integer.MIN_VALUE;
fluidLightFace = null;
}
/**
* Lights one quad of the block at x, y, z.
*
* @param xyz the four corners as x y z, in the block access's coordinates and the quad's vertex order
* @param shade also multiply in the face's directional shading, like terrain unless the pack turns it off.
* False gives AO alone
* @param fluid the block is a fluid (see {@code TerrainRendering.isFluid}). Lit like the mesher lights fluids,
* where the back face vanilla draws right after each face gets its light from the same side as
* the front. Pass a block's quads in the order they were made. Only use the light for fluids,
* the mesher gives them no AO
* @param brightness out, per vertex AO (times shading if asked), 0 to 1
* @param light out, per vertex lightmap, {@code sky << 16 | block}, each 0-240
*/
public void light(float[] xyz, int x, int y, int z, boolean shade, boolean fluid, float[] brightness,
int[] light) {
final int rx = x & ~15, ry = y & ~15, rz = z & ~15;
if (rx != regionX || ry != regionY || rz != regionZ) {
regionX = rx;
regionY = ry;
regionZ = rz;
cache.reset(rx, ry, rz);
}
smooth.reset();
flat.reset();
for (int i = 0; i < 4; i++) {
vertices[i].x = xyz[i * 3];
vertices[i].y = xyz[i * 3 + 1];
vertices[i].z = xyz[i * 3 + 2];
}
final boolean flippedCopy = fluid && fluidLightFace != null && isReversedFluidQuad(xyz);
quad.setup(QuadUtil.calculateNormal(vertices), x, y, z, fluid ? ModelQuadFlags.IS_VANILLA_SHADED : 0,
flippedCopy ? fluidLightFace : null);
// Same rule as the mesher, smooth lighting on and the block doesn't give off light
final boolean smoothLighting = Minecraft.getMinecraft().gameSettings.ambientOcclusion != 0
&& LightDataAccess.unpackLU(cache.get(x, y, z)) == 0;
final LightPipeline pipeline = smoothLighting ? smooth : flat;
pipeline.calculate(quad, x, y, z, out, quad.getCullFace(), quad.getLightFace(), shade, true);
System.arraycopy(out.br, 0, brightness, 0, 4);
System.arraycopy(out.lm, 0, light, 0, 4);
if (fluid && !flippedCopy) {
fluidLightFace = quad.getLightFace();
System.arraycopy(xyz, 0, fluidXyz, 0, 12);
} else if (!fluid) {
fluidLightFace = null;
}
}
private boolean isReversedFluidQuad(float[] xyz) {
for (int i = 0; i < 4; i++) {
final int src = REVERSED[i] * 3;
if (xyz[i * 3] != fluidXyz[src] || xyz[i * 3 + 1] != fluidXyz[src + 1]
|| xyz[i * 3 + 2] != fluidXyz[src + 2]) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,340 @@
package com.gtnewhorizons.angelica.api.terrain;
import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.api.glstate.GLState;
import com.gtnewhorizons.angelica.api.shaders.ShaderPacks;
import com.gtnewhorizons.angelica.glsm.backend.BackendManager;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.hooks.GLSMHooks;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.BlockMaterialAttribute;
import com.gtnewhorizons.angelica.rendering.StateAwareTessellator;
import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer;
import com.gtnewhorizons.angelica.utils.AnimationsRenderUtils;
import com.prupe.mcpatcher.mal.block.RenderBlocksUtils;
import net.coderbot.iris.Iris;
import net.coderbot.iris.block_rendering.BlockMaterialMapping;
import net.coderbot.iris.block_rendering.BlockRenderingSettings;
import net.coderbot.iris.gl.shader.ProgramCreator;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline;
import net.coderbot.iris.pipeline.WorldRenderingPhase;
import net.coderbot.iris.shadows.ShadowRenderingState;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.minecraft.block.Block;
import net.minecraft.block.BlockDoublePlant;
import net.minecraft.block.BlockDynamicLiquid;
import net.minecraft.block.BlockStaticLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.world.IBlockAccess;
import org.joml.Matrix4f;
import java.util.Map;
/**
* For mods that bake block geometry outside the chunk renderer (moving structures, in-world previews) and want it to
* look like terrain, shaderpacks included.
* <p>
* Under a shaderpack terrain gets the pack's terrain programs, its block.properties materials (mc_Entity) and the
* pack's own AO and directional shading. Draw between {@link #beginTerrainDraw} and {@link #endTerrainDraw} to get the
* terrain programs, and use the getters here to bake the way the pack wants. Without a shaderpack nothing changes.
*/
public final class TerrainRendering {
private static int terrainDrawDepth;
private static boolean terrainDrawPushed;
private static int localGridId;
private TerrainRendering() {}
/**
* Draws until {@link #endTerrainDraw} use the pack's terrain program instead of the one for the current phase
* (entities, block entities). Main thread, end it in a finally block. Nests, the outermost call picks the program.
*
* @param translucent true for render pass 1 geometry (glass, water), false for solid and cutout
*/
public static void beginTerrainDraw(boolean translucent) {
if (terrainDrawDepth++ > 0) return;
terrainDrawPushed = ShaderPacks.isInUse();
if (terrainDrawPushed) {
GbufferPrograms.pushOverridePhase(translucent ? WorldRenderingPhase.TERRAIN_TRANSLUCENT : WorldRenderingPhase.TERRAIN_CUTOUT);
}
}
public static void endTerrainDraw() {
if (terrainDrawDepth == 0) return;
// While the terrain program is still bound, so it gets the real uniforms back
if (terrainDrawDepth == 1) endLocalGrid();
if (--terrainDrawDepth > 0) return;
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
}
/** Internal, start of each frame. Ends a terrain draw that never got ended (e.g. the caller threw). */
public static void resetForFrame() {
if (terrainDrawDepth == 0) return;
AngelicaMod.LOGGER.warn("A terrain draw was never ended, ending it");
LocalGridFrame.end();
if (terrainDrawPushed) GbufferPrograms.popOverridePhase();
terrainDrawPushed = false;
terrainDrawDepth = 0;
}
/**
* Call inside {@link #beginTerrainDraw}, in a try-with-resources. Until the grid is closed or the terrain draw
* ends, the pack sees the current modelview's model space as the world. For geometry drawn rotated or off the block
* grid: packs pick out parts of some blocks by where a pixel is inside its world block (cauldron water, end portal
* frame eyes), and off the grid that lands in the wrong spot.
* <p>
* Only the uniforms a pack works out world space from change (camera, matrices, upPosition, eyePosition and the
* like), plus the pack's own custom uniforms made from them. View space and shadows come out the same. Model space
* up counts as up. Draws in between must use the modelview it was started with.
* <p>
* Does nothing without a pack, in the shadow pass, on the SDL GPU backend, if a grid is already on or if the
* modelview can't be inverted. Packs that go by at_midBlock instead get it right from the vertex data alone, see
* {@link #getMidBlockAttributeLocation}.
*
* @return the grid, {@link LocalGrid#isActive} says whether it's on
*/
public static LocalGrid beginLocalGrid() {
if (!terrainDrawPushed || LocalGridFrame.isActive() || BackendManager.RENDER_BACKEND.isSDLGPU()
|| ShadowRenderingState.areShadowsCurrentlyBeingRendered()) {
return LocalGrid.OFF;
}
final Matrix4f modelView = GLState.getModelViewMatrix(new Matrix4f());
if (!LocalGridFrame.begin(modelView)) return LocalGrid.OFF;
refreshBoundUniforms();
return new LocalGrid(++localGridId, modelView);
}
private static void endLocalGrid() {
if (!LocalGridFrame.isActive()) return;
LocalGridFrame.end();
refreshBoundUniforms();
}
// The camera and matrix uniforms are only worked out once a frame, so work them out again and push them to the
// terrain program (binding it first if it's still pending)
private static void refreshBoundUniforms() {
GLSMHooks.resolvePendingProgram();
if (Iris.getPipelineManager().getPipelineNullable() instanceof DeferredWorldRenderingPipeline drp) {
drp.refreshUniforms(LocalGridFrame.UNIFORMS);
}
}
/**
* True when the pack wants AO in the vertex color's alpha instead of multiplied into the color, so it can apply it
* itself. Put the AO from {@link TerrainLighter} in alpha when this is set.
*/
public static boolean usesSeparateAo() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo();
}
/**
* True when the chunk mesher runs its own light pipeline over terrain, the same one {@link TerrainLighter} runs. It
* only relights the faces {@link #isSmoothLit} marks (and fluids under a pack), everything else keeps the light it
* was baked with. AO goes in the color's alpha when {@link #usesSeparateAo}, multiplied into the color otherwise.
*/
public static boolean usesTerrainLighting() {
return ShaderPacks.isInUse() || BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()
|| ClientProxy.options().quality.useCeleritasSmoothLighting;
}
/** True when the pack does its own directional shading, so terrain is baked without vanilla's per-face shading. */
public static boolean disablesDirectionalShading() {
return ShaderPacks.isInUse() && BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading();
}
/**
* The Forge render pass the pack moves this block to (e.g. {@code layer.translucent} in block.properties), or -1 if
* it doesn't move it or there's no pack. The chunk mesher only draws a moved block in that pass, so do the same.
*/
public static int getRenderPassOverride(Block block) {
if (!ShaderPacks.isInUse()) return -1;
final Map<Block, BlockRenderLayer> overrides = BlockRenderingSettings.INSTANCE.getBlockTypeIds();
if (overrides == null) return -1;
final BlockRenderLayer layer = overrides.get(block);
return layer == null ? -1 : layer.toVanillaPass();
}
/** The pack's block.properties id for this block, -1 if it's unmapped or there's no pack. */
public static int getBlockMaterialId(Block block, int metadata) {
return ShaderPacks.isInUse() ? BlockMaterialAttribute.blockMaterialId(block, metadata) : -1;
}
/**
* The id the chunk mesher gives this block where it stands, which isn't always the plain lookup. A fluid with no
* entry uses its still or flowing twin's, grass under snow gets the pack's snowy entry and the top half of a double
* plant is looked up as the plant its bottom half says. -1 if it's unmapped or there's no pack.
*/
public static int getBlockMaterialId(IBlockAccess world, Block block, int metadata, int x, int y, int z) {
if (!ShaderPacks.isInUse()) return -1;
if (isFluid(block)) {
int id = BlockMaterialAttribute.blockMaterialId(block, metadata);
if (id == -1) {
Block twin = null;
if (block instanceof BlockStaticLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) - 1);
else if (block instanceof BlockDynamicLiquid) twin = Block.getBlockById(Block.getIdFromBlock(block) + 1);
if (twin != null) id = BlockMaterialAttribute.blockMaterialId(twin, metadata);
}
return id;
}
int effectiveMeta = metadata;
if (BlockRenderingSettings.INSTANCE.hasSnowyEntries()
&& BlockRenderingSettings.INSTANCE.getSnowyBlocks().contains(block)
&& RenderBlocksUtils.isSnowCovered(world, x, y, z)) {
effectiveMeta |= BlockMaterialMapping.SNOWY_META_BIT;
} else if (block instanceof BlockDoublePlant doublePlant && BlockDoublePlant.func_149887_c(metadata)) {
effectiveMeta = 0x8 | (doublePlant.func_149885_e(world, x, y, z) & 7);
}
return BlockMaterialAttribute.blockMaterialId(block, effectiveMeta);
}
/**
* What the chunk mesher counts as a fluid, water or lava material. Under a pack it lights fluid quads with its
* light pipeline but leaves out the AO, pass that on to {@link TerrainLighter#light}.
*/
public static boolean isFluid(Block block) {
final Material material = block.getMaterial();
return material == Material.water || material == Material.lava;
}
/**
* While on, RenderBlocks draws into this tessellator like it does for the chunk mesher. Pass the one it draws into
* ({@code Tessellator.instance} on the main thread). Standard blocks that would take vanilla's smooth lighting path
* are drawn flat instead, with no AO or face shading, and their vertices get marked (see {@link #isSmoothLit}).
* Light those with {@link TerrainLighter} and leave the rest alone, that's all the mesher does. Only kicks in when
* the mesher would do it too: smooth lighting with Celeritas smooth lighting on, or a pack using separate AO. Turn
* it off again in a finally block.
*/
public static void setMeshing(Tessellator tessellator, boolean meshing) {
((StateAwareTessellator) tessellator).angelica$setCeleritasMeshing(meshing);
}
/**
* True while the vertices being added are from a face the chunk mesher would relight (see {@link #setMeshing}),
* vanilla's smooth lighting path or a renderer that asked for the same. Check it per vertex as they're added.
*/
public static boolean isSmoothLit(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isAppliedAo();
}
/** True while the vertices being added are from a renderer that wants no directional shading on them. */
public static boolean hasNoDirectionalShading(Tessellator tessellator) {
return ((StateAwareTessellator) tessellator).angelica$isNoDirectionalShading();
}
/**
* Vertex attribute location the pack's programs read mc_Entity from. Bake two shorts per vertex here, the material
* id and 0 (1 for fluids, like the mesher). Only bind it while a shaderpack is in use.
*/
public static int getMaterialAttributeLocation() {
return ProgramCreator.MC_ENTITY;
}
/**
* Vertex attribute location the pack's programs read mc_midTexCoord from, the middle of the vertex's sprite. Packs
* use it for sprite bounds (e.g. POM). Two floats per vertex. Only bind it while a shaderpack is in use, and
* between {@link #beginOwnExtendedAttributes} and {@link #endOwnExtendedAttributes}.
*/
public static int getMidTexCoordAttributeLocation() {
return ProgramCreator.MC_MID_TEX_COORD;
}
/**
* Vertex attribute location the pack's programs read at_tangent from. Four floats per vertex, xyz plus w for the
* handedness. Same rules as {@link #getMidTexCoordAttributeLocation}.
*/
public static int getTangentAttributeLocation() {
return ProgramCreator.AT_TANGENT;
}
/**
* Vertex attribute location the pack's programs read at_midBlock from. Four bytes per vertex, not normalized: the
* offset from the vertex to the middle of its block times 64, then the block's light emission (0-15). Bake the
* offset in model space and packs that use it get blocks right even off the grid, no {@link #beginLocalGrid}
* needed. Only bind it while a shaderpack is in use.
*/
public static int getMidBlockAttributeLocation() {
return ProgramCreator.AT_MIDBLOCK;
}
/**
* Angelica fills in mc_midTexCoord and at_tangent itself for client array draws out of a VBO, guessing from the
* buffer layout, and binds that over whatever the draw set. Draws until {@link #endOwnExtendedAttributes} bring
* their own and are left alone. Nests, main thread.
*/
public static void beginOwnExtendedAttributes() {
FfpExtendedAttribs.beginInternalDraw();
}
public static void endOwnExtendedAttributes() {
FfpExtendedAttribs.endInternalDraw();
}
/**
* Angelica only animates sprites it saw drawn this frame, and geometry baked once and drawn from a buffer never
* goes through the tessellator again. This records the sprites used on this thread until it's closed.
* Call {@link SpriteCapture#markUsed} each frame the baked geometry is drawn. Close it on the same thread, in a
* finally block.
*/
public static SpriteCapture captureSprites() {
return new SpriteCapture(AnimationsRenderUtils.captureSprites());
}
/** See {@link #beginLocalGrid}. */
public static final class LocalGrid implements AutoCloseable {
private static final LocalGrid OFF = new LocalGrid(0, null);
private static boolean warnedModelView;
private final int id;
private final Matrix4f modelView;
private LocalGrid(int id, Matrix4f modelView) {
this.id = id;
this.modelView = modelView;
}
public boolean isActive() {
return id != 0 && id == localGridId && LocalGridFrame.isActive();
}
/** Ends it. Does nothing if it never started or the terrain draw already ended it. */
@Override
public void close() {
if (!isActive()) return;
// The one rule callers can break without noticing. Only catches a modelview left changed, not one changed
// and put back, but that's cheap enough to always check
if (!warnedModelView && !GLState.getModelViewMatrix(new Matrix4f()).equals(modelView, 1e-4f)) {
warnedModelView = true;
AngelicaMod.LOGGER.warn("Modelview changed during a local grid, draws in it have to use the one it "
+ "started with", new Throwable());
}
endLocalGrid();
}
}
/** See {@link #captureSprites}. */
public static final class SpriteCapture implements AutoCloseable {
private final AnimationsRenderUtils.SpriteCapture capture;
private SpriteCapture(AnimationsRenderUtils.SpriteCapture capture) {
this.capture = capture;
}
/** Marks the recorded sprites as drawn this frame so they keep animating. */
public void markUsed() {
capture.markUsed();
}
/** Stops recording. The sprites recorded so far stay. */
@Override
public void close() {
capture.close();
}
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|terrain", apiVersion = "1")
package com.gtnewhorizons.angelica.api.terrain;
import cpw.mods.fml.common.API;
@@ -1,15 +0,0 @@
package com.gtnewhorizons.angelica.api.tesr;
import com.gtnewhorizons.angelica.rendering.tesr.GlowReplayExclusions;
/// Under Fancy translucency, block entities drawing glows (blended draws without depth writes) in the translucent
/// pass are rendered a second time. Renderers that advance state per call opt out here.
public final class TesrGlowDepth {
private TesrGlowDepth() {}
/// Excludes block entities of `type`, or rendered by a renderer of `type`, including subclasses.
public static void excludeFromReplay(Class<?> type) {
GlowReplayExclusions.exclude(type);
}
}
@@ -1,5 +1,5 @@
/** TESR mesh cache/batch API (Render thread only) */ /** TESR mesh cache/batch API (Render thread only) */
@API(owner = "angelica", provides = "angelica|tesr", apiVersion = "4") @API(owner = "angelica", provides = "angelica|tesr", apiVersion = "3")
package com.gtnewhorizons.angelica.api.tesr; package com.gtnewhorizons.angelica.api.tesr;
import cpw.mods.fml.common.API; import cpw.mods.fml.common.API;
@@ -0,0 +1,59 @@
package com.gtnewhorizons.angelica.api.world;
import com.gtnewhorizons.angelica.AngelicaMod;
import net.minecraftforge.client.MinecraftForgeClient;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* A spot in the world pass for mods that draw their own world geometry (moving structures, previews, effects).
* <p>
* Forge's {@code RenderWorldLastEvent} fires after Angelica has run the pack's composite and final passes, so anything
* drawn there misses the pack's lighting, fog and shadows. Drawers registered here run right after block entities,
* once per Forge render pass, with the pack's block entity program active like for a TESR. Without a pack they still
* run there.
* <p>
* The modelview is the camera's like for TESRs, so draw relative to the camera
* ({@code TileEntityRendererDispatcher.staticPlayerX/Y/Z}). Put back any GL state you change. Main thread only.
*/
public final class WorldDrawStage {
/** Draws world geometry for one Forge render pass. */
@FunctionalInterface
public interface Drawer {
/**
* @param pass Forge render pass, 0 for solid and cutout, 1 for translucent. Same as
* {@code MinecraftForgeClient.getRenderPass()}
* @param partialTicks the frame's partial ticks
*/
void draw(int pass, float partialTicks);
}
private static final CopyOnWriteArrayList<Drawer> drawers = new CopyOnWriteArrayList<>();
private WorldDrawStage() {}
public static void register(Drawer drawer) {
drawers.addIfAbsent(drawer);
}
public static void unregister(Drawer drawer) {
drawers.remove(drawer);
}
/** Internal, called by Angelica's renderer after block entities. */
public static void run(float partialTicks) {
if (drawers.isEmpty()) return;
final int pass = MinecraftForgeClient.getRenderPass();
for (Drawer drawer : drawers) {
try {
drawer.draw(pass, partialTicks);
} catch (Throwable t) {
// One broken drawer shouldn't take the frame down or spam the log every frame
drawers.remove(drawer);
AngelicaMod.LOGGER.error("World drawer {} threw, removed it", drawer, t);
}
}
}
}
@@ -0,0 +1,4 @@
@API(owner = "angelica", provides = "angelica|world", apiVersion = "1")
package com.gtnewhorizons.angelica.api.world;
import cpw.mods.fml.common.API;
@@ -1,25 +0,0 @@
The menu blur in this package is based on [Blur](https://github.com/tterrag1098/Blur), used under the following license:
```
MIT License
Copyright (c) 2017 tterrag
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
@@ -1,206 +0,0 @@
package com.gtnewhorizons.angelica.blur;
import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat2v;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMDraws;
import com.gtnewhorizons.angelica.glsm.GLSMFramebuffer;
import com.gtnewhorizons.angelica.glsm.GLSMPrograms;
import com.gtnewhorizons.angelica.glsm.GLSMQueries;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.GLSMVertexInput;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.render.PanoramaRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import org.apache.commons.lang3.ArrayUtils;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import java.nio.ByteBuffer;
/**
* Blurs the world behind open GUIs and fades in a configurable background gradient.
* Based on Blur by tterrag (https://github.com/tterrag1098/Blur) under the MIT license, see LICENSE-Blur.md.
* Reimplemented on top of Angelica's own blur shader instead of a vanilla post-processing shader.
*/
public class MenuBlur {
private static final Minecraft mc = Minecraft.getMinecraft();
private static GlProgram<BlurUniforms> blurProgram;
private static StateSet allState;
private static int emptyVao;
// The blur runs on half resolution copies of the screen, which is much cheaper and looks the same once blurred
private static int horizontalFbo, horizontalTexture, verticalFbo, verticalTexture;
private static int sourceWidth, sourceHeight, halfWidth, halfHeight;
private static boolean blurring;
private static long fadeStartMillis;
/** Called right after the world has been drawn, before the HUD and the open GUI. */
public static void renderBlur() {
final boolean shouldBlur = shouldBlur();
if (shouldBlur && !blurring) {
fadeStartMillis = System.currentTimeMillis();
}
blurring = shouldBlur;
if (!blurring) return;
// The radius grows with the fade, so the blur gets stronger over the first moments
final float radius = (float) Math.floor(AngelicaConfig.menuBlurRadius * getProgress());
if (radius < 1.0F) return;
final Framebuffer mainFramebuffer = mc.getFramebuffer();
if (blurProgram == null) init();
final int previousProgram = GLSMPrograms.getActiveProgram();
final int previousVao = GLSMQueries.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING);
final int previousFilter = mainFramebuffer.framebufferFilter;
final int stateDepth = GLSMAttribStack.pushState(allState);
try {
ensureBlurTargets(mainFramebuffer.framebufferWidth, mainFramebuffer.framebufferHeight);
GLSMBlend.disableBlend();
GLSMDepthStencilAlpha.disableDepthTest();
GLSMDepthStencilAlpha.glDepthMask(false);
GLSMBlend.glColorMask(true, true, true, true);
GLSMRasterizer.disableCull();
GLSMRasterizer.disableScissorTest();
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
blurProgram.bind();
GLSMVertexInput.glBindVertexArray(emptyVao);
final BlurUniforms uniforms = blurProgram.getInterface();
// Each half resolution pixel covers two screen pixels, so half the radius gives the same strength
uniforms.radius.setFloat(radius * 0.5F);
// Horizontal pass, shrinking the screen to half size. Linear filtering makes every
// half size pixel average the four screen pixels it covers instead of picking one.
mainFramebuffer.setFramebufferFilter(GL11.GL_LINEAR);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, horizontalFbo);
GLSMRasterizer.glViewport(0, 0, halfWidth, halfHeight);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, mainFramebuffer.framebufferTexture);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
uniforms.direction.set(1.0F / halfWidth, 0.0F);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
// Vertical pass, still at half size
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, verticalFbo);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, horizontalTexture);
uniforms.direction.set(0.0F, 1.0F / halfHeight);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
// Stretch the result back over the screen. A radius of 0 makes the blur shader a plain copy.
mainFramebuffer.bindFramebuffer(true);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, verticalTexture);
uniforms.radius.setFloat(0.0F);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
} finally {
mainFramebuffer.setFramebufferFilter(previousFilter);
GLSMVertexInput.glBindVertexArray(previousVao);
GLSMPrograms.glUseProgram(previousProgram);
GLSMAttribStack.popStateTo(stateDepth);
mainFramebuffer.bindFramebuffer(true);
}
}
/** Replaces one of the two vanilla GUI background gradient colors while the blur is showing. */
public static int getBackgroundColor(int vanillaColor, String configuredColor) {
if (!blurring) return vanillaColor;
final int color;
try {
color = Integer.parseUnsignedInt(configuredColor, 16);
} catch (NumberFormatException e) {
return vanillaColor;
}
final float progress = getProgress();
final int alpha = (int) ((color >>> 24) * progress);
final int red = (int) ((color >> 16 & 0xFF) * progress);
final int green = (int) ((color >> 8 & 0xFF) * progress);
final int blue = (int) ((color & 0xFF) * progress);
return alpha << 24 | red << 16 | green << 8 | blue;
}
private static boolean shouldBlur() {
return AngelicaConfig.enableMenuBlur
&& mc.theWorld != null
&& mc.currentScreen != null
&& !ArrayUtils.contains(AngelicaConfig.menuBlurExcludedGuis, mc.currentScreen.getClass().getName());
}
private static float getProgress() {
if (AngelicaConfig.menuBlurFadeTime <= 0) return 1.0F;
return Math.min((System.currentTimeMillis() - fadeStartMillis) / (float) AngelicaConfig.menuBlurFadeTime, 1.0F);
}
private static void init() {
blurProgram = PanoramaRenderer.loadProgram("angelica:menu_blur", "angelica:panorama_blur", "angelica:panorama_blur", BlurUniforms::new);
allState = StateSet.forMask(GL11.GL_ALL_ATTRIB_BITS);
emptyVao = GLSMVertexInput.glGenVertexArrays();
}
private static void ensureBlurTargets(int width, int height) {
if (horizontalFbo != 0 && width == sourceWidth && height == sourceHeight) return;
if (horizontalFbo != 0) {
GLSMFramebuffer.glDeleteFramebuffers(horizontalFbo);
GLSMFramebuffer.glDeleteFramebuffers(verticalFbo);
GLSMTextures.glDeleteTextures(horizontalTexture);
GLSMTextures.glDeleteTextures(verticalTexture);
}
sourceWidth = width;
sourceHeight = height;
halfWidth = Math.max((width + 1) / 2, 1);
halfHeight = Math.max((height + 1) / 2, 1);
horizontalTexture = createTexture(halfWidth, halfHeight);
horizontalFbo = createFramebuffer(horizontalTexture);
verticalTexture = createTexture(halfWidth, halfHeight);
verticalFbo = createFramebuffer(verticalTexture);
}
private static int createTexture(int width, int height) {
final int texture = GLSMTextures.glGenTextures();
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, 0);
return texture;
}
private static int createFramebuffer(int colorTexture) {
final int fbo = GLSMFramebuffer.glGenFramebuffers();
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
GLSMFramebuffer.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, colorTexture, 0);
final int status = GLSMFramebuffer.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER);
if (status != GL30.GL_FRAMEBUFFER_COMPLETE) {
throw new RuntimeException("Menu blur FBO incomplete: 0x" + Integer.toHexString(status));
}
return fbo;
}
private static class BlurUniforms {
final GlUniformFloat2v direction;
final GlUniformFloat radius;
BlurUniforms(ShaderBindingContext ctx) {
direction = ctx.bindUniform("u_Direction", GlUniformFloat2v::new);
radius = ctx.bindUniform("u_Radius", GlUniformFloat::new);
}
}
}
@@ -1,45 +0,0 @@
package com.gtnewhorizons.angelica.common;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.function.Supplier;
public class BlockTesrTranslucentTest extends Block {
private final Supplier<TileEntity> tile;
public BlockTesrTranslucentTest(Supplier<TileEntity> tile) {
super(Material.glass);
this.tile = tile;
setHardness(0.3f);
setLightOpacity(0);
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public int getRenderType() {
return -1;
}
@Override
public boolean hasTileEntity(int metadata) {
return true;
}
@Override
public TileEntity createTileEntity(World world, int metadata) {
return tile.get();
}
}
@@ -1,30 +0,0 @@
package com.gtnewhorizons.angelica.common;
import net.minecraft.tileentity.TileEntity;
public abstract class TileTesrTranslucentTest extends TileEntity {
private static final int SOLID_PASS = 8;
public int variant() {
return getBlockMetadata() & ~SOLID_PASS;
}
@Override
public boolean shouldRenderInPass(int pass) {
return pass == ((getBlockMetadata() & SOLID_PASS) != 0 ? 0 : 1);
}
@Override
public boolean canUpdate() {
return false;
}
public static class Provider extends TileTesrTranslucentTest {}
public static class Model extends TileTesrTranslucentTest {}
public static class Decal extends TileTesrTranslucentTest {}
public static class Glow extends TileTesrTranslucentTest {}
}
@@ -177,11 +177,6 @@ public class AngelicaConfig {
@Config.RequiresMcRestart @Config.RequiresMcRestart
public static String[] entityShadowReplayExcludedClasses; public static String[] entityShadowReplayExcludedClasses;
@Config.Comment("Tile entity or renderer classes whose glows Fancy translucency records as they draw instead of rendering the tile entity a second time. For renderers that advance an animation or other state on each render.")
@Config.DefaultStringList({})
@Config.RequiresMcRestart
public static String[] glowDepthReplayExcludedClasses;
@Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.") @Config.Comment("Skip the end-of-frame shader buffer copy by ping-ponging buffers. Disable if a shader pack misrenders.")
@Config.DefaultBoolean(true) @Config.DefaultBoolean(true)
@Config.RequiresMcRestart @Config.RequiresMcRestart
@@ -296,32 +291,6 @@ public class AngelicaConfig {
@Config.RequiresMcRestart @Config.RequiresMcRestart
public static boolean enableZoom; public static boolean enableZoom;
@Config.Comment("Blur the world behind open GUIs.")
@Config.DefaultBoolean(false)
public static boolean enableMenuBlur;
@Config.Comment("How strong the menu blur is, in pixels.")
@Config.DefaultInt(12)
@Config.RangeInt(min = 1, max = 100)
public static int menuBlurRadius;
@Config.Comment("How long the menu blur takes to fade in, in milliseconds.")
@Config.DefaultInt(200)
@Config.RangeInt(min = 0, max = 2000)
public static int menuBlurFadeTime;
@Config.Comment("GUI classes that never get the menu blur.")
@Config.DefaultStringList({"net.minecraft.client.gui.GuiChat", "net.coderbot.iris.gui.screen.ShaderPackScreen"})
public static String[] menuBlurExcludedGuis;
@Config.Comment("Top color of the GUI background gradient while the menu blur is showing, as ARGB hex.")
@Config.DefaultString("75000000")
public static String menuBlurGradientTopColor;
@Config.Comment("Bottom color of the GUI background gradient while the menu blur is showing, as ARGB hex.")
@Config.DefaultString("75000000")
public static String menuBlurGradientBottomColor;
@Config.Comment("Optimizes in-world item rendering") @Config.Comment("Optimizes in-world item rendering")
@Config.DefaultBoolean(true) @Config.DefaultBoolean(true)
@Config.RequiresMcRestart @Config.RequiresMcRestart
@@ -22,7 +22,7 @@ public final class AngelicaEntries {
} }
public static void dynamicLights(DebugScreenDisplayer displayer, DebugContext context) { public static void dynamicLights(DebugScreenDisplayer displayer, DebugContext context) {
if (!DynamicLights.configEnabled || !DynamicLights.isEnabled()) return; if (!DynamicLights.configEnabled || !DynamicLights.isActive()) return;
final DynamicLights lights = DynamicLights.get(); final DynamicLights lights = DynamicLights.get();
final DebugFact fact = displayer.fact(DebugGroup.ANGELICA, "Dynamic Lights"); final DebugFact fact = displayer.fact(DebugGroup.ANGELICA, "Dynamic Lights");
fact.value(lights.getLightSourcesCount()).text(" sources, ").value(lights.getLastUpdateCount()).text(" updated"); fact.value(lights.getLightSourcesCount()).text(" sources, ").value(lights.getLastUpdateCount()).text(" updated");
@@ -40,6 +40,7 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
public class DynamicLights { public class DynamicLights {
@@ -53,18 +54,50 @@ public class DynamicLights {
public static final boolean configEnabled = AngelicaConfig.enableDynamicLights; public static final boolean configEnabled = AngelicaConfig.enableDynamicLights;
private static final double MAX_RADIUS = 7.75; private static final double MAX_RADIUS = 7.75;
private static final double MAX_RADIUS_SQUARED = MAX_RADIUS * MAX_RADIUS;
private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>(); private final Set<IDynamicLightSource> dynamicLightSources = new ObjectOpenHashSet<>();
private IDynamicLightSource[] lightSourceArray = new IDynamicLightSource[0]; private static final IDynamicLightSource[] NO_SOURCES = new IDynamicLightSource[0];
private IDynamicLightSource[] lightSourceArray = NO_SOURCES;
// The sources that light things under a shaderpack without shader force, see isActive
private IDynamicLightSource[] shaderpackSourceArray = NO_SOURCES;
private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock lightSourcesLock = new ReentrantReadWriteLock();
private volatile int lightSourceCount = 0; private volatile int lightSourceCount = 0;
private volatile int shaderpackSourceCount = 0;
private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager(); private final ChunkRebuildManager chunkRebuildManager = new ChunkRebuildManager();
private long lastUpdate = System.currentTimeMillis(); private long lastUpdate = System.currentTimeMillis();
private int lastUpdateCount = 0; private int lastUpdateCount = 0;
// Which sources gave light at the last update: 0 none, 1 the ones lit under shaderpacks, 2 all of them
private int litState = -1;
/** Must be called under write lock. */ /** Must be called under write lock. */
private void rebuildLightSourceArray() { private void rebuildLightSourceArray() {
this.lightSourceArray = this.dynamicLightSources.toArray(new IDynamicLightSource[0]); this.lightSourceArray = this.dynamicLightSources.toArray(NO_SOURCES);
int count = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) count++;
}
final IDynamicLightSource[] shaderpackSources = new IDynamicLightSource[count];
int i = 0;
for (IDynamicLightSource source : this.lightSourceArray) {
if (source.angelica$isLitUnderShaderpacks()) shaderpackSources[i++] = source;
}
this.shaderpackSourceArray = shaderpackSources;
this.shaderpackSourceCount = count;
}
/** The sources that give light right now. Call under the read lock. */
private IDynamicLightSource[] activeSources() {
if (isEnabled()) return this.lightSourceArray;
return configEnabled && Mode.isEnabled() ? this.shaderpackSourceArray : NO_SOURCES;
}
/** A tracked source changed whether it's lit under shaderpacks. */
public void onShaderpackLitChanged(IDynamicLightSource lightSource) {
this.lightSourcesLock.writeLock().lock();
try {
if (this.dynamicLightSources.contains(lightSource)) rebuildLightSourceArray();
} finally {
this.lightSourcesLock.writeLock().unlock();
}
} }
public static DynamicLights get() { public static DynamicLights get() {
@@ -81,6 +114,22 @@ public class DynamicLights {
(ShaderForce || !IrisApi.getInstance().isShaderPackInUse()); (ShaderForce || !IrisApi.getInstance().isShaderPackInUse());
} }
/**
* True when a light that's lit under shaderpacks (or not, see {@link IDynamicLightSource#angelica$isLitUnderShaderpacks})
* gives light right now. Those only skip the shaderpack check, dynamic lights turned off still means off.
*/
public static boolean isEnabled(boolean litUnderShaderpacks) {
return isEnabled() || litUnderShaderpacks && configEnabled && Mode.isEnabled();
}
/**
* True when any light gives light right now: all of them ({@link #isEnabled()}), or only the ones lit under
* shaderpacks when a pack turned the rest off. What the light pipeline checks before it does any dynamic light work.
*/
public static boolean isActive() {
return isEnabled() || configEnabled && Mode.isEnabled() && get().shaderpackSourceCount > 0;
}
public boolean hasLightSources() { public boolean hasLightSources() {
return lightSourceCount > 0; return lightSourceCount > 0;
} }
@@ -99,7 +148,13 @@ public class DynamicLights {
* @param renderer the renderer * @param renderer the renderer
*/ */
public void updateAll(@NotNull IDynamicLightWorldRenderer renderer) { public void updateAll(@NotNull IDynamicLightWorldRenderer renderer) {
if (!isEnabled()) final int state = isEnabled() ? 2 : configEnabled && Mode.isEnabled() ? 1 : 0;
if (state != this.litState) {
if (this.litState != -1) relightAll(renderer);
this.litState = state;
}
if (!isActive())
return; return;
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
@@ -129,7 +184,7 @@ public class DynamicLights {
} }
this.lightSourcesLock.readLock().lock(); this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) { for (var lightSource : activeSources()) {
// Entity type filter // Entity type filter
if (!EntityLightConfig.isEntityTypeEnabled(lightSource)) { if (!EntityLightConfig.isEntityTypeEnabled(lightSource)) {
continue; continue;
@@ -151,6 +206,23 @@ public class DynamicLights {
} }
} }
/**
* The player switched dynamic lights, shader force or the shaderpack, so which sources give light changed. The
* sections they lit rebuild, and every source starts over on its next update. Without this a light that went dark
* stays in the terrain until something else rebuilds it, and one that sits still never comes back.
*/
private void relightAll(@NotNull IDynamicLightWorldRenderer renderer) {
this.lightSourcesLock.readLock().lock();
try {
for (IDynamicLightSource source : this.lightSourceArray) {
source.angelica$scheduleTrackedChunksRebuild(renderer);
source.angelica$resetDynamicLight();
}
} finally {
this.lightSourcesLock.readLock().unlock();
}
}
public int getLastUpdateCount() { public int getLastUpdateCount() {
return this.lastUpdateCount; return this.lastUpdateCount;
} }
@@ -245,7 +317,7 @@ public class DynamicLights {
} }
} }
this.lightSourceCount = 0; this.lightSourceCount = 0;
this.lightSourceArray = new IDynamicLightSource[0]; rebuildLightSourceArray();
this.lightSourcesLock.writeLock().unlock(); this.lightSourcesLock.writeLock().unlock();
} }
@@ -282,7 +354,7 @@ public class DynamicLights {
public double getDynamicLightLevel(int x, int y, int z) { public double getDynamicLightLevel(int x, int y, int z) {
double result = 0; double result = 0;
this.lightSourcesLock.readLock().lock(); this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) { for (var lightSource : activeSources()) {
result = maxDynamicLightLevel(x, y, z, lightSource, result); result = maxDynamicLightLevel(x, y, z, lightSource, result);
} }
this.lightSourcesLock.readLock().unlock(); this.lightSourcesLock.readLock().unlock();
@@ -296,7 +368,7 @@ public class DynamicLights {
public double getDynamicLightLevel(double x, double y, double z) { public double getDynamicLightLevel(double x, double y, double z) {
double result = 0; double result = 0;
this.lightSourcesLock.readLock().lock(); this.lightSourcesLock.readLock().lock();
for (var lightSource : this.lightSourceArray) { for (var lightSource : activeSources()) {
result = maxDynamicLightLevelExact(x, y, z, lightSource, result); result = maxDynamicLightLevelExact(x, y, z, lightSource, result);
} }
this.lightSourcesLock.readLock().unlock(); this.lightSourcesLock.readLock().unlock();
@@ -317,14 +389,11 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ() + 0.5; final double dz = z - lightSource.angelica$getDynamicLightZ() + 0.5;
final double distanceSquared = dx * dx + dy * dy + dz * dz; final double distanceSquared = dx * dx + dy * dy + dz * dz;
// 7.75 because else we would have to update more chunks and that's not a good idea. // Held torch reach is 7.75 because else we would have to update more chunks and that's not a good idea.
// 15 (max range for blocks) would be too much and a bit cheaty. // Lights that ask for more get it (see angelica$getReach), and rebuild more chunks for it.
if (distanceSquared <= MAX_RADIUS_SQUARED) { final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS; if (lightLevel > currentLightLevel) {
final double lightLevel = multiplier * (double) luminance; return lightLevel;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
} }
} }
return currentLightLevel; return currentLightLevel;
@@ -342,12 +411,9 @@ public class DynamicLights {
final double dz = z - lightSource.angelica$getDynamicLightZ(); final double dz = z - lightSource.angelica$getDynamicLightZ();
final double distanceSquared = dx * dx + dy * dy + dz * dz; final double distanceSquared = dx * dx + dy * dy + dz * dz;
if (distanceSquared <= MAX_RADIUS_SQUARED) { final double lightLevel = levelAt(lightSource, luminance, distanceSquared);
final double multiplier = 1.0 - Math.sqrt(distanceSquared) / MAX_RADIUS; if (lightLevel > currentLightLevel) {
final double lightLevel = multiplier * (double) luminance; return lightLevel;
if (lightLevel > currentLightLevel) {
return lightLevel;
}
} }
} }
return currentLightLevel; return currentLightLevel;
@@ -370,7 +436,7 @@ public class DynamicLights {
} }
public static int addDynamicLight(IBlockAccess world, int x, int y, int z, int lightmap) { public static int addDynamicLight(IBlockAccess world, int x, int y, int z, int lightmap) {
if (!isEnabled()) return lightmap; if (!isActive()) return lightmap;
final DynamicLights dl = get(); final DynamicLights dl = get();
if (!dl.hasLightSources()) return lightmap; if (!dl.hasLightSources()) return lightmap;
final double dynamicLightLevel = dl.getDynamicLightLevel(x, y, z); final double dynamicLightLevel = dl.getDynamicLightLevel(x, y, z);
@@ -378,27 +444,81 @@ public class DynamicLights {
return lightmap; return lightmap;
} }
/**
* Calls the consumer for every lit light source within radius of the point. Runs on a snapshot of the sources, so
* the consumer may add or remove lights.
*/
public void forEachSourceNear(double x, double y, double z, double radius, Consumer<IDynamicLightSource> consumer) {
final IDynamicLightSource[] sources;
this.lightSourcesLock.readLock().lock();
try {
sources = activeSources();
} finally {
this.lightSourcesLock.readLock().unlock();
}
final double radiusSq = radius * radius;
for (IDynamicLightSource source : sources) {
if (source.angelica$getLuminance() <= 0) continue;
final double dx = source.angelica$getDynamicLightX() - x;
final double dy = source.angelica$getDynamicLightY() - y;
final double dz = source.angelica$getDynamicLightZ() - z;
if (dx * dx + dy * dy + dz * dz <= radiusSq) consumer.accept(source);
}
}
/** Light level of a source of this luminance at this distance, with the held torch reach. */
public static double falloff(int luminance, double distance) {
return falloff(luminance, -1, distance);
}
/**
* Light level of a source of this luminance and reach (see {@link IDynamicLightSource#angelica$getReach}) at this
* distance.
*/
public static double falloff(int luminance, float reach, double distance) {
if (luminance <= 0 || reach == 0) return 0;
// Held torch: straight down to 0 at 7.75 blocks, whatever the luminance
if (reach < 0) return distance > MAX_RADIUS ? 0 : (1.0 - distance / MAX_RADIUS) * luminance;
// Like block light: down 15 / reach levels a block, so 15 is vanilla
return Math.max(0, luminance - distance * 15.0 / reach);
}
/** How far the source's light gets at its current luminance, 0 when it's dark. */
public static double reachOf(@NotNull IDynamicLightSource source) {
final int luminance = source.angelica$getLuminance();
if (luminance <= 0) return 0;
final float reach = source.angelica$getReach();
return reach < 0 ? MAX_RADIUS : reach * luminance / 15.0;
}
private static double levelAt(@NotNull IDynamicLightSource source, int luminance, double distanceSquared) {
final double reach = reachOf(source);
if (distanceSquared >= reach * reach) return 0;
return falloff(luminance, source.angelica$getReach(), Math.sqrt(distanceSquared));
}
public List<IDynamicLightSource> getSourcesForChunk(int chunkMinX, int chunkMinY, int chunkMinZ) { public List<IDynamicLightSource> getSourcesForChunk(int chunkMinX, int chunkMinY, int chunkMinZ) {
// Chunk center // Chunk center
final double centerX = chunkMinX + 8.0; final double centerX = chunkMinX + 8.0;
final double centerY = chunkMinY + 8.0; final double centerY = chunkMinY + 8.0;
final double centerZ = chunkMinZ + 8.0; final double centerZ = chunkMinZ + 8.0;
// Max distance from chunk center to any corner is sqrt(3) * 8 ≈ 13.86 // Smooth lighting reads the cells a block outside the section too, and the middle of the furthest of those is
// Add MAX_RADIUS to get the search radius (13.86 + 7.75)^2 ≈ 467 // sqrt(3) * 8.5 ≈ 14.72 from the chunk center. Plus the source's reach (7.75 for a held torch), slightly padded
final double searchRadiusSq = 470.0; // Slightly padded for safety // for safety
List<IDynamicLightSource> result = null; List<IDynamicLightSource> result = null;
this.lightSourcesLock.readLock().lock(); this.lightSourcesLock.readLock().lock();
try { try {
for (var source : this.lightSourceArray) { for (var source : activeSources()) {
final double dx = source.angelica$getDynamicLightX() - centerX; final double dx = source.angelica$getDynamicLightX() - centerX;
final double dy = source.angelica$getDynamicLightY() - centerY; final double dy = source.angelica$getDynamicLightY() - centerY;
final double dz = source.angelica$getDynamicLightZ() - centerZ; final double dz = source.angelica$getDynamicLightZ() - centerZ;
final double distSq = dx * dx + dy * dy + dz * dz; final double distSq = dx * dx + dy * dy + dz * dz;
final double searchRadius = 14.8 + reachOf(source);
if (distSq <= searchRadiusSq) { if (distSq <= searchRadius * searchRadius) {
if (result == null) { if (result == null) {
result = new ArrayList<>(); result = new ArrayList<>();
} }
@@ -416,7 +536,7 @@ public class DynamicLights {
int accum = 0; int accum = 0;
this.lightSourcesLock.readLock().lock(); this.lightSourcesLock.readLock().lock();
try { try {
for (var lightSource : this.lightSourceArray) { for (var lightSource : activeSources()) {
accum = accumulateSourceRGB(x, y, z, lightSource, accum); accum = accumulateSourceRGB(x, y, z, lightSource, accum);
} }
} finally { } finally {
@@ -446,9 +566,8 @@ public class DynamicLights {
final double dz = z - source.angelica$getDynamicLightZ(); final double dz = z - source.angelica$getDynamicLightZ();
final double distSq = dx * dx + dy * dy + dz * dz; final double distSq = dx * dx + dy * dy + dz * dz;
if (distSq > MAX_RADIUS_SQUARED) return accum; final double multiplier = levelAt(source, luminance, distSq) / luminance;
if (multiplier <= 0) return accum;
final double multiplier = 1.0 - Math.sqrt(distSq) / MAX_RADIUS;
final int r = (int) (BlockLightProvider.unpackR(rgb) * multiplier); final int r = (int) (BlockLightProvider.unpackR(rgb) * multiplier);
final int g = (int) (BlockLightProvider.unpackG(rgb) * multiplier); final int g = (int) (BlockLightProvider.unpackG(rgb) * multiplier);
final int b = (int) (BlockLightProvider.unpackB(rgb) * multiplier); final int b = (int) (BlockLightProvider.unpackB(rgb) * multiplier);
@@ -44,6 +44,24 @@ public interface IDynamicLightSource {
return DynamicLights.isEnabled() && DynamicLights.get().containsLightSource(this); return DynamicLights.isEnabled() && DynamicLights.get().containsLightSource(this);
} }
/**
* Whether this gives light under a shaderpack without the player's shader force option, for lights that stand in
* for real blocks a pack has no other way to light. False for entities and held items, the pack does those.
*/
default boolean angelica$isLitUnderShaderpacks() {
return false;
}
/**
* How far a luminance 15 light of this source gets, 0-15, falling 15 / reach levels a block like block light (15
* is vanilla). -1 for Angelica's held torch falloff, straight down to 0 at 7.75 blocks. The source has to track and
* rebuild every chunk section its light gets into (plus a block, smooth lighting reads the cells next to a face),
* see {@link DynamicLights#reachOf}.
*/
default float angelica$getReach() {
return -1;
}
/** /**
* Sets whether the dynamic light is enabled or not. * Sets whether the dynamic light is enabled or not.
* <p> * <p>
@@ -0,0 +1,202 @@
package com.gtnewhorizons.angelica.dynamiclights;
import com.gtnewhorizon.gtnhlib.blockpos.BlockPos;
import com.gtnewhorizon.gtnhlib.blockpos.IBlockPos;
import com.gtnewhorizons.angelica.api.dynamiclights.PositionalLight;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import net.minecraft.util.MathHelper;
import org.jetbrains.annotations.NotNull;
/**
* {@link PositionalLight} for mods. Tracks chunks like entity lights do (see MixinEntity), but only the sections its
* light gets into, worked out from its reach: 8 or fewer up to reach 7, mostly 8 for a held torch, up to 27 for a long
* one. Plus the ones it left.
*/
public final class PositionalLightSource implements IDynamicLightSource, PositionalLight {
private volatile double x, y, z;
private volatile int luminance;
private volatile boolean litUnderShaderpacks;
private volatile float reach = TORCH_REACH;
private boolean removed;
private int lastLuminance;
private float lastReach = TORCH_REACH;
private double prevX, prevY, prevZ;
private LongOpenHashSet tracked = new LongOpenHashSet();
private LongOpenHashSet prevTracked = new LongOpenHashSet();
@Override
public void setPosition(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
// Also adds it back after a world unload drops Angelica's lights
syncTracking();
}
@Override
public void setLuminance(int luminance) {
if (removed) return;
this.luminance = Math.max(0, Math.min(15, luminance));
syncTracking();
}
@Override
public double getX() {
return x;
}
@Override
public double getY() {
return y;
}
@Override
public double getZ() {
return z;
}
@Override
public int getLuminance() {
return luminance;
}
@Override
public void setLitUnderShaderpacks(boolean lit) {
if (litUnderShaderpacks == lit) return;
litUnderShaderpacks = lit;
DynamicLights.get().onShaderpackLitChanged(this);
// It may have just gone dark (or lit) under a pack. Redo its chunks either way, the next update puts the light
// back in where it still counts
angelica$resetDynamicLight();
final IDynamicLightWorldRenderer renderer = DynamicLights.getActiveRenderer();
if (renderer != null) angelica$scheduleTrackedChunksRebuild(renderer);
}
@Override
public void setReach(float reach) {
// Anything under 0 (or NaN) is the held torch
this.reach = reach >= 0 ? Math.min(15, reach) : TORCH_REACH;
}
@Override
public float getReach() {
return reach;
}
@Override
public float angelica$getReach() {
return reach;
}
@Override
public boolean isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public boolean angelica$isLitUnderShaderpacks() {
return litUnderShaderpacks;
}
@Override
public void remove() {
if (removed) return;
removed = true;
luminance = 0;
syncTracking();
}
// In Angelica's lights while lit and out of them otherwise, dynamic lights on or not. DynamicLights.updateTracking
// only removes while they're on, and re-adds on every call while they're off
private void syncTracking() {
final DynamicLights lights = DynamicLights.get();
final boolean lit = luminance > 0;
if (lit == lights.containsLightSource(this)) return;
angelica$resetDynamicLight();
if (lit) lights.addLightSource(this);
else lights.removeLightSource(this);
}
@Override
public double angelica$getDynamicLightX() {
return x;
}
@Override
public double angelica$getDynamicLightY() {
return y;
}
@Override
public double angelica$getDynamicLightZ() {
return z;
}
@Override
public void angelica$resetDynamicLight() {
lastLuminance = 0;
}
@Override
public int angelica$getLuminance() {
return luminance;
}
@Override
public void angelica$dynamicLightTick() {}
@Override
public boolean angelica$updateDynamicLight(@NotNull IDynamicLightWorldRenderer renderer) {
final double x = this.x, y = this.y, z = this.z;
final int luminance = this.luminance;
final float reach = this.reach;
// Small changes in reach count like small moves, a structure being scaled changes it every frame
if (Math.abs(x - prevX) <= 0.1 && Math.abs(y - prevY) <= 0.1 && Math.abs(z - prevZ) <= 0.1
&& luminance == lastLuminance && Math.abs(reach - lastReach) <= 0.1) {
return false;
}
prevX = x;
prevY = y;
prevZ = z;
lastLuminance = luminance;
lastReach = reach;
final LongOpenHashSet newTracked = prevTracked;
newTracked.clear();
// Every section the light gets into, plus a block: smooth lighting on a face reads the cells in front of it,
// which can be in the next section. Reach is at most 15, so never past the sections right next to this one
final double far = DynamicLights.reachOf(this) + 1;
if (far > 1) {
final int cx = MathHelper.floor_double(x) >> 4, cy = MathHelper.floor_double(y) >> 4,
cz = MathHelper.floor_double(z) >> 4;
final int x0 = x - (cx << 4) < far ? -1 : 0, x1 = ((cx + 1) << 4) - x < far ? 1 : 0;
final int y0 = y - (cy << 4) < far ? -1 : 0, y1 = ((cy + 1) << 4) - y < far ? 1 : 0;
final int z0 = z - (cz << 4) < far ? -1 : 0, z1 = ((cz + 1) << 4) - z < far ? 1 : 0;
for (int dx = x0; dx <= x1; dx++) {
for (int dy = y0; dy <= y1; dy++) {
for (int dz = z0; dz <= z1; dz++) track(renderer, new BlockPos(cx + dx, cy + dy, cz + dz), newTracked);
}
}
}
// Whatever's left in the old set is out of range now
angelica$scheduleTrackedChunksRebuild(renderer);
prevTracked = tracked;
tracked = newTracked;
return true;
}
private void track(IDynamicLightWorldRenderer renderer, IBlockPos chunk, LongOpenHashSet newTracked) {
DynamicLights.scheduleChunkRebuild(renderer, chunk);
DynamicLights.updateTrackedChunks(chunk, tracked, newTracked);
}
@Override
public void angelica$scheduleTrackedChunksRebuild(@NotNull IDynamicLightWorldRenderer renderer) {
final LongIterator it = tracked.iterator();
while (it.hasNext()) DynamicLights.scheduleChunkRebuildForRemoval(renderer, it.nextLong());
}
}
@@ -265,15 +265,6 @@ public class DarkModeFontTransform {
new MethodInfo("chylex.hee.gui.GuiTransportBeacon func_73863_a(IIF)V # drawScreen"), new MethodInfo("chylex.hee.gui.GuiTransportBeacon func_73863_a(IIF)V # drawScreen"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString") new MethodInfo("net.minecraft.client.gui.FontRenderer func_78276_b(Ljava/lang/String;III)I # drawString")
), ),
// NotEnoughItems
RecolorTarget.includeMethodCall(
new MethodInfo("codechicken.nei.recipe.RecipeTooltipLineHandler draw(II)V"),
new MethodInfo("codechicken.lib.gui.GuiDraw drawStringC(Ljava/lang/String;III)V")
),
RecolorTarget.includeMethodCall(
new MethodInfo("codechicken.nei.recipe.widget.RecipeWidget draw(II)V"),
new MethodInfo("codechicken.nei.recipe.IRecipeHandler drawForeground(I)V")
),
//endregion //endregion
//region Exclude Methods //region Exclude Methods
// Applied Energistics 2 // Applied Energistics 2
@@ -292,10 +283,6 @@ public class DarkModeFontTransform {
RecolorTarget.excludeMethodCall( RecolorTarget.excludeMethodCall(
new MethodInfo("gregtech.api.recipe.RecipeMapFrontend drawNEIOverlayText(Ljava/lang/String;Lcodechicken/nei/PositionedStack;IFZLcom/gtnewhorizons/modularui/api/math/Alignment;)V"), new MethodInfo("gregtech.api.recipe.RecipeMapFrontend drawNEIOverlayText(Ljava/lang/String;Lcodechicken/nei/PositionedStack;IFZLcom/gtnewhorizons/modularui/api/math/Alignment;)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString") new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
),
RecolorTarget.excludeMethodCall(
new MethodInfo("gregtech.nei.GTNEIDefaultHandler$FixedPositionedStack draw(II)V"),
new MethodInfo("net.minecraft.client.gui.FontRenderer func_85187_a(Ljava/lang/String;IIIZ)I # drawString")
), ),
// GT NEI Ore Plugin // GT NEI Ore Plugin
RecolorTarget.excludeMethodCall( RecolorTarget.excludeMethodCall(
@@ -418,11 +405,6 @@ public class DarkModeFontTransform {
new MethodInfo("de.eydamos.guiadvanced.form.Button func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"), new MethodInfo("de.eydamos.guiadvanced.form.Button func_146112_a(Lnet/minecraft/client/Minecraft;II)V # drawButton"),
new MethodInfo("de.eydamos.guiadvanced.form.Button func_73732_a(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;III)V # drawCenteredString") new MethodInfo("de.eydamos.guiadvanced.form.Button func_73732_a(Lnet/minecraft/client/gui/FontRenderer;Ljava/lang/String;III)V # drawCenteredString")
), ),
// ServerUtilities
RecolorTarget.includeButtonMethodCall(
new MethodInfo("serverutils.lib.gui.SimpleTextButton draw(Lserverutils/lib/gui/Theme;IIII)V"),
new MethodInfo("serverutils.lib.gui.Theme drawString(Ljava/lang/String;IILserverutils/lib/icon/Color4I;I)I")
),
//endregion //endregion
}; };
@@ -301,15 +301,6 @@ public enum Mixins implements IMixins {
) )
), ),
ANGELICA_GLOW_DEPTH_REPLAY(new MixinBuilder("Drop particles and sounds a block entity renderer starts while Fancy translucency replays it into the glow depth")
.setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableIris)
.addClientMixins(
"angelica.tesr.MixinEffectRenderer_GlowDepthReplay",
"angelica.tesr.MixinSoundHandler_GlowDepthReplay"
)
),
ANGELICA_TESR_PROVIDER_DISPATCH(new MixinBuilder("Route TesrMeshProvider renderers through the batched mesh cache, and observe renderers that mix model parts with their own draws") ANGELICA_TESR_PROVIDER_DISPATCH(new MixinBuilder("Route TesrMeshProvider renderers through the batched mesh cache, and observe renderers that mix model parts with their own draws")
.setPhase(Phase.EARLY) .setPhase(Phase.EARLY)
.setApplyIf(() -> AngelicaConfig.enableTESRProviderDispatch || AngelicaConfig.enableEntityBatching) .setApplyIf(() -> AngelicaConfig.enableTESRProviderDispatch || AngelicaConfig.enableEntityBatching)
@@ -560,8 +551,6 @@ public enum Mixins implements IMixins {
, "shaders.MixinEntityRenderer" , "shaders.MixinEntityRenderer"
, "shaders.MixinGuiIngameForge" , "shaders.MixinGuiIngameForge"
, "shaders.MixinFramebuffer" , "shaders.MixinFramebuffer"
, "angelica.rendering.MixinEntityRenderer_TranslucencyLayers"
, "angelica.rendering.MixinFramebuffer_TranslucencyLayers"
, "shaders.MixinItem" , "shaders.MixinItem"
, "shaders.MixinItemRenderer_ItemId" , "shaders.MixinItemRenderer_ItemId"
, "shaders.MixinLocale" , "shaders.MixinLocale"
@@ -676,14 +665,6 @@ public enum Mixins implements IMixins {
"angelica.zoom.MixinMouseFilter" "angelica.zoom.MixinMouseFilter"
)), )),
ANGELICA_MENU_BLUR(new MixinBuilder("Blur the world behind open GUIs")
.setPhase(Phase.EARLY)
.addExcludedMod(TargetedMod.BLUR)
.addClientMixins(
"angelica.blur.MixinEntityRenderer_MenuBlur",
"angelica.blur.MixinGuiScreen_MenuBlur"
)),
ANGELICA_FPS_REDUCER(new MixinBuilder("Reduce frame rate and volume while unfocused, minimized, or idle") ANGELICA_FPS_REDUCER(new MixinBuilder("Reduce frame rate and volume while unfocused, minimized, or idle")
.setPhase(Phase.EARLY) .setPhase(Phase.EARLY)
.addClientMixins( .addClientMixins(
@@ -9,7 +9,6 @@ public enum TargetedMod implements ITargetMod {
ARCHAICFIX("org.embeddedt.archaicfix.ArchaicCore", "archaicfix"), ARCHAICFIX("org.embeddedt.archaicfix.ArchaicCore", "archaicfix"),
BACKHAND("xonin.backhand.coremod.BackhandLoadingPlugin", "backhand"), BACKHAND("xonin.backhand.coremod.BackhandLoadingPlugin", "backhand"),
BLUR("com.tterrag.blur.BlurPlugin", "blur"),
BOTANIA(null, "Botania"), BOTANIA(null, "Botania"),
CAMPFIRE_BACKPORT(null, "campfirebackport"), CAMPFIRE_BACKPORT(null, "campfirebackport"),
CHISEL(null, "chisel"), CHISEL(null, "chisel"),
@@ -304,7 +304,7 @@ public final class TracyFramePlots {
Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan()); Tracy.plotInt(P_QUEUE_TASKS_RAN, AngelicaRenderQueue.getLastFrameTasksRan());
Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs()); Tracy.plotInt(P_QUEUE_TIME_NS, AngelicaRenderQueue.getLastFrameTimeNs());
if (DynamicLights.isEnabled()) { if (DynamicLights.isActive()) {
final DynamicLights dl = DynamicLights.get(); final DynamicLights dl = DynamicLights.get();
Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount()); Tracy.plotInt(P_DYN_LIGHT_SOURCES, dl.getLightSourcesCount());
Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount()); Tracy.plotInt(P_DYN_UPDATES, dl.getLastUpdateCount());
@@ -40,7 +40,6 @@ import com.gtnewhorizons.angelica.AngelicaMod;
import com.gtnewhorizons.angelica.common.BlockError; import com.gtnewhorizons.angelica.common.BlockError;
import com.gtnewhorizons.angelica.common.BlockIsbrhTest; import com.gtnewhorizons.angelica.common.BlockIsbrhTest;
import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest; import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat; import com.gtnewhorizons.angelica.compat.bettercrashes.BetterCrashesCompat;
import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.AngelicaConfig;
@@ -76,7 +75,6 @@ import com.gtnewhorizons.angelica.rendering.ClipPlaneTestRenderer;
import com.gtnewhorizons.angelica.rendering.FpsReducer; import com.gtnewhorizons.angelica.rendering.FpsReducer;
import com.gtnewhorizons.angelica.rendering.FramePacer; import com.gtnewhorizons.angelica.rendering.FramePacer;
import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer; import com.gtnewhorizons.angelica.rendering.IsbrhTestRenderer;
import com.gtnewhorizons.angelica.rendering.TesrTranslucentTestRenderers;
import com.gtnewhorizons.angelica.rendering.TextureSamplers; import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasSetup;
import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer;
@@ -152,10 +150,6 @@ public final class ClientProxy extends CommonProxy {
BlockIsbrhTest.renderId = RenderingRegistry.getNextAvailableRenderId(); BlockIsbrhTest.renderId = RenderingRegistry.getNextAvailableRenderId();
RenderingRegistry.registerBlockHandler(BlockIsbrhTest.renderId, new IsbrhTestRenderer()); RenderingRegistry.registerBlockHandler(BlockIsbrhTest.renderId, new IsbrhTestRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityClipPlaneTest.class, new ClipPlaneTestRenderer()); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityClipPlaneTest.class, new ClipPlaneTestRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Provider.class, new TesrTranslucentTestRenderers.Provider());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Model.class, new TesrTranslucentTestRenderers.Model());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Decal.class, new TesrTranslucentTestRenderers.Decal());
ClientRegistry.bindTileEntitySpecialRenderer(TileTesrTranslucentTest.Glow.class, new TesrTranslucentTestRenderers.Glow());
} }
AngelicaJar.configureShaderDiskCache(event.getSourceFile()); AngelicaJar.configureShaderDiskCache(event.getSourceFile());
if (AngelicaConfig.enableIris) { if (AngelicaConfig.enableIris) {
@@ -2,18 +2,13 @@ package com.gtnewhorizons.angelica.proxy;
import com.gtnewhorizons.angelica.common.BlockClipPlaneTest; import com.gtnewhorizons.angelica.common.BlockClipPlaneTest;
import com.gtnewhorizons.angelica.common.BlockIsbrhTest; import com.gtnewhorizons.angelica.common.BlockIsbrhTest;
import com.gtnewhorizons.angelica.common.BlockTesrTranslucentTest;
import com.gtnewhorizons.angelica.common.BlockTest; import com.gtnewhorizons.angelica.common.BlockTest;
import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest; import com.gtnewhorizons.angelica.common.TileEntityClipPlaneTest;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.AngelicaConfig;
import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.tileentity.TileEntity;
import java.util.function.Supplier;
public class CommonProxy { public class CommonProxy {
@@ -23,18 +18,9 @@ public class CommonProxy {
GameRegistry.registerBlock(new BlockIsbrhTest(), "test_isbrh"); GameRegistry.registerBlock(new BlockIsbrhTest(), "test_isbrh");
GameRegistry.registerBlock(new BlockClipPlaneTest(), "test_clip_plane"); GameRegistry.registerBlock(new BlockClipPlaneTest(), "test_clip_plane");
GameRegistry.registerTileEntity(TileEntityClipPlaneTest.class, "angelica:test_clip_plane"); GameRegistry.registerTileEntity(TileEntityClipPlaneTest.class, "angelica:test_clip_plane");
registerTesrTest("test_tesr_provider", TileTesrTranslucentTest.Provider.class, TileTesrTranslucentTest.Provider::new);
registerTesrTest("test_tesr_model", TileTesrTranslucentTest.Model.class, TileTesrTranslucentTest.Model::new);
registerTesrTest("test_tesr_decal", TileTesrTranslucentTest.Decal.class, TileTesrTranslucentTest.Decal::new);
registerTesrTest("test_tesr_glow", TileTesrTranslucentTest.Glow.class, TileTesrTranslucentTest.Glow::new);
} }
} }
private static void registerTesrTest(String name, Class<? extends TileEntity> tile, Supplier<TileEntity> factory) {
GameRegistry.registerBlock(new BlockTesrTranslucentTest(factory), name);
GameRegistry.registerTileEntity(tile, "angelica:" + name);
}
public void init(FMLInitializationEvent event) {} public void init(FMLInitializationEvent event) {}
public void postInit(FMLPostInitializationEvent event) {} public void postInit(FMLPostInitializationEvent event) {}
@@ -103,12 +103,8 @@ public class PanoramaRenderer {
} }
public static <T> GlProgram<T> loadProgram(String name, String vertBase, String fragBase, Function<ShaderBindingContext, T> factory) { public static <T> GlProgram<T> loadProgram(String name, String vertBase, String fragBase, Function<ShaderBindingContext, T> factory) {
return loadProgram(name, vertBase, fragBase, ShaderConstants.EMPTY, factory);
}
public static <T> GlProgram<T> loadProgram(String name, String vertBase, String fragBase, ShaderConstants fragConstants, Function<ShaderBindingContext, T> factory) {
final GlShader vert = ShaderLoader.loadShader(ShaderType.VERTEX, vertBase + ".vert", ShaderConstants.EMPTY); final GlShader vert = ShaderLoader.loadShader(ShaderType.VERTEX, vertBase + ".vert", ShaderConstants.EMPTY);
final GlShader frag = ShaderLoader.loadShader(ShaderType.FRAGMENT, fragBase + ".frag", fragConstants); final GlShader frag = ShaderLoader.loadShader(ShaderType.FRAGMENT, fragBase + ".frag", ShaderConstants.EMPTY);
try { try {
final GlProgram<T> program = GlProgram.builder(name).attachShader(vert).attachShader(frag).link(factory); final GlProgram<T> program = GlProgram.builder(name).attachShader(vert).attachShader(frag).link(factory);
program.bind(); program.bind();
@@ -15,6 +15,15 @@ public interface StateAwareTessellator {
void angelica$setAppliedAo(boolean flag); void angelica$setAppliedAo(boolean flag);
void angelica$setNoDirectionalShading(boolean flag); void angelica$setNoDirectionalShading(boolean flag);
/// The state the next vertex gets. False for tessellators that don't track it.
default boolean angelica$isAppliedAo() {
return false;
}
default boolean angelica$isNoDirectionalShading() {
return false;
}
/// Sets whether we're doing terrain meshing as part of celeritas -- collects additional information. /// Sets whether we're doing terrain meshing as part of celeritas -- collects additional information.
/// ///
/// Enables per-vertex AO state collection into [#angelica$getVertexStates()]. /// Enables per-vertex AO state collection into [#angelica$getVertexStates()].
@@ -1,215 +0,0 @@
package com.gtnewhorizons.angelica.rendering;
import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshProvider;
import com.gtnewhorizons.angelica.api.tesr.TesrMeshSink;
import com.gtnewhorizons.angelica.common.TileTesrTranslucentTest;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMEnable;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.utils.WorkaroundUtils;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import org.lwjgl.opengl.GL11;
public final class TesrTranslucentTestRenderers {
private static final double HALF = 0.4375;
private TesrTranslucentTestRenderers() {}
private static void pane(Tessellator t, double half) {
rect(t, -half, -half, half, half);
}
private static void rect(Tessellator t, double x0, double y0, double x1, double y1) {
t.setNormal(0f, 0f, -1f);
t.addVertexWithUV(0.5 + x0, 0.5 + y0, 0.5, 0, 1);
t.addVertexWithUV(0.5 + x0, 0.5 + y1, 0.5, 0, 0);
t.addVertexWithUV(0.5 + x1, 0.5 + y1, 0.5, 1, 0);
t.addVertexWithUV(0.5 + x1, 0.5 + y0, 0.5, 1, 1);
}
private static void drawPane(double half) {
final Tessellator t = Tessellator.instance;
t.startDrawingQuads();
pane(t, half);
t.draw();
}
private static void apply(TesrMaterial material) {
if (material.transparency() == TesrMaterial.Transparency.ADDITIVE) {
GLSMBlend.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
} else {
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
}
GLSMCurrentAttribs.glColor4f(material.colorRed(), material.colorGreen(), material.colorBlue(), material.colorAlpha());
}
private abstract static class PaneRenderer extends TileEntitySpecialRenderer {
void begin(double x, double y, double z) {
bindTexture(WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND);
GLSMMatrices.glPushMatrix();
GLSMMatrices.glTranslated(x, y, z);
GLSMEnable.glDisable(GL11.GL_CULL_FACE);
GLSMEnable.glEnable(GL11.GL_BLEND);
}
static void end() {
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GLSMEnable.glDisable(GL11.GL_BLEND);
GLSMEnable.glEnable(GL11.GL_CULL_FACE);
GLSMMatrices.glPopMatrix();
}
}
public static final class Provider extends PaneRenderer implements TesrMeshProvider {
private static final TesrMaterial[] MATERIALS = {
TesrMaterial.builder().color(1f, 0f, 0f, 0.5f).translucent().noCull().build(),
TesrMaterial.builder().color(0.5f, 0f, 0.5f, 1f).additive().noCull().build() };
private static final Object[] KEYS = { new Object(), new Object() };
private static int kind(TileEntity te) {
return ((TileTesrTranslucentTest) te).variant() == 1 ? 1 : 0;
}
@Override
public Object angelica$meshKey(TileEntity te) {
return KEYS[kind(te)];
}
@Override
public void angelica$build(TesrMeshSink sink, TileEntity te) {
pane(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, MATERIALS[kind(te)]), HALF);
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(MATERIALS[kind(te)]);
drawPane(HALF);
end();
}
}
public static final class Model extends PaneRenderer {
private static final TesrMaterial TRANSLUCENT_GREEN = TesrMaterial.builder().color(0f, 1f, 0f, 0.5f).translucent().build();
private static final TesrMaterial TRANSLUCENT_YELLOW = TesrMaterial.builder().color(1f, 1f, 0f, 0.5f).translucent().build();
private static final TesrMaterial TRANSLUCENT_MAGENTA = TesrMaterial.builder().color(1f, 0f, 1f, 0.5f).translucent().build();
private static final TesrMaterial ADDITIVE_CYAN = TesrMaterial.builder().color(0f, 0.6f, 0.6f, 1f).additive().build();
private final ModelBase model = new ModelBase() {};
private final ModelRenderer base = new ModelRenderer(model, 0, 0);
private final ModelRenderer pane = paneAt(0f);
private final ModelRenderer paneFar = paneAt(0.16f);
private final ModelRenderer paneNear = paneAt(-0.16f);
public Model() {
base.addBox(-1f, 7f, -1f, 2, 1, 2);
}
private ModelRenderer paneAt(float z) {
final ModelRenderer renderer = new ModelRenderer(model, 0, 0);
renderer.addBox(-7f, -7f, z, 14, 14, 0);
return renderer;
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
final float scale = 1f / 16f;
bindTexture(WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND);
GLSMMatrices.glPushMatrix();
GLSMMatrices.glTranslated(x + 0.5, y + 0.5, z + 0.5);
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
base.render(scale);
GLSMEnable.glEnable(GL11.GL_BLEND);
switch (((TileTesrTranslucentTest) te).variant()) {
case 0 -> {
apply(TRANSLUCENT_GREEN);
pane.render(scale);
}
case 1 -> {
apply(TRANSLUCENT_YELLOW);
GLSMMatrices.glTranslated(-0.5, -0.5, -0.5);
drawPane(HALF);
}
default -> {
apply(TRANSLUCENT_MAGENTA);
paneFar.render(scale);
apply(ADDITIVE_CYAN);
pane.render(scale);
apply(TRANSLUCENT_GREEN);
paneNear.render(scale);
}
}
end();
}
}
public static final class Decal extends PaneRenderer implements TesrMeshProvider {
private static final TesrMaterial WRITER = TesrMaterial.builder().color(1f, 1f, 1f, 0.5f).translucent().noCull().build();
private static final TesrMaterial DECAL = TesrMaterial.builder().color(0f, 0f, 0f, 0.8f).translucent().depthEqual().noCull().build();
private static final Object KEY = new Object();
private static final double INNER = HALF / 2;
private static void writer(Tessellator t) {
rect(t, -HALF, INNER, HALF, HALF);
rect(t, -HALF, -HALF, HALF, -INNER);
rect(t, -HALF, -INNER, -INNER, INNER);
rect(t, INNER, -INNER, HALF, INNER);
pane(t, INNER);
}
@Override
public Object angelica$meshKey(TileEntity te) {
return KEY;
}
@Override
public void angelica$build(TesrMeshSink sink, TileEntity te) {
writer(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, WRITER));
pane(sink.angelica$bucket(DefaultVertexFormat.POSITION_TEXTURE_NORMAL, WorkaroundUtils.GL_TEXTURE_2D_WORKAROUND, DECAL), INNER);
}
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(WRITER);
final Tessellator t = Tessellator.instance;
t.startDrawingQuads();
writer(t);
t.draw();
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_EQUAL);
apply(DECAL);
drawPane(INNER);
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_LEQUAL);
end();
}
}
public static final class Glow extends PaneRenderer {
private static final TesrMaterial TRANSLUCENT_ORANGE = TesrMaterial.builder().color(1f, 0.5f, 0f, 0.6f).translucent().build();
@Override
public void renderTileEntityAt(TileEntity te, double x, double y, double z, float partialTicks) {
begin(x, y, z);
apply(TRANSLUCENT_ORANGE);
GLSMDepthStencilAlpha.glDepthMask(false);
drawPane(HALF);
GLSMDepthStencilAlpha.glDepthMask(true);
end();
}
}
}
@@ -112,7 +112,7 @@ public class AngelicaChunkBuildContext extends ChunkBuildContext {
} }
public void setupDynamicLights(int chunkOriginX, int chunkOriginY, int chunkOriginZ) { public void setupDynamicLights(int chunkOriginX, int chunkOriginY, int chunkOriginZ) {
if (DynamicLights.isEnabled()) { if (DynamicLights.isActive()) {
this.dynamicLightsInstance = DynamicLights.get(); this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(chunkOriginX, chunkOriginY, chunkOriginZ); this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(chunkOriginX, chunkOriginY, chunkOriginZ);
} else { } else {
@@ -13,7 +13,6 @@ import com.gtnewhorizons.angelica.rendering.TextureSamplers;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider;
import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder;
import com.gtnewhorizons.angelica.rendering.culling.GpuCulling; import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucencyLayers;
import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions;
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink; import com.gtnewhorizons.angelica.rendering.voxelization.SdlShadowVoxelizationSink;
@@ -197,7 +196,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
if (program != null) { if (program != null) {
program.bind(); program.bind();
program.getInterface().setupState(pass); program.getInterface().setupState(pass);
if (pass == AngelicaRenderPassConfiguration.TRANSLUCENT_PASS) TranslucencyLayers.INSTANCE.beginTerrainSplit(program.handle());
} }
} }
@@ -206,7 +204,6 @@ class AngelicaChunkRenderer extends DefaultChunkRenderer {
if (irisProgram != null) { if (irisProgram != null) {
endIrisPass(pass); endIrisPass(pass);
} else { } else {
if (pass == AngelicaRenderPassConfiguration.TRANSLUCENT_PASS) TranslucencyLayers.INSTANCE.endTerrainSplit();
super.end(pass); super.end(pass);
} }
} }
@@ -80,8 +80,7 @@ public class AngelicaRenderPassConfiguration {
TRANSLUCENT_PASS = builderForRenderType(1, false, translucentCutoff, vertexType) TRANSLUCENT_PASS = builderForRenderType(1, false, translucentCutoff, vertexType)
.name("translucent") .name("translucent")
.useReverseOrder(true) .useReverseOrder(true)
.useTranslucencySorting(ClientProxy.options().performance.translucencyMode.sorts()) .useTranslucencySorting(ClientProxy.options().performance.translucencySorting)
.extraDefine("TRANSLUCENCY_SPLIT", "")
.build(); .build();
TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, translucentCutoff, true); TRANSLUCENT_MATERIAL = new Material(TRANSLUCENT_PASS, translucentCutoff, true);
@@ -1,19 +1,19 @@
package com.gtnewhorizons.angelica.rendering.celeritas; package com.gtnewhorizons.angelica.rendering.celeritas;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator;
import java.util.List; import java.util.List;
import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache; import com.gtnewhorizons.angelica.compat.bop.FogBiomeCache;
import com.gtnewhorizons.angelica.render.CloudRenderer; import com.gtnewhorizons.angelica.render.CloudRenderer;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.client.MinecraftForgeClient;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -37,22 +37,15 @@ import org.embeddedt.embeddium.impl.render.viewport.frustum.SimpleFrustum;
import org.joml.FrustumIntersection; import org.joml.FrustumIntersection;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import com.gtnewhorizons.angelica.compat.ModStatus; import com.gtnewhorizons.angelica.compat.ModStatus;
import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI; import com.gtnewhorizons.angelica.compat.cubicchunks.CubicChunksAPI;
import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.config.AngelicaConfig;
import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights;
import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer; import com.gtnewhorizons.angelica.dynamiclights.IDynamicLightWorldRenderer;
import com.gtnewhorizons.angelica.glsm.DepthEcho;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs; import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices; import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer; import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs; import com.gtnewhorizons.angelica.glsm.ffp.FfpExtendedAttribs;
import com.gtnewhorizons.angelica.glsm.profiling.Tracy; import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache; import com.gtnewhorizons.angelica.mixins.interfaces.ITileEntityBoundingBoxCache;
@@ -65,8 +58,6 @@ import com.gtnewhorizons.angelica.rendering.culling.GpuCulling;
import com.gtnewhorizons.angelica.render.WeatherRenderer; import com.gtnewhorizons.angelica.render.WeatherRenderer;
import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller; import com.gtnewhorizons.angelica.rendering.culling.GpuTerrainCuller;
import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache; import com.gtnewhorizons.angelica.rendering.tesr.AngelicaTesrMeshCache;
import com.gtnewhorizons.angelica.rendering.tesr.GlowReplayExclusions;
import com.gtnewhorizons.angelica.rendering.tesr.ImmediateDrawOrder;
import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher; import com.gtnewhorizons.angelica.rendering.tesr.ModelPartBatcher;
import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws; import com.gtnewhorizons.angelica.rendering.tesr.PendingTesrDraws;
import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity; import com.gtnewhorizons.angelica.rendering.tesr.SectionBuiltBlockEntity;
@@ -75,12 +66,6 @@ import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHold
import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution; import com.gtnewhorizons.angelica.rendering.tesr.TesrAttribution;
import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer; import com.gtnewhorizons.angelica.rendering.tesr.TesrBatchRenderer;
import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle; import com.gtnewhorizons.angelica.rendering.tesr.TesrLifecycle;
import com.gtnewhorizons.angelica.rendering.tesr.TesrProviderDispatch;
import com.gtnewhorizons.angelica.rendering.tesr.TranslucentPeel;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucencyLayers;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucentLayer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.layer.GbufferPrograms;
import net.coderbot.iris.pipeline.ShadowRenderer; import net.coderbot.iris.pipeline.ShadowRenderer;
public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, AngelicaRenderSectionManager, BlockRenderLayer, TileEntity, CeleritasWorldRenderer.TileEntityRenderContext> implements IDynamicLightWorldRenderer { public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, AngelicaRenderSectionManager, BlockRenderLayer, TileEntity, CeleritasWorldRenderer.TileEntityRenderContext> implements IDynamicLightWorldRenderer {
@@ -90,7 +75,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
private static final Tracy.ZoneId Z_TESR_DISPATCH = Tracy.zoneId("tesrDispatch", Tracy.COLOR_CLIENT); private static final Tracy.ZoneId Z_TESR_DISPATCH = Tracy.zoneId("tesrDispatch", Tracy.COLOR_CLIENT);
private static final Tracy.ZoneId Z_TESR_MODEL_PARTS = Tracy.zoneId("tesrModelParts", Tracy.COLOR_CLIENT); private static final Tracy.ZoneId Z_TESR_MODEL_PARTS = Tracy.zoneId("tesrModelParts", Tracy.COLOR_CLIENT);
private static final Tracy.ZoneId Z_TESR_RENDER_TE = Tracy.zoneId("tesrRenderTE", Tracy.COLOR_CLIENT); private static final Tracy.ZoneId Z_TESR_RENDER_TE = Tracy.zoneId("tesrRenderTE", Tracy.COLOR_CLIENT);
private static final long P_BLOCK_ENTITIES_RENDERED = Tracy.plotHandle("blockEntitiesRendered");
private final Minecraft mc; private final Minecraft mc;
private static CeleritasWorldRenderer instance; private static CeleritasWorldRenderer instance;
@@ -110,13 +94,10 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
private final ObjectArrayList<TileEntity> frameTEs = new ObjectArrayList<>(); private final ObjectArrayList<TileEntity> frameTEs = new ObjectArrayList<>();
private final ObjectArrayList<TileEntity> frameOverride = new ObjectArrayList<>(); private final ObjectArrayList<TileEntity> frameOverride = new ObjectArrayList<>();
private final ObjectArrayList<TileEntity> glowReplay = new ObjectArrayList<>();
private final TileEntityDepthOrder depthOrder = new TileEntityDepthOrder(); // For sorting transparent TESRs
private final Matrix4f savedTextureMatrix = new Matrix4f(); private final TileEntityOrderer tileEntityOrderer = new TileEntityOrderer();
private PassOne passOne = PassOne.NONE; private final ArrayList<TileEntity> sortedTileEntities = new ArrayList<>();
private enum PassOne { NONE, PENDING, DRAWN_EARLY }
private CeleritasWorldRenderer(Minecraft mc) { private CeleritasWorldRenderer(Minecraft mc) {
// Private constructor for singleton // Private constructor for singleton
@@ -191,6 +172,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
DynamicLights.setActiveRenderer(null); DynamicLights.setActiveRenderer(null);
this.frameTEs.clear(); this.frameTEs.clear();
this.frameOverride.clear(); this.frameOverride.clear();
this.sortedTileEntities.clear();
ShadowRenderer.visibleTileEntities.clear(); ShadowRenderer.visibleTileEntities.clear();
ShadowRenderer.globalTileEntities.clear(); ShadowRenderer.globalTileEntities.clear();
TesrLifecycle.reset(); TesrLifecycle.reset();
@@ -316,7 +298,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
IrisShaderProviderHolder.shouldUseFaceCulling()); IrisShaderProviderHolder.shouldUseFaceCulling());
} }
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) { if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(viewport); DynamicLights.get().processChunkRebuilds(viewport);
} }
} }
@@ -349,7 +331,7 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
super.setupShadowTerrain(playerViewport, shadowViewport, cameraState, frame, spectator); super.setupShadowTerrain(playerViewport, shadowViewport, cameraState, frame, spectator);
if (DynamicLights.isEnabled() && DynamicLights.FrustumCullingEnabled) { if (DynamicLights.isActive() && DynamicLights.FrustumCullingEnabled) {
DynamicLights.get().processChunkRebuilds(shadowViewport); DynamicLights.get().processChunkRebuilds(shadowViewport);
} }
@@ -403,15 +385,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return camera; return camera;
} }
public boolean hasVisibleLayer(BlockRenderLayer renderLayer) {
final Collection<TerrainRenderPass> passes = this.renderSectionManager.getRenderPassConfiguration().vanillaRenderStages().get(renderLayer);
if (passes == null) return false;
for (final TerrainRenderPass pass : passes) {
if (this.renderSectionManager.getRenderLists().hasPass(pass)) return true;
}
return false;
}
@Override @Override
public void drawChunkLayer(BlockRenderLayer renderLayer, double x, double y, double z) { public void drawChunkLayer(BlockRenderLayer renderLayer, double x, double y, double z) {
if (DEBUG_WIREFRAME_MODE) { if (DEBUG_WIREFRAME_MODE) {
@@ -435,116 +408,6 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
GLSMCurrentAttribs.glColor4f(1, 1, 1, 1); GLSMCurrentAttribs.glColor4f(1, 1, 1, 1);
} }
public void renderBlockEntitiesBeforeTranslucent(float partialTicks) {
if (passOne != PassOne.PENDING) return;
passOne = PassOne.DRAWN_EARLY;
glowReplay.clear();
if (!anyRendersInPassOne()) return;
final Minecraft mc = Minecraft.getMinecraft();
final boolean layered = TranslucencyLayers.INSTANCE.active();
final int previousPass = MinecraftForgeClient.getRenderPass();
final int depth = GLSMAttribStack.pushState(StateSet.BLOCK_ENTITY_PASS);
savedTextureMatrix.set(GLSMTextures.getTextures().getTextureUnitMatrix(0));
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
GLSMMatrices.glPushMatrix();
try {
GLSMDepthStencilAlpha.glDepthMask(true);
GLSMDepthStencilAlpha.enableAlphaTest();
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
GLSMTextures.enableTexture();
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
// A layer reads its color as premultiplied, which a blend-disabled draw does not write (TranslucencyLayers).
if (layered) {
GLSMBlend.enableBlend();
GLSMBlend.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
} else if (mc.gameSettings.fancyGraphics) {
GLSMBlend.disableBlend();
}
if (mc.gameSettings.fancyGraphics) GLSMRasterizer.glShadeModel(GL11.GL_FLAT);
RenderHelper.enableStandardItemLighting();
mc.entityRenderer.enableLightmap(partialTicks);
ForgeHooksClient.setRenderPass(1);
if (layered) TranslucencyLayers.INSTANCE.begin(TranslucentLayer.BLOCK_ENTITIES);
try {
renderBlockEntitiesInPhase(partialTicks);
if (layered) replayGlowDepth(partialTicks);
} finally {
if (layered) TranslucencyLayers.INSTANCE.end();
}
} finally {
ForgeHooksClient.setRenderPass(previousPass);
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
GLSMMatrices.glPopMatrix();
GLSMMatrices.setTextureMatrix(0, savedTextureMatrix);
GLSMAttribStack.popStateTo(depth);
}
}
private void replayGlowDepth(float partialTicks) {
if (glowReplay.isEmpty()) return;
try {
if (!TranslucencyLayers.INSTANCE.beginGlowReplay()) return;
try {
for (int i = 0; i < glowReplay.size(); i++) {
replayTE(glowReplay.get(i), partialTicks);
}
} finally {
TranslucencyLayers.INSTANCE.endGlowReplay();
}
} finally {
glowReplay.clear();
}
}
/// Calls the renderer directly, since a depth-only replay must not feed the dispatcher's lighting or
/// batch-eligibility tracking.
private static void replayTE(TileEntity tileEntity, float partialTicks) {
final TileEntitySpecialRenderer renderer = TileEntityRendererDispatcher.instance.getSpecialRenderer(tileEntity);
if (renderer == null) return;
final double x = tileEntity.xCoord - TileEntityRendererDispatcher.staticPlayerX;
final double y = tileEntity.yCoord - TileEntityRendererDispatcher.staticPlayerY;
final double z = tileEntity.zCoord - TileEntityRendererDispatcher.staticPlayerZ;
final int depth = GLSMAttribStack.pushState(StateSet.BLEND);
GLSMCurrentAttribs.glColor4f(1f, 1f, 1f, 1f);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
TesrBatchRenderer.INSTANCE.beginScope();
try {
if (AngelicaConfig.enableTESRProviderDispatch && TesrProviderDispatch.tryRender(renderer, tileEntity, x, y, z)) return;
renderer.renderTileEntityAt(tileEntity, x, y, z, partialTicks);
} catch (RuntimeException e) {
if (!tileEntity.isInvalid()) throw e;
} finally {
TesrBatchRenderer.INSTANCE.endScope();
GLSMAttribStack.popStateTo(depth);
}
}
private boolean anyRendersInPassOne() {
for (int i = 0; i < frameOverride.size(); i++) {
if (frameOverride.get(i).shouldRenderInPass(1)) return true;
}
return false;
}
public boolean takeLatePassOne() {
final boolean late = passOne != PassOne.DRAWN_EARLY;
passOne = PassOne.NONE;
return late;
}
public void renderBlockEntitiesInPhase(float partialTicks) {
if (Iris.enabled) {
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
}
try {
final int rendered = renderBlockEntities(partialTicks);
if (Tracy.ENABLED) Tracy.plotInt(P_BLOCK_ENTITIES_RENDERED, rendered);
} finally {
if (Iris.enabled) GbufferPrograms.endBlockEntities();
}
}
public int renderBlockEntities(float partialTicks) { public int renderBlockEntities(float partialTicks) {
AngelicaTesrMeshCache.INSTANCE.tick(); AngelicaTesrMeshCache.INSTANCE.tick();
final int pass = MinecraftForgeClient.getRenderPass(); final int pass = MinecraftForgeClient.getRenderPass();
@@ -557,70 +420,66 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
TileEntityRendererDispatcher.staticPlayerZ); TileEntityRendererDispatcher.staticPlayerZ);
ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES); ModelPartBatcher.INSTANCE.begin(ModelPartBatcher.Mode.BLOCK_ENTITIES);
PendingTesrDraws.beginPass(); PendingTesrDraws.beginPass();
ImmediateDrawOrder.beginPass();
TranslucentPeel.beginPass();
int count = 0; int count = 0;
try { if (pass == 0) {
if (pass == 0) { teRenderContext.set(partialTicks, pass);
teRenderContext.set(partialTicks, pass); final Viewport viewport = this.currentViewport;
final Viewport viewport = this.currentViewport; this.teTransform = viewport != null ? viewport.getTransform() : null;
this.teTransform = viewport != null ? viewport.getTransform() : null; this.teFrustum = viewport != null && ClientProxy.options().performance.sectionGatedTesrCulling && viewport.getFrustum() instanceof SimpleFrustum simpleFrustum ? simpleFrustum.getFrustumIntersection() : null;
this.teFrustum = viewport != null && ClientProxy.options().performance.sectionGatedTesrCulling && viewport.getFrustum() instanceof SimpleFrustum simpleFrustum ? simpleFrustum.getFrustumIntersection() : null; this.teCullEpoch++;
this.teCullEpoch++; this.teCamX = TileEntityRendererDispatcher.staticPlayerX;
this.teCamX = TileEntityRendererDispatcher.staticPlayerX; this.teCamY = TileEntityRendererDispatcher.staticPlayerY;
this.teCamY = TileEntityRendererDispatcher.staticPlayerY; this.teCamZ = TileEntityRendererDispatcher.staticPlayerZ;
this.teCamZ = TileEntityRendererDispatcher.staticPlayerZ; frameTEs.clear();
frameTEs.clear(); frameOverride.clear();
frameOverride.clear(); if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_COLLECT);
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_COLLECT); try {
try { super.renderBlockEntities(teRenderContext);
super.renderBlockEntities(teRenderContext); } finally {
} finally { if (Tracy.ENABLED) Tracy.endZone();
if (Tracy.ENABLED) Tracy.endZone(); }
} this.teFrustum = null;
this.teFrustum = null; this.teTransform = null;
this.teTransform = null; if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH); try {
try { for (int i = 0; i < frameTEs.size(); i++) {
if (ClientProxy.options().performance.translucencyMode.sorts()) { final TileEntity te = frameTEs.get(i);
depthOrder.sortBackToFront(frameTEs, teCamX, teCamY, teCamZ); if (!(te instanceof OverridesShouldRenderInPass)) {
} dispatchTE(te, partialTicks);
for (int i = 0; i < frameTEs.size(); i++) { count++;
final TileEntity te = frameTEs.get(i); continue;
if (!(te instanceof OverridesShouldRenderInPass)) { }
dispatchTE(te, partialTicks); frameOverride.add(te);
count++; if (te.shouldRenderInPass(0)) {
continue; dispatchTE(te, partialTicks);
} count++;
frameOverride.add(te); }
if (te.shouldRenderInPass(0)) { }
dispatchTE(te, partialTicks); } finally {
count++; if (Tracy.ENABLED) Tracy.endZone();
} }
} } else {
} finally { if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH);
if (Tracy.ENABLED) Tracy.endZone(); try {
} sortedTileEntities.clear();
passOne = PassOne.PENDING; for (int i = 0; i < frameOverride.size(); i++) {
} else { final TileEntity te = frameOverride.get(i);
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_DISPATCH); if (te.shouldRenderInPass(pass)) {
try { sortedTileEntities.add(te);
for (int i = 0; i < frameOverride.size(); i++) { }
final TileEntity te = frameOverride.get(i); }
if (te.shouldRenderInPass(pass)) { if (sortedTileEntities.size() > 1 && ClientProxy.options().performance.translucencySorting) {
dispatchTE(te, partialTicks); sortedTileEntities.sort(tileEntityOrderer.setLastCameraState(lastCameraState));
count++; }
} for (int i = 0; i < sortedTileEntities.size(); i++) {
} dispatchTE(sortedTileEntities.get(i), partialTicks);
} finally { }
if (Tracy.ENABLED) Tracy.endZone(); count = sortedTileEntities.size();
} } finally {
if (Tracy.ENABLED) Tracy.endZone();
} }
} finally {
ImmediateDrawOrder.endPass();
} }
PendingTesrDraws.endPass(); PendingTesrDraws.endPass();
TranslucentPeel.flush();
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_MODEL_PARTS); if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_MODEL_PARTS);
try { try {
ModelPartBatcher.INSTANCE.flush(); ModelPartBatcher.INSTANCE.flush();
@@ -759,17 +618,14 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
} }
} }
PendingTesrDraws.beforeTileEntity(tileEntity); PendingTesrDraws.beforeTileEntity(tileEntity);
TranslucentPeel.beforeBlockEntity();
try { try {
final long start = Tracy.ENABLED ? System.nanoTime() : 0L; final long start = Tracy.ENABLED ? System.nanoTime() : 0L;
final boolean attribute = Tracy.ENABLED && TesrAttribution.currentRenderable == null; final boolean attribute = Tracy.ENABLED && TesrAttribution.currentRenderable == null;
if (attribute) TesrAttribution.currentRenderable = tileEntity.getClass(); if (attribute) TesrAttribution.currentRenderable = tileEntity.getClass();
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_RENDER_TE); if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_RENDER_TE);
if (DepthEcho.armed() && !GlowReplayExclusions.excludes(tileEntity)) DepthEcho.beginTracking();
try { try {
TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks); TileEntityRendererDispatcher.instance.renderTileEntity(tileEntity, partialTicks);
} finally { } finally {
if (DepthEcho.endTracking()) glowReplay.add(tileEntity);
if (Tracy.ENABLED) Tracy.endZone(); if (Tracy.ENABLED) Tracy.endZone();
if (attribute) TesrAttribution.currentRenderable = null; if (attribute) TesrAttribution.currentRenderable = null;
if (Tracy.ENABLED) RenderClassTimings.TESR.add(teLabelClass(tileEntity), System.nanoTime() - start); if (Tracy.ENABLED) RenderClassTimings.TESR.add(teLabelClass(tileEntity), System.nanoTime() - start);
@@ -817,4 +673,27 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer<WorldClient, Ang
return this; return this;
} }
} }
private static class TileEntityOrderer implements Comparator<TileEntity> {
public CameraState lastCameraState;
public TileEntityOrderer() {
super();
}
public TileEntityOrderer setLastCameraState(CameraState lastCameraState) {
this.lastCameraState = lastCameraState;
return this;
}
@Override
public int compare(TileEntity te1, TileEntity te2) {
final double x = this.lastCameraState.x();
final double y = this.lastCameraState.y();
final double z = this.lastCameraState.z();
final double d1 = te1.getDistanceFrom(x, y, z);
final double d2 = te2.getDistanceFrom(x, y, z);
return Double.compare(d2, d1);
}
}
} }
@@ -1,79 +0,0 @@
package com.gtnewhorizons.angelica.rendering.celeritas;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.minecraft.tileentity.TileEntity;
import java.util.Arrays;
final class TileEntityDepthOrder {
private static final int RADIX_BITS = 8;
private static final int BUCKETS = 1 << RADIX_BITS;
private final int[] counts = new int[BUCKETS];
private int[] keys = new int[0];
private int[] keysScratch = new int[0];
private int[] order = new int[0];
private int[] orderScratch = new int[0];
private TileEntity[] entities = new TileEntity[0];
void sortBackToFront(ObjectArrayList<TileEntity> list, double camX, double camY, double camZ) {
final int n = list.size();
if (n < 2) return;
final Object[] source = list.elements();
if (keys.length < n) {
final int capacity = source.length;
keys = new int[capacity];
keysScratch = new int[capacity];
order = new int[capacity];
orderScratch = new int[capacity];
entities = new TileEntity[capacity];
}
for (int i = 0; i < n; i++) {
final TileEntity te = (TileEntity) source[i];
final double dx = te.xCoord + 0.5 - camX;
final double dy = te.yCoord + 0.5 - camY;
final double dz = te.zCoord + 0.5 - camZ;
keys[i] = Integer.MAX_VALUE - Float.floatToRawIntBits((float) (dx * dx + dy * dy + dz * dz));
order[i] = i;
entities[i] = te;
}
final int[] sorted = sortOrder(n);
for (int i = 0; i < n; i++) {
source[i] = entities[sorted[i]];
entities[sorted[i]] = null;
}
}
private int[] sortOrder(int n) {
int[] keyIn = keys, keyOut = keysScratch;
int[] idxIn = order, idxOut = orderScratch;
for (int shift = 0; shift < Integer.SIZE; shift += RADIX_BITS) {
Arrays.fill(counts, 0);
for (int i = 0; i < n; i++) counts[(keyIn[i] >>> shift) & (BUCKETS - 1)]++;
if (counts[(keyIn[0] >>> shift) & (BUCKETS - 1)] == n) continue;
int sum = 0;
for (int b = 0; b < BUCKETS; b++) {
final int c = counts[b];
counts[b] = sum;
sum += c;
}
for (int i = 0; i < n; i++) {
final int dst = counts[(keyIn[i] >>> shift) & (BUCKETS - 1)]++;
keyOut[dst] = keyIn[i];
idxOut[dst] = idxIn[i];
}
final int[] k = keyIn;
keyIn = keyOut;
keyOut = k;
final int[] x = idxIn;
idxIn = idxOut;
idxOut = x;
}
keys = keyIn;
keysScratch = keyOut;
order = idxIn;
orderScratch = idxOut;
return idxIn;
}
}
@@ -227,7 +227,7 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
Arrays.fill(this.biomeData, null); Arrays.fill(this.biomeData, null);
// Pre-filter dynamic light sources for this chunk section // Pre-filter dynamic light sources for this chunk section
if (DynamicLights.isEnabled()) { if (DynamicLights.isActive()) {
this.dynamicLightsInstance = DynamicLights.get(); this.dynamicLightsInstance = DynamicLights.get();
this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(this.origin.getMinX(), this.origin.getMinY(), this.origin.getMinZ()); this.chunkLightSources = dynamicLightsInstance.getSourcesForChunk(this.origin.getMinX(), this.origin.getMinY(), this.origin.getMinZ());
} else { } else {
@@ -467,18 +467,6 @@ public class WorldSlice implements IBlockAccessExtended, FLBlockAccess, LiquidLo
return fl$getFluid(x, y, z); return fl$getFluid(x, y, z);
} }
public int liquidlogged$getFluidLevel(int x, int y, int z) {
if (this.context == null || !blockBoxContains(this.volume, x, y, z)) {
return 0;
}
final int relX = x - this.baseX;
final int relY = y - this.baseY;
final int relZ = z - this.baseZ;
return this.sections[getLocalSectionIndex(relX >> 4, relY >> 4, relZ >> 4)]
.getFluidLevel(relX & 15, relY & 15, relZ & 15);
}
public void fl$setFluid(int x, int y, int z, @Nullable Fluid fluid) { public void fl$setFluid(int x, int y, int z, @Nullable Fluid fluid) {
throw new UnsupportedOperationException("Cannot set fluids in a world slice. WorldSlice is read-only"); throw new UnsupportedOperationException("Cannot set fluids in a world slice. WorldSlice is read-only");
} }
@@ -10,7 +10,6 @@ import com.gtnewhorizons.angelica.compat.mojang.ChunkSectionPos;
import com.gtnewhorizons.angelica.mixins.interfaces.IChunkTileEntityMapHolder; import com.gtnewhorizons.angelica.mixins.interfaces.IChunkTileEntityMapHolder;
import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap; import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedAPI; import com.gtnewhorizons.liquidlogged.api.LiquidLoggedAPI;
import com.gtnewhorizons.liquidlogged.api.LiquidLoggedBlockAccess;
import com.gtnewhorizons.liquidlogged.api.SectionFluidsView; import com.gtnewhorizons.liquidlogged.api.SectionFluidsView;
import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap; import it.unimi.dsi.fastutil.shorts.Short2ObjectOpenHashMap;
import mega.fluidlogged.internal.mixin.hook.FLSubChunk; import mega.fluidlogged.internal.mixin.hook.FLSubChunk;
@@ -27,9 +26,6 @@ import net.minecraft.world.chunk.NibbleArray;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.Fluid;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Map; import java.util.Map;
public class ClonedChunkSection { public class ClonedChunkSection {
@@ -49,7 +45,6 @@ public class ClonedChunkSection {
// Fluids stored in blocks by LiquidLogged, indexed y << 8 | z << 4 | x; null when the section holds none // Fluids stored in blocks by LiquidLogged, indexed y << 8 | z << 4 | x; null when the section holds none
private Fluid[] liquidLoggedFluids; private Fluid[] liquidLoggedFluids;
private byte[] liquidLoggedFluidLevels;
private long lastUsedTimestamp = Long.MAX_VALUE; private long lastUsedTimestamp = Long.MAX_VALUE;
@@ -148,57 +143,12 @@ public class ClonedChunkSection {
final SectionFluidsView view = LiquidLoggedAPI.getSection(section); final SectionFluidsView view = LiquidLoggedAPI.getSection(section);
if (view == null || view.isEmpty()) { if (view == null || view.isEmpty()) {
this.liquidLoggedFluids = null; this.liquidLoggedFluids = null;
this.liquidLoggedFluidLevels = null;
return; return;
} }
if (this.liquidLoggedFluids == null) { if (this.liquidLoggedFluids == null) {
this.liquidLoggedFluids = new Fluid[SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH]; this.liquidLoggedFluids = new Fluid[SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH * SECTION_BLOCK_LENGTH];
} }
view.copyTo(this.liquidLoggedFluids); view.copyTo(this.liquidLoggedFluids);
final MethodHandle getter = LiquidLoggedLevels.GETTER;
if (getter == null) {
return;
}
final int minX = this.pos.getMinX();
final int minY = this.pos.getMinY();
final int minZ = this.pos.getMinZ();
try {
final LiquidLoggedBlockAccess access = (LiquidLoggedBlockAccess) this.world;
for (int i = 0; i < this.liquidLoggedFluids.length; i++) {
final int level = this.liquidLoggedFluids[i] == null ? 0
: (int) getter.invokeExact(access, minX + (i & 15), minY + (i >> 8), minZ + ((i >> 4) & 15));
if (level != 0 && this.liquidLoggedFluidLevels == null) {
this.liquidLoggedFluidLevels = new byte[this.liquidLoggedFluids.length];
}
if (this.liquidLoggedFluidLevels != null) {
this.liquidLoggedFluidLevels[i] = (byte) level;
}
}
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable e) {
throw new IllegalStateException("Could not read LiquidLogged fluid levels", e);
}
}
private static final class LiquidLoggedLevels {
private static final MethodHandle GETTER = findGetter();
private static MethodHandle findGetter() {
try {
return MethodHandles.publicLookup().findVirtual(LiquidLoggedBlockAccess.class, "liquidlogged$getFluidLevel",
MethodType.methodType(int.class, int.class, int.class, int.class));
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
public int getFluidLevel(int x, int y, int z) {
return this.liquidLoggedFluidLevels == null ? 0 : this.liquidLoggedFluidLevels[y << 8 | z << 4 | x];
} }
public Fluid getFluid(int x, int y, int z) { public Fluid getFluid(int x, int y, int z) {
@@ -1,6 +1,7 @@
package com.gtnewhorizons.angelica.rendering.particles; package com.gtnewhorizons.angelica.rendering.particles;
import com.gtnewhorizons.angelica.rendering.RenderFailures; import com.gtnewhorizons.angelica.rendering.RenderFailures;
import com.gtnewhorizons.angelica.api.particles.ParticleRendering;
import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher; import com.gtnewhorizons.angelica.client.rendering.DeferredDrawBatcher;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack; import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBuffers; import com.gtnewhorizons.angelica.glsm.GLSMBuffers;
@@ -138,6 +139,8 @@ public final class ParticleInstancer {
STATE.sample(); STATE.sample();
SCRATCH.brightness = runTessellator.brightness; SCRATCH.brightness = runTessellator.brightness;
if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return; if (!descriptor.describe(fx, partialTicks, SCRATCH, STATE)) return;
// Drawn from its fields, so a mod's size factor goes on here. The capture path below gets it from renderParticle
SCRATCH.half *= ParticleRendering.renderScale(fx);
runTessellator.color = SCRATCH.colorABGR; runTessellator.color = SCRATCH.colorABGR;
runTessellator.hasColor = true; runTessellator.hasColor = true;
@@ -31,7 +31,6 @@ final class BatchStateFallback {
final long before = GLSMDraws.drawCalls; final long before = GLSMDraws.drawCalls;
try { try {
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW); GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
if (models.hasQueuedGeometry() || tesrs.hasQueuedGeometry()) TranslucentPeel.flush();
models.flushForStateChange(); models.flushForStateChange();
tesrs.flushForStateChange(); tesrs.flushForStateChange();
} finally { } finally {
@@ -1,42 +0,0 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.config.AngelicaConfig;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
public final class GlowReplayExclusions {
private static final ReferenceOpenHashSet<Class<?>> registered = new ReferenceOpenHashSet<>();
private static final Reference2ObjectOpenHashMap<Class<?>, Boolean> excluded = new Reference2ObjectOpenHashMap<>();
private GlowReplayExclusions() {}
public static void exclude(Class<?> type) {
if (registered.add(type)) excluded.clear();
}
public static boolean excludes(TileEntity tileEntity) {
final Class<? extends TileEntity> type = tileEntity.getClass();
Boolean result = excluded.get(type);
if (result == null) {
final TileEntitySpecialRenderer renderer = TileEntityRendererDispatcher.instance.getSpecialRendererByClass(type);
result = matches(type) || renderer != null && matches(renderer.getClass());
excluded.put(type, result);
}
return result;
}
private static boolean matches(Class<?> type) {
final String[] names = AngelicaConfig.glowDepthReplayExcludedClasses;
for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
if (registered.contains(c)) return true;
if (names != null) for (String name : names) {
if (c.getName().equals(name)) return true;
}
}
return false;
}
}
@@ -1,49 +0,0 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
/// Draws what the batchers have queued before a blended `glBegin`, display list, Tessellator or unbatched template draw
/// of a block entity, which would otherwise land under batched geometry dispatched before it. Vertex array and buffer
/// draws are not hooked.
public final class ImmediateDrawOrder {
private static final Runnable FLUSH = ImmediateDrawOrder::flush;
private ImmediateDrawOrder() {}
public static void beginPass() {
if (!ClientProxy.options().performance.translucencyMode.sorts() || TesrBatchRenderer.deferredPipeline() != null) return;
BatchStateGuard.drawFlush = FLUSH;
}
public static void endPass() {
BatchStateGuard.drawFlush = null;
}
static void flush() {
if (!GLSMBlend.getBlendMode().isEnabled()) return;
// A Tessellator draw triggers this from inside Tessellator.draw, and pending draws use the Tessellator
if (!Tessellator.instance.isDrawing) PendingTesrDraws.flush();
final ModelPartBatcher models = ModelPartBatcher.INSTANCE;
final TesrBatchRenderer tesrs = TesrBatchRenderer.INSTANCE;
if (!models.hasQueuedGeometry() && !tesrs.hasQueuedGeometry()) return;
final int mode = GLSMMatrices.getMatrixMode().getMode();
final int unit = GLSMTextures.getActiveTextureUnit();
try {
GLSMMatrices.glMatrixMode(GL11.GL_MODELVIEW);
TranslucentPeel.flush();
models.flushForStateChange();
tesrs.flushAndContinue();
} finally {
GLSMMatrices.glMatrixMode(mode);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
}
}
}
@@ -144,14 +144,6 @@ final class InstancedTemplateRenderer {
* Draws a base run's recorded template upload again, every instance in one color. * Draws a base run's recorded template upload again, every instance in one color.
*/ */
int redrawTemplates(TexRun base, int colorABGR) { int redrawTemplates(TexRun base, int colorABGR) {
return redrawTemplates(base, true, colorABGR);
}
int replayTemplates(TexRun run) {
return redrawTemplates(run, false, 0);
}
private int redrawTemplates(TexRun base, boolean constantColor, int colorABGR) {
long recordOffset = base.uploadOffset; long recordOffset = base.uploadOffset;
neutralizeExtendedAttribs(); neutralizeExtendedAttribs();
GLSMPrograms.setFfpInstancing(Instancing.TEMPLATE); GLSMPrograms.setFfpInstancing(Instancing.TEMPLATE);
@@ -161,9 +153,9 @@ final class InstancedTemplateRenderer {
bindRingTo(mesh.vao, TEMPLATE_FLAGS); bindRingTo(mesh.vao, TEMPLATE_FLAGS);
InstancedAttribs.pointTemplate(recordOffset); InstancedAttribs.pointTemplate(recordOffset);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
if (constantColor) setConstantColor(colorABGR); setConstantColor(colorABGR);
GLSMDraws.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, count); GLSMDraws.glDrawArraysInstanced(mesh.drawMode, 0, mesh.vertexCount, count);
if (constantColor) GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR); GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
recordOffset += (long) count * InstancedAttribs.STRIDE; recordOffset += (long) count * InstancedAttribs.STRIDE;
} }
GLSMPrograms.setFfpInstancing(Instancing.NONE); GLSMPrograms.setFfpInstancing(Instancing.NONE);
@@ -228,23 +220,15 @@ final class InstancedTemplateRenderer {
} }
void redrawCubes(long offset, int instances, int colorABGR) { void redrawCubes(long offset, int instances, int colorABGR) {
redrawCubes(offset, instances, true, colorABGR);
}
void replayCubes(long offset, int instances) {
redrawCubes(offset, instances, false, 0);
}
private void redrawCubes(long offset, int instances, boolean constantColor, int colorABGR) {
neutralizeExtendedAttribs(); neutralizeExtendedAttribs();
bindRingTo(UnitCubeMesh.vao(), UnitCubeMesh.VERTEX_FLAGS); bindRingTo(UnitCubeMesh.vao(), UnitCubeMesh.VERTEX_FLAGS);
CubeInstancedAttribs.pointInstanceAttribs(offset); CubeInstancedAttribs.pointInstanceAttribs(offset);
GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLSMBuffers.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
if (constantColor) setConstantColor(colorABGR); setConstantColor(colorABGR);
GLSMPrograms.setFfpInstancing(Instancing.CUBE); GLSMPrograms.setFfpInstancing(Instancing.CUBE);
GLSMDraws.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, instances); GLSMDraws.glDrawArraysInstanced(GL11.GL_QUADS, 0, UnitCubeMesh.VERTEX_COUNT, instances);
GLSMPrograms.setFfpInstancing(Instancing.NONE); GLSMPrograms.setFfpInstancing(Instancing.NONE);
if (constantColor) GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR); GLSMVertexInput.glEnableVertexAttribArray(InstancedAttribs.LOC_COLOR);
GLSMVertexInput.glBindVertexArray(0); GLSMVertexInput.glBindVertexArray(0);
} }
@@ -329,39 +329,13 @@ public final class ModelPartBatcher {
} }
} }
void queueShadows() {
if (active && mode == Mode.BLOCK_ENTITIES && !shadow) shadows.flush(activeSource);
}
void drawOpaque() {
if (active && mode == Mode.BLOCK_ENTITIES && !shadow) activeSource.endBatchWithType(TransparencyType.OPAQUE, activeGroups);
}
boolean beginPeel() {
if (!active || mode != Mode.BLOCK_ENTITIES || shadow) return false;
if (!activeSource.hasPendingLayers()) return false;
activeSource.openDrawState();
return true;
}
void drawPeeled(boolean replay) {
activeGroups.setPeelReplay(!replay, replay);
activeSource.drawPending(activeGroups);
}
void endPeel() {
if (!active || mode != Mode.BLOCK_ENTITIES || shadow) return;
activeGroups.setPeelReplay(false, false);
activeSource.discard();
}
void flushForStateChange() { void flushForStateChange() {
if (!active) return; if (!active) return;
flushNow(false); flushNow(false);
active = true; active = true;
mvCaptured = false; mvCaptured = false;
texCaptured = false; texCaptured = false;
activeGroups.continuePass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline); activeGroups.beginPass(identity, 0, 0, 0, instancedThisCycle ? TesrBatchRenderer.INSTANCE.instancedRenderer : null, shaderPipeline);
} }
private void flushNow(boolean allowHold) { private void flushNow(boolean allowHold) {
@@ -886,7 +860,6 @@ public final class ModelPartBatcher {
return result; return result;
} }
case DRAW_NOW_EXPECTED -> { case DRAW_NOW_EXPECTED -> {
BatchStateGuard.beforeDraw();
BatchEligibility.beginExpectedDraws(GLSMDraws.drawCalls); BatchEligibility.beginExpectedDraws(GLSMDraws.drawCalls);
try { try {
return TessellatorStreamingDrawer.draw(tess); return TessellatorStreamingDrawer.draw(tess);
@@ -895,7 +868,6 @@ public final class ModelPartBatcher {
} }
} }
default -> { default -> {
BatchStateGuard.beforeDraw();
return TessellatorStreamingDrawer.draw(tess); return TessellatorStreamingDrawer.draw(tess);
} }
} }
@@ -1,6 +1,5 @@
package com.gtnewhorizons.angelica.rendering.tesr; package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.glsm.DepthEcho;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
/** /**
@@ -41,12 +40,7 @@ public final class PendingTesrDraws {
final Pending owner = pending; final Pending owner = pending;
if (owner == null) return; if (owner == null) return;
pending = null; pending = null;
DepthEcho.beginImmediate(); owner.flush();
try {
owner.flush();
} finally {
DepthEcho.endImmediate();
}
} }
public interface Pending { public interface Pending {
@@ -66,13 +66,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private final TemplateBuffer[] budgetSeen = new TemplateBuffer[PROMOTE_MAX_TEMPLATES]; private final TemplateBuffer[] budgetSeen = new TemplateBuffer[PROMOTE_MAX_TEMPLATES];
private double camX, camY, camZ; private double camX, camY, camZ;
private long frameMark; private long frameMark;
/// `frameMark` advances per segment, so limits measured in frames count passes here.
private long passMark;
private int segment;
private boolean peelRecording;
private boolean peelReplaying;
private final ObjectArrayList<Group> deferredPromotions = new ObjectArrayList<>();
private final ObjectArrayList<DepthEqualSet> deferredSwitches = new ObjectArrayList<>();
GlintCapture glintCapture; GlintCapture glintCapture;
long rebakes; long rebakes;
@@ -444,11 +437,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
} }
private static final class SegmentGroups {
final ObjectArrayList<Group> groups = new ObjectArrayList<>();
long frameMark = -1;
}
static final class Group { static final class Group {
final RenderLayer layer; final RenderLayer layer;
final TesrMaterial material; final TesrMaterial material;
@@ -463,7 +451,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
final Anchor anchor = new Anchor(); final Anchor anchor = new Anchor();
boolean anchored; boolean anchored;
long frameMark = -1; long frameMark = -1;
long passMark = -1;
long lastUsedMs; long lastUsedMs;
final int entityColor; final int entityColor;
final int itemId; final int itemId;
@@ -636,7 +623,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>>> groups = new Reference2ObjectOpenHashMap<>(); private final Reference2ObjectOpenHashMap<RenderLayer, Reference2ObjectOpenHashMap<TesrMaterial, Object2ObjectOpenHashMap<DrawStateKey, Group>>> groups = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>(); private final Reference2ObjectOpenHashMap<RenderLayer, ObjectArrayList<Group>> byLayer = new Reference2ObjectOpenHashMap<>();
private final Reference2ObjectOpenHashMap<RenderLayer, SegmentGroups> segmentGroups = new Reference2ObjectOpenHashMap<>();
private long openScope; private long openScope;
private DepthEqualSet openDepthEqualSet; private DepthEqualSet openDepthEqualSet;
private final ObjectArrayList<Group> openWriters = new ObjectArrayList<>(); private final ObjectArrayList<Group> openWriters = new ObjectArrayList<>();
@@ -662,18 +648,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) { void beginPass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
startSegment(base, camX, camY, camZ, instancedRenderer, deferred);
passMark++;
segment = 0;
}
void continuePass(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
startSegment(base, camX, camY, camZ, instancedRenderer, deferred);
// Baked groups are keyed by segment, so a group split by a flush keeps one mesh per side instead of rebaking
segment++;
}
private void startSegment(Matrix4f base, double camX, double camY, double camZ, InstancedTemplateRenderer instancedRenderer, TesrInstancingPipeline deferred) {
if (glintCapture != null) glintCapture.invalidate(); if (glintCapture != null) glintCapture.invalidate();
glintCapture = null; glintCapture = null;
baseMV.set(base); baseMV.set(base);
@@ -696,28 +670,27 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
/** Mutable lookup avoids allocating a key for each queued model part. Stored keys are never mutated. */ /** Mutable lookup avoids allocating a key for each queued model part. Stored keys are never mutated. */
private static final class DrawStateKey { private static final class DrawStateKey {
int entity, block, item, color, segment; int entity, block, item, color;
DrawStateKey set(int entity, int block, int item, int color, int segment) { DrawStateKey set(int entity, int block, int item, int color) {
this.entity = entity; this.entity = entity;
this.block = block; this.block = block;
this.item = item; this.item = item;
this.color = color; this.color = color;
this.segment = segment;
return this; return this;
} }
boolean matches(int entity, int block, int item, int color, int segment) { boolean matches(int entity, int block, int item, int color) {
return this.entity == entity && this.block == block && this.item == item && this.color == color && this.segment == segment; return this.entity == entity && this.block == block && this.item == item && this.color == color;
} }
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof DrawStateKey key && matches(key.entity, key.block, key.item, key.color, key.segment); return other instanceof DrawStateKey key && matches(key.entity, key.block, key.item, key.color);
} }
@Override @Override
public int hashCode() { return (((entity * 31 + block) * 31 + item) * 31 + color) * 31 + segment; } public int hashCode() { return ((entity * 31 + block) * 31 + item) * 31 + color; }
} }
private final DrawStateKey lookupState = new DrawStateKey(); private final DrawStateKey lookupState = new DrawStateKey();
@@ -756,7 +729,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
group = byState.get(lookupState); group = byState.get(lookupState);
if (group == null) { if (group == null) {
final DrawStateKey key = new DrawStateKey().set(lookupState.entity, lookupState.block, lookupState.item, lookupState.color, lookupState.segment); final DrawStateKey key = new DrawStateKey().set(lookupState.entity, lookupState.block, lookupState.item, lookupState.color);
group = new Group(layer, material, perInstance ? 0 : id, key); group = new Group(layer, material, perInstance ? 0 : id, key);
group.lastUsedMs = nowMs; group.lastUsedMs = nowMs;
byState.put(key, group); byState.put(key, group);
@@ -773,13 +746,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private void keyLookup(boolean perInstance, int id) { private void keyLookup(boolean perInstance, int id) {
if (perInstance) { if (perInstance) {
lookupState.set(0, 0, 0, 0, 0); lookupState.set(0, 0, 0, 0);
return; return;
} }
final CapturedRenderingState captured = CapturedRenderingState.INSTANCE; final CapturedRenderingState captured = CapturedRenderingState.INSTANCE;
final boolean entityKind = source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY; final boolean entityKind = source.effectiveIdKind() == AngelicaBufferSource.GroupIdKind.ENTITY;
lookupState.set(entityKind ? id : captured.getCurrentRenderedEntity(), entityKind ? captured.getCurrentRenderedBlockEntity() : id, lookupState.set(entityKind ? id : captured.getCurrentRenderedEntity(), entityKind ? captured.getCurrentRenderedBlockEntity() : id,
captured.getCurrentRenderedItem(), AngelicaBufferSource.packEntityColor(captured.getCurrentEntityColor()), segment); captured.getCurrentRenderedItem(), AngelicaBufferSource.packEntityColor(captured.getCurrentEntityColor()));
} }
void forceStreaming(RenderLayer layer, TesrMaterial material, int blockEntityId) { void forceStreaming(RenderLayer layer, TesrMaterial material, int blockEntityId) {
@@ -893,8 +866,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
resetPromotion(group); resetPromotion(group);
} }
} }
// touch recorded this geometry as stream segments, but it draws with the baked columns
TranslucentPeel.queued(layer, this, group);
} }
toAnchorRelative(group, currentMV); toAnchorRelative(group, currentMV);
final Matrix4f bakedTexMatrix = atlasSlot != null ? atlasSlot.uvMatrix : texMatrix; final Matrix4f bakedTexMatrix = atlasSlot != null ? atlasSlot.uvMatrix : texMatrix;
@@ -1020,7 +991,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
adoptAnchor(group, set); adoptAnchor(group, set);
} else if (set.anchorFrame < 0) { } else if (set.anchorFrame < 0) {
set.anchor.set(group.anchor); set.anchor.set(group.anchor);
set.anchorFrame = passMark; set.anchorFrame = frameMark;
for (int i = 0, n = set.members.size(); i < n; i++) { for (int i = 0, n = set.members.size(); i < n; i++) {
final Group member = set.members.get(i); final Group member = set.members.get(i);
if (member.frameMark == frameMark && !member.queuedThisFrame) adoptAnchor(member, set); if (member.frameMark == frameMark && !member.queuedThisFrame) adoptAnchor(member, set);
@@ -1052,13 +1023,13 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
private void refresh(DepthEqualSet set) { private void refresh(DepthEqualSet set) {
if (set.checkedFrame == passMark) return; if (set.checkedFrame == frameMark) return;
set.checkedFrame = passMark; set.checkedFrame = frameMark;
if (set.anchorFrame != passMark && set.anchor.stale(camX, camY, camZ)) set.anchor.moveTo(camX, camY, camZ); if (set.anchorFrame != frameMark && set.anchor.stale(camX, camY, camZ)) set.anchor.moveTo(camX, camY, camZ);
set.anchorFrame = passMark; set.anchorFrame = frameMark;
if ((set.streamMembers > 0 || set.instanced) && set.instanced != allCanInstance(set)) { if ((set.streamMembers > 0 || set.instanced) && set.instanced != allCanInstance(set)) {
set.instanced = !set.instanced; set.instanced = !set.instanced;
set.effectiveFrame = passMark - 1; set.effectiveFrame = frameMark - 1;
} }
} }
@@ -1181,7 +1152,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (group.frameMark != frameMark) { if (group.frameMark != frameMark) {
final DepthEqualSet set = activeDepthEqualSet(group); final DepthEqualSet set = activeDepthEqualSet(group);
if (set != null) refresh(set); if (set != null) refresh(set);
if (passMark - group.passMark > IDLE_RESET_FRAMES) { if (frameMark - group.frameMark > IDLE_RESET_FRAMES) {
resetPromotion(group); resetPromotion(group);
} else if (promoted(group)) { } else if (promoted(group)) {
final boolean pinned = set != null && set.streamMembers > 0; final boolean pinned = set != null && set.streamMembers > 0;
@@ -1200,14 +1171,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
} }
if (set != null) { if (set != null) {
if (passMark > set.effectiveFrame) adopt(group, set.instanced); if (frameMark > set.effectiveFrame) adopt(group, set.instanced);
} else if (group.stream && !group.streamPath) { } else if (group.stream && !group.streamPath) {
resetPromotion(group); resetPromotion(group);
} }
group.queuedThisFrame = false; group.queuedThisFrame = false;
group.frameMark = frameMark; group.frameMark = frameMark;
group.passMark = passMark;
addToSegment(group);
group.lastUsedMs = nowMs; group.lastUsedMs = nowMs;
group.dirty = false; group.dirty = false;
group.clearInstances(); group.clearInstances();
@@ -1220,37 +1189,12 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
source.declareUse(layer); source.declareUse(layer);
} }
if (drawsInstanced(group)) {
TranslucentPeel.queuedUnordered(layer);
} else if (group.streamPath) {
TranslucentPeel.queued(layer, source, layer);
} else {
TranslucentPeel.queued(layer, this, group);
}
}
private void addToSegment(Group group) {
SegmentGroups entry = segmentGroups.get(group.layer);
if (entry == null) {
entry = new SegmentGroups();
segmentGroups.put(group.layer, entry);
}
if (entry.frameMark != frameMark) {
entry.groups.clear();
entry.frameMark = frameMark;
}
entry.groups.add(group);
}
private ObjectArrayList<Group> segmentGroups(RenderLayer layer) {
final SegmentGroups entry = segmentGroups.get(layer);
return entry != null && entry.frameMark == frameMark ? entry.groups : null;
} }
private void switchSetNextFrame(DepthEqualSet set, boolean instanced) { private void switchSetNextFrame(DepthEqualSet set, boolean instanced) {
if (set.instanced == instanced) return; if (set.instanced == instanced) return;
set.instanced = instanced; set.instanced = instanced;
set.effectiveFrame = passMark; set.effectiveFrame = frameMark;
} }
private static DepthEqualSet activeDepthEqualSet(Group group) { private static DepthEqualSet activeDepthEqualSet(Group group) {
@@ -1261,7 +1205,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
private boolean allStable(DepthEqualSet set) { private boolean allStable(DepthEqualSet set) {
for (int i = 0, n = set.members.size(); i < n; i++) { for (int i = 0, n = set.members.size(); i < n; i++) {
final Group member = set.members.get(i); final Group member = set.members.get(i);
if (member.streamPath && passMark - member.passMark <= IDLE_RESET_FRAMES && (member.probe == null || member.probe.stableProbes < DEMOTE_AFTER_STABLE_PROBES)) return false; if (member.streamPath && frameMark - member.frameMark <= IDLE_RESET_FRAMES && (member.probe == null || member.probe.stableProbes < DEMOTE_AFTER_STABLE_PROBES)) return false;
} }
return true; return true;
} }
@@ -1286,7 +1230,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
@Override @Override
public boolean hasDraws(RenderLayer layer) { public boolean hasDraws(RenderLayer layer) {
final ObjectArrayList<Group> list = segmentGroups(layer); final ObjectArrayList<Group> list = byLayer.get(layer);
if (list == null) return false; if (list == null) return false;
for (int i = 0, n = list.size(); i < n; i++) { for (int i = 0, n = list.size(); i < n; i++) {
if (live(list.get(i))) return true; if (live(list.get(i))) return true;
@@ -1297,7 +1241,7 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
@Override @Override
public void drawLayer(RenderLayer layer) { public void drawLayer(RenderLayer layer) {
if (glintCapture != null) glintCapture.invalidate(); if (glintCapture != null) glintCapture.invalidate();
final ObjectArrayList<Group> list = segmentGroups(layer); final ObjectArrayList<Group> list = byLayer.get(layer);
if (list == null) return; if (list == null) return;
boolean matrixAvailable = true; boolean matrixAvailable = true;
boolean cubeAvailable = true; boolean cubeAvailable = true;
@@ -1430,10 +1374,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
private void drawRetained(Group group) { private void drawRetained(Group group) {
if (peelReplaying) {
draw(group);
return;
}
final InstanceColumns cols = group.templateColumns; final InstanceColumns cols = group.templateColumns;
final Snapshot snapshot = group.snapshot; final Snapshot snapshot = group.snapshot;
boolean instanceChanged = false; boolean instanceChanged = false;
@@ -1454,13 +1394,9 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (instanceChanged && !group.stream && !group.streamPath && rebakesTooOften(group) && withinTemplateBudget(cols.templates)) { if (instanceChanged && !group.stream && !group.streamPath && rebakesTooOften(group) && withinTemplateBudget(cols.templates)) {
final DepthEqualSet set = activeDepthEqualSet(group); final DepthEqualSet set = activeDepthEqualSet(group);
if (set != null) { if (set != null) {
if (set.streamMembers == 0 && allCanInstance(set)) { if (set.streamMembers == 0 && allCanInstance(set)) switchSetNextFrame(set, true);
if (peelRecording) deferredSwitches.add(set);
else switchSetNextFrame(set, true);
}
} else if (canInstance(group) || group.opaque && templatesMatchLayerDrawMode(group)) { } else if (canInstance(group) || group.opaque && templatesMatchLayerDrawMode(group)) {
if (peelRecording) deferredPromotions.add(group); promote(group);
else promote(group);
} }
} }
} }
@@ -1503,21 +1439,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
return ++group.promoteWindowRebakes >= PROMOTE_AFTER_REBAKES; return ++group.promoteWindowRebakes >= PROMOTE_AFTER_REBAKES;
} }
void setPeelReplay(boolean recording, boolean replaying) {
peelRecording = recording;
peelReplaying = replaying;
// Promoting deletes the mesh the peel replays draw, so promotions wait until the peel ends
if (recording || replaying) return;
for (int i = 0, n = deferredPromotions.size(); i < n; i++) promote(deferredPromotions.get(i));
for (int i = 0, n = deferredSwitches.size(); i < n; i++) switchSetNextFrame(deferredSwitches.get(i), true);
deferredPromotions.clear();
deferredSwitches.clear();
}
private boolean replays(TexRun run) {
return peelReplaying && run.uploadPass == frameMark && instanced.canRedraw(run.uploadRingEpoch, run.uploadBuffer);
}
private void drawTemplateRuns(InstanceColumns cols, boolean combineGlint, boolean itemStencil) { private void drawTemplateRuns(InstanceColumns cols, boolean combineGlint, boolean itemStencil) {
for (int r = 0, n = cols.runs.size(); r < n; r++) { for (int r = 0, n = cols.runs.size(); r < n; r++) {
final TexRun run = cols.runs.get(r); final TexRun run = cols.runs.get(r);
@@ -1536,13 +1457,9 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (canRedraw(run)) { if (canRedraw(run)) {
instancedDraws += instanced.redrawTemplates(run.sourceRun, run.color); instancedDraws += instanced.redrawTemplates(run.sourceRun, run.color);
redrawnInstances += run.parts; redrawnInstances += run.parts;
} else if (replays(run)) {
instancedDraws += instanced.replayTemplates(run);
redrawnInstances += run.parts;
} else { } else {
final boolean record = run.glintBase || peelRecording; instancedDraws += instanced.drawTemplates(cols, run, nowMs, run.glintBase);
instancedDraws += instanced.drawTemplates(cols, run, nowMs, record); if (run.glintBase) recordUpload(run);
if (record) recordUpload(run);
} }
instancedInstances += run.parts; instancedInstances += run.parts;
} finally { } finally {
@@ -1563,12 +1480,9 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
if (canRedraw(run)) { if (canRedraw(run)) {
instanced.redrawCubes(run.sourceRun.uploadOffset, run.instances, run.color); instanced.redrawCubes(run.sourceRun.uploadOffset, run.instances, run.color);
redrawnInstances += run.instances; redrawnInstances += run.instances;
} else if (replays(run)) {
instanced.replayCubes(run.uploadOffset, run.instances);
redrawnInstances += run.instances;
} else { } else {
run.uploadOffset = instanced.drawCubes(cols, run); run.uploadOffset = instanced.drawCubes(cols, run);
if (run.glintBase || peelRecording) recordUpload(run); if (run.glintBase) recordUpload(run);
} }
instancedDraws++; instancedDraws++;
cubeInstances += run.instances; cubeInstances += run.instances;
@@ -1724,7 +1638,6 @@ final class RetainedTesrGroups implements AngelicaBufferSource.LayerDrawHook {
} }
} }
byLayer.clear(); byLayer.clear();
segmentGroups.clear();
groups.clear(); groups.clear();
openScope = 0; openScope = 0;
openDepthEqualSet = null; openDepthEqualSet = null;
@@ -7,7 +7,6 @@ import com.gtnewhorizons.angelica.api.tesr.TesrMaterial;
import com.gtnewhorizons.angelica.api.tesr.TesrShader; import com.gtnewhorizons.angelica.api.tesr.TesrShader;
import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer; import com.gtnewhorizons.angelica.client.font.BatchingFontRenderer;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer; import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.DepthEcho;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack; import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBlend; import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs; import com.gtnewhorizons.angelica.glsm.GLSMCurrentAttribs;
@@ -83,9 +82,6 @@ public final class TesrBatchRenderer {
private RetainedTesrGroups pendingDeferredHook; private RetainedTesrGroups pendingDeferredHook;
private final Matrix4f modelView = new Matrix4f(); private final Matrix4f modelView = new Matrix4f();
private final Matrix4f passBase = new Matrix4f();
private double passCamX, passCamY, passCamZ;
private InstancedTemplateRenderer passInstanced;
private final Matrix4f identity = new Matrix4f(); private final Matrix4f identity = new Matrix4f();
private final Vector3f scratchVec = new Vector3f(); private final Vector3f scratchVec = new Vector3f();
@@ -116,12 +112,7 @@ public final class TesrBatchRenderer {
bufferSource.capturePassLighting(); bufferSource.capturePassLighting();
BatchDrawDefaults.capturePassFramebuffer(); BatchDrawDefaults.capturePassFramebuffer();
final DeferredWorldRenderingPipeline deferred = deferredPipeline(); final DeferredWorldRenderingPipeline deferred = deferredPipeline();
passBase.set(baseMV); retained[passKey].beginPass(baseMV, camX, camY, camZ, instancedCapable() ? instancedRenderer : null, deferred);
passCamX = camX;
passCamY = camY;
passCamZ = camZ;
passInstanced = instancedCapable() ? instancedRenderer : null;
retained[passKey].beginPass(baseMV, camX, camY, camZ, passInstanced, deferred);
if (passKey == PASS_MAIN_0) { if (passKey == PASS_MAIN_0) {
instancedRenderer.releaseRetired(); instancedRenderer.releaseRetired();
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
@@ -203,7 +194,6 @@ public final class TesrBatchRenderer {
} }
public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) { public void queue(TemplateBuffer template, ResourceLocation texture, TesrMaterial material) {
if (DepthEcho.replaying() && cannotBlend(material)) return;
modelView.set(GLSMMatrices.getModelViewMatrix()); modelView.set(GLSMMatrices.getModelViewMatrix());
final int packedLight = currentPackedLight(material); final int packedLight = currentPackedLight(material);
final int colorABGR = resolveColor(material); final int colorABGR = resolveColor(material);
@@ -226,13 +216,6 @@ public final class TesrBatchRenderer {
} }
} }
private static boolean cannotBlend(TesrMaterial material) {
if (material == TesrMaterial.CURRENT_STATE) return false;
final TesrMaterial.Transparency transparency = material.transparency();
return transparency == TesrMaterial.Transparency.OPAQUE || transparency == TesrMaterial.Transparency.GLINT || material.special().isGlint()
|| material.isDepthEqual() || material.isDepthOnly();
}
private static Matrix4f captureTextureMatrix() { private static Matrix4f captureTextureMatrix() {
final Matrix4f texMatrix = GLSMTextures.getTextures().getTextureUnitMatrix(0); final Matrix4f texMatrix = GLSMTextures.getTextures().getTextureUnitMatrix(0);
return MatrixHelper.isIdentity(texMatrix) ? null : texMatrix; return MatrixHelper.isIdentity(texMatrix) ? null : texMatrix;
@@ -418,37 +401,6 @@ public final class TesrBatchRenderer {
BatchingFontRenderer.flushDeferredText(); BatchingFontRenderer.flushDeferredText();
} }
void drawOpaque() {
if (activePass >= 0) bufferSource.endBatchWithType(TransparencyType.OPAQUE, retained[activePass]);
}
boolean beginPeel() {
if (activePass < 0) return false;
if (!bufferSource.hasPendingLayers()) return false;
bufferSource.openDrawState();
return true;
}
void drawPeeled(boolean replay) {
retained[activePass].setPeelReplay(!replay, replay);
bufferSource.drawPending(retained[activePass]);
}
void endPeel() {
if (activePass < 0) return;
retained[activePass].setPeelReplay(false, false);
bufferSource.discard();
}
void flushAndContinue() {
if (activePass < 0) return;
final RetainedTesrGroups hook = retained[activePass];
bufferSource.endBatchWithType(TransparencyType.OPAQUE, hook);
bufferSource.endBatch(hook);
BatchingFontRenderer.flushDeferredText();
hook.continuePass(passBase, passCamX, passCamY, passCamZ, passInstanced, null);
}
private void flushNow() { private void flushNow() {
final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null; final RetainedTesrGroups hook = activePass >= 0 ? retained[activePass] : null;
if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE); if (Tracy.ENABLED) Tracy.beginZone(Z_TESR_OPAQUE);
@@ -661,7 +613,6 @@ public final class TesrBatchRenderer {
try { try {
layer.startDrawing(); layer.startDrawing();
layerStarted = true; layerStarted = true;
BatchStateGuard.beforeDraw();
immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount); immediateMesh.upload(format, template.drawMode, immediateScratch, vertexCount);
immediateMesh.render(); immediateMesh.render();
} catch (Throwable t) { } catch (Throwable t) {
@@ -10,8 +10,6 @@ public final class TesrLifecycle {
public static void reset() { public static void reset() {
TesrBatchRenderer.INSTANCE.clearRetained(); TesrBatchRenderer.INSTANCE.clearRetained();
TranslucentPeel.destroy();
ImmediateDrawOrder.endPass();
ModelPartBatcher.INSTANCE.clear(); ModelPartBatcher.INSTANCE.clear();
EntityTextureAtlas.INSTANCE.clear(); EntityTextureAtlas.INSTANCE.clear();
DroppedItemInstancer.forgetItemDraws(); DroppedItemInstancer.forgetItemDraws();
@@ -1,363 +0,0 @@
package com.gtnewhorizons.angelica.rendering.tesr;
import com.gtnewhorizons.angelica.compat.mojang.RenderLayer;
import com.gtnewhorizons.angelica.glsm.DepthPeel;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMFramebuffer;
import com.gtnewhorizons.angelica.glsm.GLSMQueries;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.rendering.translucency.TranslucencyLayers;
import me.jellysquid.mods.sodium.client.gui.options.named.TranslucencyMode;
import net.coderbot.batchedentityrendering.impl.TransparencyType;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.rendertarget.IRenderTargetExt;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import net.minecraftforge.client.MinecraftForgeClient;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL14;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GL33;
import java.nio.ByteBuffer;
import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND;
/// Depth peels the translucent geometry the block entity batchers have queued ([DepthPeel]), since batches group it by
/// layer and material rather than by depth. A flush whose translucent geometry comes from one block entity in one
/// batch that keeps submission order is not peeled.
///
/// Each of the first [#SLOTS_PER_PASS] peeled flushes of a pass keeps its own peel count, and later ones peel
/// [#MAX_PEELS]. Occlusion queries, read back frames later without stalling, lower a count one peel at a time while
/// its last peel draws nothing and reset it when the rest pass draws.
public final class TranslucentPeel {
private static final int MAX_PEELS = 4;
private static final int SLOTS_PER_PASS = 32;
private static int width;
private static int height;
private static int depthVersion = -1;
private static DepthBufferFormat depthFormat;
private static Target[] peels;
private static Target sceneDepth;
private static StateSet clearState;
private static final Slot[] slots = new Slot[2 * SLOTS_PER_PASS];
private static int passFlushes;
private static boolean replay;
private static Object firstSource;
private static Object firstBatch;
private static int firstBlockEntity;
private static int blockEntity;
private static boolean mixed;
private TranslucentPeel() {}
static boolean enabled() {
return ClientProxy.options().performance.translucencyMode == TranslucencyMode.FANCY && Iris.enabled
&& TesrBatchRenderer.deferredPipeline() == null;
}
public static void beginPass() {
passFlushes = 0;
resetBatches();
}
public static void beforeBlockEntity() {
blockEntity++;
}
/// `source` and `batch` identify one draw: an `AngelicaBufferSource` and a layer, or [RetainedTesrGroups] and a
/// group.
public static void queued(RenderLayer layer, Object source, Object batch) {
if (mixed || layer.getTransparencyType() == TransparencyType.OPAQUE) return;
if (firstBatch == null) {
firstSource = source;
firstBatch = batch;
firstBlockEntity = blockEntity;
} else if (batch != firstBatch || source != firstSource || blockEntity != firstBlockEntity) {
mixed = true;
}
}
public static void queuedUnordered(RenderLayer layer) {
if (layer.getTransparencyType() != TransparencyType.OPAQUE) mixed = true;
}
private static void resetBatches() {
firstSource = null;
firstBatch = null;
mixed = false;
}
public static void flush() {
final ModelPartBatcher models = ModelPartBatcher.INSTANCE;
final TesrBatchRenderer tesrs = TesrBatchRenderer.INSTANCE;
BatchStateGuard.suspend();
try {
models.drawOpaque();
tesrs.drawOpaque();
} finally {
BatchStateGuard.resume();
}
if (!enabled()) {
if (peels != null) destroy();
return;
}
models.queueShadows();
final boolean peeling = mixed;
resetBatches();
if (!peeling) return;
BatchStateGuard.suspend();
try {
final boolean modelsQueued = models.beginPeel();
final boolean tesrsQueued = tesrs.beginPeel();
if (modelsQueued || tesrsQueued) peel(modelsQueued, tesrsQueued);
} finally {
try {
tesrs.endPeel();
} finally {
try {
models.endPeel();
} finally {
BatchStateGuard.resume();
}
}
}
}
private static void draw(boolean models, boolean tesrs) {
if (models) ModelPartBatcher.INSTANCE.drawPeeled(replay);
if (tesrs) TesrBatchRenderer.INSTANCE.drawPeeled(replay);
replay = true;
}
private static void peel(boolean models, boolean tesrs) {
replay = false;
final int target = GLSMFramebuffer.getDrawFramebuffer();
final int read = GLSMFramebuffer.getReadFramebuffer();
if (!syncSize() || target != Minecraft.getMinecraft().getFramebuffer().framebufferObject && target != TranslucencyLayers.INSTANCE.openFramebuffer()) {
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, read);
draw(models, tesrs);
return;
}
final int unit = GLSMTextures.getActiveTextureUnit();
final int previousPeelTexture = GLSMTextures.getTextures().getTextureUnitBindings(DepthPeel.TEXTURE_UNIT).getBinding();
final int previousSceneTexture = GLSMTextures.getTextures().getTextureUnitBindings(DepthPeel.SCENE_TEXTURE_UNIT).getBinding();
final Slot slot = slot(passFlushes++);
final int count = slot != null ? slot.update() : MAX_PEELS;
final boolean query = slot != null && slot.beginQueries(count);
boolean completed = false;
try {
blitDepth(target, sceneDepth.framebuffer.getId());
bindTexture(DepthPeel.SCENE_TEXTURE_UNIT, sceneDepth.depth);
Target bound = sceneDepth;
for (int i = 0; i < count; i++) {
final Target current = peels[i % 2];
clearDepth(current);
current.framebuffer.bind();
bindTexture(DepthPeel.TEXTURE_UNIT, bound.depth);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
DepthPeel.setPass(DepthPeel.Pass.DEPTH, i == 0);
if (query) slot.begin(i);
draw(models, tesrs);
if (query) slot.end();
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
bindTexture(DepthPeel.TEXTURE_UNIT, current.depth);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
DepthPeel.setPass(DepthPeel.Pass.COLOR, false);
draw(models, tesrs);
bound = current;
}
DepthPeel.setPass(DepthPeel.Pass.REST, false);
if (query) slot.begin(count);
draw(models, tesrs);
if (query) slot.end();
if (DepthPeel.skippedApplicationDraws()) {
DepthPeel.setPass(DepthPeel.Pass.APPLICATION, false);
draw(models, tesrs);
}
completed = true;
} finally {
if (!completed && slot != null) slot.abandon();
DepthPeel.setPass(DepthPeel.Pass.OFF, false);
bindTexture(DepthPeel.TEXTURE_UNIT, previousPeelTexture);
bindTexture(DepthPeel.SCENE_TEXTURE_UNIT, previousSceneTexture);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, read);
}
}
private static Slot slot(int flush) {
if (flush >= SLOTS_PER_PASS) return null;
final int index = (MinecraftForgeClient.getRenderPass() == 1 ? SLOTS_PER_PASS : 0) + flush;
if (slots[index] == null) slots[index] = new Slot();
return slots[index];
}
private static void clearDepth(Target target) {
if (clearState == null) clearState = StateSet.forMask(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_SCISSOR_BIT);
final int saved = GLSMAttribStack.pushState(clearState);
try {
GLSMRasterizer.disableScissorTest();
GLSMDepthStencilAlpha.glDepthMask(true);
GLSMDepthStencilAlpha.glClearDepth(0.0);
target.framebuffer.bind();
GLSMFramebuffer.glClear(GL11.GL_DEPTH_BUFFER_BIT);
} finally {
GLSMAttribStack.popStateTo(saved);
}
}
private static void blitDepth(int from, int to) {
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, from);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, to);
GLSMFramebuffer.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST);
}
private static void bindTexture(int unit, int texture) {
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
private static boolean syncSize() {
final Framebuffer main = Minecraft.getMinecraft().getFramebuffer();
final IRenderTargetExt ext = (IRenderTargetExt) main;
if (peels != null && main.framebufferWidth == width && main.framebufferHeight == height && ext.iris$getDepthBufferVersion() == depthVersion) return true;
destroyTargets();
width = main.framebufferWidth;
height = main.framebufferHeight;
depthVersion = ext.iris$getDepthBufferVersion();
final int mainDepth = ext.iris$getDepthTextureId();
if (width <= 0 || height <= 0 || mainDepth <= 0) return false;
depthFormat = DepthBufferFormat.fromGlEnumOrDefault(TextureInfoCache.INSTANCE.getInfo(mainDepth).getInternalFormat());
sceneDepth = new Target(depthFormat.getGlInternalFormat(), depthFormat.getGlType(), depthFormat.getGlFormat());
peels = new Target[] { Target.float32(), Target.float32() };
return true;
}
public static void destroy() {
destroyTargets();
for (int i = 0; i < slots.length; i++) {
if (slots[i] != null) slots[i].delete();
slots[i] = null;
}
}
private static void destroyTargets() {
if (peels != null) for (Target target : peels) target.destroy();
if (sceneDepth != null) sceneDepth.destroy();
peels = null;
sceneDepth = null;
}
private static final class Slot {
private int count = MAX_PEELS;
private final int[] queries = new int[MAX_PEELS + 1];
private int issued = -1;
private boolean querying;
int update() {
if (issued < 0) return count;
for (int i = 0; i <= issued; i++) {
if (GLSMQueries.glGetQueryObjecti(queries[i], GL15.GL_QUERY_RESULT_AVAILABLE) == 0) return count;
}
int drawn = issued;
for (int i = 0; i < issued; i++) {
if (GLSMQueries.glGetQueryObjecti(queries[i], GL15.GL_QUERY_RESULT) == 0) {
drawn = i;
break;
}
}
if (drawn == issued && GLSMQueries.glGetQueryObjecti(queries[issued], GL15.GL_QUERY_RESULT) != 0) {
count = MAX_PEELS;
} else if (drawn < count) {
count = Math.max(1, count - 1);
}
issued = -1;
return count;
}
boolean beginQueries(int peels) {
if (issued >= 0 || RENDER_BACKEND.isSDLGPU()) return false;
if (queries[0] == 0) {
try {
for (int i = 0; i < queries.length; i++) queries[i] = GLSMQueries.glGenQueries();
} catch (UnsupportedOperationException e) {
return false;
}
}
issued = peels;
return true;
}
void begin(int peel) {
GLSMQueries.glBeginQuery(GL33.GL_ANY_SAMPLES_PASSED, queries[peel]);
querying = true;
}
void end() {
querying = false;
GLSMQueries.glEndQuery(GL33.GL_ANY_SAMPLES_PASSED);
}
void abandon() {
if (querying) end();
issued = -1;
}
void delete() {
if (queries[0] == 0) return;
for (int query : queries) GLSMQueries.glDeleteQueries(query);
}
}
private static final class Target {
final int depth;
final GlFramebuffer framebuffer = new GlFramebuffer();
Target(int internalFormat, int format, int type) {
depth = texture(internalFormat, format, type);
framebuffer.addDepthAttachment(depth);
framebuffer.noDrawBuffers();
RenderSystem.readBuffer(framebuffer.getId(), GL11.GL_NONE);
}
static Target float32() {
return new Target(GL30.GL_DEPTH_COMPONENT32F, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT);
}
private static int texture(int internalFormat, int format, int type) {
final int previous = GLSMQueries.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int texture = GLSMTextures.glGenTextures();
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL11.GL_NONE);
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, (ByteBuffer) null);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, previous);
return texture;
}
void destroy() {
framebuffer.destroy();
GLSMTextures.glDeleteTextures(depth);
}
}
}
@@ -1,485 +0,0 @@
package com.gtnewhorizons.angelica.rendering.translucency;
import com.gtnewhorizons.angelica.glsm.DepthEcho;
import com.gtnewhorizons.angelica.glsm.GLSMAttribStack;
import com.gtnewhorizons.angelica.glsm.GLSMBlend;
import com.gtnewhorizons.angelica.glsm.GLSMDepthStencilAlpha;
import com.gtnewhorizons.angelica.glsm.GLSMDraws;
import com.gtnewhorizons.angelica.glsm.GLSMFramebuffer;
import com.gtnewhorizons.angelica.glsm.GLSMPrograms;
import com.gtnewhorizons.angelica.glsm.GLSMQueries;
import com.gtnewhorizons.angelica.glsm.GLSMRasterizer;
import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.GLSMVertexInput;
import com.gtnewhorizons.angelica.glsm.RenderSystem;
import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.glsm.hooks.BatchStateGuard;
import com.gtnewhorizons.angelica.glsm.stacks.ColorMaskStack;
import com.gtnewhorizons.angelica.glsm.texture.DepthBufferFormat;
import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache;
import com.gtnewhorizons.angelica.proxy.ClientProxy;
import com.gtnewhorizons.angelica.render.PanoramaRenderer;
import net.coderbot.iris.Iris;
import net.coderbot.iris.gl.framebuffer.GlFramebuffer;
import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline;
import net.coderbot.iris.rendertarget.IRenderTargetExt;
import net.minecraft.client.Minecraft;
import net.minecraft.client.shader.Framebuffer;
import org.embeddedt.embeddium.impl.gl.shader.GlProgram;
import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL30;
import java.nio.ByteBuffer;
/// Draws each [TranslucentLayer] into its own target, seeded with the main depth, and composites the drawn layers over
/// the main framebuffer per pixel, farthest first. Layers hold premultiplied color with coverage alpha (GLSM layer
/// blending), and the composite writes the nearest layer depth.
///
/// The terrain layer has a second sheet for fragments behind the block-entity layer, so a tile entity inside a
/// block's own translucent model is covered only by the faces in front of it.
///
/// Glows (blended block-entity draws that write no depth) would sort at the opaque depth behind them, so
/// [DepthEcho] records their depth separately, and it is merged into the block-entity layer before anything
/// reads that depth.
public final class TranslucencyLayers {
private static final int LAYERS = TranslucentLayer.values().length;
private static final int FIRST_LAYER_UNIT = 1;
private static final int TERRAIN_BEHIND_UNIT = FIRST_LAYER_UNIT + 2 * LAYERS;
private static final int SPLIT_DEPTH_UNIT = TERRAIN_BEHIND_UNIT + 1;
private static final int[] SINGLE_BUFFER = { 0 };
private static final int[] SPLIT_BUFFERS = { 0, 1 };
private static final int[] BEHIND_BUFFER = { 1 };
public static final TranslucencyLayers INSTANCE = new TranslucencyLayers(new MinecraftTarget());
interface MainTarget {
int framebuffer();
int depthTexture();
int width();
int height();
int depthVersion();
}
private final MainTarget main;
private final Target[] layers = new Target[LAYERS];
private Target depthSnapshot;
private int width;
private int height;
private int depthVersion = -1;
private DepthBufferFormat depthFormat;
private boolean decided;
private boolean active;
private int drawnMask;
private TranslucentLayer open;
private int savedDraw;
private int savedRead;
private boolean alphaMasked;
private boolean splitting;
private boolean behindDrawn;
private Target glowDepth;
private boolean replayingGlows;
private CompositeProgram program;
private CompositeProgram behindProgram;
private GlProgram<Object> glowMergeProgram;
private int vao;
private StateSet prepareState;
private StateSet compositeState;
private StateSet clearDepthState;
private final Runnable compositePass = this::drawComposite;
private final Runnable glowMergePass = this::drawGlowMerge;
TranslucencyLayers(MainTarget main) {
this.main = main;
}
/// Whether layering applies is decided on the first [#active] call, once Iris has prepared the frame's pipeline.
public void beginFrame() {
decided = false;
resetFrame();
}
void beginFrame(boolean active) {
this.active = active;
decided = true;
resetFrame();
}
private void resetFrame() {
drawnMask = 0;
behindDrawn = false;
DepthEcho.takeEchoed();
}
public boolean active() {
if (!decided) {
active = ClientProxy.options().performance.translucencyMode.composites() && Iris.enabled
&& Iris.getPipelineManager().getPipelineNullable() instanceof FixedFunctionWorldRenderingPipeline;
decided = true;
}
return active;
}
public boolean beginIfActive(TranslucentLayer layer) {
if (!active()) return false;
begin(layer);
return true;
}
public void begin(TranslucentLayer layer) {
if (open != null) throw new IllegalStateException("Translucency layer " + open + " is still open");
BatchStateGuard.beforeChange();
savedDraw = GLSMFramebuffer.getDrawFramebuffer();
savedRead = GLSMFramebuffer.getReadFramebuffer();
syncSize();
if (layer == TranslucentLayer.TERRAIN) mergeGlowDepth();
final Target target = layer(layer);
final int bit = 1 << layer.ordinal();
if ((drawnMask & bit) == 0) {
drawnMask |= bit;
prepare(target);
if (layer == TranslucentLayer.BLOCK_ENTITIES) clearDepth(glowDepth());
}
target.framebuffer.bind();
if (layer == TranslucentLayer.BLOCK_ENTITIES) DepthEcho.arm(glowDepth.framebuffer.getId(), target.framebuffer.getId());
open = layer;
GLSMBlend.setLayerBlending(true);
final ColorMaskStack mask = GLSMBlend.getColorMask();
alphaMasked = !mask.alpha;
if (alphaMasked) GLSMBlend.glColorMask(mask.red, mask.green, mask.blue, true);
}
public void end() {
BatchStateGuard.beforeChange();
DepthEcho.disarm();
if (alphaMasked) {
final ColorMaskStack mask = GLSMBlend.getColorMask();
GLSMBlend.glColorMask(mask.red, mask.green, mask.blue, false);
}
GLSMBlend.setLayerBlending(false);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, savedDraw);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, savedRead);
open = null;
}
public boolean redirectsMainBind() {
return open != null;
}
public int openFramebuffer() {
return open != null ? layers[open.ordinal()].framebuffer.getId() : 0;
}
public void bindOpenLayer() {
(replayingGlows ? glowDepth : layers[open.ordinal()]).framebuffer.bind();
}
public boolean beginGlowReplay() {
if (!DepthEcho.armed()) return false;
BatchStateGuard.beforeChange();
glowDepth.framebuffer.bind();
replayingGlows = true;
DepthEcho.beginReplay();
return true;
}
public void endGlowReplay() {
BatchStateGuard.beforeChange();
DepthEcho.endReplay();
replayingGlows = false;
layers[open.ordinal()].framebuffer.bind();
}
public void beginTerrainSplit(int program) {
splitting = open == TranslucentLayer.TERRAIN && (drawnMask & (1 << TranslucentLayer.BLOCK_ENTITIES.ordinal())) != 0;
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(program, "u_SplitEnabled"), splitting ? 1 : 0);
if (!splitting) return;
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(program, "u_SplitDepth"), SPLIT_DEPTH_UNIT);
final Target terrain = layers[TranslucentLayer.TERRAIN.ordinal()];
if (!behindDrawn) {
behindDrawn = true;
terrain.attachBehind(width, height);
terrain.framebuffer.drawBuffers(BEHIND_BUFFER);
clear(terrain);
}
final int unit = GLSMTextures.getActiveTextureUnit();
bindTexture(SPLIT_DEPTH_UNIT, layers[TranslucentLayer.BLOCK_ENTITIES.ordinal()].depth);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
terrain.framebuffer.drawBuffers(SPLIT_BUFFERS);
}
public void endTerrainSplit() {
if (!splitting) return;
splitting = false;
layers[TranslucentLayer.TERRAIN.ordinal()].framebuffer.drawBuffers(SINGLE_BUFFER);
final int unit = GLSMTextures.getActiveTextureUnit();
bindTexture(SPLIT_DEPTH_UNIT, 0);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
}
public void composite() {
if (drawnMask == 0) return;
BatchStateGuard.beforeChange();
syncSize();
if (drawnMask == 0) return;
try {
mergeGlowDepth();
fullscreenPass(compositePass);
} finally {
drawnMask = 0;
behindDrawn = false;
}
}
private void drawComposite() {
final Target snapshot = depthSnapshot();
blit(main.framebuffer(), snapshot.framebuffer.getId(), GL11.GL_DEPTH_BUFFER_BIT);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_FRAMEBUFFER, main.framebuffer());
GLSMBlend.enableBlend();
GLSMBlend.tryBlendFuncSeparate(GL11.GL_ONE, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ZERO, GL11.GL_ONE);
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_ALWAYS);
bindTexture(0, snapshot.depth);
for (int i = 0; i < LAYERS; i++) {
if ((drawnMask & (1 << i)) == 0) continue;
bindTexture(FIRST_LAYER_UNIT + i, layers[i].color);
bindTexture(FIRST_LAYER_UNIT + LAYERS + i, layers[i].depth);
}
if (behindDrawn) bindTexture(TERRAIN_BEHIND_UNIT, layers[TranslucentLayer.TERRAIN.ordinal()].behind);
final CompositeProgram composite = behindDrawn ? behindProgram : program;
GLSMPrograms.glUseProgram(composite.program.handle());
GLSMPrograms.glUniform1i(composite.maskUniform, drawnMask);
}
private void mergeGlowDepth() {
if (!DepthEcho.takeEchoed() || (drawnMask & (1 << TranslucentLayer.BLOCK_ENTITIES.ordinal())) == 0) return;
fullscreenPass(glowMergePass);
}
private void drawGlowMerge() {
layers[TranslucentLayer.BLOCK_ENTITIES.ordinal()].framebuffer.bind();
GLSMBlend.disableBlend();
GLSMBlend.glColorMask(false, false, false, false);
GLSMDepthStencilAlpha.glDepthFunc(GL11.GL_LESS);
bindTexture(0, glowDepth.depth);
GLSMPrograms.glUseProgram(glowMergeProgram.handle());
}
private void fullscreenPass(Runnable setup) {
final int draw = GLSMFramebuffer.getDrawFramebuffer();
final int read = GLSMFramebuffer.getReadFramebuffer();
final int activeProgram = GLSMPrograms.getActiveProgram();
final int activeVao = GLSMQueries.glGetInteger(GL30.GL_VERTEX_ARRAY_BINDING);
if (program == null) initProgram();
final int depth = GLSMAttribStack.pushState(compositeState);
try {
GLSMRasterizer.disableScissorTest();
GLSMRasterizer.disableCull();
GLSMDepthStencilAlpha.enableDepthTest();
GLSMDepthStencilAlpha.glDepthMask(true);
setup.run();
GLSMRasterizer.glViewport(0, 0, width, height);
GLSMVertexInput.glBindVertexArray(vao);
GLSMDraws.glDrawArrays(GL11.GL_TRIANGLES, 0, 3);
} finally {
GLSMVertexInput.glBindVertexArray(activeVao);
GLSMPrograms.glUseProgram(activeProgram);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, draw);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, read);
GLSMAttribStack.popStateTo(depth);
}
}
public void destroy() {
destroyTargets();
if (program != null) {
program.program.delete();
behindProgram.program.delete();
glowMergeProgram.delete();
GLSMVertexInput.glDeleteVertexArrays(vao);
program = null;
behindProgram = null;
glowMergeProgram = null;
}
}
private void initProgram() {
program = new CompositeProgram("angelica:translucency_composite", ShaderConstants.EMPTY);
behindProgram = new CompositeProgram("angelica:translucency_composite_behind", ShaderConstants.builder().add("TERRAIN_BEHIND").build());
glowMergeProgram = PanoramaRenderer.loadProgram("angelica:translucency_glow_depth", "angelica:panorama_blur", "angelica:translucency_glow_depth", ctx -> ctx);
final int merge = glowMergeProgram.handle();
GLSMPrograms.glUseProgram(merge);
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(merge, "u_GlowDepth"), 0);
GLSMPrograms.glUseProgram(0);
vao = GLSMVertexInput.glGenVertexArrays();
compositeState = StateSet.forMask(GL11.GL_ALL_ATTRIB_BITS);
}
private void prepare(Target target) {
clear(target);
blit(main.framebuffer(), target.framebuffer.getId(), depthFormat.isCombinedStencil() ? GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_STENCIL_BUFFER_BIT : GL11.GL_DEPTH_BUFFER_BIT);
}
private void clear(Target target) {
if (prepareState == null) prepareState = StateSet.forMask(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_SCISSOR_BIT);
final int depth = GLSMAttribStack.pushState(prepareState);
try {
GLSMRasterizer.disableScissorTest();
GLSMBlend.glColorMask(true, true, true, true);
target.framebuffer.bind();
GLSMBlend.glClearColor(0f, 0f, 0f, 0f);
GLSMFramebuffer.glClear(GL11.GL_COLOR_BUFFER_BIT);
} finally {
GLSMAttribStack.popStateTo(depth);
}
}
private void clearDepth(Target target) {
if (clearDepthState == null) clearDepthState = StateSet.forMask(GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_SCISSOR_BIT);
final int depth = GLSMAttribStack.pushState(clearDepthState);
try {
GLSMRasterizer.disableScissorTest();
GLSMDepthStencilAlpha.glDepthMask(true);
GLSMDepthStencilAlpha.glClearDepth(1.0);
target.framebuffer.bind();
GLSMFramebuffer.glClear(GL11.GL_DEPTH_BUFFER_BIT);
} finally {
GLSMAttribStack.popStateTo(depth);
}
}
private void blit(int from, int to, int mask) {
GLSMFramebuffer.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, from);
GLSMFramebuffer.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, to);
GLSMFramebuffer.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, GL11.GL_NEAREST);
}
private static void bindTexture(int unit, int texture) {
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0 + unit);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
}
private void syncSize() {
if (main.width() == width && main.height() == height && main.depthVersion() == depthVersion) return;
destroyTargets();
width = main.width();
height = main.height();
depthVersion = main.depthVersion();
depthFormat = DepthBufferFormat.fromGlEnumOrDefault(TextureInfoCache.INSTANCE.getInfo(main.depthTexture()).getInternalFormat());
}
private Target layer(TranslucentLayer layer) {
final int i = layer.ordinal();
if (layers[i] == null) layers[i] = new Target(width, height, depthFormat, true);
return layers[i];
}
private Target glowDepth() {
if (glowDepth == null) glowDepth = new Target(width, height, depthFormat, false);
return glowDepth;
}
private Target depthSnapshot() {
if (depthSnapshot == null) depthSnapshot = new Target(width, height, depthFormat, false);
return depthSnapshot;
}
private void destroyTargets() {
for (int i = 0; i < LAYERS; i++) {
if (layers[i] != null) layers[i].destroy();
layers[i] = null;
}
if (depthSnapshot != null) depthSnapshot.destroy();
depthSnapshot = null;
if (glowDepth != null) glowDepth.destroy();
glowDepth = null;
DepthEcho.disarm();
resetFrame();
}
private static final class CompositeProgram {
final GlProgram<Object> program;
final int maskUniform;
CompositeProgram(String name, ShaderConstants constants) {
program = PanoramaRenderer.loadProgram(name, "angelica:panorama_blur", "angelica:translucency_composite", constants, ctx -> ctx);
final int handle = program.handle();
GLSMPrograms.glUseProgram(handle);
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(handle, "u_Depth"), 0);
for (int i = 0; i < LAYERS; i++) {
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(handle, "u_Layer" + i), FIRST_LAYER_UNIT + i);
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(handle, "u_LayerDepth" + i), FIRST_LAYER_UNIT + LAYERS + i);
}
GLSMPrograms.glUniform1i(GLSMPrograms.glGetUniformLocation(handle, "u_TerrainBehind"), TERRAIN_BEHIND_UNIT);
maskUniform = GLSMPrograms.glGetUniformLocation(handle, "u_LayerMask");
GLSMPrograms.glUseProgram(0);
}
}
private static final class Target {
final int color;
final int depth;
final GlFramebuffer framebuffer;
int behind;
Target(int width, int height, DepthBufferFormat depthFormat, boolean withColor) {
depth = texture(width, height, depthFormat.getGlInternalFormat(), depthFormat.getGlType(), depthFormat.getGlFormat());
framebuffer = new GlFramebuffer();
framebuffer.addDepthAttachment(depth);
if (withColor) {
color = texture(width, height, GL11.GL_RGBA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE);
framebuffer.addColorAttachment(0, color);
framebuffer.drawBuffers(SINGLE_BUFFER);
framebuffer.readBuffer(0);
} else {
color = 0;
framebuffer.noDrawBuffers();
RenderSystem.readBuffer(framebuffer.getId(), GL11.GL_NONE);
}
}
void attachBehind(int width, int height) {
if (behind != 0) return;
behind = texture(width, height, GL11.GL_RGBA8, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE);
framebuffer.addColorAttachment(1, behind);
}
private static int texture(int width, int height, int internalFormat, int format, int type) {
final int previous = GLSMQueries.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
final int texture = GLSMTextures.glGenTextures();
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, texture);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
GLSMTextures.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, (ByteBuffer) null);
GLSMTextures.glBindTexture(GL11.GL_TEXTURE_2D, previous);
return texture;
}
void destroy() {
framebuffer.destroy();
if (color != 0) GLSMTextures.glDeleteTextures(color);
if (behind != 0) GLSMTextures.glDeleteTextures(behind);
GLSMTextures.glDeleteTextures(depth);
}
}
private static final class MinecraftTarget implements MainTarget {
private static Framebuffer fb() {
return Minecraft.getMinecraft().getFramebuffer();
}
@Override public int framebuffer() { return fb().framebufferObject; }
@Override public int depthTexture() { return ((IRenderTargetExt) fb()).iris$getDepthTextureId(); }
@Override public int width() { return fb().framebufferWidth; }
@Override public int height() { return fb().framebufferHeight; }
@Override public int depthVersion() { return ((IRenderTargetExt) fb()).iris$getDepthBufferVersion(); }
}
}
@@ -1,9 +0,0 @@
package com.gtnewhorizons.angelica.rendering.translucency;
public enum TranslucentLayer {
TERRAIN,
BLOCK_ENTITIES,
PARTICLES,
WEATHER,
CLOUDS
}
@@ -47,7 +47,6 @@ import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import me.jellysquid.mods.sodium.client.gui.options.named.ParticleMode; import me.jellysquid.mods.sodium.client.gui.options.named.ParticleMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling; import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling;
import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode; import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TranslucencyMode;
import me.jellysquid.mods.sodium.client.gui.options.storage.AngelicaOptionsStorage; import me.jellysquid.mods.sodium.client.gui.options.storage.AngelicaOptionsStorage;
import me.jellysquid.mods.sodium.client.gui.options.storage.CubicChunksOptionStorage; import me.jellysquid.mods.sodium.client.gui.options.storage.CubicChunksOptionStorage;
import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage; import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage;
@@ -404,23 +403,15 @@ public class SodiumGameOptionPages {
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build() .build()
) )
.add(OptionImpl.createBuilder(TranslucencyMode.class, sodiumOpts) .add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.translucency_mode.name")) .setName(I18n.format("sodium.options.translucency_sorting.name"))
.setTooltip(I18n.format("sodium.options.translucency_mode.tooltip")) .setTooltip(I18n.format("sodium.options.translucency_sorting.tooltip"))
.setControl(o -> new CyclingControl<>(o, TranslucencyMode.class)) .setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.performance.translucencyMode = value, opts -> opts.performance.translucencyMode) .setBinding((opts, value) -> opts.performance.translucencySorting = value, opts -> opts.performance.translucencySorting)
.setImpact(OptionImpact.MEDIUM) .setImpact(OptionImpact.MEDIUM)
.setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD)
.build() .build()
) )
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.block_entities_before_translucent_terrain.name"))
.setTooltip(I18n.format("sodium.options.block_entities_before_translucent_terrain.tooltip"))
.setControl(TickBoxControl::new)
.setBinding((opts, value) -> opts.performance.blockEntitiesBeforeTranslucentTerrain = value, opts -> opts.performance.blockEntitiesBeforeTranslucentTerrain)
.setImpact(OptionImpact.LOW)
.build()
)
.add(OptionImpl.createBuilder(boolean.class, sodiumOpts) .add(OptionImpl.createBuilder(boolean.class, sodiumOpts)
.setName(I18n.format("sodium.options.use_entity_culling.name")) .setName(I18n.format("sodium.options.use_entity_culling.name"))
.setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip")) .setTooltip(I18n.format("sodium.options.use_entity_culling.tooltip"))
@@ -861,29 +852,6 @@ public class SodiumGameOptionPages {
.build()); .build());
} }
groups.add(OptionGroup.createBuilder()
.add(OptionImpl.createBuilder(boolean.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlur"))
.setTooltip(I18n.format("options.angelica.menuBlur.tooltip"))
.setControl(TickBoxControl::new)
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> AngelicaConfig.enableMenuBlur = value, opts -> AngelicaConfig.enableMenuBlur)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlurRadius"))
.setTooltip(I18n.format("options.angelica.menuBlurRadius.tooltip"))
.setControl(option -> new SliderControl(option, 1, 100, 1, ControlValueFormatter.number()))
.setImpact(OptionImpact.LOW)
.setBinding((opts, value) -> AngelicaConfig.menuBlurRadius = value, opts -> AngelicaConfig.menuBlurRadius)
.build())
.add(OptionImpl.createBuilder(int.class, angelicaOpts)
.setName(I18n.format("options.angelica.menuBlurFadeTime"))
.setTooltip(I18n.format("options.angelica.menuBlurFadeTime.tooltip"))
.setControl(option -> new SliderControl(option, 0, 2000, 50, ControlValueFormatter.milliseconds()))
.setBinding((opts, value) -> AngelicaConfig.menuBlurFadeTime = value, opts -> AngelicaConfig.menuBlurFadeTime)
.build())
.build());
return new OptionPage(I18n.format("sodium.options.pages.appearance"), ImmutableList.copyOf(groups)); return new OptionPage(I18n.format("sodium.options.pages.appearance"), ImmutableList.copyOf(groups));
} }
@@ -15,7 +15,6 @@ import me.jellysquid.mods.sodium.client.gui.options.named.MipmapGeneration;
import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling; import me.jellysquid.mods.sodium.client.gui.options.named.TexelSampling;
import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode; import me.jellysquid.mods.sodium.client.gui.options.named.TextureFilterMode;
import me.jellysquid.mods.sodium.client.gui.options.named.TranslucencyMode;
import net.coderbot.iris.Iris; import net.coderbot.iris.Iris;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.OpenGlHelper;
@@ -25,7 +24,6 @@ import org.embeddedt.embeddium.impl.render.chunk.occlusion.AsyncOcclusionMode;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
@@ -126,7 +124,7 @@ public class SodiumGameOptions {
if (Files.exists(path)) { if (Files.exists(path)) {
try (FileReader reader = new FileReader(path.toFile())) { try (FileReader reader = new FileReader(path.toFile())) {
config = read(reader); config = GSON.fromJson(reader, SodiumGameOptions.class);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Could not parse config", e); throw new RuntimeException("Could not parse config", e);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
@@ -144,6 +142,23 @@ public class SodiumGameOptions {
config.configPath = path; config.configPath = path;
if (config.advanced.streamingUploadStrategy == null) {
config.advanced.streamingUploadStrategy = StreamingUploader.UploadStrategy.MAP_BUFFER_RANGE;
}
if (config.quality.textureFilterMode == null) {
config.quality.textureFilterMode = TextureFilterMode.RGSS_ANISOTROPIC;
}
if (config.quality.texelSampling == null) {
config.quality.texelSampling = TexelSampling.LINEAR;
}
config.quality.guiBlockSupersampling = Integer.highestOneBit(MathHelper.clamp_int(config.quality.guiBlockSupersampling, 1, 16));
if (config.quality.mipmapGeneration == null) {
config.quality.mipmapGeneration = MipmapGeneration.MODERN_VANILLA;
}
if (GLStateManager.capabilities != null) { if (GLStateManager.capabilities != null) {
if (!GLStateManager.capabilities.OpenGL32) { if (!GLStateManager.capabilities.OpenGL32) {
config.performance.cpuRenderAheadLimit = 0; config.performance.cpuRenderAheadLimit = 0;
@@ -164,43 +179,6 @@ public class SodiumGameOptions {
return config; return config;
} }
static SodiumGameOptions read(Reader reader) {
final SodiumGameOptions config = GSON.fromJson(reader, SodiumGameOptions.class);
config.normalize();
return config;
}
private void normalize() {
if (this.advanced.streamingUploadStrategy == null) {
this.advanced.streamingUploadStrategy = StreamingUploader.UploadStrategy.MAP_BUFFER_RANGE;
}
if (this.quality.textureFilterMode == null) {
this.quality.textureFilterMode = TextureFilterMode.RGSS_ANISOTROPIC;
}
if (this.quality.texelSampling == null) {
this.quality.texelSampling = TexelSampling.LINEAR;
}
this.quality.guiBlockSupersampling = Integer.highestOneBit(MathHelper.clamp_int(this.quality.guiBlockSupersampling, 1, 16));
if (this.quality.mipmapGeneration == null) {
this.quality.mipmapGeneration = MipmapGeneration.MODERN_VANILLA;
}
if (this.performance.translucencySorting != null) {
this.performance.translucencyMode = this.performance.translucencySorting ? TranslucencyMode.FAST : TranslucencyMode.OFF;
this.performance.translucencySorting = null;
}
if (this.performance.translucencyMode == null) {
this.performance.translucencyMode = TranslucencyMode.FAST;
}
}
String toJson() {
return GSON.toJson(this);
}
private static boolean isLwjgl2() { private static boolean isLwjgl2() {
return SodiumGameOptions.class.getClassLoader().getResource("org/lwjgl/Sys.class") != null; return SodiumGameOptions.class.getClassLoader().getResource("org/lwjgl/Sys.class") != null;
} }
@@ -218,7 +196,7 @@ public class SodiumGameOptions {
throw new IOException("Not a directory: " + dir); throw new IOException("Not a directory: " + dir);
} }
Files.writeString(this.configPath, toJson()); Files.writeString(this.configPath, GSON.toJson(this));
if (Iris.enabled) { if (Iris.enabled) {
try { try {
if (Iris.getIrisConfig() != null) { if (Iris.getIrisConfig() != null) {
@@ -255,9 +233,7 @@ public class SodiumGameOptions {
public boolean useFogOcclusion = true; public boolean useFogOcclusion = true;
public boolean useBlockFaceCulling = true; public boolean useBlockFaceCulling = true;
public boolean useCompactVertexFormat = true; public boolean useCompactVertexFormat = true;
public TranslucencyMode translucencyMode = TranslucencyMode.FAST; public boolean translucencySorting = true;
public Boolean translucencySorting;
public boolean blockEntitiesBeforeTranslucentTerrain = true;
public boolean useRenderPassOptimization = true; public boolean useRenderPassOptimization = true;
public int cpuRenderAheadLimit = 3; public int cpuRenderAheadLimit = 3;
} }
@@ -43,10 +43,6 @@ public interface ControlValueFormatter {
return (v) -> v + "s"; return (v) -> v + "s";
} }
static ControlValueFormatter milliseconds() {
return (v) -> v + "ms";
}
static ControlValueFormatter quantity(String name) { static ControlValueFormatter quantity(String name) {
return (v) -> I18n.format(name, v); return (v) -> I18n.format(name, v);
} }
@@ -1,26 +0,0 @@
package me.jellysquid.mods.sodium.client.gui.options.named;
public enum TranslucencyMode implements NamedState {
OFF("options.off"),
FAST("options.graphics.fast"),
FANCY("options.graphics.fancy");
private final String name;
TranslucencyMode(String name) {
this.name = name;
}
@Override
public String getKey() {
return this.name;
}
public boolean sorts() {
return this != OFF;
}
public boolean composites() {
return this == FANCY;
}
}
@@ -9,7 +9,6 @@ import com.gtnewhorizons.angelica.glsm.GLSMMatrices;
import com.gtnewhorizons.angelica.glsm.GLSMTextures; import com.gtnewhorizons.angelica.glsm.GLSMTextures;
import com.gtnewhorizons.angelica.glsm.LightingSnapshot; import com.gtnewhorizons.angelica.glsm.LightingSnapshot;
import com.gtnewhorizons.angelica.glsm.StateSet; import com.gtnewhorizons.angelica.glsm.StateSet;
import com.gtnewhorizons.angelica.rendering.tesr.TranslucentPeel;
import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArrayList;
@@ -67,14 +66,12 @@ public class AngelicaBufferSource implements Groupable {
} }
public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) { public SegmentedBufferBuilder getBuffer(RenderLayer type, int blockEntityId) {
TranslucentPeel.queued(type, this, type);
renderOrderManager.begin(type); renderOrderManager.begin(type);
int affinity = affinities.getAndMoveToLast(type); int affinity = affinities.getAndMoveToLast(type);
if (affinity == -1) { if (affinity == -1) {
if (affinities.size() < builders.length) { if (affinities.size() < builders.length) {
affinity = affinities.size(); affinity = affinities.size();
} else { } else {
TranslucentPeel.queuedUnordered(affinities.firstKey());
affinity = affinities.removeFirstInt(); affinity = affinities.removeFirstInt();
} }
affinities.put(type, affinity); affinities.put(type, affinity);
@@ -166,7 +163,16 @@ public class AngelicaBufferSource implements Groupable {
public void endBatch(LayerDrawHook hook) { public void endBatch(LayerDrawHook hook) {
ensurePrepared(); ensurePrepared();
try { try {
drawOrder(hook); int lastGlint = -1;
for (int i = 0, n = order.size(); i < n; i++) {
if (getTransparencyType(order.get(i)) == TransparencyType.DECAL) lastGlint = i;
}
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != TransparencyType.AFTER_GLINT) drawLayer(layer, hook);
if (i == lastGlint) drawAfterGlintLayers(hook);
}
if (lastGlint < 0) drawAfterGlintLayers(hook);
} catch (Throwable t) { } catch (Throwable t) {
discardAfterFailure(t); discardAfterFailure(t);
throw t; throw t;
@@ -175,29 +181,6 @@ public class AngelicaBufferSource implements Groupable {
finish(); finish();
} }
public void drawPending(LayerDrawHook hook) {
ensurePrepared();
drawOrder(hook);
}
public void openDrawState() {
ensureDrawState();
saveIrisState();
}
private void drawOrder(LayerDrawHook hook) {
int lastGlint = -1;
for (int i = 0, n = order.size(); i < n; i++) {
if (getTransparencyType(order.get(i)) == TransparencyType.DECAL) lastGlint = i;
}
for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i);
if (getTransparencyType(layer) != TransparencyType.AFTER_GLINT) drawLayer(layer, hook);
if (i == lastGlint) drawAfterGlintLayers(hook);
}
if (lastGlint < 0) drawAfterGlintLayers(hook);
}
private void drawAfterGlintLayers(LayerDrawHook hook) { private void drawAfterGlintLayers(LayerDrawHook hook) {
for (int i = 0, n = order.size(); i < n; i++) { for (int i = 0, n = order.size(); i < n; i++) {
final RenderLayer layer = order.get(i); final RenderLayer layer = order.get(i);
@@ -215,14 +198,6 @@ public class AngelicaBufferSource implements Groupable {
finish(); finish();
} }
private void ensureDrawState() {
if (drawStateDepth >= 0) return;
drawStateDepth = GLSMAttribStack.pushState(StateSet.BATCH);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
if (passLighting != null) GLSMLighting.applyLighting(passLighting);
drawDefaults.apply();
}
private void restoreDrawState() { private void restoreDrawState() {
if (drawStateDepth >= 0) { if (drawStateDepth >= 0) {
drawDefaults.restore(); drawDefaults.restore();
@@ -252,7 +227,12 @@ public class AngelicaBufferSource implements Groupable {
final boolean hasDynamic = segments != null && !segments.isEmpty(); final boolean hasDynamic = segments != null && !segments.isEmpty();
final boolean hasRetained = hook != null && hook.hasDraws(layer); final boolean hasRetained = hook != null && hook.hasDraws(layer);
if (!hasDynamic && !hasRetained) return; if (!hasDynamic && !hasRetained) return;
ensureDrawState(); if (drawStateDepth < 0) {
drawStateDepth = GLSMAttribStack.pushState(StateSet.BATCH);
GLSMTextures.glActiveTexture(GL13.GL_TEXTURE0);
if (passLighting != null) GLSMLighting.applyLighting(passLighting);
drawDefaults.apply();
}
saveIrisState(); saveIrisState();
layer.startDrawing(); layer.startDrawing();
Throwable failure = null; Throwable failure = null;
@@ -30,6 +30,12 @@ public class SmoothFloat {
private float cachedHalfLifeDown; private float cachedHalfLifeDown;
private float cachedDecayDown; private float cachedDecayDown;
// What the accumulator was at the start of this frame. Custom uniforms can be evaluated again mid-frame (see
// LocalGridFrame), and each of those calls has to smooth from the same point instead of stepping again.
private int frame = -1;
private float frameStartAccumulator;
private boolean frameStartHasInitialValue;
/** /**
* Computes an exponential decay factor based on the given decay constant and time value * Computes an exponential decay factor based on the given decay constant and time value
* *
@@ -58,6 +64,16 @@ public class SmoothFloat {
* Takes one value from the unsmoothed value sequence, and smooths it into our accumulator * Takes one value from the unsmoothed value sequence, and smooths it into our accumulator
*/ */
public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) { public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) {
final int now = SystemTimeUniforms.COUNTER.getAsInt();
if (now != frame) {
frame = now;
frameStartAccumulator = accumulator;
frameStartHasInitialValue = hasInitialValue;
} else {
accumulator = frameStartAccumulator;
hasInitialValue = frameStartHasInitialValue;
}
if (halfLifeUp != cachedHalfLifeUp) { if (halfLifeUp != cachedHalfLifeUp) {
cachedHalfLifeUp = halfLifeUp; cachedHalfLifeUp = halfLifeUp;
if (halfLifeUp == 0.0f) { if (halfLifeUp == 0.0f) {
@@ -967,6 +967,15 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
return current; return current;
} }
/** Evaluates these built-in uniforms again and pushes them to the bound pass, see LocalGridFrame. */
public void refreshUniforms(String[] names) {
customUniforms.refreshInputs(names);
if (current != null && current.liveProgram != null
&& GLSMPrograms.getActiveProgram() == current.liveProgram.getProgramId()) {
current.pushCustomUniforms();
}
}
public int getActivePassProgramId() { public int getActivePassProgramId() {
if (current == null) return -1; if (current == null) return -1;
final Program p = current.boundProgram(); final Program p = current.boundProgram();
@@ -1497,6 +1506,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R
} }
} }
void pushCustomUniforms() {
DeferredWorldRenderingPipeline.this.customUniforms.push(liveProgram == program ? this : liveProgram);
}
private void bindSelected() { private void bindSelected() {
final Program selected = select(activeInstancing, GLSMRasterizer.clipEmulationActive()); final Program selected = select(activeInstancing, GLSMRasterizer.clipEmulationActive());
liveProgram = selected; liveProgram = selected;
@@ -1,6 +1,8 @@
package net.coderbot.iris.pipeline; package net.coderbot.iris.pipeline;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.gtnewhorizons.angelica.api.shadows.ShadowCasters;
import com.gtnewhorizons.angelica.api.shadows.ShadowStage;
import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.Camera;
import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil;
import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack;
@@ -869,6 +871,24 @@ public class ShadowRenderer {
profiler.endSection(); profiler.endSection();
} }
private void renderShadowCasters(ShadowStage stage, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks) {
if (!ShadowCasters.hasCasters()) return;
try (GLDebug.Scope s = GLDebug.scope("shadow:casters")) {
GLSMMatrices.glPushMatrix();
MODELVIEW_BUFFER.clear().rewind();
modelView.peek().getModel().get(MODELVIEW_BUFFER);
GLSMMatrices.glLoadMatrix(MODELVIEW_BUFFER);
GbufferPrograms.beginBlockEntities();
GbufferPrograms.setBlockEntityDefaults();
try {
ShadowCasters.renderAll(stage, cameraX, cameraY, cameraZ, partialTicks);
} finally {
GbufferPrograms.endBlockEntities();
GLSMMatrices.glPopMatrix();
}
}
}
public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) { public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) {
final Minecraft mc = Minecraft.getMinecraft(); final Minecraft mc = Minecraft.getMinecraft();
final RenderGlobal rg = mc.renderGlobal; final RenderGlobal rg = mc.renderGlobal;
@@ -1027,6 +1047,9 @@ public class ShadowRenderer {
} }
} }
// Mod geometry that should shadow like terrain, so not tied to the pack's block entity shadow setting
renderShadowCasters(ShadowStage.SOLID, modelView, entityX, entityY, entityZ, tickDelta);
profiler.endStartSection("iris_shadow_draw_entities"); profiler.endStartSection("iris_shadow_draw_entities");
// NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some // NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some
@@ -1044,6 +1067,7 @@ public class ShadowRenderer {
try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) { try (GLDebug.Scope s = GLDebug.scope("shadow:translucent")) {
rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks()); rg.sortAndRender(mc.renderViewEntity, 1, playerCamera.getPartialTicks());
} }
renderShadowCasters(ShadowStage.TRANSLUCENT, modelView, entityX, entityY, entityZ, tickDelta);
} }
// Note: Apparently tripwire isn't rendered in the shadow pass. // Note: Apparently tripwire isn't rendered in the shadow pass.
@@ -29,6 +29,7 @@ public class CameraUniforms {
public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) { public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) {
final CameraPositionTracker tracker = new CameraPositionTracker(notifier); final CameraPositionTracker tracker = new CameraPositionTracker(notifier);
LocalGridFrame.trackCamera(tracker);
uniforms uniforms
.uniform1f(ONCE, "near", () -> 0.05) .uniform1f(ONCE, "near", () -> 0.05)
@@ -0,0 +1,260 @@
package net.coderbot.iris.uniforms;
import org.joml.Matrix3d;
import org.joml.Matrix4f;
import org.joml.Matrix4fc;
import org.joml.Vector3d;
import org.joml.Vector3dc;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import org.joml.Vector3ic;
import org.joml.Vector4f;
import org.joml.Vector4fc;
import java.util.HashMap;
import java.util.Map;
import java.util.function.DoubleSupplier;
import java.util.function.DoubleUnaryOperator;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* Lets a draw's own model space stand in for the world's block grid, for geometry drawn rotated or off the grid
* (structures, previews).
* <p>
* Packs pick out parts of some blocks by where a pixel is inside its world block, {@code fract(playerPos +
* cameraPosition)}, e.g. the water in a cauldron or the eye of an end portal frame. Off the grid that cuts through the
* block in the wrong place. While this is active the uniforms describe a world where the draw's model coordinates are
* world coordinates, moved by whole blocks to stay near the real position. View space, clip space and the shadow map
* come out exactly the same, so only what a pack works out in world space changes.
* <p>
* Every uniform that changes is in the remap tables below, keyed by name. The custom uniform input holder wraps those
* suppliers when it's built (see the wrap methods), so the uniform classes themselves don't know about any of this. A
* new world space uniform only needs a line here. The uniforms are worked out once a frame, so starting or ending this
* works them out again and pushes them to the bound program, see {@link #UNIFORMS}.
*/
public final class LocalGridFrame {
private static final Map<String, UnaryOperator<Vector3d>> VEC3D = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3fc>> VEC3F = new HashMap<>();
private static final Map<String, UnaryOperator<Vector3ic>> VEC3I = new HashMap<>();
private static final Map<String, UnaryOperator<Vector4fc>> VEC4F = new HashMap<>();
private static final Map<String, UnaryOperator<Matrix4fc>> MATRIX = new HashMap<>();
private static final Map<String, DoubleUnaryOperator> DOUBLE = new HashMap<>();
/** Every uniform that changes under the frame. */
public static final String[] UNIFORMS;
private static boolean active;
private static CameraUniforms.CameraPositionTracker tracker;
// Model to player space is T = V^-1 * M, linear part L and translation t. Everything below comes from that
private static final Matrix4f postfix = new Matrix4f();
private static final Matrix4f postfixInverse = new Matrix4f();
private static final Matrix3d linearInverse = new Matrix3d();
private static final Vector3d eye = new Vector3d();
private static final Vector3d modelCamera = new Vector3d();
private static final Vector3d modelOrigin = new Vector3d();
private static final Vector4f up = new Vector4f();
// What the remaps hand back. Like the suppliers they wrap (CameraUniforms and MatrixUniforms keep scratch objects
// too), a value is only good until the next remap runs. The cached uniforms in the input holder all copy it
// straight away, anything new that takes a wrapped supplier has to do the same
private static final Matrix4f scratch = new Matrix4f();
private static final Vector3d current = new Vector3d();
private static final Vector3d previous = new Vector3d();
private static final Vector3d point = new Vector3d();
private static final Vector3d offset = new Vector3d();
private static final Vector3d direction = new Vector3d();
private static final Vector3f offset3f = new Vector3f();
private static final Vector4f offset4f = new Vector4f();
static {
// World positions. The shifted ones keep Iris's shift, the unshifted ones read the real camera directly
VEC3D.put("cameraPosition", LocalGridFrame::camera);
DOUBLE.put("eyeAltitude", y -> Math.rint(y + modelOrigin.y) + modelCamera.y);
VEC3D.put("previousCameraPosition", real -> tracker == null ? real
: previousCamera(tracker.getCurrentCameraPosition(), real));
VEC3I.put("cameraPositionInt", real -> CameraUniforms.getCameraPositionInt(unshiftedCamera()));
VEC3F.put("cameraPositionFract", real -> CameraUniforms.getCameraPositionFract(unshiftedCamera()));
VEC3I.put("previousCameraPositionInt", real -> tracker == null ? real
: CameraUniforms.getCameraPositionInt(unshiftedPreviousCamera()));
VEC3F.put("previousCameraPositionFract", real -> tracker == null ? real
: CameraUniforms.getCameraPositionFract(unshiftedPreviousCamera()));
VEC3D.put("eyePosition", real -> worldPosition(CameraUniforms.getUnshiftedCameraPosition(), real));
// Offsets from the unshifted camera
VEC3D.put("relativeEyePosition", LocalGridFrame::offset);
VEC3D.put("relativeVehiclePosition", LocalGridFrame::offset);
// -256 on every axis means nothing is selected
VEC3F.put("currentSelectedBlockPos", real -> real.x() == -256.0f && real.y() == -256.0f && real.z() == -256.0f
? real : offset3f.set(offset(point.set(real.x(), real.y(), real.z()))));
// w is 0 when there's no bolt
VEC4F.put("lightningBoltPosition", real -> {
if (real.w() == 0.0f) return real;
final Vector3d moved = offset(point.set(real.x(), real.y(), real.z()));
return offset4f.set((float) moved.x, (float) moved.y, (float) moved.z, real.w());
});
// Directions in the world
VEC3D.put("playerLookVector", LocalGridFrame::direction);
VEC3D.put("playerBodyVector", LocalGridFrame::direction);
VEC3D.put("vehicleLookVector", LocalGridFrame::direction);
// View space, so only up changes
VEC4F.put("upPosition", real -> up);
// Matrices that take world space positions relative to the camera
MATRIX.put("gbufferModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferPreviousModelView", LocalGridFrame::modelView);
MATRIX.put("shadowModelView", LocalGridFrame::modelView);
MATRIX.put("gbufferModelViewInverse", LocalGridFrame::modelViewInverse);
MATRIX.put("shadowModelViewInverse", LocalGridFrame::modelViewInverse);
UNIFORMS = Stream.of(VEC3D, VEC3F, VEC3I, VEC4F, MATRIX, DOUBLE).flatMap(m -> m.keySet().stream())
.toArray(String[]::new);
}
private LocalGridFrame() {}
public static boolean isActive() {
return active;
}
/** The pipeline's camera tracker, for the uniforms that need the camera rather than their own value. */
static void trackCamera(CameraUniforms.CameraPositionTracker cameraTracker) {
tracker = cameraTracker;
}
/**
* @param drawModelView the modelview the geometry is drawn with
* @return false when it can't be done (a modelview that can't be inverted)
*/
public static boolean begin(Matrix4fc drawModelView) {
final Matrix4f view = new Matrix4f(MatrixUniforms.getGbufferModelView());
final Matrix4f viewInverse = new Matrix4f(view).invert();
final Matrix4f model = new Matrix4f(viewInverse).mul(drawModelView);
if (!Float.isFinite(model.determinant()) || Math.abs(model.determinant3x3()) < 1e-8f) return false;
// The camera's eye in player space, and in model space
eye.set(viewInverse.m30(), viewInverse.m31(), viewInverse.m32());
final Matrix3d linear = new Matrix3d(model.m00(), model.m01(), model.m02(), model.m10(), model.m11(),
model.m12(), model.m20(), model.m21(), model.m22());
linearInverse.set(linear).invert();
modelOrigin.set(model.m30(), model.m31(), model.m32());
modelCamera.set(eye).sub(modelOrigin);
linearInverse.transform(modelCamera);
// gbufferModelView' = V * translate(eye) * L, so V' * (p - camera) lands where M * p does
postfix.identity().translate((float) eye.x, (float) eye.y, (float) eye.z)
.mul(new Matrix4f().set3x3(model));
postfix.invert(postfixInverse);
// Model space up in view space, 100 long like the real upPosition
final Vector3f modelUp = model.transformDirection(new Vector3f(0, 1, 0)).normalize(100);
view.transformDirection(modelUp);
up.set(modelUp, 0);
active = true;
return true;
}
public static void end() {
active = false;
}
// The wrap methods are for the custom uniform input holder, each hands back the supplier with the remap applied
// while the frame is active, or the same supplier if that uniform doesn't change
public static Supplier<Vector3d> wrap3d(String name, Supplier<Vector3d> real) {
return wrap(VEC3D.get(name), real);
}
public static Supplier<Vector3fc> wrap3f(String name, Supplier<Vector3fc> real) {
return wrap(VEC3F.get(name), real);
}
public static Supplier<Vector3ic> wrap3i(String name, Supplier<Vector3ic> real) {
return wrap(VEC3I.get(name), real);
}
public static Supplier<Vector4fc> wrap4f(String name, Supplier<Vector4fc> real) {
return wrap(VEC4F.get(name), real);
}
public static Supplier<Matrix4fc> wrapMatrix(String name, Supplier<Matrix4fc> real) {
return wrap(MATRIX.get(name), real);
}
public static DoubleSupplier wrapDouble(String name, DoubleSupplier real) {
final DoubleUnaryOperator remap = DOUBLE.get(name);
if (remap == null) return real;
return () -> active ? remap.applyAsDouble(real.getAsDouble()) : real.getAsDouble();
}
private static <T> Supplier<T> wrap(UnaryOperator<T> remap, Supplier<T> real) {
if (remap == null) return real;
return () -> active ? remap.apply(real.get()) : real.get();
}
/** Where the model origin really is, rounded to whole blocks, so the frame's world stays near the real one. */
private static Vector3d shift(Vector3dc realCamera, Vector3d dest) {
return dest.set(
Math.rint(realCamera.x() + modelOrigin.x),
Math.rint(realCamera.y() + modelOrigin.y),
Math.rint(realCamera.z() + modelOrigin.z));
}
/** cameraPosition (or its unshifted twin) for a real one. */
private static Vector3d camera(Vector3d realCamera) {
return shift(realCamera, current).add(modelCamera);
}
private static Vector3d unshiftedCamera() {
return camera(CameraUniforms.getUnshiftedCameraPosition());
}
private static Vector3d unshiftedPreviousCamera() {
final Vector3d realPrevious = tracker.getPreviousCameraPositionUnshifted();
return previousCamera(CameraUniforms.getUnshiftedCameraPosition(), realPrevious);
}
/** previousCameraPosition, from the camera's last step turned into model space. */
private static Vector3d previousCamera(Vector3d realCamera, Vector3d realPrevious) {
previous.set(realCamera).sub(realPrevious);
linearInverse.transform(previous);
return previous.negate().add(camera(realCamera));
}
/** A real world position (eyePosition) moved into the frame's world, against the unshifted camera. */
private static Vector3d worldPosition(Vector3dc realCamera, Vector3dc realPosition) {
point.set(realPosition).sub(realCamera).sub(modelOrigin);
linearInverse.transform(point);
return shift(realCamera, current).add(point);
}
/**
* An offset from the unshifted camera (relativeEyePosition and co), as the same offset in the frame's world. Works
* out to {@link #worldPosition} minus the unshifted cameraPosition.
*/
private static Vector3d offset(Vector3d realOffset) {
return linearInverse.transform(offset.set(realOffset).sub(eye));
}
/** A world space direction turned into model space, same length. */
private static Vector3d direction(Vector3d real) {
final double length = real.length();
if (length == 0) return real;
return linearInverse.transform(direction.set(real)).normalize(length);
}
/** gbufferModelView, gbufferPreviousModelView or shadowModelView for a real one. */
private static Matrix4fc modelView(Matrix4fc real) {
return scratch.set(real).mul(postfix);
}
/** Their inverses, (R * P)^-1 = P^-1 * R^-1 for the real inverse. */
private static Matrix4fc modelViewInverse(Matrix4fc realInverse) {
return scratch.set(postfixInverse).mul(realInverse);
}
}
@@ -22,7 +22,7 @@ public final class MatrixUniforms {
} }
private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f(); private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f();
private static Matrix4fc getGbufferModelView() { static Matrix4fc getGbufferModelView() {
final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix(); final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix();
final Entity view = Minecraft.getMinecraft().renderViewEntity; final Entity view = Minecraft.getMinecraft().renderViewEntity;
if (view == null) { if (view == null) {
@@ -8,6 +8,7 @@ import net.coderbot.iris.gl.uniform.FloatSupplier;
import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformHolder;
import com.gtnewhorizons.angelica.glsm.shader.UniformType; import com.gtnewhorizons.angelica.glsm.shader.UniformType;
import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency;
import net.coderbot.iris.uniforms.LocalGridFrame;
import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform; import net.coderbot.iris.uniforms.custom.cached.BooleanCachedUniform;
import net.coderbot.iris.uniforms.custom.cached.CachedUniform; import net.coderbot.iris.uniforms.custom.cached.CachedUniform;
import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform; import net.coderbot.iris.uniforms.custom.cached.Float2VectorCachedUniform;
@@ -94,7 +95,8 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) { public Builder uniform1f(UniformUpdateFrequency updateFrequency, String name, DoubleSupplier value) {
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) value.getAsDouble())); final DoubleSupplier wrapped = LocalGridFrame.wrapDouble(name, value);
return this.put(name, new FloatCachedUniform(name, updateFrequency, () -> (float) wrapped.getAsDouble()));
} }
@Override @Override
@@ -119,11 +121,13 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3fc> value) { public Builder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3fc> value) {
value = LocalGridFrame.wrap3f(name, value);
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value)); return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, value));
} }
@Override @Override
public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3ic> value) { public Builder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3ic> value) {
value = LocalGridFrame.wrap3i(name, value);
return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value)); return this.put(name, new Int3VectorCachedUniform(name, updateFrequency, value));
} }
@@ -134,9 +138,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) { public Builder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector3f held = new Vector3f(); Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> { return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = value.get(); final Vector4fc vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z()); held.set(vec.x(), vec.y(), vec.z());
return held; return held;
})); }));
@@ -144,9 +149,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3d> value) { public UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector3d> value) {
final Supplier<Vector3d> wrapped = LocalGridFrame.wrap3d(name, value);
Vector3f held = new Vector3f(); Vector3f held = new Vector3f();
return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> { return this.put(name, new Float3VectorCachedUniform(name, updateFrequency, () -> {
Vector3d vec = value.get(); Vector3d vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z()); held.set(vec.x(), vec.y(), vec.z());
return held; return held;
})); }));
@@ -154,9 +160,10 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) { public UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier<Vector4fc> value) {
final Supplier<Vector4fc> wrapped = LocalGridFrame.wrap4f(name, value);
Vector4f held = new Vector4f(); Vector4f held = new Vector4f();
return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> { return this.put(name, new Float4VectorCachedUniform(name, updateFrequency, () -> {
final Vector4fc vec = value.get(); final Vector4fc vec = wrapped.get();
held.set(vec.x(), vec.y(), vec.z(), vec.w()); held.set(vec.x(), vec.y(), vec.z(), vec.w());
return held; return held;
})); }));
@@ -175,6 +182,7 @@ public class CustomUniformFixedInputUniformsHolder {
@Override @Override
public UniformHolder uniformMatrix( public UniformHolder uniformMatrix(
UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4fc> value) { UniformUpdateFrequency updateFrequency, String name, Supplier<Matrix4fc> value) {
value = LocalGridFrame.wrapMatrix(name, value);
return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value)); return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value));
} }
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more