diff --git a/README.MD b/README.MD index 594f8ce3b..0038a73df 100644 --- a/README.MD +++ b/README.MD @@ -50,6 +50,7 @@ Targets GL 3.3+ core profile * CodeChicken[Core](https://github.com/GTNewHorizons/CodeChickenCore/releases)/[Lib](https://github.com/GTNewHorizons/CodeChickenLib/releases) <1.2.0 - Threading issues, use 1.3.0+ * Neodymium - Untested, but unlikely to be compatible. (Chunk Meshing is definitely incompatible, other features might work depending on config) * SmoothFont - Equivalent functionality added +* ClientFixer - Use a resource pack like [GTNH-FTI-Standard-Font](https://github.com/Eldrinn-Elantey/GTNH-FTI-Standard-Font) # Credits * ShadersMod diff --git a/build.gradle.kts b/build.gradle.kts index 80dbd0b83..39188ae6e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,9 +1,14 @@ +import xyz.wagyourtail.jvmdg.gradle.flags.DowngradeFlags +import xyz.wagyourtail.jvmdg.gradle.task.DowngradeJar import xyz.wagyourtail.jvmdg.gradle.task.files.DowngradeFiles plugins { id("com.gtnewhorizons.gtnhconvention") } +tasks.withType().configureEach { logLevel.set("FATAL") } +tasks.withType().configureEach { logLevel.set("FATAL") } + minecraft { extraRunJvmArguments.add("-Dangelica.enableTestBlocks=true") extraRunJvmArguments.add("-Dangelica.dumpClass=true") diff --git a/dependencies.gradle b/dependencies.gradle index 71ab98681..e2b46f9c3 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -68,7 +68,7 @@ configurations.all { dependencies { compileOnly("com.github.GTNewHorizons:Hodgepodge:2.7.14:dev") - compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.0.7") { transitive = false } + compileOnly("com.gtnewhorizons.retrofuturabootstrap:RetroFuturaBootstrap:1.1.0") { transitive = false } // runtimeOnlyNonPublishable("com.github.GTNewHorizons:lwjgl3ify:3.0.99") compileOnly("org.projectlombok:lombok:1.18.42") { transitive = false } diff --git a/glsm/build.gradle.kts b/glsm/build.gradle.kts index be4a84be5..3610c5ee5 100644 --- a/glsm/build.gradle.kts +++ b/glsm/build.gradle.kts @@ -124,6 +124,7 @@ tasks.withType().configureEach { downgradeTo.set(JavaVersion.VERSION_1_8) multiReleaseOriginal.set(false) multiReleaseVersions.set(emptySet()) + logLevel.set("FATAL") } val downgradeDepsForTest by tasks.registering(DowngradeFiles::class) { @@ -139,6 +140,7 @@ val downgradeMainClasses by tasks.registering(DowngradeFiles::class) { val downgradeTestClasses by tasks.registering(DowngradeFiles::class) { inputCollection = sourceSets["test"].output.classesDirs classpath = sourceSets["test"].compileClasspath + sourceSets["test"].output.classesDirs.files.forEach { outputs.dir(temporaryDir.resolve(it.name)) } dependsOn(tasks.named("testClasses")) } @@ -174,6 +176,19 @@ tasks.test { jvmArgs("-Djava.library.path=${extractNatives.get().property("destinationFolder").let { (it as DirectoryProperty).asFile.get().path }}") } +val verifyTestsRan by tasks.registering { + val resultsDir = layout.buildDirectory.dir("test-results/test") + dependsOn(tasks.test) + doLast { + val dir = resultsDir.get().asFile + val xmls = dir.listFiles { f -> f.name.startsWith("TEST-") && f.name.endsWith(".xml") } ?: emptyArray() + check(xmls.isNotEmpty()) { + ":glsm:test produced no TEST-*.xml in $dir - test task likely went NO-SOURCE" + } + } +} +tasks.check { dependsOn(verifyTestsRan) } + publishing { publications { create("mavenJava") { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java index ca7983886..bb8b47650 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java @@ -11,6 +11,7 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import static com.gtnewhorizons.angelica.glsm.backend.BackendManager.RENDER_BACKEND; import org.joml.Matrix3f; import org.joml.Matrix4f; +import org.joml.Vector3f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; @@ -112,6 +113,7 @@ public class CompatUniformManager { private static final FloatBuffer clipPlaneBuf = BufferUtils.createFloatBuffer(32); // 8 planes * vec4 private static final Matrix3f normalMatrix = new Matrix3f(); private static final Matrix4f scratchMatrix = new Matrix4f(); + private static final Vector3f scratchCol = new Vector3f(); private static final float LIGHTMAP_SCALE = 1.0f / 256.0f; private static final FloatBuffer lightmapMatrixBuf; @@ -132,6 +134,16 @@ public class CompatUniformManager { private CompatUniformManager() {} + /** + * Normalize each column of a 3x3 matrix in place. Used to strip the residual 1/scale that + * inverse-transpose introduces. + */ + private static void normalizeColumnsInPlace(Matrix3f m) { + m.setColumn(0, m.getColumn(0, scratchCol).normalize()); + m.setColumn(1, m.getColumn(1, scratchCol).normalize()); + m.setColumn(2, m.getColumn(2, scratchCol).normalize()); + } + public static void onLinkProgram(int program) { int[] locs = new int[LOC_COUNT]; boolean hasAny = false; @@ -222,13 +234,17 @@ public class CompatUniformManager { // Normal Matrix (inverse-transpose of upper-left 3x3 of ModelView) if (locs[LOC_NORMAL] != -1 || locs[LOC_IRIS_NORMAL] != -1) { mv.normal(normalMatrix); - normalMatrix.get(mat3Buf); if (locs[LOC_NORMAL] != -1) { + normalMatrix.get(mat3Buf); RENDER_BACKEND.uniformMatrix3(locs[LOC_NORMAL], false, mat3Buf); } + // Column-normalized to unit magnitude if (locs[LOC_IRIS_NORMAL] != -1) { + normalizeColumnsInPlace(normalMatrix); + normalMatrix.get(mat3Buf); RENDER_BACKEND.uniformMatrix3(locs[LOC_IRIS_NORMAL], false, mat3Buf); } + } } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java index e1385bf87..37ee1ff69 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/FeedbackManager.java @@ -142,7 +142,7 @@ public class FeedbackManager { final int byteCount = count * stride; ensureReadbackCapacity(byteCount); readbackBuf.clear().limit(byteCount); - RENDER_BACKEND.getBufferSubData(GL15.GL_ARRAY_BUFFER, (long) first * stride + posOffset, readbackBuf); + readPositionBuffer((long) first * stride + posOffset, readbackBuf); emitAllPrimitives(mode, count, i -> i, stride); } @@ -170,7 +170,7 @@ public class FeedbackManager { final int byteCount = vertexCount * stride; ensureReadbackCapacity(byteCount); readbackBuf.clear().limit(byteCount); - RENDER_BACKEND.getBufferSubData(GL15.GL_ARRAY_BUFFER, (long) minIdx * stride + posOffset, readbackBuf); + readPositionBuffer((long) minIdx * stride + posOffset, readbackBuf); final int base = minIdx; emitAllPrimitives(mode, indexCount, i -> ImmediateModeRecorder.readIndex(indexBuf, type, 0, i) - base, stride); @@ -251,7 +251,23 @@ public class FeedbackManager { final int byteCount = vertexCount * stride; ensureReadbackCapacity(byteCount); readbackBuf.clear().limit(byteCount); - RENDER_BACKEND.getBufferSubData(GL15.GL_ARRAY_BUFFER, (long) minIdx * stride + posOffset, readbackBuf); + readPositionBuffer((long) minIdx * stride + posOffset, readbackBuf); + } + + private static void readPositionBuffer(long offset, ByteBuffer destination) { + final int positionVbo = VertexAttribState.get(0).vboId; + final int previousVbo = GLStateManager.getBoundVBO(); + + if (positionVbo != 0 && positionVbo != previousVbo) { + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, positionVbo); + } + try { + RENDER_BACKEND.getBufferSubData(GL15.GL_ARRAY_BUFFER, offset, destination); + } finally { + if (positionVbo != 0 && positionVbo != previousVbo) { + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, previousVbo); + } + } } private static void emitVertex(int vertexIndex, int stride) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index 491bcbd46..80f282ffa 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -150,15 +150,43 @@ public class GLStateManager { public static int projGeneration; // projection matrix changes public static int texMatrixGeneration; // texture matrix changes public static int lightingGeneration; - public static int fragmentGeneration; // fog + alpha ref + public static int fragmentGeneration; // fog + alpha ref + overlay color public static int colorGeneration; // current vertex color public static int clipPlaneGeneration; // clip plane equation changes + @Getter private static float overlayR = 0.0f; + @Getter private static float overlayG = 0.0f; + @Getter private static float overlayB = 0.0f; + @Getter private static float overlayA = 0.0f; + + public static void setOverlayColor(float r, float g, float b, float a) { + if (r == overlayR && g == overlayG && b == overlayB && a == overlayA) return; + overlayR = r; overlayG = g; overlayB = b; overlayA = a; + fragmentGeneration++; + } + + @Getter private static float shaderColorR = 1.0f; + @Getter private static float shaderColorG = 1.0f; + @Getter private static float shaderColorB = 1.0f; + @Getter private static float shaderColorA = 1.0f; + + public static void setShaderColor(float r, float g, float b, float a) { + if (r == shaderColorR && g == shaderColorG && b == shaderColorB && a == shaderColorA) return; + shaderColorR = r; shaderColorG = g; shaderColorB = b; shaderColorA = a; + if (GLSMHooks.SHADER_COLOR_CHANGE.hasListeners()) { + GLSMHooks.shaderColorChangeEvent.red = r; + GLSMHooks.shaderColorChangeEvent.green = g; + GLSMHooks.shaderColorChangeEvent.blue = b; + GLSMHooks.shaderColorChangeEvent.alpha = a; + GLSMHooks.SHADER_COLOR_CHANGE.post(GLSMHooks.shaderColorChangeEvent); + } + } + // Deferred vertex attribute upload flags — set when state changes, flushed before draw - private static boolean dirtyColorAttrib; + private static boolean dirtyColorAttrib = true; private static boolean dirtyNormalAttrib; private static boolean dirtyTexCoordAttrib; - private static boolean dirtyLightmapAttrib; + private static boolean dirtyLightmapAttrib = true; /** Flush deferred vertex attribute uploads. Called before draw to ensure default attrib values are current. */ public static void flushDeferredVertexAttribs() { @@ -1997,7 +2025,14 @@ public class GLStateManager { } } - /** Shrink texture to 1x1 to free GPU memory, unbind from all units, but keep the name valid. */ + /** + * Defer deleting textures until it has been reclaimed. + * Why you might ask? In compat profile if you bind a texture that doesn't exist, ie a deleted texture, + * mesa will silently create it for you, in core this is an error. Why would you be binding a deleted texture? + * Damned if I know, but vanilla and mods do it... they create one, delete it, and then bind it.... + * + * So... we shrink the texture to 1x1 to free GPU memory, unbind from all units, but keep the name valid. + * */ private static void deferDeleteTexture(int id) { if (id == 0) return; @@ -3903,7 +3938,12 @@ public class GLStateManager { return switch (pname) { case GL11.GL_TEXTURE_WIDTH -> info.getWidth(); case GL11.GL_TEXTURE_HEIGHT -> info.getHeight(); - case GL11.GL_TEXTURE_INTERNAL_FORMAT -> info.getInternalFormat(); + case GL11.GL_TEXTURE_INTERNAL_FORMAT -> { + if (info.needsInternalFormatResolve() && isRecordingDisplayList()) { + throw new IllegalStateException(String.format("glGetTexLevelParameteri(GL_TEXTURE_INTERNAL_FORMAT) needs to resolve a generic compressed format for texture %d during display list recording", getBoundTextureForServerState())); + } + yield info.getResolvedInternalFormat(); + } default -> { if (isRecordingDisplayList()) { throw new IllegalStateException(String.format( diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java index 8a5153e55..566152e2a 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java @@ -12,7 +12,7 @@ import org.lwjgl.opengl.GL13; * Packed-long fragment shader permutation key for FFP emulation. * * Layout: - * long[0]: global bits (10) + unit 0 (47 bits at offset 10) + * long[0]: global bits (11) + unit 0 (47 bits at offset 11) * long[1..3]: unit 1..3 (47 bits each, low-aligned) * Only max(1, nrEnabledUnits) longs are significant. * @@ -63,12 +63,13 @@ public final class FragmentKey { public static final int FOG_EXP = 2; public static final int FOG_EXP2 = 3; - private static final int GLOBAL_BITS = 10; + private static final int GLOBAL_BITS = 11; private static final int BIT_FOG_MODE = 0; // 2 bits private static final int BIT_ALPHA_TEST = 2; // 1 bit private static final int BIT_ALPHA_FUNC = 3; // 3 bits private static final int BIT_SEPARATE_SPECULAR = 6; // 1 bit private static final int BIT_NR_ENABLED_UNITS = 7; // 3 bits + private static final int BIT_OVERLAY_ENABLED = 10; // 1 bit private static final int U_ENABLED = 0; private static final int U_MODE = 1; // 3 bits @@ -119,6 +120,11 @@ public final class FragmentKey { global |= ((long) (encodeAlphaFunc(GLStateManager.getAlphaState().getFunction()) & 0x7)) << BIT_ALPHA_FUNC; } + // Damage overlay + if (GLStateManager.getOverlayA() != 0.0f) { + global |= (1L << BIT_OVERLAY_ENABLED); + } + // Separate specular if (GLStateManager.getLightingState().isEnabled() && GLStateManager.getLightModel().colorControl == GL12.GL_SEPARATE_SPECULAR_COLOR) { @@ -227,6 +233,7 @@ public final class FragmentKey { public int alphaTestFunc() { return (int) ((packed[0] >> BIT_ALPHA_FUNC) & 0x7); } public boolean separateSpecular() { return ((packed[0] >> BIT_SEPARATE_SPECULAR) & 1) != 0; } public int nrEnabledUnits() { return (int) ((packed[0] >> BIT_NR_ENABLED_UNITS) & 0x7); } + public boolean overlayEnabled() { return ((packed[0] >> BIT_OVERLAY_ENABLED) & 1) != 0; } private long unitBits(int i) { return (i == 0) ? (packed[0] >>> GLOBAL_BITS) : packed[i]; @@ -252,6 +259,28 @@ public final class FragmentKey { return false; } + /** Per-unit enable bits as a 4-bit mask (bit i = unit i enabled). */ + public int enabledUnitMask() { + int mask = 0; + final int n = Math.min(nrEnabledUnits(), MAX_UNITS); + for (int i = 0; i < n; i++) { + if (unitEnabled(i)) mask |= (1 << i); + } + return mask; + } + + /** Per-unit enable bits from a packed scratch as a 4-bit mask (bit i = unit i enabled). */ + public static int unitMaskFromPacked(long[] packed, int len) { + int mask = 0; + if (len < 1) return 0; + if (((packed[0] >>> GLOBAL_BITS) & 1L) != 0) mask |= 1; + final int n = Math.min(len, MAX_UNITS); + for (int i = 1; i < n; i++) { + if ((packed[i] & 1L) != 0) mask |= (1 << i); + } + return mask; + } + public boolean lightmapEnabled() { return nrEnabledUnits() > 1 && unitEnabled(1); } @@ -338,10 +367,10 @@ public final class FragmentKey { default -> "?"; }; final StringBuilder sb = new StringBuilder(); - sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b units=%d", + sb.append(String.format("FFPFragmentKey[fog=%s alpha=%b(%s) specSep=%b overlay=%b units=%d", fogName, alphaTestEnabled(), alphaTestEnabled() ? String.format("0x%04X", decodeAlphaFunc(alphaTestFunc())) : "-", - separateSpecular(), nrEnabledUnits())); + separateSpecular(), overlayEnabled(), nrEnabledUnits())); for (int i = 0; i < nrEnabledUnits(); i++) { if (!unitEnabled(i)) { sb.append(String.format(" u%d=OFF", i)); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java index 66ea1fb97..2eb874cfd 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java @@ -65,6 +65,9 @@ public final class FragmentShaderGenerator { sb.append("uniform vec4 u_TexEnvColor").append(i).append(";\n"); } } + if (key.overlayEnabled()) { + sb.append("uniform vec4 u_OverlayColor;\n"); + } if (key.fogMode() != FragmentKey.FOG_NONE) { sb.append("uniform vec4 u_FogParams;\n"); sb.append("uniform vec4 u_FogColor;\n"); @@ -83,14 +86,21 @@ public final class FragmentShaderGenerator { if (!key.textureEnabled()) { sb.append(" // No texture -- vertex color only\n"); sb.append(" vec4 color = v_Color;\n"); + emitOverlay(sb, key); return; } - // Process units in order; "previous" starts as vertex color + // Process units in order; "previous" starts as vertex color. boolean firstUnit = true; + boolean overlayInjected = false; for (int i = 0; i < key.nrEnabledUnits(); i++) { if (!key.unitEnabled(i)) continue; + if (!firstUnit && !overlayInjected) { + emitOverlay(sb, key); + overlayInjected = true; + } + final String texVar = "tex" + i + "Color"; final String envColorVar = "u_TexEnvColor" + i; final String prevVar = firstUnit ? "v_Color" : "color"; @@ -103,6 +113,16 @@ public final class FragmentShaderGenerator { } firstUnit = false; } + + if (!overlayInjected) emitOverlay(sb, key); + } + + /** + * Emit the modern-style damage overlay mix. + */ + private static void emitOverlay(StringBuilder sb, FragmentKey key) { + if (!key.overlayEnabled()) return; + sb.append(" color.rgb = mix(color.rgb, u_OverlayColor.rgb, u_OverlayColor.a);\n"); } private static void emitSimpleUnit(StringBuilder sb, FragmentKey key, int unit, String texVar, String envColorVar, String prevVar, String assign) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java index c6af3bc3c..c31bde665 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java @@ -92,6 +92,7 @@ public class Program { public final int[] locSampler = { -1, -1, -1, -1 }; public int locAlphaRef = -1; public final int[] locTexEnvColor = { -1, -1, -1, -1 }; + public int locOverlayColor = -1; public int locFogParams = -1; public int locFogColor = -1; @@ -171,6 +172,7 @@ public class Program { for (int i = 0; i < 4; i++) { locTexEnvColor[i] = loc("u_TexEnvColor" + i); } + locOverlayColor = loc("u_OverlayColor"); locFogParams = loc("u_FogParams"); locFogColor = loc("u_FogColor"); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java index a8eb6bef0..a544f18ab 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java @@ -116,8 +116,9 @@ public class ShaderManager { } } - final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap); final int fkLen = FragmentKey.packFromState(currentFKScratch); + final int fragMask = FragmentKey.unitMaskFromPacked(currentFKScratch, fkLen); + final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap, fragMask); if (vkPacked != currentVertexKeyPacked || !Arrays.equals(currentFKScratch, 0, fkLen, currentFKPacked, 0, currentFKLen)) { commitVariant(vkPacked, fkLen); @@ -141,8 +142,9 @@ public class ShaderManager { } private void updateVariant(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { - final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap); final int fkLen = FragmentKey.packFromState(currentFKScratch); + final int fragMask = FragmentKey.unitMaskFromPacked(currentFKScratch, fkLen); + final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap, fragMask); commitVariant(vkPacked, fkLen); } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java index 40aaf6a0f..38384ebe7 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java @@ -422,6 +422,16 @@ public class Uniforms { } } + if (fk.overlayEnabled() && program.locOverlayColor != -1) { + vec4Buf.clear(); + vec4Buf.put(GLStateManager.getOverlayR()); + vec4Buf.put(GLStateManager.getOverlayG()); + vec4Buf.put(GLStateManager.getOverlayB()); + vec4Buf.put(GLStateManager.getOverlayA()); + vec4Buf.flip(); + RENDER_BACKEND.uniform4(program.locOverlayColor, vec4Buf); + } + // Fog if (fk.fogMode() != FragmentKey.FOG_NONE) { uploadFog(program); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java index 1a2be6391..9576f7e30 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -123,7 +123,7 @@ public final class VertexKey { }; } - public static long packFromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { + public static long packFromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap, int fragUnitMask) { long bits = 0; final boolean lighting = GLStateManager.getLightingState().isEnabled(); @@ -170,7 +170,7 @@ public final class VertexKey { final TextureUnitArray texUnit = GLStateManager.getTextures(); for (int i = 0; i < MAX_UNITS; i++) { - if (texUnit.getTextureUnitStates(i).isEnabled()) { + if ((fragUnitMask & (1 << i)) != 0) { bits |= (1L << (BIT_UNIT_TEX_BASE + i)); } if (!MatrixHelper.isIdentity(texUnit.getTextureUnitMatrix(i))) { @@ -224,8 +224,8 @@ public final class VertexKey { return bits; } - public static VertexKey fromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { - return new VertexKey(packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap)); + public static VertexKey fromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap, int fragUnitMask) { + return new VertexKey(packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap, fragUnitMask)); } static VertexKey fromPacked(long packed) { diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java index b68e4553c..c2e27ee82 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/GLSMHooks.java @@ -19,6 +19,7 @@ public final class GLSMHooks { public static final EventBus LIGHTMAP_COORDS = EventBus.create(LightmapCoordsEvent.class); public static final EventBus ALPHA_STATE_CHANGE = EventBus.create(AlphaStateChangeEvent.class); public static final EventBus SPLASH_DESTROY = EventBus.create(SplashDestroyEvent.class); + public static final EventBus SHADER_COLOR_CHANGE = EventBus.create(ShaderColorChangeEvent.class); // Reusable event instances public static final TextureBindEvent textureBindEvent = new TextureBindEvent(); @@ -29,6 +30,7 @@ public final class GLSMHooks { public static final FogStateChangeEvent fogStateChangeEvent = new FogStateChangeEvent(); public static final LightmapCoordsEvent lightmapCoordsEvent = new LightmapCoordsEvent(); public static final AlphaStateChangeEvent alphaStateChangeEvent = new AlphaStateChangeEvent(); + public static final ShaderColorChangeEvent shaderColorChangeEvent = new ShaderColorChangeEvent(); private GLSMHooks() {} } diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ShaderColorChangeEvent.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ShaderColorChangeEvent.java new file mode 100644 index 000000000..c19632f95 --- /dev/null +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/hooks/events/ShaderColorChangeEvent.java @@ -0,0 +1,10 @@ +package com.gtnewhorizons.angelica.glsm.hooks.events; + +import net.minecraftforge.eventbus.api.event.MutableEvent; + +public final class ShaderColorChangeEvent extends MutableEvent { + public float red; + public float green; + public float blue; + public float alpha; +} diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java index 70b05de79..b238e0ec4 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfo.java @@ -9,6 +9,7 @@ public class TextureInfo { @Getter protected final int id; protected int internalFormat = -1; + protected int resolvedInternalFormat = -1; protected int width = -1; protected int height = -1; @@ -34,6 +35,17 @@ public class TextureInfo { return internalFormat; } + public int getResolvedInternalFormat() { + if (resolvedInternalFormat == -1) { + resolvedInternalFormat = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + } + return resolvedInternalFormat; + } + + public boolean needsInternalFormatResolve() { + return resolvedInternalFormat == -1; + } + public int getWidth() { if (width == -1) { width = RenderSystem.getTexLevelParameteri(id, 0, GL11.GL_TEXTURE_WIDTH); diff --git a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java index 5fa290a80..7d3f2e416 100644 --- a/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java +++ b/glsm/src/main/java/com/gtnewhorizons/angelica/glsm/texture/TextureInfoCache.java @@ -5,6 +5,9 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL21; +import org.lwjgl.opengl.GL30; import java.nio.Buffer; import java.util.concurrent.locks.ReentrantLock; @@ -45,6 +48,7 @@ public class TextureInfoCache { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; info.internalFormat = internalformat; + info.resolvedInternalFormat = isGenericCompressedInternalFormat(internalformat) ? -1 : internalformat; info.width = width; info.height = height; } @@ -55,11 +59,24 @@ public class TextureInfoCache { final TextureInfo info = getInfo(GLStateManager.getBoundTextureForServerState()); if (info == null) return; info.internalFormat = internalformat; + info.resolvedInternalFormat = isGenericCompressedInternalFormat(internalformat) ? -1 : internalformat; info.width = width; info.height = height; } } + public static boolean isGenericCompressedInternalFormat(int internalFormat) { + return switch (internalFormat) { + case GL30.GL_COMPRESSED_RED, + GL30.GL_COMPRESSED_RG, + GL13.GL_COMPRESSED_RGB, + GL13.GL_COMPRESSED_RGBA, + GL21.GL_COMPRESSED_SRGB, + GL21.GL_COMPRESSED_SRGB_ALPHA -> true; + default -> false; + }; + } + public void onDeleteTexture(int id) { if (id < 0) return; diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java index e48de33ed..d6f9b0695 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_TextureInfoCache_UnitTest.java @@ -6,6 +6,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL21; +import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.EXTTextureCompressionS3TC; import java.lang.reflect.Field; import java.nio.ByteBuffer; @@ -15,6 +19,98 @@ import static org.junit.jupiter.api.Assertions.*; @ExtendWith(GLSMExtension.class) public class GLSM_TextureInfoCache_UnitTest { + @Test + void testGenericCompressedUploadResolvesToSpecificFormat() { + int texId = GL11.glGenTextures(); + try { + GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId); + ByteBuffer pixels = BufferUtils.createByteBuffer(64 * 64 * 4); + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL13.GL_COMPRESSED_RGBA, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + + int format = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + assertNotEquals(-1, format); + assertNotEquals(GL30.GL_COMPRESSED_RED, format); + assertNotEquals(GL30.GL_COMPRESSED_RG, format); + assertNotEquals(GL13.GL_COMPRESSED_RGB, format); + assertNotEquals(GL13.GL_COMPRESSED_RGBA, format); + assertNotEquals(GL21.GL_COMPRESSED_SRGB, format); + assertNotEquals(GL21.GL_COMPRESSED_SRGB_ALPHA, format); + } finally { + GL11.glDeleteTextures(texId); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + } + } + + @Test + void testNonGenericUploadCachesWithoutRoundtrip() { + int texId = GL11.glGenTextures(); + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + ByteBuffer pixels = BufferUtils.createByteBuffer(64 * 64 * 4); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + + TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texId); + assertFalse(info.needsInternalFormatResolve()); + assertEquals(GL11.GL_RGBA8, info.getResolvedInternalFormat()); + assertEquals(GL11.GL_RGBA8, GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT)); + } finally { + GL11.glDeleteTextures(texId); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + } + } + + @Test + void testGenericCompressedPreservesAsPassedInternalFormat() { + int texId = GL11.glGenTextures(); + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + ByteBuffer pixels = BufferUtils.createByteBuffer(64 * 64 * 4); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL13.GL_COMPRESSED_RGBA, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + + TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texId); + assertEquals(GL13.GL_COMPRESSED_RGBA, info.getInternalFormat()); + assertTrue(info.needsInternalFormatResolve()); + } finally { + GL11.glDeleteTextures(texId); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + } + } + + @Test + void testRepeatedQueryAfterResolveUsesCache() { + int texId = GL11.glGenTextures(); + try { + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texId); + ByteBuffer pixels = BufferUtils.createByteBuffer(64 * 64 * 4); + GLStateManager.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL13.GL_COMPRESSED_RGBA, 64, 64, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels); + + TextureInfo info = TextureInfoCache.INSTANCE.getInfo(texId); + assertTrue(info.needsInternalFormatResolve()); + int first = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + assertFalse(info.needsInternalFormatResolve()); + int second = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_INTERNAL_FORMAT); + assertEquals(first, second); + } finally { + GL11.glDeleteTextures(texId); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); + } + } + + @Test + void testIsGenericCompressedInternalFormatHelper() { + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL30.GL_COMPRESSED_RED)); + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL30.GL_COMPRESSED_RG)); + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL13.GL_COMPRESSED_RGB)); + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL13.GL_COMPRESSED_RGBA)); + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL21.GL_COMPRESSED_SRGB)); + assertTrue(TextureInfoCache.isGenericCompressedInternalFormat(GL21.GL_COMPRESSED_SRGB_ALPHA)); + assertFalse(TextureInfoCache.isGenericCompressedInternalFormat(GL11.GL_RGBA)); + assertFalse(TextureInfoCache.isGenericCompressedInternalFormat(GL11.GL_RGBA8)); + assertFalse(TextureInfoCache.isGenericCompressedInternalFormat(EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)); + assertFalse(TextureInfoCache.isGenericCompressedInternalFormat(0)); + assertFalse(TextureInfoCache.isGenericCompressedInternalFormat(-1)); + } + /** * Texture deletion is server-side; cache must be invalidated regardless of client caching state. */ diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SharedDrawableVaoTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SharedDrawableVaoTest.java index 7402231ea..e6c404f4d 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SharedDrawableVaoTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/SharedDrawableVaoTest.java @@ -21,6 +21,8 @@ class SharedDrawableVaoTest { private static final String VERT_330 = "#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n"; private static final String FRAG_330 = "#version 330 core\nout vec4 o;\nvoid main() { o = vec4(0.0); }\n"; + private static boolean ownsDisplay = false; + @BeforeAll static void createContext() throws LWJGLException { assumeTrue(!Display.isCreated(), "inherited Display -- skipping to avoid profile drift"); @@ -31,11 +33,13 @@ class SharedDrawableVaoTest { new PixelFormat().withDepthBits(24).withStencilBits(8), new ContextAttribs(4, 1).withProfileCore(true).withForwardCompatible(true)); GL30.glBindVertexArray(GL30.glGenVertexArrays()); + ownsDisplay = true; } @AfterAll static void destroyContext() { - if (Display.isCreated()) Display.destroy(); + if (ownsDisplay && Display.isCreated()) Display.destroy(); + ownsDisplay = false; } @Test diff --git a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPCombineShaderTest.java b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPCombineShaderTest.java index c038f6bfe..ba287cd6c 100644 --- a/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPCombineShaderTest.java +++ b/glsm/src/test/java/com/gtnewhorizons/angelica/glsm/ffp/FFPCombineShaderTest.java @@ -128,7 +128,7 @@ class FFPCombineShaderTest { setupXaeroState(); FragmentKey fk = FragmentKey.fromState(); - VertexKey vk = VertexKey.fromState(true, false, true, false); + VertexKey vk = VertexKey.fromState(true, false, true, false, fk.enabledUnitMask()); String fragSource = FragmentShaderGenerator.generate(fk); String vertSource = VertexShaderGenerator.generate(vk); diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java index fd791ca45..41077abf4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -354,6 +354,9 @@ public final class BatchingFontRenderer { boolean curDinnerbone = false; boolean curGradient = false; FontOverlayShader curShader = null; + boolean curShadow = false; + boolean curShadowCustomColor = false; + int curShadowColorOverride = 0; int gradientStartRgb = 0, gradientEndRgb = 0; int gradientCharIndex = 0, gradientTotalChars = 0; float gradientStep = 0f; @@ -473,6 +476,20 @@ public final class BatchingFontRenderer { curDinnerbone = !curDinnerbone; } } + case 'u' -> { + int customRgb = (charIdx + SECTION_X_LENGTH < stringEnd) + ? ColorCodeUtils.parseSectionXAt(string, charIdx + 1) + : -1; + if (customRgb != -1) { + curShadow = true; + curShadowCustomColor = true; + curShadowColorOverride = customRgb; + charIdx += SECTION_X_LENGTH; + } else { + curShadow = !curShadow; + if (!curShadow) curShadowCustomColor = false; + } + } case 'g' -> { if (AngelicaConfig.enableGradients && charIdx + GRADIENT_PAYLOAD < stringEnd) { int color1 = ColorCodeUtils.parseSectionXAt(string, charIdx + 1); @@ -499,6 +516,8 @@ public final class BatchingFontRenderer { curWave = false; curDinnerbone = false; curGradient = false; + curShadow = false; + curShadowCustomColor = false; curColor = color; curShadowColor = shadowColor; if (curShader != null) { @@ -522,6 +541,8 @@ public final class BatchingFontRenderer { int flags = (curItalic ? FLAG_ITALIC : 0) | (curDinnerbone ? FLAG_DINNERBONE : 0); + if (chr == ColorCodeUtils.ESCAPED_AMPERSAND) { chr = '&'; } + final FontTextureArray fontProvider; if (this.overrideTextureArray != null) { fontProvider = overrideTextureArray; @@ -608,12 +629,16 @@ public final class BatchingFontRenderer { continue; } - if (enableShadow) { + final boolean drawShadow = enableShadow || curShadow; + if (drawShadow) { + final int effectiveShadowColor = curShadowCustomColor + ? ((curColor & 0xFF000000) | (curShadowColorOverride & 0x00FFFFFF)) + : curShadowColor; pushQuad( curX + shadowOffset, renderY + shadowOffset, glyphW - 1, heightSouth, uStart, vStart, uSize, vSize, - curShadowColor, + effectiveShadowColor, layer, flags ); @@ -758,6 +783,7 @@ public final class BatchingFontRenderer { } public float getCharWidthFine(char chr) { + if (chr == ColorCodeUtils.ESCAPED_AMPERSAND) { chr = '&'; } if (chr == FORMATTING_CHAR) { return -1; } if (chr == ' ' || chr == '\u00A0' || chr == '\u202F') { diff --git a/src/main/java/com/gtnewhorizons/angelica/client/font/ColorCodeUtils.java b/src/main/java/com/gtnewhorizons/angelica/client/font/ColorCodeUtils.java index a5d0230ce..d4fe59b98 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/ColorCodeUtils.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/ColorCodeUtils.java @@ -18,6 +18,7 @@ public final class ColorCodeUtils { private ColorCodeUtils() {} public static final char FORMATTING_CHAR = '§'; + public static final char ESCAPED_AMPERSAND = ''; public static final int SECTION_X_PAYLOAD = 12; public static final int SECTION_X_LENGTH = 14; @@ -25,7 +26,7 @@ public final class ColorCodeUtils { public static final int GRADIENT_LENGTH = 30; /** Valid single {@code &} codes. {@code g} is excluded; {@code &g} only converts as part of a gradient. */ - public static final String VALID_SINGLE_CODES = "0123456789abcdefklmnorqvyz"; + public static final String VALID_SINGLE_CODES = "0123456789abcdefklmnorqzvuy"; private static final String[] SECTION_PREFIX = new String[128]; static { @@ -87,6 +88,14 @@ public final class ColorCodeUtils { StringBuilder sb = null; int last = 0; while (idx != -1 && idx + 1 < len) { + if (idx > 0 && text.charAt(idx - 1) == '\\') { + if (sb == null) sb = new StringBuilder(len + 16); + sb.append(text, last, idx - 1); + sb.append(ESCAPED_AMPERSAND); + last = idx + 1; + idx = text.indexOf('&', last); + continue; + } if (text.charAt(idx + 1) == '#' && idx + 7 < len) { boolean validHex = true; for (int i = 2; i <= 7; i++) { diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 537a441a8..f152c6ba4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -132,6 +132,10 @@ public class AngelicaConfig { @Config.DefaultBoolean(true) public static boolean enableDinnerboneText; + @Config.Comment("Enable per-segment drop shadow toggle (&u) and colored shadow (&u&#RRGGBB)") + @Config.DefaultBoolean(true) + public static boolean enableDropShadow; + @Config.Comment("Wave text amplitude (how far characters bounce)") @Config.DefaultFloat(2.0f) @Config.RangeFloat(min = 1.0f, max = 8.0f) diff --git a/src/main/java/com/gtnewhorizons/angelica/event/ChunkBiomeDataChangedEvent.java b/src/main/java/com/gtnewhorizons/angelica/event/ChunkBiomeDataChangedEvent.java new file mode 100644 index 000000000..a3a6c8fbc --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/event/ChunkBiomeDataChangedEvent.java @@ -0,0 +1,21 @@ +package com.gtnewhorizons.angelica.event; + +import net.minecraftforge.eventbus.api.bus.EventBus; +import net.minecraftforge.eventbus.api.event.MutableEvent; + +public final class ChunkBiomeDataChangedEvent extends MutableEvent { + + public static final EventBus BUS = EventBus.create(ChunkBiomeDataChangedEvent.class); + + private static final ChunkBiomeDataChangedEvent INSTANCE = new ChunkBiomeDataChangedEvent(); + + public int chunkX; + public int chunkZ; + + public static void post(int chunkX, int chunkZ) { + if (!BUS.hasListeners()) return; + INSTANCE.chunkX = chunkX; + INSTANCE.chunkZ = chunkZ; + BUS.post(INSTANCE); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/event/RenderHandEvent.java b/src/main/java/com/gtnewhorizons/angelica/event/RenderHandEvent.java new file mode 100644 index 000000000..9b10c73d4 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/event/RenderHandEvent.java @@ -0,0 +1,25 @@ +package com.gtnewhorizons.angelica.event; + +import net.minecraftforge.eventbus.api.bus.CancellableEventBus; +import net.minecraftforge.eventbus.api.event.RecordEvent; +import net.minecraftforge.eventbus.api.event.characteristic.Cancellable; + +/** + * Posted from {@link net.coderbot.iris.pipeline.HandRenderer}'s {@code canRender} + *

+ * Cancel the event to prevent the hand from rendering. + */ +public record RenderHandEvent() implements RecordEvent, Cancellable { + + public static final CancellableEventBus BUS = CancellableEventBus.create(RenderHandEvent.class); + + private static final RenderHandEvent INSTANCE = new RenderHandEvent(); + + /** + * @return true if a listener cancelled the event, meaning the hand should NOT render. + */ + public static boolean post() { + if (!BUS.hasListeners()) return false; + return BUS.post(INSTANCE); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java index 33c246a94..cb149a240 100644 --- a/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java +++ b/src/main/java/com/gtnewhorizons/angelica/iris/IrisGLSMBridge.java @@ -26,6 +26,7 @@ public class IrisGLSMBridge { private static Runnable fogStartListener = null; private static Runnable fogEndListener = null; private static Runnable fogDensityListener = null; + private static Runnable colorModulatorListener = null; static { StateUpdateNotifiers.alphaFuncNotifier = listener -> alphaFuncListener = listener; @@ -35,6 +36,7 @@ public class IrisGLSMBridge { StateUpdateNotifiers.fogStartNotifier = listener -> fogStartListener = listener; StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener; StateUpdateNotifiers.fogDensityNotifier = listener -> fogDensityListener = listener; + StateUpdateNotifiers.colorModulatorNotifier = listener -> colorModulatorListener = listener; } public static void register() { @@ -108,6 +110,10 @@ public class IrisGLSMBridge { } }); + GLSMHooks.SHADER_COLOR_CHANGE.addListener(event -> { + if (Iris.enabled && colorModulatorListener != null) colorModulatorListener.run(); + }); + GLSMHooks.FOG_STATE_CHANGE.addListener(event -> { if (Iris.enabled) { if (fogModeListener != null) fogModeListener.run(); @@ -157,17 +163,17 @@ public class IrisGLSMBridge { GLSMHooks.PROGRAM_CHANGE.addListener(event -> { if (!Iris.enabled) return; if (event.postBind) return; - + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (!(pipeline instanceof DeferredWorldRenderingPipeline drp)) return; if (!drp.shouldOverrideShaders()) return; if (drp.getActivePassProgramId() == -1) return; - + if (DepthColorStorage.isOwnedProgram(event.newProgram)) { DepthColorStorage.unlockDepthColor(); } }); - + GLSMHooks.PROGRAM_CHANGE.addListener(event -> { if (!Iris.enabled) return; if (!event.postBind) return; diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java index 9acf5084c..a7f452a6e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/AngelicaClientTweaker.java @@ -53,8 +53,15 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix Launch.classLoader.addTransformerExclusion("com.gtnewhorizons.angelica.loading"); Launch.classLoader.addTransformerExclusion("com.gtnewhorizons.angelica.glsm.GLStateManager"); - if (Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE) { + final boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE; + if (rfbLoaded) { addLwjgl3ifyExclusions(); + } else { + // Fucking java 8 and non RFB + try { + Class.forName("com.gtnewhorizon.gtnhlib.core.GTNHLibCore", true, Launch.classLoader); + } catch (ClassNotFoundException ignored) { + } } try { @@ -84,7 +91,6 @@ public final class AngelicaClientTweaker implements IFMLLoadingPlugin, IEarlyMix // packages to avoid interfering with mixin delegation on game classes. AngelicaLateTweaker removes this registration once // mixins are setup. if (FMLLaunchHandler.side().isClient()) { - final boolean rfbLoaded = Launch.blackboard.getOrDefault("angelica.rfbPluginLoaded", Boolean.FALSE) == Boolean.TRUE; if (!rfbLoaded) { final String transformer = "com.gtnewhorizons.angelica.loading.fml.transformers.EarlyRedirectorTransformer"; FMLRelaunchLog.finer("Registering transformer %s", transformer); diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java index 437b208af..ca06665bc 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBAngelicaRedirector.java @@ -52,12 +52,20 @@ public class RFBAngelicaRedirector implements RfbClassTransformer { } @Override - public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, - @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, + @NotNull String className, @NotNull ClassNodeHandle classNode) { final boolean changed = inner.transformClassNode(className, classNode.getNode()); if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); } + return changed; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + transformClassIfNeeded(classLoader, context, manifest, className, classNode); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBCeleritasBlockTransformer.java b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBCeleritasBlockTransformer.java index bfc63357e..eff33fe73 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBCeleritasBlockTransformer.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBCeleritasBlockTransformer.java @@ -59,12 +59,20 @@ public class RFBCeleritasBlockTransformer implements RfbClassTransformer { } @Override - public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, - @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, + @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, + @NotNull String className, @NotNull ClassNodeHandle classNode) { final boolean changed = inner.transformClassNode(className, classNode.getNode()); if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); } + return changed; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + transformClassIfNeeded(classLoader, context, manifest, className, classNode); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBIsbrhTessellatorAbuseTransformer.java b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBIsbrhTessellatorAbuseTransformer.java index d21c40fe3..37178da30 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBIsbrhTessellatorAbuseTransformer.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/rfb/transformers/RFBIsbrhTessellatorAbuseTransformer.java @@ -49,11 +49,19 @@ public class RFBIsbrhTessellatorAbuseTransformer implements RfbClassTransformer } @Override - public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { - if (inner.transformClassNode(classNode.getNode(), this.isObf)) { + final boolean changed = inner.transformClassNode(classNode.getNode(), this.isObf); + if (changed) { classNode.computeMaxs(); AngelicaClassDump.dumpRFBClass(className, classNode, this); } + return changed; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + transformClassIfNeeded(classLoader, context, manifest, className, classNode); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index dc3e38d7a..998af4d4e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -45,7 +45,9 @@ public enum Mixins implements IMixins { , "angelica.bugfixes.MixinRenderCreeper_AuraDepth" , "angelica.bugfixes.MixinRenderGlobal_DeferredEntityOverlay" , "angelica.bugfixes.MixinRenderGlobal_DestroyBlock" + , "angelica.bugfixes.MixinRenderMooshroom_MushroomTint" , "angelica.bugfixes.MixinRendererLivingEntity_DeferredEntityOverlay" + , "angelica.bugfixes.MixinRendererLivingEntity_OverlayTint" , "angelica.bugfixes.MixinRenderWither_ArmorCentering" , "angelica.bugfixes.MixinRendererLivingEntity_EyeDepth" , "angelica.debug.MixinMinecraft_FPSCap" @@ -275,6 +277,8 @@ public enum Mixins implements IMixins { , "shaders.MixinRenderNameTag" , "shaders.MixinRenderPlayerArmor" , "shaders.MixinTileEntityBeaconRenderer" + , "shaders.MixinWorldNbtCache" + , "shaders.MixinNetHandlerPlayClient_NbtRemesh" , "shaders.MixinRenderEndPortal" , "shaders.MixinTileEntityRendererDispatcher" , "shaders.MixinGlProgram" diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java new file mode 100644 index 000000000..868933f19 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java @@ -0,0 +1,75 @@ +package com.gtnewhorizons.angelica.render; + +import java.nio.ByteBuffer; + +final class CloudEdges { + private static final int CELL_EMPTY_THRESHOLD = 10; + + final int width, height; + private final int wMask, hMask; + private final boolean whPow2; + private final long[] opaqueBits; + final int opaqueCount; + + CloudEdges(int width, int height, ByteBuffer rgba) { + this.width = width; + this.height = height; + this.wMask = width - 1; + this.hMask = height - 1; + this.whPow2 = (width & wMask) == 0 && (height & hMask) == 0; + final int total = width * height; + final long[] bits = new long[(total + 63) >>> 6]; + int op = 0; + for (int i = 0; i < total; i++) { + if ((rgba.get(i * 4 + 3) & 0xFF) >= CELL_EMPTY_THRESHOLD) { + bits[i >>> 6] |= 1L << (i & 63); + op++; + } + } + this.opaqueBits = bits; + this.opaqueCount = op; + } + + boolean cellOpaque(int x, int z) { + final int xw, zh; + if (whPow2) { + xw = x & wMask; + zh = z & hMask; + } else { + xw = Math.floorMod(x, width); + zh = Math.floorMod(z, height); + } + final int idx = xw + zh * width; + return ((opaqueBits[idx >>> 6] >>> (idx & 63)) & 1L) != 0L; + } + + long readOpaqueRowBits(int x0, int z) { + final int zMod, x0Mod; + if (whPow2) { + zMod = z & hMask; + x0Mod = x0 & wMask; + } else { + zMod = Math.floorMod(z, height); + x0Mod = Math.floorMod(x0, width); + } + if (x0Mod + 10 <= width) { + return readContigBits(opaqueBits, (long) zMod * width + x0Mod, 10); + } + final int colsBeforeWrap = width - x0Mod; + final long firstPart = readContigBits(opaqueBits, (long) zMod * width + x0Mod, colsBeforeWrap); + final long secondPart = readContigBits(opaqueBits, (long) zMod * width, 10 - colsBeforeWrap); + return firstPart | (secondPart << colsBeforeWrap); + } + + private static long readContigBits(long[] bits, long startBitIdx, int count) { + final int wordIdx = (int) (startBitIdx >>> 6); + final int bitOff = (int) (startBitIdx & 63); + final long mask = count == 64 ? -1L : (1L << count) - 1L; + final long w0 = bits[wordIdx]; + if (bitOff + count <= 64) { + return (w0 >>> bitOff) & mask; + } + final long w1 = bits[wordIdx + 1]; + return ((w0 >>> bitOff) | (w1 << (64 - bitOff))) & mask; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java index 76cd80425..71ced4a19 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java @@ -21,59 +21,118 @@ package com.gtnewhorizons.angelica.render; -import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; -import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.glsm.GLStateManager; -import com.gtnewhorizons.angelica.client.rendering.GlUniformFloat2v; import jss.notfine.core.Settings; import jss.notfine.gui.options.named.GraphicsQualityOff; +import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; -import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.entity.Entity; +import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import org.embeddedt.embeddium.impl.gl.shader.GlProgram; import org.embeddedt.embeddium.impl.gl.shader.GlShader; -import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; import org.embeddedt.embeddium.impl.gl.shader.ShaderType; -import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v; -import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; -import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt; -import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.joml.Matrix4f; import org.joml.Matrix4fStack; +import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; public class CloudRenderer implements IResourceManagerReloadListener { - private static final float PX_SIZE = 1 / 256F; - private static final int TOP_SECTIONS = 12; - private static final int HEIGHT = 4; - private static final float INSET = 0.001F; - private static final float ALPHA = 0.8F; + private static final byte F_TOP = 0, F_BOTTOM = 1, F_X = 2, F_Z = 3; + private static final float[] FACTOR_VALUES = {0.7f, 1.0f, 0.9f, 0.8f}; // {top, bottom, X, Z} + private static final int[] FACTOR_BYTE_SHIFTED; + static { + FACTOR_BYTE_SHIFTED = new int[4]; + for (int i = 0; i < 4; i++) { + final int b = Math.round(FACTOR_VALUES[i] * 255f) & 0xFF; + FACTOR_BYTE_SHIFTED[i] = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) ? b : (b << 24); + } + } + private static final int FACTOR_ATTRIB_LOC = 5; - private static final boolean WIREFRAME = false; + private static final int VERTEX_STRIDE = 24; + private static final int NORMAL_OFFSET = 20; + private static final int QUAD_BYTES = 4 * VERTEX_STRIDE; + + private static final int CELLS_PER_CHUNK = 8; + + private static final float SCROLL_SPEED = 1.0f / 256.0f; + private static final float EDGE_OVERLAP = 0.0001f; + + private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN; + + private static final int N_POS_X = packNormalInt((byte) 127, (byte) 0, (byte) 0); + private static final int N_NEG_X = packNormalInt((byte) -127, (byte) 0, (byte) 0); + private static final int N_POS_Y = packNormalInt((byte) 0, (byte) 127, (byte) 0); + private static final int N_NEG_Y = packNormalInt((byte) 0, (byte) -127, (byte) 0); + private static final int N_POS_Z = packNormalInt((byte) 0, (byte) 0, (byte) 127); + private static final int N_NEG_Z = packNormalInt((byte) 0, (byte) 0, (byte) -127); private final Minecraft mc = Minecraft.getMinecraft(); private final ResourceLocation texture = new ResourceLocation("textures/environment/clouds.png"); - private IVertexArrayObject vao; - private int cloudMode = -1; - private int renderDistance = -1; - private int cloudElevation = -1; - private int scaleMult = -1; + private CloudEdges edges; + private int edgesGeneration; + private int texW, texH; + private int mipmapTexId = -1; + private int cloudTexId = -1; - private int texW; - private int texH; + private IVertexArrayObject vao; + private int cachedVertexCount; + private int eboId = -1; + private int eboQuadCapacity; + + private int anchorCellX = Integer.MIN_VALUE, anchorCellZ = Integer.MIN_VALUE; + private int anchorMarginCells = 0; + private int cachedEdgesGeneration = Integer.MIN_VALUE; + private boolean cachedEmitTopFace, cachedEmitBottomFace, cachedCameraInsideCloud; + private int cachedRenderRadius = -1; + private float cachedCloudInteriorHeight = Float.NaN; + + private int cloudMode = -1, renderDistance = -1, cloudElevation = -1, scaleMult = -1; + + private ByteBuffer emitBuffer; + private long emitBufferAddr; + private int emitBufferCapacity; + private long writeAddr, writeEnd; + + private ByteBuffer sortedBuffer; + private long sortedBufferAddr; + private int sortedBufferCapacity; + + private ByteBuffer edgeStagingBuffer; + private int edgeStagingCapacity; + + private byte[] quadFactor = new byte[2048]; + private int quadCount; + + private final int[] factorQuadCount = new int[4]; + private final int[] factorVertOffset = new int[4]; + private final long[] factorWriteAddr = new long[4]; + + private final int[] chunkOpaqueRows = new int[10]; + private long[] globalEmit; + private long[] globalEmitTodo; + private int gridRows, gridCols, gridLongsPerRow, gridMinX, gridMinZ; + private long[] runMaskScratch = new long[8]; private GlProgram program; private final Matrix4f mvpScratch = new Matrix4f(); @@ -83,207 +142,57 @@ public class CloudRenderer implements IResourceManagerReloadListener { } private static CloudRenderer instance; + public static CloudRenderer getCloudRenderer() { - if (instance == null) - instance = new CloudRenderer(); + if (instance == null) instance = new CloudRenderer(); return instance; } - private int getScale() { - return (cloudMode == 2 ? 12 : 8) * scaleMult; + public static int getCloudTextureWidth() { + return instance != null && instance.texW > 0 ? instance.texW : 256; } - private float ceilToScale(float value) { - final float scale = getScale(); - return (float)Math.ceil(value / scale) * scale; - } - - private float meshExtent() { - return ceilToScale(renderDistance * 4 * 16); - } - - private void vertices(Tessellator tessellator) { - final GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore(); - final boolean fancy = cloudGraphicsQuality == GraphicsQualityOff.FANCY || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics; - - final float scale = getScale(); - final float CULL_DIST = 2 * scale; - - final float bCol = fancy ? 0.7F : 1F; - - final float sectEnd = meshExtent(); - final float sectStart = -sectEnd; - - final float sectStep = ceilToScale(sectEnd * 2 / TOP_SECTIONS); - final float sectPx = PX_SIZE / scale; - - tessellator.startDrawingQuads(); - - float sectX0 = sectStart; - float sectX1 = sectX0; - - while (sectX1 < sectEnd) { - sectX1 += sectStep; - - if (sectX1 > sectEnd) - sectX1 = sectEnd; - - float sectZ0 = sectStart; - float sectZ1 = sectZ0; - - while (sectZ1 < sectEnd) { - sectZ1 += sectStep; - - if (sectZ1 > sectEnd) - sectZ1 = sectEnd; - - final float u0 = sectX0 * sectPx; - final float u1 = sectX1 * sectPx; - final float v0 = sectZ0 * sectPx; - final float v1 = sectZ1 * sectPx; - - // Bottom - tessellator.setColorRGBA_F(bCol, bCol, bCol, ALPHA); - tessellator.addVertexWithUV(sectX0, 0, sectZ0, u0, v0); - tessellator.addVertexWithUV(sectX1, 0, sectZ0, u1, v0); - tessellator.addVertexWithUV(sectX1, 0, sectZ1, u1, v1); - tessellator.addVertexWithUV(sectX0, 0, sectZ1, u0, v1); - - if (fancy) { - final int height = HEIGHT * scaleMult; - // Top - tessellator.setColorRGBA_F(1, 1, 1, ALPHA); - tessellator.addVertexWithUV(sectX0, height, sectZ0, u0, v0); - tessellator.addVertexWithUV(sectX0, height, sectZ1, u0, v1); - tessellator.addVertexWithUV(sectX1, height, sectZ1, u1, v1); - tessellator.addVertexWithUV(sectX1, height, sectZ0, u1, v0); - - float slice; - float sliceCoord0; - float sliceCoord1; - - for (slice = sectX0; slice < sectX1; ) { - sliceCoord0 = slice * sectPx; - sliceCoord1 = sliceCoord0 + PX_SIZE; - - // X sides - if (slice > -CULL_DIST) { - slice += INSET; - tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA); - tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1); - tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1); - tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0); - tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0); - slice -= INSET; - } - - slice += scale; - - if (slice <= CULL_DIST) { - slice -= INSET; - tessellator.setColorRGBA_F(0.9F, 0.9F, 0.9F, ALPHA); - tessellator.addVertexWithUV(slice, 0, sectZ0, sliceCoord0, v0); - tessellator.addVertexWithUV(slice, height, sectZ0, sliceCoord1, v0); - tessellator.addVertexWithUV(slice, height, sectZ1, sliceCoord1, v1); - tessellator.addVertexWithUV(slice, 0, sectZ1, sliceCoord0, v1); - slice += INSET; - } - } - - for (slice = sectZ0; slice < sectZ1; ) { - sliceCoord0 = slice * sectPx; - sliceCoord1 = sliceCoord0 + PX_SIZE; - - // Z sides - if (slice > -CULL_DIST) { - slice += INSET; - tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA); - tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0); - tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1); - tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1); - tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0); - slice -= INSET; - } - - slice += scale; - - if (slice <= CULL_DIST) { - slice -= INSET; - tessellator.setColorRGBA_F(0.8F, 0.8F, 0.8F, ALPHA); - tessellator.addVertexWithUV(sectX1, 0, slice, u1, sliceCoord0); - tessellator.addVertexWithUV(sectX1, height, slice, u1, sliceCoord1); - tessellator.addVertexWithUV(sectX0, height, slice, u0, sliceCoord1); - tessellator.addVertexWithUV(sectX0, 0, slice, u0, sliceCoord0); - slice += INSET; - } - } - } - - sectZ0 = sectZ1; - } - - sectX0 = sectX1; - } - } - - private void dispose() { - if (vao != null) { - vao.delete(); - vao = null; - } - if (program != null) { - program.delete(); - program = null; - } - } - - private void build() { - final DirectTessellator tessellator = TessellatorManager.startCapturingDirect(); - this.vertices(tessellator); - this.vao = DirectTessellator.stopCapturingToVBO(VertexBufferType.IMMUTABLE); - } - - private int fullCoord(double coord, int scale) { // Corrects misalignment of UV offset when on negative coords. - return ((int) coord / scale) - (coord < 0 ? 1 : 0); - } - - private boolean isBuilt() { - return vao != null; + public static int getScaleMult() { + return instance != null && instance.scaleMult > 0 ? instance.scaleMult : 1; } public void checkSettings() { - final GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff)Settings.MODE_CLOUDS.option.getStore(); + final GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff) Settings.MODE_CLOUDS.option.getStore(); final int cloudQualitySetting = cloudGraphicsQuality == GraphicsQualityOff.FANCY || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics ? 2 : 1; final boolean newEnabled = cloudGraphicsQuality != GraphicsQualityOff.OFF && mc.gameSettings.shouldRenderClouds() && mc.theWorld != null && mc.theWorld.provider.isSurfaceWorld(); - final int targetDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int)Settings.RENDER_DISTANCE_CLOUDS.option.getStore()); - final int cloudScaleMult = (int)Settings.CLOUD_SCALE.option.getStore(); + final int targetDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int) Settings.RENDER_DISTANCE_CLOUDS.option.getStore()); + final int cloudScaleMult = (int) Settings.CLOUD_SCALE.option.getStore(); - if (isBuilt() - && (!newEnabled + if (!newEnabled || cloudQualitySetting != cloudMode || targetDistance != renderDistance - || cloudScaleMult != scaleMult)) { - dispose(); + || cloudScaleMult != scaleMult) { + invalidateGeometry(); } cloudMode = cloudQualitySetting; renderDistance = targetDistance; scaleMult = cloudScaleMult; - cloudElevation = mc.theWorld == null ? 128 : (int)mc.theWorld.provider.getCloudHeight(); - //Allows the setting to work with RFG and similar without hardcoding. - //The minimum height check is so stuff like Aether cloud height doesn't get messed up. - if(cloudElevation >= 96) { - cloudElevation = (int)Settings.CLOUD_HEIGHT.option.getStore(); + cloudElevation = mc.theWorld == null ? 128 : (int) mc.theWorld.provider.getCloudHeight(); + // Allows the setting to work with RFG and similar without hardcoding. + // The minimum height check is so stuff like Aether cloud height doesn't get messed up. + if (cloudElevation >= 96) { + cloudElevation = (int) Settings.CLOUD_HEIGHT.option.getStore(); } + } - if (newEnabled && !isBuilt()) { - build(); - } + private void invalidateGeometry() { + anchorCellX = Integer.MIN_VALUE; + anchorCellZ = Integer.MIN_VALUE; + cachedRenderRadius = -1; + cachedEdgesGeneration = Integer.MIN_VALUE; + cachedCloudInteriorHeight = Float.NaN; + cachedVertexCount = 0; } private void initProgram() { @@ -301,196 +210,724 @@ public class CloudRenderer implements IResourceManagerReloadListener { frag.delete(); } - final CloudUniforms u = program.getInterface(); - final float start = renderDistance * 16.0f; - final float end = meshExtent(); - final float range = end - start; - program.bind(); - u.cloudTex.setInt(0); - u.fogParams.set(new float[] { - range != 0.0f ? -1.0f / range : 0.0f, - range != 0.0f ? end / range : 1.0f, - 0.0f, 0.0f - }); + program.getInterface().tex.setInt(0); program.unbind(); } - private void uploadFogUniforms(float partialTicks) { + private void uploadFogUniforms(float partialTicks, int renderRadius, float cloudInteriorWidth) { final CloudUniforms u = program.getInterface(); final boolean fogEnabled = GLStateManager.getFogMode().isEnabled(); u.setFogEnabled(fogEnabled); - if (fogEnabled) { + final float start = renderDistance * 16.0f; + final float end = renderRadius * CELLS_PER_CHUNK * cloudInteriorWidth; + final float range = end - start; + u.setFogParams(range != 0.0f ? -1.0f / range : 0.0f, range != 0.0f ? end / range : 1.0f); final Vec3 sky = mc.theWorld.getSkyColor(mc.renderViewEntity, partialTicks); u.setFogColor((float) sky.xCoord, (float) sky.yCoord, (float) sky.zCoord); } } - private static class CloudUniforms { - final GlUniformMatrix4f mvp; - final GlUniformFloat3v colorMult; - final GlUniformFloat2v texOffset; - final GlUniformFloat2v fogOrigin; - final GlUniformFloat4v fogParams; - final GlUniformFloat4v fogColor; - final GlUniformInt fogEnabled; - final GlUniformInt cloudTex; - - private int lastFogEnabled = -1; - private float lastFogR = Float.NaN, lastFogG = Float.NaN, lastFogB = Float.NaN; - private float lastColorR = Float.NaN, lastColorG = Float.NaN, lastColorB = Float.NaN; - private final float[] fogColorBuf = new float[4]; - - CloudUniforms(ShaderBindingContext ctx) { - mvp = ctx.bindUniform("u_MVPMatrix", GlUniformMatrix4f::new); - colorMult = ctx.bindUniform("u_ColorMultiplier", GlUniformFloat3v::new); - texOffset = ctx.bindUniform("u_TexOffset", GlUniformFloat2v::new); - fogOrigin = ctx.bindUniform("u_FogOrigin", GlUniformFloat2v::new); - fogParams = ctx.bindUniform("u_FogParams", GlUniformFloat4v::new); - fogColor = ctx.bindUniform("u_FogColor", GlUniformFloat4v::new); - fogEnabled = ctx.bindUniform("u_FogEnabled", GlUniformInt::new); - cloudTex = ctx.bindUniform("u_CloudTexture", GlUniformInt::new); - } - - void setFogEnabled(boolean enabled) { - final int val = enabled ? 1 : 0; - if (val != lastFogEnabled) { - lastFogEnabled = val; - fogEnabled.setInt(val); - } - } - - void setFogColor(float r, float g, float b) { - if (r != lastFogR || g != lastFogG || b != lastFogB) { - lastFogR = r; lastFogG = g; lastFogB = b; - fogColorBuf[0] = r; fogColorBuf[1] = g; fogColorBuf[2] = b; fogColorBuf[3] = 1.0f; - fogColor.set(fogColorBuf); - } - } - - void setColorMult(float r, float g, float b) { - if (r != lastColorR || g != lastColorG || b != lastColorB) { - lastColorR = r; lastColorG = g; lastColorB = b; - colorMult.set(r, g, b); - } - } - } - public boolean render(int cloudTicks, float partialTicks) { - if (!isBuilt()) - return false; + if (mc.theWorld == null || mc.renderViewEntity == null) return false; + if (cloudMode != 2 || scaleMult <= 0) return false; + boolean textureSetupDone = false; + if (edges == null) { + if (mc.renderEngine == null) return false; + mc.renderEngine.bindTexture(texture); + setupCloudTexture(); + textureSetupDone = true; + if (edges == null) return false; + } if (program == null) { initProgram(); if (program == null) return false; } final Entity entity = mc.renderViewEntity; + final float cloudInteriorWidth = 12.0f * scaleMult; + final float cloudInteriorHeight = 4.0f * scaleMult; + final double cloudTick = cloudTicks + (double) partialTicks; - final double totalOffset = cloudTicks + partialTicks; + final float cameraOffsetY = (float) (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks); + double cameraOffsetX = (entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks + cloudTick * 0.03D) / cloudInteriorWidth; + double cameraOffsetZ = (entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks) / cloudInteriorWidth; + cameraOffsetX -= MathHelper.floor_double(cameraOffsetX / 2048.0D) * 2048; + cameraOffsetZ -= MathHelper.floor_double(cameraOffsetZ / 2048.0D) * 2048; - final double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks + totalOffset * 0.03; - final double y = cloudElevation - (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks) + 0.33; - double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks; + final float cameraRelativeY = cloudElevation - cameraOffsetY + 0.33F; + final float cameraRelativeX = (float) (cameraOffsetX - MathHelper.floor_double(cameraOffsetX)); + final float cameraRelativeZ = (float) (cameraOffsetZ - MathHelper.floor_double(cameraOffsetZ)); - final int scale = getScale(); + final int anchorX = MathHelper.floor_double(cameraOffsetX); + final int anchorZ = MathHelper.floor_double(cameraOffsetZ); - if (cloudMode == 2) - z += 0.33 * scale; + final boolean emitTopFace = cameraRelativeY + cloudInteriorHeight >= 0.0F; + final boolean emitBottomFace = cameraRelativeY <= 0.0F; + final boolean cameraInsideY = cameraRelativeY <= 0.0F && cameraRelativeY + cloudInteriorHeight >= 0.0F; + final boolean cameraInsideCloud = cameraInsideY && edges.cellOpaque(anchorX, anchorZ); - int offU = fullCoord(x, scale); - int offV = fullCoord(z, scale); + final int renderRadius = (int) Math.ceil(renderDistance * 64.0f / (CELLS_PER_CHUNK * cloudInteriorWidth)); - GLStateManager.glPushMatrix(); - GLStateManager.glTranslated((offU * scale) - x, y, (offV * scale) - z); + final boolean anchorInRange = vao != null + && Math.abs(anchorX - anchorCellX) <= anchorMarginCells + && Math.abs(anchorZ - anchorCellZ) <= anchorMarginCells; + final boolean geomCacheValid = anchorInRange + && cachedEdgesGeneration == edgesGeneration + && cachedEmitTopFace == emitTopFace + && cachedEmitBottomFace == emitBottomFace + && cachedCameraInsideCloud == cameraInsideCloud + && cachedRenderRadius == renderRadius + && cachedCloudInteriorHeight == cloudInteriorHeight; - final float fogOriginX = (float)(x - offU * scale); - final float fogOriginZ = (float)(z - offV * scale); + if (!geomCacheValid) { + final int marginCells = cameraInsideCloud ? 0 : Math.max(CELLS_PER_CHUNK, renderRadius * CELLS_PER_CHUNK / 4); + rebuildGeometry(anchorX, anchorZ, renderRadius, cloudInteriorHeight, emitTopFace, emitBottomFace, cameraInsideCloud, marginCells); + anchorCellX = anchorX; + anchorCellZ = anchorZ; + anchorMarginCells = marginCells; + cachedEdgesGeneration = edgesGeneration; + cachedEmitTopFace = emitTopFace; + cachedEmitBottomFace = emitBottomFace; + cachedCameraInsideCloud = cameraInsideCloud; + cachedRenderRadius = renderRadius; + cachedCloudInteriorHeight = cloudInteriorHeight; + } - offU = offU % texW; - offV = offV % texH; + if (vao == null || cachedVertexCount == 0) return true; - GLStateManager.disableCull(); - - GLStateManager.enableBlend(); - GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); + mc.renderEngine.bindTexture(texture); + if (!textureSetupDone) setupCloudTexture(); final Vec3 color = mc.theWorld.getCloudColour(partialTicks); float r = (float) color.xCoord; float g = (float) color.yCoord; float b = (float) color.zCoord; - if (mc.gameSettings.anaglyph) { - final float tempR = r * 0.3F + g * 0.59F + b * 0.11F; - final float tempG = r * 0.3F + g * 0.7F; - final float tempB = r * 0.3F + b * 0.7F; + final float tempR = (r * 30.0F + g * 59.0F + b * 11.0F) / 100.0F; + final float tempG = (r * 30.0F + g * 70.0F) / 100.0F; + final float tempB = (r * 30.0F + b * 70.0F) / 100.0F; r = tempR; g = tempG; b = tempB; } - GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); - mc.renderEngine.bindTexture(texture); - program.bind(); + final boolean shadersActive = IrisApi.getInstance().isShaderPackInUse(); - final CloudUniforms u = program.getInterface(); - final Matrix4fStack mv = GLStateManager.getModelViewMatrix(); - GLStateManager.getProjectionMatrix().mul(mv, mvpScratch); - u.mvp.set(mvpScratch); - u.texOffset.set(offU * PX_SIZE, offV * PX_SIZE); - u.setColorMult(r, g, b); - u.fogOrigin.set(fogOriginX, fogOriginZ); + final float origFogStart = GLStateManager.getFogState().getStart(); + final float origFogEnd = GLStateManager.getFogState().getEnd(); + final float cloudExtentBlocks = renderRadius * CELLS_PER_CHUNK * cloudInteriorWidth; + final boolean pushFog = GLStateManager.getFogMode().isEnabled() && GLStateManager.getFogState().getFogMode() == GL11.GL_LINEAR && origFogEnd < cloudExtentBlocks; + if (pushFog) { + final float ratio = cloudExtentBlocks / origFogEnd; + GLStateManager.glFogf(GL11.GL_FOG_START, origFogStart * ratio); + GLStateManager.glFogf(GL11.GL_FOG_END, cloudExtentBlocks); + } - uploadFogUniforms(partialTicks); + final float anchorDriftX = (float) (anchorX - anchorCellX); + final float anchorDriftZ = (float) (anchorZ - anchorCellZ); + if (!shadersActive) { + program.bind(); + final CloudUniforms u = program.getInterface(); + final Matrix4fStack mv = GLStateManager.getModelViewMatrix(); + mv.pushMatrix(); + mv.scale(cloudInteriorWidth, 1.0f, cloudInteriorWidth); + mv.translate(-(cameraRelativeX + anchorDriftX), cameraRelativeY, -(cameraRelativeZ + anchorDriftZ)); + GLStateManager.getProjectionMatrix().mul(mv, mvpScratch); + mv.popMatrix(); + u.mvp.set(mvpScratch); + uploadFogUniforms(partialTicks, renderRadius, cloudInteriorWidth); + + drawAllFactors(r, g, b, false); + program.unbind(); + } else { + GLStateManager.glPushMatrix(); + GLStateManager.glScalef(cloudInteriorWidth, 1.0f, cloudInteriorWidth); + GLStateManager.glTranslatef(-(cameraRelativeX + anchorDriftX), cameraRelativeY, -(cameraRelativeZ + anchorDriftZ)); + drawAllFactors(r, g, b, true); + GLStateManager.glPopMatrix(); + } + + if (pushFog) { + GLStateManager.glFogf(GL11.GL_FOG_START, origFogStart); + GLStateManager.glFogf(GL11.GL_FOG_END, origFogEnd); + } + return true; + } + + private void drawAllFactors(float r, float g, float b, boolean shadersActive) { vao.bind(); + GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId); - // Depth pass to prevent insides rendering from the outside. + GLStateManager.disableBlend(); + GLStateManager.glDepthMask(true); GLStateManager.glColorMask(false, false, false, false); - vao.draw(); + // Depth prepass: alpha must match color pass so discard threshold writes same depth coverage. + if (shadersActive) { + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, CloudUniforms.ALPHA); + } else { + program.getInterface().setColorMult(1.0f, 1.0f, 1.0f); + } + final int totalQuads = cachedVertexCount / 4; + GLStateManager.glDrawElements(GL11.GL_TRIANGLES, totalQuads * 6, GL11.GL_UNSIGNED_INT, 0L); if (!mc.gameSettings.anaglyph) { GLStateManager.glColorMask(true, true, true, true); } else { switch (EntityRenderer.anaglyphField) { - case 0: - GLStateManager.glColorMask(false, true, true, true); - break; - case 1: - GLStateManager.glColorMask(true, false, false, true); - break; + case 0 -> GLStateManager.glColorMask(false, true, true, true); + case 1 -> GLStateManager.glColorMask(true, false, false, true); + default -> GLStateManager.glColorMask(true, true, true, true); + } + } + GLStateManager.enableBlend(); + GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); + GLStateManager.glDepthMask(false); + + if (shadersActive) { + for (int f = 0; f < 4; f++) { + final int qc = factorQuadCount[f]; + if (qc == 0) continue; + final float v = FACTOR_VALUES[f]; + GLStateManager.glColor4f(v * r, v * g, v * b, CloudUniforms.ALPHA); + final long byteOffset = (long) (factorVertOffset[f] / 4) * 6L * 4L; + GLStateManager.glDrawElements(GL11.GL_TRIANGLES, qc * 6, GL11.GL_UNSIGNED_INT, byteOffset); + } + } else { + program.getInterface().setColorMult(r, g, b); + GLStateManager.glDrawElements(GL11.GL_TRIANGLES, totalQuads * 6, GL11.GL_UNSIGNED_INT, 0L); + } + + vao.unbind(); + GLStateManager.glDepthMask(true); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.disableBlend(); + } + + private void rebuildGeometry(int anchorX, int anchorZ, int renderRadius, float cloudInteriorHeight, boolean emitTopFace, boolean emitBottomFace, boolean cameraInsideCloud, int marginCells) { + prepareEmitBuffer(); + + final int marginChunks = (marginCells + CELLS_PER_CHUNK - 1) / CELLS_PER_CHUNK; + final int chunkRange = cameraInsideCloud ? 0 : (renderRadius + marginChunks); + final int outerLo = cameraInsideCloud ? -1 : -chunkRange; + final int outerHi = cameraInsideCloud ? 0 : chunkRange; + + final int radiusCellsWithMargin = cameraInsideCloud ? CELLS_PER_CHUNK : (chunkRange * CELLS_PER_CHUNK); + final int radiusCellsSq = radiusCellsWithMargin * radiusCellsWithMargin; + + final float scrollX = anchorX * SCROLL_SPEED; + final float scrollZ = anchorZ * SCROLL_SPEED; + + final int rows = (outerHi - outerLo + 1) * CELLS_PER_CHUNK; + final int lpr = (rows + 63) >>> 6; + final int minX = outerLo * CELLS_PER_CHUNK; + final int minZ = outerLo * CELLS_PER_CHUNK; + final int gridSize = rows * lpr; + if (emitTopFace || emitBottomFace) { + if (globalEmit == null || globalEmit.length < gridSize) { + globalEmit = new long[gridSize]; + globalEmitTodo = new long[gridSize]; + } else { + java.util.Arrays.fill(globalEmit, 0, gridSize, 0L); + } + this.gridRows = rows; + this.gridCols = rows; + this.gridLongsPerRow = lpr; + this.gridMinX = minX; + this.gridMinZ = minZ; + } + + final double y1 = cloudInteriorHeight; + final double ye = y1 - EDGE_OVERLAP; + + for (int chunkX = outerLo; chunkX <= outerHi; chunkX++) { + for (int chunkZ = outerLo; chunkZ <= outerHi; chunkZ++) { + emitChunk(chunkX, chunkZ, anchorX, anchorZ, radiusCellsSq, cameraInsideCloud, emitTopFace, emitBottomFace, y1, ye, scrollX, scrollZ); } } - if (WIREFRAME) { - GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); - GLStateManager.glLineWidth(2.0F); - GLStateManager.glDepthMask(false); - vao.draw(); - GLStateManager.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL); - GLStateManager.glDepthMask(true); + if (emitTopFace || emitBottomFace) { + emitTopBottomGlobalGreedy(emitTopFace, emitBottomFace, ye, scrollX, scrollZ); } - vao.draw(); - vao.unbind(); // Unbind buffer. + final int totalBytes = (int) (writeAddr - emitBufferAddr); + final int vertexCount = totalBytes / VERTEX_STRIDE; + if (vertexCount == 0) { + if (vao != null) { + vao.delete(); + vao = null; + } + cachedVertexCount = 0; + return; + } - program.unbind(); + sortQuadsByFactor(); - GLStateManager.disableBlend(); - GLStateManager.enableCull(); + if (vao == null) { + vao = VertexBufferType.MUTABLE_RESIZABLE.allocate( + DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_TRIANGLES, + sortedBuffer, vertexCount); + setupFactorAttrib(); + } else { + vao.getVBO().allocate(sortedBuffer, vertexCount); + } + cachedVertexCount = vertexCount; + ensureEbo(vertexCount / 4); + } - GLStateManager.glPopMatrix(); + private void setupFactorAttrib() { + vao.bind(); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vao.getVBO().getId()); + GLStateManager.glEnableVertexAttribArray(FACTOR_ATTRIB_LOC); + GLStateManager.glVertexAttribPointer(FACTOR_ATTRIB_LOC, 1, GL11.GL_UNSIGNED_BYTE, true, VERTEX_STRIDE, NORMAL_OFFSET + 3); + GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + vao.unbind(); + } - return true; + private void ensureEbo(int quadCount) { + if (eboId == -1) { + eboId = GLStateManager.glGenBuffers(); + } + if (quadCount <= eboQuadCapacity) return; + final java.nio.IntBuffer ib = BufferUtils.createIntBuffer(quadCount * 6); + for (int q = 0; q < quadCount; q++) { + final int v = q * 4; + ib.put(v).put(v + 1).put(v + 2); + ib.put(v).put(v + 2).put(v + 3); + } + ib.flip(); + GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId); + GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, ib, GL15.GL_STATIC_DRAW); + GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); + eboQuadCapacity = quadCount; + } + + private void deleteEbo() { + if (eboId != -1) { + GLStateManager.glDeleteBuffers(eboId); + eboId = -1; + eboQuadCapacity = 0; + } + } + + private void emitChunk(int chunkX, int chunkZ, int anchorX, int anchorZ, int radiusCellsSq, boolean cameraInsideCloud, boolean emitTopFace, boolean emitBottomFace, double y1, double ye, float scrollX, float scrollZ) { + final float chunkOffsetX = chunkX * (float) CELLS_PER_CHUNK; + final float chunkOffsetZ = chunkZ * (float) CELLS_PER_CHUNK; + final int baseU = chunkX * CELLS_PER_CHUNK + anchorX; + final int baseV = chunkZ * CELLS_PER_CHUNK + anchorZ; + + final int[] opaqueRows = this.chunkOpaqueRows; + for (int row = 0; row < 10; row++) { + opaqueRows[row] = (int) edges.readOpaqueRowBits(baseU - 1, baseV + row - 1); + } + + long emittableBits = 0L; + for (int j = 0; j < CELLS_PER_CHUNK; j++) { + int rowOpaque = (opaqueRows[j + 1] >>> 1) & 0xFF; + while (rowOpaque != 0) { + final int k = Integer.numberOfTrailingZeros(rowOpaque); + rowOpaque &= rowOpaque - 1; + final int relX = chunkX * CELLS_PER_CHUNK + k; + final int relZ = chunkZ * CELLS_PER_CHUNK + j; + if (relX * relX + relZ * relZ > radiusCellsSq) continue; + if (cameraInsideCloud && (Math.abs(relX) > 1 || Math.abs(relZ) > 1)) continue; + emittableBits |= 1L << (j * CELLS_PER_CHUNK + k); + } + } + if (emittableBits == 0L) return; + + if (cameraInsideCloud) { + long bits = emittableBits; + while (bits != 0L) { + final int bit = Long.numberOfTrailingZeros(bits); + bits &= bits - 1; + final int k = bit & 7; + final int j = bit >>> 3; + final double x0 = chunkOffsetX + k; + final double x1 = chunkOffsetX + k + 1; + final double z0 = chunkOffsetZ + j; + final double z1 = chunkOffsetZ + j + 1; + final double xe = x1 - EDGE_OVERLAP; + final double zs = z1 - EDGE_OVERLAP; + final float uC = (chunkOffsetX + k + 0.5F) * SCROLL_SPEED + scrollX; + final float vC = (chunkOffsetZ + j + 0.5F) * SCROLL_SPEED + scrollZ; + final float uL = (chunkOffsetX + k) * SCROLL_SPEED + scrollX; + final float uR = (chunkOffsetX + k + 1) * SCROLL_SPEED + scrollX; + final float vN = (chunkOffsetZ + j) * SCROLL_SPEED + scrollZ; + final float vS = (chunkOffsetZ + j + 1) * SCROLL_SPEED + scrollZ; + + ensureEmitCapacity(6 * QUAD_BYTES); + emitCloudQuad(x0, 0.0, z1, uL, vS, x1, 0.0, z1, uR, vS, x1, 0.0, z0, uR, vN, x0, 0.0, z0, uL, vN, F_TOP, N_POS_Y); + emitCloudQuad(x0, ye, z0, uL, vN, x1, ye, z0, uR, vN, x1, ye, z1, uR, vS, x0, ye, z1, uL, vS, F_BOTTOM, N_NEG_Y); + emitCloudQuad(x0, 0.0, z0, uC, vN, x0, y1, z0, uC, vN, x0, y1, z1, uC, vS, x0, 0.0, z1, uC, vS, F_X, N_POS_X); + emitCloudQuad(xe, 0.0, z1, uC, vS, xe, y1, z1, uC, vS, xe, y1, z0, uC, vN, xe, 0.0, z0, uC, vN, F_X, N_NEG_X); + emitCloudQuad(x0, 0.0, z0, uL, vC, x1, 0.0, z0, uR, vC, x1, y1, z0, uR, vC, x0, y1, z0, uL, vC, F_Z, N_POS_Z); + emitCloudQuad(x0, y1, zs, uL, vC, x1, y1, zs, uR, vC, x1, 0.0, zs, uR, vC, x0, 0.0, zs, uL, vC, F_Z, N_NEG_Z); + } + return; + } + + if (emitTopFace || emitBottomFace) { + final int globalColStart = chunkX * CELLS_PER_CHUNK - gridMinX; + final int globalRowStart = chunkZ * CELLS_PER_CHUNK - gridMinZ; + final int wordIdx = globalColStart >>> 6; + final int bitOff = globalColStart & 63; + final long[] gE = this.globalEmit; + final int lpr = this.gridLongsPerRow; + if (bitOff <= 56) { + for (int j = 0; j < CELLS_PER_CHUNK; j++) { + final long row8 = (emittableBits >>> (j * CELLS_PER_CHUNK)) & 0xFFL; + if (row8 == 0L) continue; + gE[(globalRowStart + j) * lpr + wordIdx] |= row8 << bitOff; + } + } else { + final int hiShift = 64 - bitOff; + for (int j = 0; j < CELLS_PER_CHUNK; j++) { + final long row8 = (emittableBits >>> (j * CELLS_PER_CHUNK)) & 0xFFL; + if (row8 == 0L) continue; + final int gRowOff = (globalRowStart + j) * lpr; + gE[gRowOff + wordIdx] |= row8 << bitOff; + gE[gRowOff + wordIdx + 1] |= row8 >>> hiShift; + } + } + } + + int rowsAnd = 0x3FF; + for (int r = 0; r < 10 && rowsAnd == 0x3FF; r++) rowsAnd &= opaqueRows[r]; + final boolean hasBoundary = rowsAnd != 0x3FF; + + long westFace = 0L, eastFace = 0L, northFace = 0L, southFace = 0L; + if (hasBoundary) { + long westOpaque = 0L, eastOpaque = 0L, northOpaque = 0L, southOpaque = 0L; + for (int j = 0; j < CELLS_PER_CHUNK; j++) { + final int rowShift = j * CELLS_PER_CHUNK; + westOpaque |= ((long) (opaqueRows[j + 1] & 0xFF)) << rowShift; + eastOpaque |= ((long) ((opaqueRows[j + 1] >>> 2) & 0xFF)) << rowShift; + northOpaque |= ((long) ((opaqueRows[j] >>> 1) & 0xFF)) << rowShift; + southOpaque |= ((long) ((opaqueRows[j + 2] >>> 1) & 0xFF)) << rowShift; + } + westFace = emittableBits & ~westOpaque; + eastFace = emittableBits & ~eastOpaque; + northFace = emittableBits & ~northOpaque; + southFace = emittableBits & ~southOpaque; + } + + emitZRun(westFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 0.0, N_NEG_X, false); + emitZRun(eastFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 1.0 - EDGE_OVERLAP, N_POS_X, true); + emitXRun(northFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 0.0, N_NEG_Z, false); + emitXRun(southFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 1.0 - EDGE_OVERLAP, N_POS_Z, true); + } + + private void emitZRun(long faceBits, float chunkOffsetX, float chunkOffsetZ, double y1, float scrollX, float scrollZ, double xOffset, int normalInt, boolean flip) { + while (faceBits != 0L) { + final int bit = Long.numberOfTrailingZeros(faceBits); + final int k = bit & 7; + final int j0 = bit >>> 3; + int h = 1; + while (j0 + h < CELLS_PER_CHUNK && ((faceBits >>> ((j0 + h) * CELLS_PER_CHUNK + k)) & 1L) != 0L) h++; + long mask = 0L; + for (int dh = 0; dh < h; dh++) mask |= 1L << ((j0 + dh) * CELLS_PER_CHUNK + k); + faceBits &= ~mask; + + final double x = chunkOffsetX + k + xOffset; + final double z0 = chunkOffsetZ + j0; + final double z1 = chunkOffsetZ + j0 + h; + final float uC = (chunkOffsetX + k + 0.5F) * SCROLL_SPEED + scrollX; + final float vN = (chunkOffsetZ + j0) * SCROLL_SPEED + scrollZ; + final float vS = (chunkOffsetZ + j0 + h) * SCROLL_SPEED + scrollZ; + final double za = flip ? z0 : z1; + final double zb = flip ? z1 : z0; + final float va = flip ? vN : vS; + final float vb = flip ? vS : vN; + + ensureEmitCapacity(QUAD_BYTES); + emitCloudQuad(x, 0.0, za, uC, va, x, y1, za, uC, va, x, y1, zb, uC, vb, x, 0.0, zb, uC, vb, F_X, normalInt); + } + } + + private void emitXRun(long faceBits, float chunkOffsetX, float chunkOffsetZ, double y1, float scrollX, float scrollZ, double zOffset, int normalInt, boolean flip) { + while (faceBits != 0L) { + final int bit = Long.numberOfTrailingZeros(faceBits); + final int k0 = bit & 7; + final int j = bit >>> 3; + int w = 1; + while (k0 + w < CELLS_PER_CHUNK && ((faceBits >>> (j * CELLS_PER_CHUNK + k0 + w)) & 1L) != 0L) w++; + faceBits &= ~(((1L << w) - 1L) << (j * CELLS_PER_CHUNK + k0)); + + final double x0 = chunkOffsetX + k0; + final double x1 = chunkOffsetX + k0 + w; + final double z = chunkOffsetZ + j + zOffset; + final float uL = (chunkOffsetX + k0) * SCROLL_SPEED + scrollX; + final float uR = (chunkOffsetX + k0 + w) * SCROLL_SPEED + scrollX; + final float vC = (chunkOffsetZ + j + 0.5F) * SCROLL_SPEED + scrollZ; + final double ya = flip ? 0.0 : y1; + final double yb = flip ? y1 : 0.0; + + ensureEmitCapacity(QUAD_BYTES); + emitCloudQuad(x0, ya, z, uL, vC, x1, ya, z, uR, vC, x1, yb, z, uR, vC, x0, yb, z, uL, vC, F_Z, normalInt); + } + } + + private void emitTopBottomGlobalGreedy(boolean emitTopFace, boolean emitBottomFace, double ye, float scrollX, float scrollZ) { + final int rows = this.gridRows; + final int cols = this.gridCols; + final int lpr = this.gridLongsPerRow; + final int minX = this.gridMinX; + final int minZ = this.gridMinZ; + final long[] todo = this.globalEmitTodo; + System.arraycopy(this.globalEmit, 0, todo, 0, rows * lpr); + + final int bytesPerCell = (emitTopFace ? QUAD_BYTES : 0) + (emitBottomFace ? QUAD_BYTES : 0); + + for (int row = 0; row < rows; row++) { + final int rowOff = row * lpr; + for (int wi = 0; wi < lpr; wi++) { + long word = todo[rowOff + wi]; + while (word != 0L) { + final int bit = Long.numberOfTrailingZeros(word); + final int col0 = wi * 64 + bit; + if (col0 >= cols) break; + + final int w = measureRowRun(todo, rowOff, lpr, cols, col0); + final int wiStart = col0 >>> 6; + final int wiLast = (col0 + w - 1) >>> 6; + final int spanWords = wiLast - wiStart + 1; + if (runMaskScratch.length < spanWords) { + runMaskScratch = new long[Math.max(spanWords, runMaskScratch.length * 2)]; + } + final long[] mask = runMaskScratch; + for (int s = 0; s < spanWords; s++) { + final int wIdx = wiStart + s; + final int wordColStart = wIdx * 64; + final int loBit = Math.max(0, col0 - wordColStart); + final int hiBit = Math.min(63, col0 + w - 1 - wordColStart); + final int bitsInWord = hiBit - loBit + 1; + mask[s] = (bitsInWord == 64) ? -1L : (((1L << bitsInWord) - 1L) << loBit); + } + + int h = 1; + extendRow: + while (row + h < rows) { + final int rOff = (row + h) * lpr; + for (int s = 0; s < spanWords; s++) { + final long m = mask[s]; + if ((todo[rOff + wiStart + s] & m) != m) break extendRow; + } + h++; + } + for (int rr = 0; rr < h; rr++) { + final int rOff = (row + rr) * lpr; + for (int s = 0; s < spanWords; s++) { + todo[rOff + wiStart + s] &= ~mask[s]; + } + } + + final int relX0 = col0 + minX; + final int relX1 = relX0 + w; + final int relZ0 = row + minZ; + final int relZ1 = relZ0 + h; + final double x0 = relX0, x1 = relX1, z0 = relZ0, z1 = relZ1; + final float uL = relX0 * SCROLL_SPEED + scrollX; + final float uR = relX1 * SCROLL_SPEED + scrollX; + final float vN = relZ0 * SCROLL_SPEED + scrollZ; + final float vS = relZ1 * SCROLL_SPEED + scrollZ; + + if (bytesPerCell > 0) ensureEmitCapacity(bytesPerCell); + + if (emitTopFace) { + emitCloudQuad(x0, 0.0, z0, uL, vN, x1, 0.0, z0, uR, vN, x1, 0.0, z1, uR, vS, x0, 0.0, z1, uL, vS, F_TOP, N_NEG_Y); + } + if (emitBottomFace) { + emitCloudQuad(x0, ye, z1, uL, vS, x1, ye, z1, uR, vS, x1, ye, z0, uR, vN, x0, ye, z0, uL, vN, F_BOTTOM, N_POS_Y); + } + + word = todo[rowOff + wi]; + } + } + } + } + + private static int measureRowRun(long[] arr, int rowOff, int lpr, int stride, int col0) { + int wi = col0 >>> 6; + final int bit = col0 & 63; + final long highMask = -1L << bit; + final long inv = ~arr[rowOff + wi] & highMask; + if (inv != 0L) { + final int zeroBit = Long.numberOfTrailingZeros(inv); + return Math.min(zeroBit - bit, stride - col0); + } + int run = 64 - bit; + wi++; + while (wi < lpr) { + final long w = arr[rowOff + wi]; + if (w != -1L) { + run += Long.numberOfTrailingZeros(~w); + return Math.min(run, stride - col0); + } + run += 64; + wi++; + } + return Math.min(run, stride - col0); + } + + private void prepareEmitBuffer() { + if (emitBuffer == null) { + emitBufferCapacity = 256 * 1024; + emitBuffer = MemoryUtilities.memRealloc((ByteBuffer) null, emitBufferCapacity); + emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0); + } + writeAddr = emitBufferAddr; + writeEnd = emitBufferAddr + emitBufferCapacity; + quadCount = 0; + } + + private void growEmitBuffer(int neededBytes) { + final long oldBytes = writeAddr - emitBufferAddr; + int newCap = emitBufferCapacity; + while (newCap < neededBytes) newCap *= 2; + emitBuffer = MemoryUtilities.memRealloc(emitBuffer, newCap); + emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0); + emitBufferCapacity = newCap; + writeAddr = emitBufferAddr + oldBytes; + writeEnd = emitBufferAddr + newCap; + } + + private void ensureEmitCapacity(int bytes) { + if (writeAddr + bytes > writeEnd) { + growEmitBuffer((int) (writeAddr - emitBufferAddr) + bytes); + } + } + + private void emitCloudQuad(double x0, double y0, double z0, float u0, float v0, double x1, double y1, double z1, float u1, float v1, double x2, double y2, double z2, float u2, float v2, double x3, double y3, double z3, float u3, float v3, byte factorIdx, int normalInt) { + if (quadCount == quadFactor.length) { + quadFactor = java.util.Arrays.copyOf(quadFactor, quadFactor.length * 2); + } + quadFactor[quadCount++] = factorIdx; + + final int packedNormal = normalInt | FACTOR_BYTE_SHIFTED[factorIdx]; + long a = writeAddr; + a = writeCloudVertex(a, x0, y0, z0, u0, v0, packedNormal); + a = writeCloudVertex(a, x1, y1, z1, u1, v1, packedNormal); + a = writeCloudVertex(a, x2, y2, z2, u2, v2, packedNormal); + a = writeCloudVertex(a, x3, y3, z3, u3, v3, packedNormal); + writeAddr = a; + } + + private static long writeCloudVertex(long addr, double x, double y, double z, float u, float v, int normalInt) { + MemoryUtilities.memPutFloat(addr, (float) x); + MemoryUtilities.memPutFloat(addr + 4, (float) y); + MemoryUtilities.memPutFloat(addr + 8, (float) z); + MemoryUtilities.memPutFloat(addr + 12, u); + MemoryUtilities.memPutFloat(addr + 16, v); + MemoryUtilities.memPutInt(addr + NORMAL_OFFSET, normalInt); + return addr + VERTEX_STRIDE; + } + + private static int packNormalInt(byte nx, byte ny, byte nz) { + final int x = nx & 0xFF, y = ny & 0xFF, z = nz & 0xFF; + return BIG_ENDIAN ? (x << 24) | (y << 16) | (z << 8) : x | (y << 8) | (z << 16); + } + + private void sortQuadsByFactor() { + final int qc = quadCount; + final int[] cnt = factorQuadCount; + cnt[0] = 0; + cnt[1] = 0; + cnt[2] = 0; + cnt[3] = 0; + final byte[] qf = quadFactor; + for (int q = 0; q < qc; q++) cnt[qf[q]]++; + + final int totalBytes = qc * QUAD_BYTES; + if (sortedBuffer == null || sortedBufferCapacity < totalBytes) { + int rounded = Math.max(totalBytes, 64 * 1024); + int pow2 = Integer.highestOneBit(rounded - 1) << 1; + if (pow2 <= 0) pow2 = rounded; + sortedBuffer = MemoryUtilities.memRealloc(sortedBuffer, pow2); + sortedBufferAddr = MemoryUtilities.memAddress(sortedBuffer, 0); + sortedBufferCapacity = pow2; + } + + final int[] off = factorVertOffset; + off[0] = 0; + off[1] = cnt[0] * 4; + off[2] = (cnt[0] + cnt[1]) * 4; + off[3] = (cnt[0] + cnt[1] + cnt[2]) * 4; + + final long[] dst = factorWriteAddr; + dst[0] = sortedBufferAddr; + dst[1] = dst[0] + (long) cnt[0] * QUAD_BYTES; + dst[2] = dst[1] + (long) cnt[1] * QUAD_BYTES; + dst[3] = dst[2] + (long) cnt[2] * QUAD_BYTES; + + final long src0 = emitBufferAddr; + int q = 0; + while (q < qc) { + final int f = qf[q]; + int runEnd = q + 1; + while (runEnd < qc && qf[runEnd] == f) runEnd++; + final int runLen = runEnd - q; + final long runBytes = (long) runLen * QUAD_BYTES; + MemoryUtilities.memCopy(src0 + (long) q * QUAD_BYTES, dst[f], runBytes); + dst[f] += runBytes; + q = runEnd; + } + + sortedBuffer.position(0).limit(totalBytes); + } + + private void setupCloudTexture() { + final int bound = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); + if (bound != mipmapTexId) { + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 4); + GLStateManager.glGenerateMipmap(GL11.GL_TEXTURE_2D); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); + GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); + mipmapTexId = bound; + } + if (bound != cloudTexId || edges == null) { + extractCloudEdges(); + cloudTexId = bound; + } + } + + private void extractCloudEdges() { + final int w = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); + final int h = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + if (w <= 0 || h <= 0) return; + final int needed = w * h * 4; + if (edgeStagingBuffer == null || edgeStagingCapacity < needed) { + edgeStagingBuffer = BufferUtils.createByteBuffer(needed); + edgeStagingCapacity = needed; + } else { + edgeStagingBuffer.clear(); + } + final ByteBuffer buf = edgeStagingBuffer; + GLStateManager.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf); + texW = w; + texH = h; + edges = new CloudEdges(w, h, buf); + edgesGeneration++; + invalidateGeometry(); } private void reloadTextures() { - if (mc.renderEngine != null) { - mc.renderEngine.bindTexture(texture); - texW = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH); - texH = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT); + if (mc.renderEngine == null) return; + mc.renderEngine.bindTexture(texture); + extractCloudEdges(); + if (vao != null) { + vao.delete(); + vao = null; } + deleteEbo(); + mipmapTexId = -1; + cloudTexId = -1; } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java new file mode 100644 index 000000000..53e09296b --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java @@ -0,0 +1,78 @@ +package com.gtnewhorizons.angelica.render; + +import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt; +import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f; + +final class CloudUniforms { + static final float ALPHA = 0.8f; + + final GlUniformMatrix4f mvp; + final GlUniformFloat4v colorMult; + final GlUniformFloat4v fogParams; + final GlUniformFloat4v fogColor; + final GlUniformInt fogEnabled; + final GlUniformInt tex; + + private int lastFogEnabled = -1; + private float lastFogR = Float.NaN, lastFogG = Float.NaN, lastFogB = Float.NaN; + private float lastColorR = Float.NaN, lastColorG = Float.NaN, lastColorB = Float.NaN; + private float lastFogParamX = Float.NaN, lastFogParamY = Float.NaN; + private final float[] uploadBuf = new float[4]; + + CloudUniforms(ShaderBindingContext ctx) { + mvp = ctx.bindUniform("u_MVPMatrix", GlUniformMatrix4f::new); + colorMult = ctx.bindUniform("u_ColorMult", GlUniformFloat4v::new); + fogParams = ctx.bindUniform("u_FogParams", GlUniformFloat4v::new); + fogColor = ctx.bindUniform("u_FogColor", GlUniformFloat4v::new); + fogEnabled = ctx.bindUniform("u_FogEnabled", GlUniformInt::new); + tex = ctx.bindUniform("u_Tex", GlUniformInt::new); + } + + void setFogEnabled(boolean enabled) { + final int val = enabled ? 1 : 0; + if (val != lastFogEnabled) { + lastFogEnabled = val; + fogEnabled.setInt(val); + } + } + + void setFogColor(float r, float g, float b) { + if (r != lastFogR || g != lastFogG || b != lastFogB) { + lastFogR = r; + lastFogG = g; + lastFogB = b; + uploadBuf[0] = r; + uploadBuf[1] = g; + uploadBuf[2] = b; + uploadBuf[3] = 1.0f; + fogColor.set(uploadBuf); + } + } + + void setFogParams(float x, float y) { + if (x != lastFogParamX || y != lastFogParamY) { + lastFogParamX = x; + lastFogParamY = y; + uploadBuf[0] = x; + uploadBuf[1] = y; + uploadBuf[2] = 0f; + uploadBuf[3] = 0f; + fogParams.set(uploadBuf); + } + } + + void setColorMult(float r, float g, float b) { + if (r != lastColorR || g != lastColorG || b != lastColorB) { + lastColorR = r; + lastColorG = g; + lastColorB = b; + uploadBuf[0] = r; + uploadBuf[1] = g; + uploadBuf[2] = b; + uploadBuf[3] = ALPHA; + colorMult.set(uploadBuf); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java b/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java index 58e9fe412..019a23ddd 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/EmissiveTextureAutoloader.java @@ -5,6 +5,10 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.client.resources.FallbackResourceManager; +import net.minecraft.client.resources.IResourceManager; +import net.minecraft.client.resources.IResourcePack; +import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.TextureStitchEvent; @@ -50,8 +54,23 @@ public class EmissiveTextureAutoloader { loc.getResourceDomain(), "textures/blocks/" + loc.getResourcePath() + ".png" ); + + final IResourceManager resMan = Minecraft.getMinecraft().getResourceManager(); + if (resMan instanceof SimpleReloadableResourceManager simple) { + FallbackResourceManager fallback = simple.domainResourceManagers.get(full.getResourceDomain()); + if (fallback != null) { + for (IResourcePack rp : fallback.resourcePacks) { + if (rp != null && rp.resourceExists(full)) { + return true; + } + } + return false; + } + } + + // Fallback try { - Minecraft.getMinecraft().getResourceManager().getResource(full); + resMan.getResource(full); return true; } catch (Exception ignored) { return false; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java index 964087a93..f30ee3fe1 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkBuilderMeshingTask.java @@ -12,8 +12,10 @@ import com.prupe.mcpatcher.mal.block.RenderBlocksUtils; import it.unimi.dsi.fastutil.objects.Reference2ReferenceMap; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.vertices.ExtendedDataHelper; import net.minecraft.block.Block; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; @@ -118,6 +120,10 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask blockTypeIds = provider != null ? provider.getBlockTypeIds() : null; final BlockRenderContext blockRenderContext = buildContext.getBlockRenderContext(); + final NbtConditionalIdMap teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap(); + final net.minecraft.world.World mcWorld = Minecraft.getMinecraft().theWorld; + final long currentTick = mcWorld != null ? mcWorld.getTotalWorldTime() : 0L; + final boolean threaded = isThreaded(); final List deferredBlocks = threaded ? new ArrayList<>() : null; @@ -192,7 +198,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask meshes = @@ -236,7 +242,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask teMap, long currentTick) { final var blockMaterial = block.getMaterial(); final boolean isFluid = blockMaterial == net.minecraft.block.material.Material.water || blockMaterial == net.minecraft.block.material.Material.lava; @@ -272,6 +278,27 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask deferredBlocks, AngelicaChunkBuildContext buildContext, ChunkBuildBuffers buffers, IBlockAccess region, int minX, int minY, int minZ) { + private void processDeferredBlocks(List deferredBlocks, AngelicaChunkBuildContext buildContext, ChunkBuildBuffers buffers, IBlockAccess region, int minX, int minY, int minZ, NbtConditionalIdMap teMap, long currentTick) { final BlockRenderContext blockRenderContext = buildContext.getBlockRenderContext(); @@ -308,7 +335,7 @@ public abstract class AngelicaChunkBuilderMeshingTask extends ChunkBuilderTask configuration, WorldClient world, int renderDistance, CommandList commandList, int minSection, int maxSection, int requestedThreads, ChunkTaskProvider taskProvider) { super(configuration, () -> new AngelicaChunkBuildContext(configuration, world), AngelicaChunkRenderer::new, renderDistance, commandList, minSection, maxSection, requestedThreads, true /* hasShadowPass = true for Iris */); @@ -144,9 +147,35 @@ public class AngelicaRenderSectionManager extends RenderSectionManager { this.sectionCache.invalidate(section.getChunkX(), section.getChunkY(), section.getChunkZ()); } + public void onBiomesChanged(int chunkX, int chunkZ) { + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + this.biomeRebuildColumns.add(PositionUtil.packChunk(chunkX + dx, chunkZ + dz)); + } + } + } + + private void flushBiomeRebuilds() { + if (this.biomeRebuildColumns.isEmpty()) { + return; + } + final int sectionCountY = this.world.getHeight() >> 4; + for (final LongIterator it = this.biomeRebuildColumns.iterator(); it.hasNext(); ) { + final long column = it.nextLong(); + final int cx = PositionUtil.unpackChunkX(column); + final int cz = PositionUtil.unpackChunkZ(column); + for (int cy = 0; cy < sectionCountY; cy++) { + this.sectionCache.invalidate(cx, cy, cz); + this.scheduleRebuild(cx, cy, cz, false); + } + } + this.biomeRebuildColumns.clear(); + } + @Override public void updateChunks(boolean updateImmediately) { this.sectionCache.cleanup(); + this.flushBiomeRebuilds(); super.updateChunks(updateImmediately); } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java index ac05fd4e4..9253a2fa3 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasSetup.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.event.ChunkBiomeDataChangedEvent; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.loading.AngelicaClientTweaker; import org.embeddedt.embeddium.impl.gl.device.GLRenderDevice; @@ -12,8 +13,16 @@ public class CeleritasSetup { public static void ensureInitialized() { if (!initialized && AngelicaConfig.enableCeleritas) { GLRenderDevice.VANILLA_STATE_RESETTER = () -> GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + ChunkBiomeDataChangedEvent.BUS.addListener(CeleritasSetup::onChunkBiomeDataChanged); AngelicaClientTweaker.LOGGER.debug("Celeritas init"); initialized = true; } } + + private static void onChunkBiomeDataChanged(ChunkBiomeDataChangedEvent event) { + final CeleritasWorldRenderer renderer = CeleritasWorldRenderer.getInstanceOrNull(); + if (renderer != null && renderer.isActive()) { + renderer.getRenderSectionManager().onBiomesChanged(event.chunkX, event.chunkZ); + } + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java index 3a5f5b85a..fe7612979 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasWorldRenderer.java @@ -74,6 +74,10 @@ public class CeleritasWorldRenderer extends SimpleWorldRenderer { + map.readLock(); + try { final Object2ObjectOpenHashMap delegate = map.getDelegate(); - if (delegate.isEmpty()) return; + if (!delegate.isEmpty()) { + final int minY = pos.getMinY(); + final int maxY = pos.getMaxY(); - final int minY = pos.getMinY(); - final int maxY = pos.getMaxY(); + for (Object2ObjectMap.Entry entry : Object2ObjectMaps.fastIterable(delegate)) { + final ChunkPosition tePos = entry.getKey(); + if (tePos.chunkPosY < minY || tePos.chunkPosY > maxY) continue; - for (Object2ObjectMap.Entry entry : Object2ObjectMaps.fastIterable(delegate)) { - final ChunkPosition tePos = entry.getKey(); - if (tePos.chunkPosY < minY || tePos.chunkPosY > maxY) continue; - - final TileEntity te = entry.getValue(); - if (te != null && !te.isInvalid()) { - this.tileEntities.put(ChunkSectionPos.packLocal(tePos.chunkPosX & 15, tePos.chunkPosY & 15, tePos.chunkPosZ & 15), te); + final TileEntity te = entry.getValue(); + if (te != null && !te.isInvalid()) { + this.tileEntities.put(ChunkSectionPos.packLocal(tePos.chunkPosX & 15, tePos.chunkPosY & 15, tePos.chunkPosZ & 15), te); + } } } - }); + } finally { + map.readUnlock(); + } this.tileEntities.trim(); } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/world/cloned/ClonedChunkSectionCache.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/world/cloned/ClonedChunkSectionCache.java index 807e8f78e..78e4a27b2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/world/cloned/ClonedChunkSectionCache.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/world/cloned/ClonedChunkSectionCache.java @@ -21,7 +21,13 @@ public class ClonedChunkSectionCache { public synchronized void cleanup() { this.time = getMonotonicTimeSource(); - this.byPosition.values().removeIf(entry -> this.time > (entry.getLastUsedTimestamp() + MAX_CACHE_DURATION)); + while (!this.byPosition.isEmpty()) { + final ClonedChunkSection oldest = this.byPosition.get(this.byPosition.firstLongKey()); + if (this.time <= oldest.getLastUsedTimestamp() + MAX_CACHE_DURATION) { + break; + } + this.byPosition.removeFirst(); + } } public synchronized ClonedChunkSection acquire(int x, int y, int z) { @@ -32,18 +38,17 @@ public class ClonedChunkSectionCache { while (this.byPosition.size() >= MAX_CACHE_SIZE) { this.byPosition.removeFirst(); } - section = this.createSection(x, y, z); + section = this.createSection(key, x, y, z); } section.setLastUsedTimestamp(this.time); return section; } - private ClonedChunkSection createSection(int x, int y, int z) { + private ClonedChunkSection createSection(long key, int x, int y, int z) { final ClonedChunkSection section = new ClonedChunkSection(this, this.world); - final ChunkSectionPos pos = ChunkSectionPos.from(x, y, z); - section.init(pos); - this.byPosition.putAndMoveToLast(pos.asLong(), section); + section.init(ChunkSectionPos.from(x, y, z)); + this.byPosition.putAndMoveToLast(key, section); return section; } diff --git a/src/main/java/com/gtnewhorizons/angelica/utils/ConcurrentTileEntityMap.java b/src/main/java/com/gtnewhorizons/angelica/utils/ConcurrentTileEntityMap.java index ddd23a499..cdcc621c2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/utils/ConcurrentTileEntityMap.java +++ b/src/main/java/com/gtnewhorizons/angelica/utils/ConcurrentTileEntityMap.java @@ -42,6 +42,14 @@ public class ConcurrentTileEntityMap implements Map { } } + public void readLock() { + lock.readLock().lock(); + } + + public void readUnlock() { + lock.readLock().unlock(); + } + public void withWriteLock(Runnable action) { lock.writeLock().lock(); try { diff --git a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java index 41301f6c7..6b213a3a7 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/gui/SodiumGameOptionPages.java @@ -540,56 +540,63 @@ public class SodiumGameOptionPages { groups.add(OptionGroup.createBuilder() .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("RGB Colors") - .setTooltip("Enable hex colors via &#RRGGBB syntax") + .setName(I18n.format("options.angelica.texteffects.rgb_colors")) + .setTooltip(I18n.format("options.angelica.texteffects.rgb_colors.tooltip", "\\&#RRGGBB")) .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableRGBColors = value, opts -> AngelicaConfig.enableRGBColors) .build()) .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("Gradients") - .setTooltip("Smooth color transitions via &g&#start&#end") + .setName(I18n.format("options.angelica.texteffects.gradients")) + .setTooltip(I18n.format("options.angelica.texteffects.gradients.tooltip") + " \\&g\\&#start\\&#end") .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableGradients = value, opts -> AngelicaConfig.enableGradients) .build()) .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("Rainbow") - .setTooltip("Cycling rainbow colors via &q") + .setName(I18n.format("options.angelica.texteffects.rainbow")) + .setTooltip(I18n.format("options.angelica.texteffects.rainbow.tooltip") + " \\&q") .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableRainbow = value, opts -> AngelicaConfig.enableRainbow) .build()) .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("Wave Text") - .setTooltip("Animated bouncing text via &z") + .setName(I18n.format("options.angelica.texteffects.wave_text")) + .setTooltip(I18n.format("options.angelica.texteffects.wave_text.tooltip") + " \\&z") .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableWaveText = value, opts -> AngelicaConfig.enableWaveText) .build()) .add(OptionImpl.createBuilder(int.class, angelicaOpts) - .setName("Wave Amplitude") - .setTooltip("How far wave text bounces (default 2.0)") + .setName(I18n.format("options.angelica.texteffects.wave_amplitude")) + .setTooltip(I18n.format("options.angelica.texteffects.wave_amplitude.tooltip")) .setControl(option -> new SliderControl(option, 10, 80, 5, v -> (v / 10) + "." + (v % 10))) .setBinding((opts, value) -> AngelicaConfig.waveAmplitude = value / 10f, opts -> Math.round(AngelicaConfig.waveAmplitude * 10f)) .build()) .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("Dinnerbone Text") - .setTooltip("Flipped upside down text via &v") + .setName(I18n.format("options.angelica.texteffects.dinnerbone_text")) + .setTooltip(I18n.format("options.angelica.texteffects.dinnerbone_text.tooltip") + " \\&v") .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableDinnerboneText = value, opts -> AngelicaConfig.enableDinnerboneText) .build()) .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) - .setName("Ampersand Conversion") - .setTooltip("Convert & prefix codes to formatting codes at render time") + .setName(I18n.format("options.angelica.texteffects.drop_shadow")) + .setTooltip(I18n.format("options.angelica.texteffects.drop_shadow.tooltip", "\\&u") + " \\&u\\&#RRGGBB") + .setControl(TickBoxControl::new) + .setBinding((opts, value) -> AngelicaConfig.enableDropShadow = value, + opts -> AngelicaConfig.enableDropShadow) + .build()) + .add(OptionImpl.createBuilder(boolean.class, angelicaOpts) + .setName(I18n.format("options.angelica.texteffects.ampersand_conversion")) + .setTooltip(I18n.format("options.angelica.texteffects.ampersand_conversion.tooltip", "\\&")) .setControl(TickBoxControl::new) .setBinding((opts, value) -> AngelicaConfig.enableAmpersandConversion = value, opts -> AngelicaConfig.enableAmpersandConversion) .build()) .build()); - return new OptionPage("Text Effects", ImmutableList.copyOf(groups)); + return new OptionPage(I18n.format("sodium.options.pages.text"), ImmutableList.copyOf(groups)); } } diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java b/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java index 975d223f5..8c188361d 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java +++ b/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java @@ -23,26 +23,33 @@ import java.util.Set; public class BlockMaterialMapping { + public record BlockIdMaps(Reference2ObjectMap blockMetaMap, NbtConditionalIdMap tileEntityMap) {} + /** Meta-key bit OR'd in at runtime when a snowy-tagged block has snow above it. */ public static final int SNOWY_META_BIT = 0x10; /** - * Creates a two-level map structure for block material IDs. - * Based on Iris's BlockState mapping approach adapted for 1.7.10's metadata system. + * Creates the standard block meta ID map, the TileEntity NBT-conditional map, and registers + * snowy blocks on {@link BlockRenderingSettings}. */ - public static Reference2ObjectMap createBlockMetaIdMap(Int2ObjectMap> blockPropertiesMap, boolean skipFlattening) { + public static BlockIdMaps createBlockIdMaps(Int2ObjectMap> blockPropertiesMap, boolean skipFlattening) { final Reference2ObjectMap blockMatches = new Reference2ObjectOpenHashMap<>(); + final NbtConditionalIdMap tileEntityMap = new NbtConditionalIdMap<>(); final ReferenceSet snowyBlocks = new ReferenceOpenHashSet<>(); blockPropertiesMap.forEach((intId, entries) -> { for (BlockEntry entry : entries) { - addBlockMetas(entry, blockMatches, intId, skipFlattening, snowyBlocks); + if (entry.hasNbtProperties()) { + addTileEntityEntry(entry, tileEntityMap, intId); + } else { + addBlockMetas(entry, blockMatches, tileEntityMap, intId, skipFlattening, snowyBlocks); + } } }); BlockRenderingSettings.INSTANCE.setHasSnowyEntries(!snowyBlocks.isEmpty()); BlockRenderingSettings.INSTANCE.setSnowyBlocks(snowyBlocks); - return blockMatches; + return new BlockIdMaps(blockMatches, tileEntityMap); } public static Map createBlockTypeMap(Map blockPropertiesMap) { @@ -55,7 +62,8 @@ public class BlockMaterialMapping { if (block == null && "minecraft".equals(id.getNamespace())) { final List legacyEntries = FlatteningMap.toLegacy(id.getName(), Map.of()); if (legacyEntries != null) { - block = resolveBlockOrNull(legacyEntries.getFirst().getId()); + // Use the first entry for render type (render type applies per-block) + block = resolveBlockOrNull(legacyEntries.getFirst().id()); } } @@ -80,28 +88,64 @@ public class BlockMaterialMapping { }; } + /** + * Creates an NBT-conditional ID map keyed by NamespacedId, for items or entities. + */ + public static NbtConditionalIdMap createNamespacedNbtMap(Int2ObjectMap> nbtEntries) { + NbtConditionalIdMap map = new NbtConditionalIdMap<>(); + + nbtEntries.forEach((intId, entries) -> { + for (BlockEntry entry : entries) { + if (entry.hasNbtProperties()) { + map.addCondition(entry.id(), entry.nbtProperties(), intId); + } + } + }); + + return map; + } + + private static void addTileEntityEntry(BlockEntry entry, NbtConditionalIdMap teMap, int intId) { + final NamespacedId id = entry.id(); + final ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); + + final Block block = (Block) Block.blockRegistry.getObject(resourceLocation.toString()); + + if (block == null || block == Blocks.air) { + return; + } + + teMap.addCondition(block, entry.nbtProperties(), intId); + } + /** * Adds block+metadata combinations to the material ID map. * Based on Iris's addBlockStates method, adapted for 1.7.10 metadata system. */ - private static void addBlockMetas(BlockEntry entry, Reference2ObjectMap idMap, int intId, boolean skipFlattening, ReferenceSet snowyBlocks) { - final NamespacedId id = entry.getId(); - final Map stateProps = entry.getStateProperties(); + private static void addBlockMetas(BlockEntry entry, Reference2ObjectMap idMap, + NbtConditionalIdMap tileEntityMap, int intId, + boolean skipFlattening, ReferenceSet snowyBlocks) { + final NamespacedId id = entry.id(); + final Map stateProps = entry.stateProperties(); final String snowy = stateProps.get("snowy"); final int snowyBit = "true".equals(snowy) ? SNOWY_META_BIT : 0; // Vanilla modern names go through FlatteningMap; legacy-section packs and modded blocks // resolve directly from the registry. List targets = null; - if (!skipFlattening && "minecraft".equals(id.getNamespace()) && (!stateProps.isEmpty() || entry.getMetas().isEmpty())) { + if (!skipFlattening && "minecraft".equals(id.getNamespace()) && (!stateProps.isEmpty() || entry.metas().isEmpty())) { targets = FlatteningMap.toLegacy(id.getName(), stateProps); } if (targets == null) targets = List.of(entry); for (BlockEntry target : targets) { - final Block block = resolveBlockOrNull(target.getId()); + if (target.hasNbtProperties()) { + addTileEntityEntry(target, tileEntityMap, intId); + continue; + } + final Block block = resolveBlockOrNull(target.id()); if (block == null) continue; - applyMetas(block, target.getMetas(), idMap, intId, snowyBit); + applyMetas(block, target.metas(), idMap, intId, snowyBit); if (snowy != null) snowyBlocks.add(block); } } diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java index 2ab786f53..75cc38b96 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java +++ b/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java @@ -2,6 +2,7 @@ package net.coderbot.iris.block_rendering; import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer; import it.unimi.dsi.fastutil.ints.Int2IntMap; +import it.unimi.dsi.fastutil.longs.Long2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.ReferenceSet; @@ -18,16 +19,76 @@ import java.util.Map; public class BlockRenderingSettings { public static final BlockRenderingSettings INSTANCE = new BlockRenderingSettings(); + public static final int CACHE_MISS = Integer.MIN_VALUE; + + private static final int NBT_CACHE_INTERVAL_TICKS = 20; + private static final int TE_NBT_CACHE_MAX = 8192; + + private static final Long2LongLinkedOpenHashMap teNbtIdCache = new Long2LongLinkedOpenHashMap(256); + private static final Object teNbtIdCacheLock = new Object(); + + static { + teNbtIdCache.defaultReturnValue(-1L); + } + + public static long packBlockPos(int x, int y, int z) { + return ((long) x & 0x3FFFFFFL) << 38 | ((long) y & 0xFFFL) << 26 | ((long) z & 0x3FFFFFFL); + } + + public static void invalidateTeNbtCache(int x, int y, int z) { + final long key = packBlockPos(x, y, z); + synchronized (teNbtIdCacheLock) { + teNbtIdCache.remove(key); + } + } + + public static int getCachedTeNbtId(long packedPos, long currentTick) { + final long entry; + synchronized (teNbtIdCacheLock) { + entry = teNbtIdCache.get(packedPos); + } + if (entry == -1L) { + return CACHE_MISS; + } + final long entryTick = entry >>> 32; + if (currentTick - entryTick >= NBT_CACHE_INTERVAL_TICKS) { + return CACHE_MISS; + } + return (int) entry; + } + + public static void cacheTeNbtId(long packedPos, int shaderId, long currentTick) { + // Mask tick into low 31 bits so packed value never collides with the -1L sentinel. + final long packed = ((currentTick & 0x7FFFFFFFL) << 32) | (shaderId & 0xFFFFFFFFL); + synchronized (teNbtIdCacheLock) { + teNbtIdCache.put(packedPos, packed); + while (teNbtIdCache.size() > TE_NBT_CACHE_MAX) { + teNbtIdCache.removeFirstLong(); + } + } + } + + public static void clearTeNbtCache() { + synchronized (teNbtIdCacheLock) { + teNbtIdCache.clear(); + } + } + @Getter private boolean reloadRequired; private Reference2ObjectMap blockMetaMatches; + private NbtConditionalIdMap blockNbtMap; private Map blockTypeIds; // note: no reload needed, entities are rebuilt every frame. @Setter private Object2IntFunction entityIds; + @Setter + private NbtConditionalIdMap entityNbtMap; // note: no reload needed, items are rendered every frame. @Setter private Object2IntFunction itemIds; + @Setter + private NbtConditionalIdMap itemNbtMap; @Getter private float ambientOcclusionLevel; private boolean disableDirectionalShading; @@ -41,6 +102,7 @@ public class BlockRenderingSettings { public BlockRenderingSettings() { reloadRequired = false; blockMetaMatches = null; + blockNbtMap = null; blockTypeIds = null; ambientOcclusionLevel = 1.0F; disableDirectionalShading = false; @@ -82,11 +144,32 @@ public class BlockRenderingSettings { return itemIds; } + @Nullable + public NbtConditionalIdMap getBlockNbtMap() { + return blockNbtMap; + } + + @Nullable + public NbtConditionalIdMap getItemNbtMap() { + return itemNbtMap; + } + + @Nullable + public NbtConditionalIdMap getEntityNbtMap() { + return entityNbtMap; + } + public void setBlockMetaMatches(Reference2ObjectMap blockMetaIds) { this.reloadRequired = true; this.blockMetaMatches = blockMetaIds; } + public void setBlockNbtMap(NbtConditionalIdMap blockNbtMap) { + this.reloadRequired = true; + this.blockNbtMap = blockNbtMap; + clearTeNbtCache(); + } + public boolean hasSnowyEntries() { return hasSnowyEntries; } diff --git a/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java b/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java new file mode 100644 index 000000000..eab175b7f --- /dev/null +++ b/src/main/java/net/coderbot/iris/block_rendering/NbtConditionalIdMap.java @@ -0,0 +1,233 @@ +package net.coderbot.iris.block_rendering; + +import net.coderbot.iris.Iris; +import net.coderbot.iris.shaderpack.materialmap.PropertiesTokenizer; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.ResourceLocation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Maps objects with specific NBT properties to shader IDs. Generic over the + * key type so it works for blocks, items, and entities. + * + * Example: + * block.37=flower_pot[Item=minecraft:red_flower,Data=0] + * item.10=diamond_sword[display.Name='Pointy Stick'] + */ +public class NbtConditionalIdMap { + + /** + * A single property matcher within a condition. + */ + record PropertyMatcher(String key, String[] path, String expectedValue, + long expectedLong, boolean isExpectedLong, + double expectedDouble, boolean isExpectedDouble) { + boolean isPathMatch() { return path != null; } + boolean isExistenceOnly() { return expectedValue == null; } + } + + record NbtCondition(PropertyMatcher[] matchers, int shaderId) {} + + private final Map> conditionsByKey; + + public NbtConditionalIdMap() { + this.conditionsByKey = new HashMap<>(); + } + + /** + * Registers an NBT condition. Unquoted values are resolved via item/block + * registries at registration time. Single-quoted values are kept as literals. + * Dot notation paths are pre-split here so we prevent allocations. + */ + public void addCondition(K key, Map nbtProperties, int shaderId) { + final PropertyMatcher[] matchers = new PropertyMatcher[nbtProperties.size()]; + int i = 0; + + for (Map.Entry entry : nbtProperties.entrySet()) { + final String nbtKey = entry.getKey(); + final PropertiesTokenizer.NbtValue nbtValue = entry.getValue(); + + final String resolvedValue; + if (nbtValue == null) { + resolvedValue = null; + + } else if (nbtValue.literal()) { + resolvedValue = nbtValue.value(); + + } else { + resolvedValue = resolveValue(nbtValue.value()); + } + + final String[] path = nbtKey.contains(".") ? nbtKey.split("\\.") : null; + + long expectedLong = 0; + boolean isExpectedLong = false; + double expectedDouble = 0; + boolean isExpectedDouble = false; + if (resolvedValue != null) { + try { + expectedLong = Long.parseLong(resolvedValue); + isExpectedLong = true; + } catch (NumberFormatException ignored) {} + try { + expectedDouble = Double.parseDouble(resolvedValue); + isExpectedDouble = true; + } catch (NumberFormatException ignored) {} + } + + matchers[i++] = new PropertyMatcher(nbtKey, path, resolvedValue, + expectedLong, isExpectedLong, expectedDouble, isExpectedDouble); + } + + conditionsByKey.computeIfAbsent(key, k -> new ArrayList<>()) + .add(new NbtCondition(matchers, shaderId)); + } + + public boolean hasConditions(K key) { + return conditionsByKey.containsKey(key); + } + + public boolean isEmpty() { + return conditionsByKey.isEmpty(); + } + + /** + * Resolves the shader ID by matching the provided NBT data. + */ + public int resolve(K key, NBTTagCompound nbt) { + final List conditions = conditionsByKey.get(key); + if (conditions == null) { + return -1; + } + + for (NbtCondition condition : conditions) { + if (matchesNbt(nbt, condition.matchers())) { + return condition.shaderId; + } + } + + return -1; + } + + private static boolean matchesNbt(NBTTagCompound nbt, PropertyMatcher[] matchers) { + for (PropertyMatcher matcher : matchers) { + if (matcher.isPathMatch()) { + if (!matchesPath(nbt, matcher.path(), 0, matcher)) { + return false; + } + + } else { + if (!nbt.hasKey(matcher.key())) { + return false; + } + + if (!matcher.isExistenceOnly()) { + if (!matchesNbtValue(nbt.getTag(matcher.key()), matcher)) { + return false; + } + } + } + } + return true; + } + + /** + * Search through dot-separated path in NBT data. + */ + private static boolean matchesPath(NBTBase tag, String[] path, int depth, PropertyMatcher matcher) { + if (depth == path.length) { + if (matcher.isExistenceOnly()) { + return true; + } + + return matchesNbtValue(tag, matcher); + } + + final String segment = path[depth]; + + if (tag instanceof NBTTagCompound compound) { + if (!compound.hasKey(segment)) { + return false; + } + + return matchesPath(compound.getTag(segment), path, depth + 1, matcher); + } + + if (tag instanceof NBTTagList list) { + for (int i = 0; i < list.tagCount(); i++) { + if (matchesPath(list.getCompoundTagAt(i), path, depth, matcher)) { + return true; + } + } + + return false; + } + + return false; + } + + /** + * Compares an NBT tag's value against an expected string using type-specific + * accessors to avoid toString() allocations where possible. + * Makes it so you don't need to specify the type either in the .properties files. + */ + private static boolean matchesNbtValue(NBTBase tag, PropertyMatcher matcher) { + return switch (tag.getId()) { + case 1 -> // TAG_Byte + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagByte) tag).func_150290_f() == matcher.expectedLong(); + case 2 -> // TAG_Short + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagShort) tag).func_150289_e() == matcher.expectedLong(); + case 3 -> // TAG_Int + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagInt) tag).func_150287_d() == matcher.expectedLong(); + case 4 -> // TAG_Long + matcher.isExpectedLong() && ((net.minecraft.nbt.NBTTagLong) tag).func_150291_c() == matcher.expectedLong(); + case 5 -> // TAG_Float + matcher.isExpectedDouble() && ((net.minecraft.nbt.NBTTagFloat) tag).func_150288_h() == (float) matcher.expectedDouble(); + case 6 -> // TAG_Double + matcher.isExpectedDouble() && ((net.minecraft.nbt.NBTTagDouble) tag).func_150286_g() == matcher.expectedDouble(); + case 8 -> // TAG_String + matcher.expectedValue().equals(((net.minecraft.nbt.NBTTagString) tag).func_150285_a_()); + default -> // Compounds, lists, arrays — fall back to toString + matcher.expectedValue().equals(PropertiesTokenizer.stripQuotes(tag.toString())); + }; + } + + /** + * Tries to resolve a value as a registry name (item or block) to its numeric ID. + * If the value is already numeric or can't be resolved, return it unchanged. + */ + private static String resolveValue(String value) { + try { + Integer.parseInt(value); + return value; + } catch (NumberFormatException ignored) {} + + if (!value.contains(":")) { + Iris.logger.warn("NBT value '{}' is missing a namespace, please use the full form e.g. 'minecraft:{}'", value, value); + return value; + } + + final ResourceLocation loc = new ResourceLocation(value); + + final Item item = (Item) Item.itemRegistry.getObject(loc.toString()); + if (item != null) { + return String.valueOf(Item.getIdFromItem(item)); + } + + final Block block = (Block) Block.blockRegistry.getObject(loc.toString()); + if (block != null) { + return String.valueOf(Block.getIdFromBlock(block)); + } + + Iris.logger.warn("Could not resolve '{}' to an item or block ID", value); + return value; + } +} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java index d9168e63f..813c8c4e7 100644 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java +++ b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java @@ -18,6 +18,7 @@ public enum RenderCondition { HAND_TRANSLUCENT, RAIN_SNOW, WORLD_BORDER, + LIGHTNING, SHADOW_TRANSLUCENT, // NB: Must be last due to implementation details of DeferredWorldRenderingPipeline SHADOW diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java index deeb20933..5454e8390 100644 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java +++ b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java @@ -3,5 +3,6 @@ package net.coderbot.iris.gbuffer_overrides.matching; public enum SpecialCondition { ENTITY_EYES, BEACON_BEAM, - GLINT + GLINT, + LIGHTNING } diff --git a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java b/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java index 3568d0764..fd72e1a2c 100644 --- a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java +++ b/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java @@ -2,16 +2,16 @@ package net.coderbot.iris.gl.buffer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import lombok.Getter; import org.embeddedt.embeddium.impl.gl.debug.GLDebug; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL43; public class ShaderStorageBuffer { protected final int index; protected final ShaderStorageInfo info; - protected int id; + @Getter protected int id; public ShaderStorageBuffer(int index, ShaderStorageInfo info) { this.id = RenderSystem.createBuffers(); @@ -45,16 +45,13 @@ public class ShaderStorageBuffer { GLStateManager.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, newId); // Calculation time - int newWidth = (int) (width * info.scaleX()); - int newHeight = (int) (height * info.scaleY()); - int finalSize = (newHeight * newWidth) * info.size(); + long newWidth = (long) (width * info.scaleX()); + long newHeight = (long) (height * info.scaleY()); + long finalSize = (newHeight * newWidth) * info.size(); RenderSystem.bufferStorage(GL43.GL_SHADER_STORAGE_BUFFER, finalSize, 0); RenderSystem.clearBufferSubData(GL43.GL_SHADER_STORAGE_BUFFER, GL30.GL_R8, 0, finalSize, GL11.GL_RED, GL11.GL_BYTE, new int[]{0}); RenderSystem.bindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, index, newId); id = newId; } - public int getId() { - return id; - } } diff --git a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java b/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java index 5f7e78aea..310f8d8a6 100644 --- a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java +++ b/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java @@ -1,4 +1,4 @@ package net.coderbot.iris.gl.buffer; -public record ShaderStorageInfo(int size, boolean relative, float scaleX, float scaleY) { +public record ShaderStorageInfo(long size, boolean relative, float scaleX, float scaleY) { } diff --git a/src/main/java/net/coderbot/iris/gl/program/Program.java b/src/main/java/net/coderbot/iris/gl/program/Program.java index 7c2514576..bb0b34a34 100644 --- a/src/main/java/net/coderbot/iris/gl/program/Program.java +++ b/src/main/java/net/coderbot/iris/gl/program/Program.java @@ -4,15 +4,18 @@ import lombok.Getter; import net.coderbot.iris.gl.GlResource; import net.coderbot.iris.gl.blending.DepthColorStorage; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; public final class Program extends GlResource { - + @Getter private final ProgramUniforms uniforms; - + @Getter private final ProgramSamplers samplers; - + @Getter private final ProgramImages images; @@ -25,15 +28,16 @@ public final class Program extends GlResource { DepthColorStorage.registerOwnedProgram(program); } - + public void use() { + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); GLStateManager.glUseProgram(getGlId()); - + uniforms.update(); samplers.update(); images.update(); } - + public static void unbind() { ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); @@ -45,7 +49,7 @@ public final class Program extends GlResource { DepthColorStorage.unregisterOwnedProgram(getGlId()); GLStateManager.glDeleteProgram(getGlId()); } - + public int getProgramId() { return getGlId(); } diff --git a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java b/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java index caaa98d17..181dabdf6 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java +++ b/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java @@ -8,6 +8,7 @@ import net.coderbot.iris.compat.dh.DHCompat; import net.coderbot.iris.parsing.BiomeCategories; import net.coderbot.iris.pipeline.HandRenderer; import net.coderbot.iris.pipeline.WorldRenderingPhase; +import net.coderbot.iris.shaderpack.IrisLimits; import net.coderbot.iris.shaderpack.StringPair; import net.coderbot.iris.texture.format.TextureFormat; import net.coderbot.iris.texture.format.TextureFormatLoader; @@ -81,6 +82,9 @@ public class StandardMacros { define(standardDefines, "IS_ANGELICA"); if (AngelicaConfig.defineIsIris) { define(standardDefines, "IS_IRIS"); + define(standardDefines, "IRIS_VERSION", "10803"); + define(standardDefines, "IRIS_HAS_TRANSLUCENCY_SORTING"); + define(standardDefines, "MAX_COLOR_BUFFERS", String.valueOf(IrisLimits.MAX_COLOR_BUFFERS)); } if (DHCompat.hasRenderingEnabled()) { diff --git a/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java b/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java index 6c9add282..1dd1dcafb 100644 --- a/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java +++ b/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java @@ -11,6 +11,7 @@ public class StateUpdateNotifiers { public static ValueUpdateNotifier alphaFuncNotifier; public static ValueUpdateNotifier alphaTestNotifier; public static ValueUpdateNotifier blendFuncNotifier; + public static ValueUpdateNotifier colorModulatorNotifier; public static ValueUpdateNotifier bindTextureNotifier; public static ValueUpdateNotifier normalTextureChangeNotifier; public static ValueUpdateNotifier specularTextureChangeNotifier; diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 989dfe262..82b3c3f6e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -90,6 +90,7 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; import java.util.ArrayList; import java.util.Collections; @@ -277,15 +278,19 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R holder -> CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), this.updateNotifier) ); - BlockRenderingSettings.INSTANCE.setBlockMetaMatches(BlockMaterialMapping.createBlockMetaIdMap( + final var blockIdMaps = BlockMaterialMapping.createBlockIdMaps( programs.getPack().getIdMap().getBlockProperties(), - programs.getPack().getIdMap().hasLegacySection())); + programs.getPack().getIdMap().hasLegacySection()); + BlockRenderingSettings.INSTANCE.setBlockMetaMatches(blockIdMaps.blockMetaMap()); + BlockRenderingSettings.INSTANCE.setBlockNbtMap(blockIdMaps.tileEntityMap()); BlockRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programs.getPack().getIdMap().getBlockRenderTypeMap())); BlockRenderingSettings.INSTANCE.setEntityIds(programs.getPack().getIdMap().getEntityIdMap()); + BlockRenderingSettings.INSTANCE.setEntityNbtMap(BlockMaterialMapping.createNamespacedNbtMap(programs.getPack().getIdMap().getEntityNbtEntries())); ItemMaterialHelper.clearCache(); BlockRenderingSettings.INSTANCE.setItemIds(programs.getPack().getIdMap().getItemIdMap()); + BlockRenderingSettings.INSTANCE.setItemNbtMap(BlockMaterialMapping.createNamespacedNbtMap(programs.getPack().getIdMap().getItemNbtEntries())); BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programs.getPackDirectives().getAmbientOcclusionLevel()); BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); BlockRenderingSettings.INSTANCE.setUseSeparateAo(programs.getPackDirectives().shouldUseSeparateAo()); @@ -390,6 +395,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R null, null, ProgramId.Weather, // world border uses textured_lit even though it has no lightmap :/ null, ProgramId.TexturedLit, ProgramId.TexturedLit, + ProgramId.Lightning, ProgramId.Lightning, ProgramId.Lightning, ProgramId.ShadowWater, ProgramId.ShadowWater, ProgramId.ShadowWater, ProgramId.Shadow, ProgramId.Shadow, ProgramId.Shadow }; @@ -513,7 +519,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } if (hasSetup) { ComputeProgram.unbind(); - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); } // Terrain pipeline sampler/image factory setup follows. @@ -719,6 +725,8 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return RenderCondition.ENTITY_EYES; } else if (special == SpecialCondition.GLINT) { return RenderCondition.GLINT; + } else if (special == SpecialCondition.LIGHTNING) { + return RenderCondition.LIGHTNING; } } @@ -767,11 +775,11 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R public boolean shouldOverrideShaders() { return isRenderingWorld && !isRenderingFullScreenPass && !isPostChain && isMainBound; } - + public Pass getActivePassProgram() { return current; } - + public int getActivePassProgramId() { if (current == null) return -1; final Program p = current.getProgram(); @@ -789,10 +797,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R if (!isRenderingWorld || isRenderingFullScreenPass || isPostChain || !isMainBound) { return; } - + final RenderCondition condition = getCondition(getPhase()); final Pass matched = table.match(condition, inputs); - + beginPass(matched); } @@ -1328,7 +1336,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } if (ranSetup) { ComputeProgram.unbind(); - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java b/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java index d694bbd1e..e20469d85 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java @@ -3,6 +3,7 @@ package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.compat.mojang.InteractionHand; +import com.gtnewhorizons.angelica.event.RenderHandEvent; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.celeritas.BlockRenderLayer; @@ -78,7 +79,8 @@ public class HandRenderer { !camera.isSleeping() && !mc.gameSettings.hideGUI && !GameModeUtil.isSpectator() && - !mc.playerController.enableEverythingIsScrewedUpMode(); + !mc.playerController.enableEverythingIsScrewedUpMode() && + !RenderHandEvent.post(); } public boolean isHandTranslucent(InteractionHand hand) { diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java index 070e6b574..e5dc10b61 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -34,7 +34,7 @@ class AttributeTransformer { transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); transformer.rename("gl_Vertex", "iris_Vertex"); - transformer.rename("gl_Color", "iris_Color"); + transformer.replaceExpression("gl_Color", "(iris_Color * iris_ColorModulator)"); transformer.rename("gl_Normal", "iris_Normal"); // ftransform() = gl_ModelViewProjectionMatrix * gl_Vertex diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java index f15754d67..a8bb4300e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java @@ -34,6 +34,7 @@ class CeleritasTransformer { transformer.injectFunction( "void _celeritas_init() { " + "_vert_init(); " + + "_vert_color = _vert_color * iris_ColorModulator; " + "iris_LightTexCoord = vec4(vec2(_vert_tex_light_coord), 0.0, 1.0); }"); transformer.prependMain("_celeritas_init();"); transformShared(transformer, parameters); @@ -60,6 +61,7 @@ class CeleritasTransformer { } private static void transformShared(Transformer transformer, Parameters parameters) { + transformer.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0)"); CoreTransformHelper.injectMatrixUniforms(transformer); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java index cb25a0188..fed34cd02 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java @@ -20,9 +20,10 @@ public class CommonTransformer { } if (parameters.type == ShaderType.VERTEX) { + root.injectVariable("uniform vec4 iris_ColorModulator;"); root.injectVariable("out vec4 iris_FrontColor;"); root.rename("gl_FrontColor", "iris_FrontColor"); - root.prependMain("iris_FrontColor = vec4(1.0);"); + root.prependMain("iris_FrontColor = iris_ColorModulator;"); } else if (parameters.type == ShaderType.FRAGMENT) { root.injectVariable("in vec4 iris_FrontColor;"); root.rename("gl_Color", "iris_FrontColor"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java index 024f711d2..99f928ecf 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/DHGenericTransformer.java @@ -94,7 +94,7 @@ public class DHGenericTransformer { + " float skyLight = (float(uSkyLight) + 0.5) / 16.0;" + " _vert_tex_light_coord = vec2(blockLight, skyLight);" + " dhMaterialId = aMaterial;" - + " _vert_color = iris_color;" + + " _vert_color = iris_color * iris_ColorModulator;" + " }" ); transformer.prependMain("_vert_init();"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java index 0f9ae6f93..14e75fa61 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/DHTerrainTransformer.java @@ -86,7 +86,7 @@ public class DHTerrainTransformer { + " _vert_normal = irisNormals[int(irisExtra.y)];" + " dhMaterialId = int(irisExtra.x);" + " _vert_tex_light_coord = vec2((float(lights / 16u) + 0.5) / 16.0, (mod(float(lights), 16.0) + 0.5) / 16.0);" - + " _vert_color = iris_color;" + + " _vert_color = iris_color * iris_ColorModulator;" + " }" ); transformer.prependMain("_vert_init();"); diff --git a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java index b30e69e38..a8b2aba1e 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java @@ -44,6 +44,7 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; import java.util.Map; import java.util.Objects; @@ -263,7 +264,7 @@ public class CompositeRenderer { } if (ranCompute) { - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); } Program.unbind(); diff --git a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java index 92331d046..dee5b1790 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java @@ -42,6 +42,7 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; import java.util.Map; import java.util.Objects; @@ -229,7 +230,7 @@ public class FinalPassRenderer { } } - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); if (!finalPass.mipmappedBuffers.isEmpty()) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); diff --git a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java b/src/main/java/net/coderbot/iris/shaderpack/IdMap.java index edb2f12c1..7272d6039 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/IdMap.java @@ -14,6 +14,7 @@ import net.coderbot.iris.shaderpack.materialmap.BlockEntry; import net.coderbot.iris.shaderpack.materialmap.EntityFlatteningMap; import net.coderbot.iris.shaderpack.materialmap.BlockRenderType; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import net.coderbot.iris.shaderpack.materialmap.PropertiesTokenizer; import net.coderbot.iris.shaderpack.option.ShaderPackOptions; import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor; import net.minecraft.item.Item; @@ -45,11 +46,15 @@ public class IdMap { * Maps a given item ID to an integer ID */ private final Object2IntMap itemIdMap; + @Getter + private final Int2ObjectMap> itemNbtEntries; /** * Maps a given entity ID to an integer ID */ private final Object2IntMap entityIdMap; + @Getter + private final Int2ObjectMap> entityNbtEntries; /** * Maps block states to block ids defined in block.properties @@ -106,8 +111,17 @@ public class IdMap { }); } - itemIdMap = loadProperties(shaderPath, "item.properties", shaderPackOptions, resolvedDefines).map(IdMap::parseItemIdMap).orElse(Object2IntMaps.emptyMap()); - entityIdMap = loadProperties(shaderPath, "entity.properties", shaderPackOptions, resolvedDefines).map(IdMap::parseEntityIdMap).orElse(Object2IntMaps.emptyMap()); + final ParsedIdMap parsedItems = loadProperties(shaderPath, "item.properties", shaderPackOptions, resolvedDefines) + .map(p -> parseIdMap(p, "item.", "item.properties")) + .orElse(new ParsedIdMap(Object2IntMaps.emptyMap(), new Int2ObjectOpenHashMap<>())); + itemIdMap = parsedItems.simpleMap(); + itemNbtEntries = parsedItems.nbtEntries(); + + final ParsedIdMap parsedEntities = loadProperties(shaderPath, "entity.properties", shaderPackOptions, resolvedDefines) + .map(p -> parseIdMap(p, "entity.", "entity.properties")) + .orElse(new ParsedIdMap(Object2IntMaps.emptyMap(), new Int2ObjectOpenHashMap<>())); + entityIdMap = augmentEntityIdMap(parsedEntities.simpleMap(), parsedEntities.nbtEntries()); + entityNbtEntries = parsedEntities.nbtEntries(); // TODO: Properly override block render layers @@ -166,25 +180,37 @@ public class IdMap { } } - private static Object2IntMap parseItemIdMap(Properties properties) { - return parseIdMap(properties, "item.", "item.properties"); - } - - private static Object2IntMap parseEntityIdMap(Properties properties) { - Object2IntMap idMap = parseIdMap(properties, "entity.", "entity.properties"); - - // For modern shader packs: translate modern entity names to 1.7.10 names - // so runtime lookups match EntityList's registered names directly. + /** + * For modern shaderpacks: also expose entries under their 1.7.10 entity names + * so runtime lookups match EntityList's registered names directly. + * + * Modern names whose 1.7.10 counterpart is NBT-discriminated (e.g. wither_skeleton + * is just Skeleton with SkeletonType=1) are routed into the NBT-conditional map + * instead of being aliased into the simple map — otherwise the simple lookup for + * "Skeleton" would short-circuit and match every skeleton variant. + */ + private static Object2IntMap augmentEntityIdMap( + Object2IntMap idMap, + Int2ObjectMap> nbtEntries) { Object2IntMap augmented = new Object2IntOpenHashMap<>(idMap); augmented.defaultReturnValue(-1); for (Object2IntMap.Entry entry : idMap.object2IntEntrySet()) { NamespacedId id = entry.getKey(); - if ("minecraft".equals(id.getNamespace())) { - String legacyName = EntityFlatteningMap.toLegacy(id.getName()); - if (legacyName != null) { - augmented.putIfAbsent(new NamespacedId(legacyName), entry.getIntValue()); - } + if (!"minecraft".equals(id.getNamespace())) { + continue; + } + final int intId = entry.getIntValue(); + + BlockEntry nbtMapping = EntityFlatteningMap.toLegacyWithNbt(id.getName()); + if (nbtMapping != null) { + nbtEntries.computeIfAbsent(intId, k -> new ArrayList<>()).add(nbtMapping); + continue; + } + + String legacyName = EntityFlatteningMap.toLegacy(id.getName()); + if (legacyName != null) { + augmented.putIfAbsent(new NamespacedId(legacyName), intId); } } @@ -212,67 +238,18 @@ public class IdMap { * @return List of parsed identifiers */ static List parseIdentifierList(String value, String fileName, String key) { - if (value.indexOf('"') == -1) { - String[] parts = value.split("\\s+"); - List result = new ArrayList<>(parts.length); - for (String part : parts) { - if (!part.isEmpty()) { - result.add(part); - } - } - return result; - } - - // Found quote, start of a dumb block ID - List result = new ArrayList<>(); - StringBuilder current = new StringBuilder(); - boolean inQuotes = false; - boolean escaped = false; - - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - - if (escaped) { - current.append(c); - escaped = false; - } else if (c == '\\') { - escaped = true; - } else if (c == '"') { - inQuotes = !inQuotes; - } else if (Character.isWhitespace(c) && !inQuotes) { - if (!current.isEmpty()) { - result.add(current.toString()); - current.setLength(0); - } - } else { - current.append(c); - } - } - - // Didn't close a quote, warn - if (inQuotes) { - Iris.logger.warn(fileName + " [" + key + "]: Unclosed quote"); - } - - // Trailing backslash, warn - if (escaped) { - Iris.logger.warn(fileName + " [" + key + "]: Trailing backslash"); - } - - // Add final token - if (!current.isEmpty()) { - result.add(current.toString()); - } - - return result; + return PropertiesTokenizer.tokenizeValues(value, ' '); } + record ParsedIdMap(Object2IntMap simpleMap, Int2ObjectMap> nbtEntries) {} + /** * Parses a NamespacedId map in OptiFine format */ - private static Object2IntMap parseIdMap(Properties properties, String keyPrefix, String fileName) { + private static ParsedIdMap parseIdMap(Properties properties, String keyPrefix, String fileName) { Object2IntMap idMap = new Object2IntOpenHashMap<>(); idMap.defaultReturnValue(-1); + Int2ObjectMap> nbtEntries = new Int2ObjectOpenHashMap<>(); properties.forEach((keyObject, valueObject) -> { String key = (String) keyObject; @@ -295,6 +272,20 @@ public class IdMap { // Parse identifiers for (String part : parseIdentifierList(value, fileName, key)) { + if (part.contains("[")) { + // NBT-conditional entry + try { + BlockEntry entry = BlockEntry.parse(part); + if (entry.hasNbtProperties()) { + nbtEntries.computeIfAbsent(intId, k -> new ArrayList<>()).add(entry); + } else { + idMap.put(entry.id(), intId); + } + } catch (Exception e) { + Iris.logger.warn("Failed to parse NBT entry in " + fileName + " for key " + key + ": " + part, e); + } + continue; + } if (part.contains("=")) { // Avoid tons of logspam for now Iris.logger.warn("Failed to parse an ResourceLocation in " + fileName + " for the key " + key + ": state properties are currently not supported: " + part); @@ -307,7 +298,7 @@ public class IdMap { } }); - return Object2IntMaps.unmodifiable(idMap); + return new ParsedIdMap(Object2IntMaps.unmodifiable(idMap), nbtEntries); } private static Int2ObjectMap> parseBlockMap(Properties properties, String keyPrefix, String fileName) { @@ -408,7 +399,7 @@ public class IdMap { return itemIdMap; } - public Object2IntFunction getEntityIdMap() { + public Object2IntFunction getEntityIdMap() { return entityIdMap; } diff --git a/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java b/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java index 6ff7b8dc1..2fe6b12db 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java +++ b/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java @@ -41,6 +41,7 @@ public class ProgramSet { private final ProgramSource gbuffersEntities; private final ProgramSource gbuffersEntitiesTrans; private final ProgramSource gbuffersEntitiesGlowing; + private final ProgramSource gbuffersLightning; private final ProgramSource gbuffersGlint; private final ProgramSource gbuffersEntityEyes; private final ProgramSource gbuffersBlock; @@ -120,6 +121,7 @@ public class ProgramSet { this.gbuffersEntities = readProgramSource(directory, sourceProvider, "gbuffers_entities", this, shaderProperties); this.gbuffersEntitiesTrans = readProgramSource(directory, sourceProvider, "gbuffers_entities_translucent", this, shaderProperties); this.gbuffersEntitiesGlowing = readProgramSource(directory, sourceProvider, "gbuffers_entities_glowing", this, shaderProperties); + this.gbuffersLightning = readProgramSource(directory, sourceProvider, "gbuffers_lightning", this, shaderProperties); this.gbuffersGlint = readProgramSource(directory, sourceProvider, "gbuffers_armor_glint", this, shaderProperties); this.gbuffersEntityEyes = readProgramSource(directory, sourceProvider, "gbuffers_spidereyes", this, shaderProperties); this.gbuffersBlock = readProgramSource(directory, sourceProvider, "gbuffers_block", this, shaderProperties); @@ -229,7 +231,7 @@ public class ProgramSet { programs.addAll (Arrays.asList( gbuffersBasic, gbuffersBeaconBeam, gbuffersTextured, gbuffersTexturedLit, gbuffersTerrain, gbuffersDamagedBlock, gbuffersSkyBasic, gbuffersSkyTextured, gbuffersClouds, gbuffersWeather, - gbuffersEntities, gbuffersEntitiesTrans, gbuffersEntitiesGlowing, gbuffersGlint, gbuffersEntityEyes, gbuffersBlock, gbuffersBlockTrans, + gbuffersEntities, gbuffersEntitiesTrans, gbuffersEntitiesGlowing, gbuffersLightning, gbuffersGlint, gbuffersEntityEyes, gbuffersBlock, gbuffersBlockTrans, gbuffersHand, dhShadow, dhTerrain, dhGeneric, dhWater )); @@ -382,6 +384,10 @@ public class ProgramSet { return gbuffersEntitiesGlowing.requireValid(); } + public Optional getGbuffersLightning() { + return gbuffersLightning.requireValid(); + } + public Optional getGbuffersGlint() { return gbuffersGlint.requireValid(); } @@ -437,6 +443,7 @@ public class ProgramSet { case Entities -> getGbuffersEntities(); case EntitiesTrans -> getGbuffersEntitiesTrans(); case EntitiesGlowing -> getGbuffersEntitiesGlowing(); + case Lightning -> getGbuffersLightning(); case ArmorGlint -> getGbuffersGlint(); case SpiderEyes -> getGbuffersEntityEyes(); case Hand -> getGbuffersHand(); diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java index a8f4c689c..73b4b9da9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java +++ b/src/main/java/net/coderbot/iris/shaderpack/ShaderProperties.java @@ -771,7 +771,7 @@ public class ShaderProperties { return; } - final int size = Integer.parseInt(parts[0]); + final long size = Long.parseLong(parts[0]); // Size < 1 means the shader dev intended to disable the buffer if (size < 1) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java b/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java index 28b7e60e9..48196cb9a 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java +++ b/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java @@ -23,7 +23,7 @@ public enum ProgramId { TexturedLit(ProgramGroup.Gbuffers, "textured_lit", Textured), SkyBasic(ProgramGroup.Gbuffers, "skybasic", Basic), SkyTextured(ProgramGroup.Gbuffers, "skytextured", Textured), - Clouds(ProgramGroup.Gbuffers, "clouds", Textured), + Clouds(ProgramGroup.Gbuffers, "clouds", Textured, null, new AlphaTestOverride(new AlphaTest(AlphaTestFunction.GREATER, 0.1F))), Terrain(ProgramGroup.Gbuffers, "terrain", TexturedLit), TerrainSolid(ProgramGroup.Gbuffers, "terrain_solid", Terrain), @@ -39,6 +39,7 @@ public enum ProgramId { Entities(ProgramGroup.Gbuffers, "entities", TexturedLit), EntitiesTrans(ProgramGroup.Gbuffers, "entities_translucent", Entities), EntitiesGlowing(ProgramGroup.Gbuffers, "entities_glowing", Entities), + Lightning(ProgramGroup.Gbuffers, "lightning", Entities), ArmorGlint(ProgramGroup.Gbuffers, "armor_glint", Textured), SpiderEyes(ProgramGroup.Gbuffers, "spidereyes", Textured, new BlendModeOverride(new BlendState(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO, GL11.GL_ONE)), diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java index 51582af76..1b8447ce7 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java @@ -1,124 +1,45 @@ package net.coderbot.iris.shaderpack.materialmap; -import lombok.Getter; -import net.coderbot.iris.Iris; -import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Objects; import java.util.Set; -@Getter -public class BlockEntry { - private final NamespacedId id; - private final Set metas; - private final Map stateProperties; +public record BlockEntry( + NamespacedId id, + Set metas, + Map stateProperties, + Map nbtProperties +) { + public BlockEntry(NamespacedId id, Set metas) { + this(id, metas, Collections.emptyMap(), Collections.emptyMap()); + } - public BlockEntry(NamespacedId id, Set metas) { - this(id, metas, Collections.emptyMap()); - } + public BlockEntry(NamespacedId id, Set metas, Map stateProperties) { + this(id, metas, stateProperties, Collections.emptyMap()); + } - public BlockEntry(NamespacedId id, Set metas, Map stateProperties) { - this.id = id; - this.metas = metas; - this.stateProperties = stateProperties; - } + public boolean hasNbtProperties() { + return !nbtProperties.isEmpty(); + } - /** - * Parses a block ID entry. - * - * @param entry The string representation of the entry. Must not be empty. - */ - @NotNull - public static BlockEntry parse(@NotNull String entry) { - if (entry.isEmpty()) { - throw new IllegalArgumentException("Called BlockEntry::parse with an empty string"); - } + public boolean hasStateProperties() { + return !stateProperties.isEmpty(); + } - // We can assume that this array is of at least array length because the input string is non-empty. - final String[] splitStates = entry.split(":"); - - // Trivial case: no states, no namespace - if (splitStates.length == 1) { - return new BlockEntry(new NamespacedId("minecraft", entry), Collections.emptySet()); - } - - // Examples of what we accept: - // stone - // stone:0 - // minecraft:stone:0 - // minecraft:stone:0,1,2 - // minecraft:furnace:lit=true (blockstate property) - // minecraft:oak_log:axis=y (blockstate property) - - // Less trivial case: no metas or state properties, just a namespace - if (splitStates.length == 2 && !StringUtils.isNumeric(splitStates[1].substring(0, 1)) - && !splitStates[1].contains("=")) { - return new BlockEntry(new NamespacedId(splitStates[0], splitStates[1]), Collections.emptySet()); - } - - // Complex case: metas and/or state properties - final int statesStart; - final NamespacedId id; - - if (splitStates.length == 2) { - // "stone:0" or "stone:lit=true" - statesStart = 1; - id = new NamespacedId("minecraft", splitStates[0]); - } else if (StringUtils.isNumeric(splitStates[1].substring(0, 1)) || splitStates[1].contains("=")) { - // "stone:0:something" or "stone:lit=true:something" — unlikely but handle it - statesStart = 1; - id = new NamespacedId("minecraft", splitStates[0]); - } else { - // "minecraft:stone:0" or "minecraft:furnace:lit=true" - statesStart = 2; - id = new NamespacedId(splitStates[0], splitStates[1]); - } - - final Set metas = new HashSet<>(); - final Map properties = new HashMap<>(); - - for (int index = statesStart; index < splitStates.length; index++) { - String segment = splitStates[index]; - - if (segment.contains("=")) { - // Blockstate property: key=value - for (String prop : segment.split(",")) { - int eq = prop.indexOf('='); - if (eq > 0 && eq < prop.length() - 1) { - properties.put(prop.substring(0, eq), prop.substring(eq + 1)); - } - } - } else { - // Metadata IDs: comma-separated integers - for (String metaPart : segment.split(",")) { - try { - metas.add(Integer.parseInt(metaPart)); - } catch (NumberFormatException e) { - Iris.logger.warn("Warning: the block ID map entry \"" + entry + "\" could not be fully parsed:"); - Iris.logger.warn("- Metadata ids must be a comma separated list of one or more integers, but " + segment + " is not of that form!"); - } - } - } + /** + * Parses a block ID entry. All tokenization is delegated to {@link PropertiesTokenizer}. + * + * @param entry The string representation of the entry. Must not be empty. + */ + @NotNull + public static BlockEntry parse(@NotNull String entry) { + if (entry.isEmpty()) { + throw new IllegalArgumentException("Called BlockEntry::parse with an empty string"); } - return new BlockEntry(id, metas, properties); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final BlockEntry that = (BlockEntry) o; - return Objects.equals(id, that.id) && Objects.equals(metas, that.metas) && Objects.equals(stateProperties, that.stateProperties); - } - - @Override - public int hashCode() { - return Objects.hash(id, metas, stateProperties); - } + final PropertiesTokenizer.ParsedBlockIdentifier parsed = PropertiesTokenizer.parseBlockIdentifier(entry); + return new BlockEntry(parsed.id(), parsed.metas(), parsed.stateProperties(), parsed.nbtProperties()); + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java index ee32f528d..c69848428 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/EntityFlatteningMap.java @@ -1,5 +1,6 @@ package net.coderbot.iris.shaderpack.materialmap; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -10,14 +11,15 @@ import java.util.Map; * In 1.7.10, entities are registered with names like "CaveSpider". * Some entities were also renamed or split into multiple types. * - * This map is used at lookup time: when a modern shader pack references an entity by its - * modern name, we resolve it to the 1.7.10 name that EntityList uses. */ public class EntityFlatteningMap { /** Maps modern entity name -> 1.7.10 entity name. */ private static final Map MODERN_TO_LEGACY = new HashMap<>(); + /** Maps modern entity name -> legacy entity name + NBT. */ + private static final Map MODERN_TO_LEGACY_NBT = new HashMap<>(); + static { // Simple case changes simple("Arrow", "arrow"); @@ -35,7 +37,6 @@ public class EntityFlatteningMap { simple("Pig", "pig"); simple("Sheep", "sheep"); simple("Silverfish", "silverfish"); - simple("Skeleton", "skeleton"); simple("Slime", "slime"); simple("Snowball", "snowball"); simple("Spider", "spider"); @@ -49,7 +50,6 @@ public class EntityFlatteningMap { simple("CaveSpider", "cave_spider"); simple("EnderCrystal", "end_crystal"); simple("EnderDragon", "ender_dragon"); - simple("EntityHorse", "horse"); simple("EyeOfEnderSignal", "eye_of_ender"); simple("FallingSand", "falling_block"); simple("Fireball", "fireball"); @@ -79,6 +79,36 @@ public class EntityFlatteningMap { simple("MinecartHopper", "hopper_minecart"); simple("MinecartSpawner", "spawner_minecart"); simple("MinecartTNT", "tnt_minecart"); + + MODERN_TO_LEGACY_NBT.put("skeleton", new BlockEntry( + new NamespacedId("Skeleton"), Collections.emptySet(), Collections.emptyMap(), + Map.of("SkeletonType", new PropertiesTokenizer.NbtValue("0", false)))); + MODERN_TO_LEGACY_NBT.put("wither_skeleton", new BlockEntry( + new NamespacedId("Skeleton"), Collections.emptySet(), Collections.emptyMap(), + Map.of("SkeletonType", new PropertiesTokenizer.NbtValue("1", false)))); + + // 1.7.10 EntityHorse with Type byte: 0=horse, 1=donkey, 2=mule, 3=zombie_horse, + // 4=skeleton_horse. 1.11+ split each into its own entity type. + MODERN_TO_LEGACY_NBT.put("horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("0", false)))); + MODERN_TO_LEGACY_NBT.put("donkey", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("1", false)))); + MODERN_TO_LEGACY_NBT.put("mule", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("2", false)))); + MODERN_TO_LEGACY_NBT.put("zombie_horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("3", false)))); + MODERN_TO_LEGACY_NBT.put("skeleton_horse", new BlockEntry( + new NamespacedId("EntityHorse"), Collections.emptySet(), Collections.emptyMap(), + Map.of("Type", new PropertiesTokenizer.NbtValue("4", false)))); + + // 1.7.10 Zombie with IsVillager. + MODERN_TO_LEGACY_NBT.put("zombie_villager", new BlockEntry( + new NamespacedId("Zombie"), Collections.emptySet(), Collections.emptyMap(), + Map.of("IsVillager", new PropertiesTokenizer.NbtValue("1", false)))); } /** @@ -89,6 +119,10 @@ public class EntityFlatteningMap { return MODERN_TO_LEGACY.get(modernName); } + public static BlockEntry toLegacyWithNbt(String modernName) { + return MODERN_TO_LEGACY_NBT.get(modernName); + } + private static void simple(String legacy, String modern) { MODERN_TO_LEGACY.put(modern, legacy); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java index c2108dca3..324d5ab8e 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/FlatteningMap.java @@ -158,18 +158,18 @@ public class FlatteningMap { rename("dark_oak_wall_sign", "wall_sign"); // === Skull / Head blocks (ID 144) === - // In 1.7.10, skull type is stored in tile entity, not metadata. - // All modern skull blocks map to the same 1.7.10 block. - rename("skeleton_skull", "skull"); - rename("skeleton_wall_skull", "skull"); - rename("wither_skeleton_skull", "skull"); - rename("wither_skeleton_wall_skull", "skull"); - rename("zombie_head", "skull"); - rename("zombie_wall_head", "skull"); - rename("player_head", "skull"); - rename("player_wall_head", "skull"); - rename("creeper_head", "skull"); - rename("creeper_wall_head", "skull"); + // 1.7.10 stores skull type in TileEntitySkull's SkullType byte (0=skeleton, + // 1=wither, 2=zombie, 3=player, 4=creeper). + MODERN_TO_LEGACY.put("skeleton_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("skeleton_wall_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("wither_skeleton_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("wither_skeleton_wall_skull", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("zombie_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("zombie_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("player_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("player_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("creeper_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("creeper_wall_head", List.of(new BlockEntry(new NamespacedId("minecraft", "skull"), Collections.emptySet(), Collections.emptyMap(), Map.of("SkullType", new PropertiesTokenizer.NbtValue("4", false))))); // ========================================== // Metadata variants (block split by flattening) @@ -321,29 +321,29 @@ public class FlatteningMap { meta("mossy_cobblestone_wall", "cobblestone_wall", 1); // === Flower pot (ID 140) === - // In 1.7.10, flower pot contents are in the tile entity. - // In 1.13+, each potted plant is a separate block. - rename("potted_oak_sapling", "flower_pot"); - rename("potted_spruce_sapling", "flower_pot"); - rename("potted_birch_sapling", "flower_pot"); - rename("potted_jungle_sapling", "flower_pot"); - rename("potted_acacia_sapling", "flower_pot"); - rename("potted_dark_oak_sapling", "flower_pot"); - rename("potted_fern", "flower_pot"); - rename("potted_dandelion", "flower_pot"); - rename("potted_poppy", "flower_pot"); - rename("potted_blue_orchid", "flower_pot"); - rename("potted_allium", "flower_pot"); - rename("potted_azure_bluet", "flower_pot"); - rename("potted_red_tulip", "flower_pot"); - rename("potted_orange_tulip", "flower_pot"); - rename("potted_white_tulip", "flower_pot"); - rename("potted_pink_tulip", "flower_pot"); - rename("potted_oxeye_daisy", "flower_pot"); - rename("potted_red_mushroom", "flower_pot"); - rename("potted_brown_mushroom", "flower_pot"); - rename("potted_dead_bush", "flower_pot"); - rename("potted_cactus", "flower_pot"); + // 1.7.10 stores potted contents in TileEntityFlowerPot's NBT. 1.13+ has a separate block + // per potted plant. + MODERN_TO_LEGACY.put("potted_oak_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_spruce_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("potted_birch_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_jungle_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("potted_acacia_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("potted_dark_oak_sapling", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:sapling", false), "Data", new PropertiesTokenizer.NbtValue("5", false))))); + MODERN_TO_LEGACY.put("potted_fern", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:tallgrass", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_dandelion", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:yellow_flower", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_poppy", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_blue_orchid", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("1", false))))); + MODERN_TO_LEGACY.put("potted_allium", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("2", false))))); + MODERN_TO_LEGACY.put("potted_azure_bluet", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("3", false))))); + MODERN_TO_LEGACY.put("potted_red_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("4", false))))); + MODERN_TO_LEGACY.put("potted_orange_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("5", false))))); + MODERN_TO_LEGACY.put("potted_white_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("6", false))))); + MODERN_TO_LEGACY.put("potted_pink_tulip", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("7", false))))); + MODERN_TO_LEGACY.put("potted_oxeye_daisy", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_flower", false), "Data", new PropertiesTokenizer.NbtValue("8", false))))); + MODERN_TO_LEGACY.put("potted_red_mushroom", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:red_mushroom", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_brown_mushroom", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:brown_mushroom", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_dead_bush", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:deadbush", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); + MODERN_TO_LEGACY.put("potted_cactus", List.of(new BlockEntry(new NamespacedId("minecraft", "flower_pot"), Collections.emptySet(), Collections.emptyMap(), Map.of("Item", new PropertiesTokenizer.NbtValue("minecraft:cactus", false), "Data", new PropertiesTokenizer.NbtValue("0", false))))); // === Anvil (ID 145) === // Bits 0-1 = facing, bits 2-3 = damage level @@ -928,26 +928,26 @@ public class FlatteningMap { List result = new ArrayList<>(Math.min(a.size(), b.size())); for (BlockEntry entryA : a) { for (BlockEntry entryB : b) { - if (!entryA.getId().equals(entryB.getId())) continue; + if (!entryA.id().equals(entryB.id())) continue; - Set metasA = entryA.getMetas(); - Set metasB = entryB.getMetas(); + Set metasA = entryA.metas(); + Set metasB = entryB.metas(); if (metasA.isEmpty() && metasB.isEmpty()) { // Both wildcard -> wildcard - result.add(new BlockEntry(entryA.getId(), Collections.emptySet())); + result.add(new BlockEntry(entryA.id(), Collections.emptySet())); } else if (metasA.isEmpty()) { // A is wildcard -> use B's constraint - result.add(new BlockEntry(entryA.getId(), metasB)); + result.add(new BlockEntry(entryA.id(), metasB)); } else if (metasB.isEmpty()) { // B is wildcard -> use A's constraint - result.add(new BlockEntry(entryA.getId(), metasA)); + result.add(new BlockEntry(entryA.id(), metasA)); } else { // Both have specific metas -> intersect Set intersection = new IntOpenHashSet(metasA); intersection.retainAll(metasB); if (!intersection.isEmpty()) { - result.add(new BlockEntry(entryA.getId(), intersection)); + result.add(new BlockEntry(entryA.id(), intersection)); } } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java b/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java new file mode 100644 index 000000000..5958e6b48 --- /dev/null +++ b/src/main/java/net/coderbot/iris/shaderpack/materialmap/PropertiesTokenizer.java @@ -0,0 +1,388 @@ +package net.coderbot.iris.shaderpack.materialmap; + +import net.coderbot.iris.Iris; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +// This got complicated fast + +/** + * This class handles all processing of individual block entries per material ID line. + */ +public final class PropertiesTokenizer { + + private PropertiesTokenizer() { + } + + /** + * Splits a property value into individual block identifier tokens. + */ + public static List tokenizeValues(String input, char delimiter) { + if (input.indexOf('"') == -1 && input.indexOf('\\') == -1 && input.indexOf('[') == -1) { + return tokenizeSimple(input, delimiter); + } + return tokenizeFull(input, delimiter); + } + + // Most blocks should take this path + private static List tokenizeSimple(String input, char delimiter) { + final List result = new ArrayList<>(); + final boolean isWhitespaceDelim = Character.isWhitespace(delimiter); + + if (isWhitespaceDelim) { + for (String part : input.split("\\s+")) { + if (!part.isEmpty()) { + result.add(part); + } + } + } else { + for (String part : input.split(String.valueOf(delimiter))) { + final String trimmed = part.trim(); + if (!trimmed.isEmpty()) { + result.add(trimmed); + } + } + } + return result; + } + + // Found special characters + private static List tokenizeFull(String input, char delimiter) { + final boolean isWhitespaceDelim = Character.isWhitespace(delimiter); + final List result = new ArrayList<>(); + final StringBuilder current = new StringBuilder(); + boolean inQuotes = false; + boolean escaped = false; + int bracketDepth = 0; + + for (int i = 0; i < input.length(); i++) { + final char c = input.charAt(i); + + if (escaped) { + if (bracketDepth > 0) { + // Preserve escapes inside brackets for parseBlockIdentifier + current.append('\\'); + } + current.append(c); + escaped = false; + + } else if (c == '\\') { + escaped = true; + + } else if (bracketDepth > 0) { + current.append(c); + + if (c == '[') { + bracketDepth++; + } + + else if (c == ']') { + bracketDepth--; + } + + } else if (c == '[' && !inQuotes) { + current.append(c); + bracketDepth = 1; + + } else if (c == '"') { + inQuotes = !inQuotes; + + } else if (!inQuotes && (isWhitespaceDelim ? Character.isWhitespace(c) : c == delimiter)) { + if (!current.isEmpty()) { + result.add(current.toString()); + current.setLength(0); + } + + } else { + current.append(c); + } + } + + if (inQuotes) { + Iris.logger.warn("Unclosed quote in properties token: {}", input); + } + + if (!current.isEmpty()) { + result.add(current.toString()); + } + + return result; + } + + // Begin reading the special case block + public static ParsedBlockIdentifier parseBlockIdentifier(String entry) { + final StringBuilder blockIdBuilder = new StringBuilder(); + final Map nbt = new LinkedHashMap<>(); + + boolean escaped = false; + boolean inDoubleQuotes = false; + boolean inSingleQuotes = false; + boolean inBracket = false; + + // NBT pair + StringBuilder nbtKey = new StringBuilder(); + StringBuilder nbtValue = new StringBuilder(); + boolean readingValue = false; + boolean valueLiteral = false; + + for (int i = 0; i < entry.length(); i++) { + final char c = entry.charAt(i); + + // Ignore special characters + if (escaped) { + appendCurrent(inBracket, readingValue, blockIdBuilder, nbtKey, nbtValue, c); + escaped = false; + continue; + } + if (c == '\\') { + escaped = true; + continue; + } + + // Detect special characters + if (inSingleQuotes) { + if (c == '\'') { + inSingleQuotes = false; + + } else { + nbtValue.append(c); + } + continue; + } + + if (inDoubleQuotes) { + if (c == '"') { + inDoubleQuotes = false; + + } else { + appendCurrent(inBracket, readingValue, blockIdBuilder, nbtKey, nbtValue, c); + } + continue; + } + + + if (c == '"') { + inDoubleQuotes = true; + continue; + } + + if (!inBracket) { + if (c == '[') { + inBracket = true; + nbtKey.setLength(0); + nbtValue.setLength(0); + readingValue = false; + valueLiteral = false; + + } else { + blockIdBuilder.append(c); + } + + } else { + if (c == ']') { + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + inBracket = false; + + } else if (c == '=' && !readingValue) { + readingValue = true; + valueLiteral = false; + + } else if (c == '\'' && readingValue && nbtValue.isEmpty()) { + inSingleQuotes = true; + valueLiteral = true; + + } else if (c == ',') { + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + nbtKey.setLength(0); + nbtValue.setLength(0); + readingValue = false; + valueLiteral = false; + + } else { + if (readingValue) { + nbtValue.append(c); + + } else { + nbtKey.append(c); + } + } + } + } + + if (inDoubleQuotes) { + Iris.logger.warn("Unclosed double quote in block entry: {}", entry); + } + if (inSingleQuotes) { + Iris.logger.warn("Unclosed single quote in block entry: {}", entry); + } + if (escaped) { + Iris.logger.warn("Trailing backslash in block entry: {}", entry); + } + if (inBracket) { + Iris.logger.warn("Unclosed bracket in block entry: {}", entry); + flushNbtPair(nbtKey, nbtValue, readingValue, valueLiteral, nbt); + } + + final String baseEntry = blockIdBuilder.toString().trim(); + final Map nbtProperties = nbt.isEmpty() ? Collections.emptyMap() : nbt; + + return splitBaseEntry(entry, baseEntry, nbtProperties); + } + + /** + * Splits the bracket-stripped portion of a block identifier (e.g. {@code minecraft:furnace:lit=true}) + * into its components. + * + * Accepted forms: + * stone (vanilla block) + * stone:0 (vanilla block with meta) + * minecraft:stone (block with namespaced id specified) + * minecraft:stone:0 (single meta) + * minecraft:stone:0,1,2 (multiple metas) + * minecraft:furnace:lit=true (blockstate property) + * minecraft:oak_log:axis=y,x:variant=oak (multiple blockstate properties) + * flower_pot:1[Item=minecraft:red_flower,Data=0] (used together with NBT brackets) + */ + private static ParsedBlockIdentifier splitBaseEntry(String entry, String baseEntry, Map nbtProperties) { + final Set metas = new HashSet<>(); + final Map stateProperties = new LinkedHashMap<>(); + + if (baseEntry.isEmpty()) { + return new ParsedBlockIdentifier( + new NamespacedId("minecraft", baseEntry), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + final String[] splitStates = baseEntry.split(":"); + + // Vanilla block (minecraft namespaced) + if (splitStates.length == 1) { + return new ParsedBlockIdentifier( + new NamespacedId("minecraft", baseEntry), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + // Two-segment with no metas/state properties: "minecraft:stone" + if (splitStates.length == 2 + && !StringUtils.isNumeric(splitStates[1].substring(0, 1)) + && !splitStates[1].contains("=")) { + return new ParsedBlockIdentifier( + new NamespacedId(splitStates[0], splitStates[1]), + Collections.emptySet(), + Collections.emptyMap(), + nbtProperties + ); + } + + // Metas and/or state properties + final NamespacedId id; + final int statesStart; + + if (splitStates.length == 2) { + // "stone:0" or "stone:lit=true" + id = new NamespacedId("minecraft", splitStates[0]); + statesStart = 1; + + } else if (StringUtils.isNumeric(splitStates[1].substring(0, 1)) || splitStates[1].contains("=")) { + // "stone:0:something" or "stone:lit=true:something", likely will need this for snowy blocks in the future. + id = new NamespacedId("minecraft", splitStates[0]); + statesStart = 1; + + } else { + // "minecraft:stone:0" or "minecraft:furnace:lit=true" + id = new NamespacedId(splitStates[0], splitStates[1]); + statesStart = 2; + } + + for (int index = statesStart; index < splitStates.length; index++) { + final String segment = splitStates[index]; + + if (segment.contains("=")) { + // Blockstate property segment: key=value[,key=value...] + for (String prop : segment.split(",")) { + final int eq = prop.indexOf('='); + if (eq > 0 && eq < prop.length() - 1) { + stateProperties.put(prop.substring(0, eq), prop.substring(eq + 1)); + } + } + } else { + // Metadata segment (stone:[1,2,3,4,5]) + for (String metaPart : segment.split(",")) { + try { + metas.add(Integer.parseInt(metaPart)); + } catch (NumberFormatException e) { + Iris.logger.warn("Warning: the block ID map entry \"{}\" could not be fully parsed:", entry); + Iris.logger.warn("- Metadata ids must be a comma separated list of one or more integers, but {} is not of that form!", segment); + } + } + } + } + + return new ParsedBlockIdentifier( + id, + metas.isEmpty() ? Collections.emptySet() : metas, + stateProperties.isEmpty() ? Collections.emptyMap() : stateProperties, + nbtProperties + ); + } + + private static void appendCurrent(boolean inBracket, boolean readingValue, + StringBuilder blockIdBuilder, StringBuilder nbtKey, + StringBuilder nbtValue, char c) { + if (!inBracket) { + blockIdBuilder.append(c); + + } else if (readingValue) { + nbtValue.append(c); + + } else { + nbtKey.append(c); + } + } + + private static void flushNbtPair(StringBuilder key, StringBuilder value, + boolean readingValue, boolean valueLiteral, + Map nbt) { + final String k = key.toString().trim(); + if (k.isEmpty()) return; + + if (!readingValue) { + // No = was found, existence is good enough + nbt.put(k, null); + return; + } + + nbt.put(k, new NbtValue(value.toString().trim(), valueLiteral)); + } + + public static String stripQuotes(String value) { + if (value.length() >= 2 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') { + return value.substring(1, value.length() - 1); + } + return value; + } + + public record NbtValue(String value, boolean literal) { + } + + public record ParsedBlockIdentifier( + NamespacedId id, + Set metas, + Map stateProperties, + Map nbtProperties + ) { + } +} diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java b/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java index 017c1c1a3..afd43d9ec 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java @@ -43,6 +43,7 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; +import org.lwjgl.opengl.GL43; import java.util.Map; import java.util.Objects; @@ -208,7 +209,7 @@ public class ShadowCompositeRenderer { if (ranCompute) { // Memory barrier for shader image access and texture fetch - RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT); + RenderSystem.memoryBarrier(GL42.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL42.GL_TEXTURE_FETCH_BARRIER_BIT | GL43.GL_SHADER_STORAGE_BARRIER_BIT); } Program.unbind(); diff --git a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java b/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java index 7b27b9299..9812402b2 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java @@ -89,7 +89,7 @@ public class CameraUniforms { private void update() { previousCameraPosition.set(currentCameraPosition); - previousCameraPositionUnshifted = currentCameraPositionUnshifted; + previousCameraPositionUnshifted.set(currentCameraPositionUnshifted); currentCameraPosition.set(getUnshiftedCameraPosition()).add(shift); currentCameraPositionUnshifted.set(getUnshiftedCameraPosition()); diff --git a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java index d003e3cb2..02c51ee46 100644 --- a/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java +++ b/src/main/java/net/coderbot/iris/uniforms/EntityIdHelper.java @@ -1,10 +1,16 @@ package net.coderbot.iris.uniforms; +import it.unimi.dsi.fastutil.ints.Int2LongLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import net.minecraft.nbt.NBTTagCompound; + +import java.util.IdentityHashMap; +import java.util.Map; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -21,15 +27,25 @@ public final class EntityIdHelper { private static final NamespacedId LIGHTNING_BOLT_ID = new NamespacedId("minecraft", "lightning_bolt"); private static final Object2IntMap> entityIdCache = new Object2IntOpenHashMap<>(); + private static final Map, NamespacedId> entityNameCache = new IdentityHashMap<>(); private static Object2IntFunction cachedEntityIdMap; + private static final Int2LongLinkedOpenHashMap entityNbtCache = new Int2LongLinkedOpenHashMap(); + private static final int NBT_CACHE_INTERVAL_TICKS = 20; + private static final int ENTITY_NBT_CACHE_MAX = 256; + static { entityIdCache.defaultReturnValue(Integer.MIN_VALUE); + entityNbtCache.defaultReturnValue(-1L); } private EntityIdHelper() { } + public static boolean isLightningBolt(Entity entity) { + return entity instanceof EntityLightningBolt; + } + /** * Get the entity ID for the given entity. * @@ -42,17 +58,48 @@ public final class EntityIdHelper { return -1; } - // Invalidate cache if the map changed (shader reload) + // Invalidate caches if the map changed (shader reload) if (entityIdMap != cachedEntityIdMap) { entityIdCache.clear(); + entityNameCache.clear(); + entityNbtCache.clear(); cachedEntityIdMap = entityIdMap; } + // Check NBT-conditional match first + final NbtConditionalIdMap entityNbtMap = BlockRenderingSettings.INSTANCE.getEntityNbtMap(); + if (entityNbtMap != null && !entityNbtMap.isEmpty() && entity.worldObj != null) { + final NamespacedId namespacedId = getCachedEntityName(entity); + if (namespacedId != null && entityNbtMap.hasConditions(namespacedId)) { + final int entityRuntimeId = entity.getEntityId(); + final long currentTick = entity.worldObj.getTotalWorldTime(); + final long cached = entityNbtCache.get(entityRuntimeId); + + final int nbtId; + if (cached != -1L && (currentTick - (cached >>> 32)) < NBT_CACHE_INTERVAL_TICKS) { + nbtId = (int) cached; + } else { + final NBTTagCompound nbt = new NBTTagCompound(); + entity.writeToNBT(nbt); + nbtId = entityNbtMap.resolve(namespacedId, nbt); + final long packed = ((currentTick & 0x7FFFFFFFL) << 32) | (nbtId & 0xFFFFFFFFL); + entityNbtCache.put(entityRuntimeId, packed); + while (entityNbtCache.size() > ENTITY_NBT_CACHE_MAX) { + entityNbtCache.removeFirstLong(); + } + } + + if (nbtId != -1) { + return nbtId; + } + } + } + // Normal entity type lookup - int normalId = getNormalEntityId(entity, entityIdMap); + final int normalId = getNormalEntityId(entity, entityIdMap); // Check for special entity type overrides - int specialId = getSpecialEntityId(entity, entityIdMap); + final int specialId = getSpecialEntityId(entity, entityIdMap); if (specialId != -1) { return specialId; } @@ -134,4 +181,24 @@ public final class EntityIdHelper { return id; } + + /** + * Returns a cached NamespacedId for the entity's registered type. + */ + private static NamespacedId getCachedEntityName(Entity entity) { + Class entityClass = entity.getClass(); + NamespacedId cached = entityNameCache.get(entityClass); + if (cached != null) { + return cached; + } + + String entityType = EntityList.getEntityString(entity); + if (entityType == null) { + return null; + } + + cached = new NamespacedId(entityType); + entityNameCache.put(entityClass, cached); + return cached; + } } diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java b/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java index c7be0d01a..8a14c2bdc 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java @@ -2,6 +2,7 @@ package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; +import com.gtnewhorizons.angelica.render.CloudRenderer; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.minecraft.client.Minecraft; @@ -40,6 +41,16 @@ public class IrisExclusiveUniforms { uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "eyePosition", IrisExclusiveUniforms::getEyePosition); uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "relativeEyePosition", IrisExclusiveUniforms::getRelativeEyePosition); uniforms.uniform4f(UniformUpdateFrequency.PER_TICK, "lightningBoltPosition", IrisExclusiveUniforms::getLightningBoltPosition); + uniforms.uniform1f(UniformUpdateFrequency.PER_FRAME, "cloudTime", IrisExclusiveUniforms::getCloudTime); + } + + private static float getCloudTime() { + final WorldClient level = Minecraft.getMinecraft().theWorld; + if (level == null) return 0f; + final long cycle = (long) CloudRenderer.getCloudTextureWidth() * 400L * CloudRenderer.getScaleMult(); + final long t = level.getTotalWorldTime() % cycle; + final float partial = Minecraft.getMinecraft().timer.renderPartialTicks; + return (t + partial) * 0.03F; } private static float getThunderStrength() { diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java index a55628f31..eafe9c7d5 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java @@ -12,10 +12,19 @@ import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public class IrisInternalUniforms { private static final Vector4f FOG_COLOR = new Vector4f(); + private static final Vector4f COLOR_MODULATOR = new Vector4f(1f, 1f, 1f, 1f); private IrisInternalUniforms() { } + private static Vector4f getColorModulator() { + return COLOR_MODULATOR.set( + GLStateManager.getShaderColorR(), + GLStateManager.getShaderColorG(), + GLStateManager.getShaderColorB(), + GLStateManager.getShaderColorA()); + } + private static float getEffectiveAlphaRef() { if (!GLStateManager.getAlphaTest().isEnabled() || GLStateManager.getAlphaState().getFunction() == GL11.GL_ALWAYS) { return -1.0f; @@ -44,5 +53,7 @@ public class IrisInternalUniforms { .uniform1f("iris_currentAlphaTest", IrisInternalUniforms::getEffectiveAlphaRef, StateUpdateNotifiers.alphaTestNotifier) .uniform1f("alphaTestRef", IrisInternalUniforms::getEffectiveAlphaRef, StateUpdateNotifiers.alphaTestNotifier) .uniform1i("iris_currentAlphaFunc", IrisInternalUniforms::getEffectiveAlphaFunc, StateUpdateNotifiers.alphaFuncNotifier); + + uniforms.uniform4f("iris_ColorModulator", IrisInternalUniforms::getColorModulator, StateUpdateNotifiers.colorModulatorNotifier); } } diff --git a/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java b/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java index 74c064bb4..424f8faef 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java +++ b/src/main/java/net/coderbot/iris/uniforms/ItemMaterialHelper.java @@ -6,6 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Reference2ObjectMap; import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.block.Block; import net.minecraft.item.Item; @@ -20,6 +21,7 @@ import net.minecraft.util.ResourceLocation; public class ItemMaterialHelper { private static final Reference2ObjectMap MATERIAL_CACHE = new Reference2ObjectOpenHashMap<>(); private static final int CACHE_MISS_SENTINEL = Integer.MIN_VALUE; + private static final Reference2ObjectMap ITEM_NAME_CACHE = new Reference2ObjectOpenHashMap<>(); /** * Get the material ID for an ItemStack. * For ItemBlock: checks block.properties first, then item.properties. @@ -32,6 +34,19 @@ public class ItemMaterialHelper { if (itemStack == null || itemStack.getItem() == null) { return -1; } + + // Check item NBT conditions first + final NbtConditionalIdMap itemNbtMap = BlockRenderingSettings.INSTANCE.getItemNbtMap(); + if (itemNbtMap != null && !itemNbtMap.isEmpty() && itemStack.hasTagCompound()) { + NamespacedId namespacedId = getCachedItemName(itemStack.getItem()); + if (namespacedId != null && itemNbtMap.hasConditions(namespacedId)) { + int nbtId = itemNbtMap.resolve(namespacedId, itemStack.getTagCompound()); + if (nbtId != -1) { + return nbtId; + } + } + } + return getMaterialId(itemStack.getItem(), itemStack.getItemDamage()); } @@ -73,8 +88,7 @@ public class ItemMaterialHelper { */ private static int lookupMaterialId(Item item, int metadata) { // For ItemBlock: check block.properties first - if (item instanceof ItemBlock) { - final ItemBlock itemBlock = (ItemBlock) item; + if (item instanceof ItemBlock itemBlock) { final Block block = itemBlock.field_150939_a; // The block this item places if (block != null) { @@ -94,7 +108,7 @@ public class ItemMaterialHelper { // Fall back to item.properties Object2IntFunction itemIds = BlockRenderingSettings.INSTANCE.getItemIds(); if (itemIds != null) { - String itemIdString = (String) Item.itemRegistry.getNameForObject(item); + String itemIdString = Item.itemRegistry.getNameForObject(item); if (itemIdString != null) { ResourceLocation itemId = new ResourceLocation(itemIdString); return itemIds.applyAsInt(new NamespacedId(itemId.getResourceDomain(), itemId.getResourcePath())); @@ -110,5 +124,23 @@ public class ItemMaterialHelper { */ public static void clearCache() { MATERIAL_CACHE.clear(); + ITEM_NAME_CACHE.clear(); + } + + private static NamespacedId getCachedItemName(Item item) { + NamespacedId cached = ITEM_NAME_CACHE.get(item); + if (cached != null) { + return cached; + } + + String itemIdString = Item.itemRegistry.getNameForObject(item); + if (itemIdString == null) { + return null; + } + + ResourceLocation itemId = new ResourceLocation(itemIdString); + cached = new NamespacedId(itemId.getResourceDomain(), itemId.getResourcePath()); + ITEM_NAME_CACHE.put(item, cached); + return cached; } } diff --git a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java index d1ccf7ce9..12a55429d 100644 --- a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java @@ -6,6 +6,8 @@ import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.pipeline.ShadowRenderer; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.shadow.ShadowMatrices; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.Entity; import org.joml.Matrix4f; import org.joml.Matrix4fc; @@ -17,8 +19,18 @@ public final class MatrixUniforms { private MatrixUniforms() { } + private static final Matrix4f GBUFFER_MODELVIEW_SCRATCH = new Matrix4f(); + private static Matrix4fc getGbufferModelView() { + final Matrix4fc raw = RenderingState.INSTANCE.getModelViewMatrix(); + final Entity view = Minecraft.getMinecraft().renderViewEntity; + if (view == null) { + return raw; + } + return GBUFFER_MODELVIEW_SCRATCH.set(raw).translate(0f, view.getEyeHeight(), 0f); + } + public static void addMatrixUniforms(UniformHolder uniforms, PackDirectives directives) { - addMatrix(uniforms, "ModelView", RenderingState.INSTANCE::getModelViewMatrix); + addMatrix(uniforms, "ModelView", MatrixUniforms::getGbufferModelView); // TODO: In some cases, gbufferProjectionInverse takes on a value much different than OptiFine... // We need to audit Mojang's linear algebra. addMatrix(uniforms, "Projection", RenderingState.INSTANCE::getProjectionMatrix); diff --git a/src/main/resources/assets/angelica/lang/en_US.lang b/src/main/resources/assets/angelica/lang/en_US.lang index 5bda449e5..dffc1b1b4 100644 --- a/src/main/resources/assets/angelica/lang/en_US.lang +++ b/src/main/resources/assets/angelica/lang/en_US.lang @@ -14,6 +14,7 @@ sodium.options.pages.quality=Quality sodium.options.pages.performance=Performance sodium.options.pages.advanced=Advanced sodium.options.pages.appearance=Appearance +sodium.options.pages.text=Text Effects sodium.options.view_distance.tooltip=The render distance controls how far away terrain will be rendered. Shorter distances mean that less terrain will be rendered, improving frame rates. sodium.options.simulation_distance.tooltip=The simulation distance controls how far away terrain and entities will be loaded and ticked. Shorter distances can reduce the internal server's load and may improve frame rates. sodium.options.brightness.tooltip=Controls the brightness (gamma) of the game. @@ -223,6 +224,22 @@ options.angelica.aggressiveChunkLoading=Aggressive Chunk Loading options.angelica.aggressiveChunkLoading.tooltip=Renders chunks immediately when loaded, even if neighbors aren't ready yet. Improves perceived loading speed at render distance edges. Chunks rebuild automatically when neighbors load. Useful for low render distance servers. options.angelica.disablef3=Disable F3 Additions options.angelica.disablef3.tooltip=Disables Angelica's additions to the F3 debug screen. +options.angelica.texteffects.rgb_colors=RGB Colors +options.angelica.texteffects.rgb_colors.tooltip=Enable hex colors via %s syntax +options.angelica.texteffects.gradients=Gradients +options.angelica.texteffects.gradients.tooltip=Smooth color transitions via +options.angelica.texteffects.rainbow=Rainbow +options.angelica.texteffects.rainbow.tooltip=Cycling rainbow colors via +options.angelica.texteffects.wave_text=Wave Text +options.angelica.texteffects.wave_text.tooltip=Animated bouncing text via +options.angelica.texteffects.wave_amplitude=Wave Amplitude +options.angelica.texteffects.wave_amplitude.tooltip=How far wave text bounces (default 2.0) +options.angelica.texteffects.dinnerbone_text=Dinnerbone Text +options.angelica.texteffects.dinnerbone_text.tooltip=Flipped upside down text via +options.angelica.texteffects.drop_shadow=Drop Shadow +options.angelica.texteffects.drop_shadow.tooltip=Per-segment drop shadow via %s, colored shadow via +options.angelica.texteffects.ampersand_conversion=Ampersand Conversion +options.angelica.texteffects.ampersand_conversion.tooltip=Convert %s prefix codes to formatting codes at render time sodium.options.multidraw_mode.name=Multi-Draw Mode sodium.options.multidraw_mode.tooltip=Controls how draw commands are dispatched for terrain rendering. §lDirect§r uses glMultiDrawElementsBaseVertex (default, GL 3.2+). §lIndirect§r uses GPU indirect rendering (GL 4.3+), may reduce CPU overhead on some hardware. §lIndividual§r issues individual draw calls. diff --git a/src/main/resources/assets/angelica/shaders/cloud.frag b/src/main/resources/assets/angelica/shaders/cloud.frag index c27e7735c..88e8228a5 100644 --- a/src/main/resources/assets/angelica/shaders/cloud.frag +++ b/src/main/resources/assets/angelica/shaders/cloud.frag @@ -1,11 +1,11 @@ #version 330 core -in vec4 v_Color; -in vec2 v_TexCoord0; +in vec2 v_UV; in float v_FogCoord; +in float v_Factor; -uniform sampler2D u_CloudTexture; -uniform vec3 u_ColorMultiplier; +uniform sampler2D u_Tex; +uniform vec4 u_ColorMult; uniform vec4 u_FogParams; // x: -1/(end-start), y: end/(end-start) uniform vec4 u_FogColor; uniform bool u_FogEnabled; @@ -13,11 +13,10 @@ uniform bool u_FogEnabled; out vec4 fragColor; void main() { - vec4 texColor = texture(u_CloudTexture, v_TexCoord0); - vec4 color = v_Color * texColor; - color.rgb *= u_ColorMultiplier; - - if (color.a < 0.1) discard; + vec4 texel = texture(u_Tex, v_UV); + if (texel.a < 0.1) discard; + vec4 color = texel * u_ColorMult; + color.rgb *= v_Factor; if (u_FogEnabled) { float f = clamp(v_FogCoord * u_FogParams.x + u_FogParams.y, 0.0, 1.0); diff --git a/src/main/resources/assets/angelica/shaders/cloud.vert b/src/main/resources/assets/angelica/shaders/cloud.vert index 917774c96..16a94c5aa 100644 --- a/src/main/resources/assets/angelica/shaders/cloud.vert +++ b/src/main/resources/assets/angelica/shaders/cloud.vert @@ -1,22 +1,18 @@ #version 330 core layout(location = 0) in vec3 a_Position; -layout(location = 1) in vec4 a_Color; -layout(location = 2) in vec2 a_TexCoord0; +layout(location = 2) in vec2 a_UV; +layout(location = 5) in float a_Factor; uniform mat4 u_MVPMatrix; -uniform vec2 u_TexOffset; -uniform vec2 u_FogOrigin; -out vec4 v_Color; -out vec2 v_TexCoord0; +out vec2 v_UV; out float v_FogCoord; +out float v_Factor; void main() { - vec4 pos4 = vec4(a_Position, 1.0); - gl_Position = u_MVPMatrix * pos4; - v_Color = a_Color; - v_TexCoord0 = a_TexCoord0 + u_TexOffset; - vec2 horizDelta = a_Position.xz - u_FogOrigin; - v_FogCoord = length(horizDelta); + gl_Position = u_MVPMatrix * vec4(a_Position, 1.0); + v_UV = a_UV; + v_FogCoord = length(a_Position.xz); + v_Factor = a_Factor; } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinItemRenderer_EdgeDepth.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinItemRenderer_EdgeDepth.java index 8df70d9ba..93dd011fd 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinItemRenderer_EdgeDepth.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinItemRenderer_EdgeDepth.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.llamalad7.mixinextras.injector.wrapmethod.WrapMethod; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import net.coderbot.iris.pipeline.ShadowRenderer; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; @@ -26,6 +27,11 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; * where depth passes. This determines pixel ownership without corrupting the depth buffer (damn potions...) * b. Color pass: draw only where stencil == 2, GL_ALWAYS depth test, decrement the stencil * 2→1 to reset for the next glint pass. + * + * For the shadow pass, all stencil operations are skipped. Shadow FBOs have no stencil attachment. + * On AMD Windows, glClear(GL_STENCIL_BUFFER_BIT) on a depth-only FBO causes the driver to + * promote it to GL_DEPTH24_STENCIL8 internally, corrupting depth values and breaking shadows. + * Someone needs to yell at AMD to fix this decade old bug. */ @Mixin(value = ItemRenderer.class, priority = 1100) public class MixinItemRenderer_EdgeDepth { @@ -41,11 +47,12 @@ public class MixinItemRenderer_EdgeDepth { remap = false ) private void angelica$stencilWriteStart(CallbackInfo ci) { + if (ShadowRenderer.ACTIVE) return; GLStateManager.glEnable(GL11.GL_STENCIL_TEST); - GLStateManager.glStencilMask(0xFF); + GLStateManager.glStencilMask(0x03); GLStateManager.glClearStencil(0); GLStateManager.glClear(GL11.GL_STENCIL_BUFFER_BIT); - GLStateManager.glStencilFunc(GL11.GL_ALWAYS, 1, 0xFF); + GLStateManager.glStencilFunc(GL11.GL_ALWAYS, 1, 0x03); GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_REPLACE); } @@ -55,6 +62,7 @@ public class MixinItemRenderer_EdgeDepth { remap = false ) private void angelica$stencilWriteEnd(CallbackInfo ci) { + if (ShadowRenderer.ACTIVE) return; GLStateManager.glStencilMask(0x00); GLStateManager.glDisable(GL11.GL_STENCIL_TEST); } @@ -67,9 +75,13 @@ public class MixinItemRenderer_EdgeDepth { remap = false ) private void angelica$glintStart(int func) { + if (ShadowRenderer.ACTIVE) { + GLStateManager.glDepthFunc(func); + return; + } angelica$glintMode = true; GLStateManager.glEnable(GL11.GL_STENCIL_TEST); - GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0xFF); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0x03); GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); } @@ -79,11 +91,15 @@ public class MixinItemRenderer_EdgeDepth { remap = false ) private void angelica$glintEnd(int func) { + if (ShadowRenderer.ACTIVE) { + GLStateManager.glDepthFunc(func); + return; + } angelica$glintMode = false; GLStateManager.glDepthFunc(GL11.GL_LEQUAL); GLStateManager.glDepthMask(true); GLStateManager.glDisable(GL11.GL_STENCIL_TEST); - GLStateManager.glStencilMask(0xFF); + GLStateManager.glStencilMask(0x03); } // Stencil pre-pass inside renderItemIn2D when in glint mode @@ -91,7 +107,7 @@ public class MixinItemRenderer_EdgeDepth { @WrapMethod(method = "renderItemIn2D") private static void angelica$glintPrepass(Tessellator tess, float minU, float minV, float maxU, float maxV, int w, int h, float thickness, Operation original) { - if (!angelica$glintMode || angelica$inPrepass) { + if (ShadowRenderer.ACTIVE || !angelica$glintMode || angelica$inPrepass) { original.call(tess, minU, minV, maxU, maxV, w, h, thickness); return; } @@ -102,21 +118,21 @@ public class MixinItemRenderer_EdgeDepth { GLStateManager.glColorMask(false, false, false, false); GLStateManager.glDepthMask(false); GLStateManager.glDepthFunc(GL11.GL_LEQUAL); - GLStateManager.glStencilMask(0xFF); - GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0xFF); + GLStateManager.glStencilMask(0x03); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0x03); GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_INCR); original.call(tess, minU, minV, maxU, maxV, w, h, thickness); // Color pass: draw only at pre-pass pixels. GLStateManager.glColorMask(true, true, true, true); - GLStateManager.glStencilFunc(GL11.GL_EQUAL, 2, 0xFF); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 2, 0x03); GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_DECR); GLStateManager.glDepthFunc(GL11.GL_ALWAYS); original.call(tess, minU, minV, maxU, maxV, w, h, thickness); // Restore state for the next glint renderItemIn2D call GLStateManager.glStencilMask(0x00); - GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0xFF); + GLStateManager.glStencilFunc(GL11.GL_EQUAL, 1, 0x03); GLStateManager.glStencilOp(GL11.GL_KEEP, GL11.GL_KEEP, GL11.GL_KEEP); GLStateManager.glDepthFunc(GL11.GL_LEQUAL); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderMooshroom_MushroomTint.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderMooshroom_MushroomTint.java new file mode 100644 index 000000000..221db4c1f --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRenderMooshroom_MushroomTint.java @@ -0,0 +1,70 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; + +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.renderer.entity.RenderMooshroom; +import net.minecraft.entity.passive.EntityMooshroom; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * Make it so that the mushrooms on the mooshroom are also tinted when the mob is damaged. + */ +@Mixin(RenderMooshroom.class) +public class MixinRenderMooshroom_MushroomTint { + + @Unique private static final float ANGELICA$RED_MIX = 1.0F - (0xB2 / 255.0F); + + @Unique private boolean angelica$mushroomTintActive; + @Unique private boolean angelica$mushroomTintShaderPath; + + @Inject( + method = "renderEquippedItems(Lnet/minecraft/entity/passive/EntityMooshroom;F)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/RenderBlocks;renderBlockAsItem(Lnet/minecraft/block/Block;IF)V", + ordinal = 0), + require = 1, expect = 1 + ) + private void angelica$applyMushroomTint(EntityMooshroom entity, float partialTick, CallbackInfo ci) { + if (entity.hurtTime <= 0 && entity.deathTime <= 0) return; + angelica$mushroomTintShaderPath = angelica$isShaderPackActive(); + if (angelica$mushroomTintShaderPath) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + } else { + GLStateManager.setOverlayColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + } + angelica$mushroomTintActive = true; + } + + @Inject( + method = "renderEquippedItems(Lnet/minecraft/entity/passive/EntityMooshroom;F)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/RenderBlocks;renderBlockAsItem(Lnet/minecraft/block/Block;IF)V", + ordinal = 2, + shift = At.Shift.AFTER), + require = 1, expect = 1 + ) + private void angelica$clearMushroomTint(EntityMooshroom entity, float partialTick, CallbackInfo ci) { + if (!angelica$mushroomTintActive) return; + if (angelica$mushroomTintShaderPath) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor(0.0F, 0.0F, 0.0F, 0.0F); + } else { + GLStateManager.setOverlayColor(0.0F, 0.0F, 0.0F, 0.0F); + } + angelica$mushroomTintActive = false; + } + + @Unique + private static boolean angelica$isShaderPackActive() { + if (!AngelicaConfig.enableIris) return false; + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + return pipeline != null && !(pipeline instanceof FixedFunctionWorldRenderingPipeline); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java new file mode 100644 index 000000000..9c787cd49 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/bugfixes/MixinRendererLivingEntity_OverlayTint.java @@ -0,0 +1,179 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.bugfixes; + +import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.coderbot.iris.Iris; +import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.model.ModelBase; +import net.minecraft.client.renderer.entity.RendererLivingEntity; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL14; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * Single-pass damage-overlay tint, modeled on modern Minecraft's OverlayTexture. + */ +@Mixin(RendererLivingEntity.class) +public class MixinRendererLivingEntity_OverlayTint { + + @Unique private static final float ANGELICA$RED_MIX = 1.0F - (0xB2 / 255.0F); + + @Unique private boolean angelica$skipReRender; + @Unique private boolean angelica$ffpOverlayActive; + @Unique private boolean angelica$shaderEntityColorActive; + + @Unique private boolean angelica$emissivePass; + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderModel(Lnet/minecraft/entity/EntityLivingBase;FFFFFF)V"), + require = 1, expect = 1 + ) + private void angelica$setupOverlay(EntityLivingBase entity, double x, double y, double z, + float yaw, float partialTick, CallbackInfo ci) { + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glEnable(GL11.GL_ALPHA_TEST); + GLStateManager.glDepthFunc(GL11.GL_LEQUAL); + GLStateManager.glDepthMask(true); + + if (entity.hurtTime <= 0 && entity.deathTime <= 0) return; + if (angelica$isShaderPackActive()) { + // Iris path + CapturedRenderingState.INSTANCE.setCurrentEntityColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + angelica$shaderEntityColorActive = true; + } else { + // FFP path + GLStateManager.setOverlayColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + angelica$ffpOverlayActive = true; + } + angelica$skipReRender = true; + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V"), + require = 1, expect = 1 + ) + private void angelica$teardownOverlay(EntityLivingBase entity, double x, double y, double z, + float yaw, float partialTick, CallbackInfo ci) { + if (angelica$ffpOverlayActive) { + GLStateManager.setOverlayColor(0.0F, 0.0F, 0.0F, 0.0F); + angelica$ffpOverlayActive = false; + } + if (angelica$shaderEntityColorActive) { + // Don't tint held items + CapturedRenderingState.INSTANCE.setCurrentEntityColor(0.0F, 0.0F, 0.0F, 0.0F); + angelica$shaderEntityColorActive = false; + } + } + + /** + * Skip the vanilla re-render block. + */ + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V"), + slice = @Slice( + from = @At(value = "FIELD", + target = "Lnet/minecraft/entity/EntityLivingBase;hurtTime:I", + ordinal = 1) + ), + require = 1, expect = 1 + ) + private void angelica$skipOverlayReRender(ModelBase model, Entity entity, + float p1, float p2, float p3, float p4, float p5, float p6, Operation original) { + if (angelica$skipReRender) return; + original.call(model, entity, p1, p2, p3, p4, p5, p6); + } + + /** + * Prevent bleed by saving last state and comparing with current blend state. + */ + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I"), + require = 1, expect = 1 + ) + private int angelica$detectEmissivePass(RendererLivingEntity self, EntityLivingBase entity, int pass, + float partialTick, Operation original) { + GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + final int result = original.call(self, entity, pass, partialTick); + final int srcAfter = GLStateManager.glGetInteger(GL14.GL_BLEND_SRC_RGB); + final int dstAfter = GLStateManager.glGetInteger(GL14.GL_BLEND_DST_RGB); + angelica$emissivePass = srcAfter == GL11.GL_ONE && dstAfter == GL11.GL_ONE; + return result; + } + + /** + * Skip the overlay on emissive eye pass. + */ + @WrapOperation( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/model/ModelBase;render(Lnet/minecraft/entity/Entity;FFFFFF)V"), + slice = @Slice( + from = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;shouldRenderPass(Lnet/minecraft/entity/EntityLivingBase;IF)I"), + to = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/entity/RendererLivingEntity;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V") + ), + require = 1, expect = 1 + ) + private void angelica$untintEmissivePass(ModelBase model, Entity entity, + float p1, float p2, float p3, float p4, float p5, float p6, Operation original) { + if (!angelica$skipReRender || !angelica$emissivePass) { + original.call(model, entity, p1, p2, p3, p4, p5, p6); + return; + } + if (angelica$ffpOverlayActive) { + GLStateManager.setOverlayColor(0.0F, 0.0F, 0.0F, 0.0F); + original.call(model, entity, p1, p2, p3, p4, p5, p6); + GLStateManager.setOverlayColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + } else if (angelica$shaderEntityColorActive) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor(0.0F, 0.0F, 0.0F, 0.0F); + original.call(model, entity, p1, p2, p3, p4, p5, p6); + CapturedRenderingState.INSTANCE.setCurrentEntityColor(1.0F, 0.0F, 0.0F, ANGELICA$RED_MIX); + } else { + original.call(model, entity, p1, p2, p3, p4, p5, p6); + } + } + + @Inject( + method = "doRender(Lnet/minecraft/entity/EntityLivingBase;DDDFF)V", + at = @At("RETURN") + ) + private void angelica$reset(CallbackInfo ci) { + if (angelica$ffpOverlayActive) { + GLStateManager.setOverlayColor(0.0F, 0.0F, 0.0F, 0.0F); + angelica$ffpOverlayActive = false; + } + if (angelica$shaderEntityColorActive) { + CapturedRenderingState.INSTANCE.setCurrentEntityColor(0.0F, 0.0F, 0.0F, 0.0F); + angelica$shaderEntityColorActive = false; + } + angelica$skipReRender = false; + angelica$emissivePass = false; + } + + @Unique + private static boolean angelica$isShaderPackActive() { + if (!AngelicaConfig.enableIris) return false; + final WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); + return pipeline != null && !(pipeline instanceof FixedFunctionWorldRenderingPipeline); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java index 4c355d2fc..74c31184c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/fontrenderer/MixinFontRenderer.java @@ -308,6 +308,17 @@ public abstract class MixinFontRenderer implements FontRendererAccessor, IFontPa } else if (code >= 'k' && code <= 'o') { styles.append(ColorCodeUtils.sectionPrefix(code)); i++; + } else if (code == 'u') { + if (i + 2 + SECTION_X_LENGTH <= len && ColorCodeUtils.isValidSectionX(text, i + 2)) { + final StringBuilder cb = EXTRACT_COLOR; + cb.setLength(0); + for (int j = 0; j < 2 + SECTION_X_LENGTH; j++) cb.append(text.charAt(i + j)); + effects.append(cb); + i += 1 + SECTION_X_LENGTH; + } else { + effects.append(ColorCodeUtils.sectionPrefix(code)); + i++; + } } else if (code == 'q' || code == 'z' || code == 'v') { effects.append(ColorCodeUtils.sectionPrefix(code)); i++; diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinChunk.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinChunk.java index 2adaae84f..359f2edda 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinChunk.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinChunk.java @@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.mixins.early.celeritas.terrain; import java.util.Map; +import com.gtnewhorizon.gtnhlib.hash.Fnv1a64; +import com.gtnewhorizons.angelica.event.ChunkBiomeDataChangedEvent; import com.gtnewhorizons.angelica.mixins.interfaces.IChunkTileEntityMapHolder; import com.gtnewhorizons.angelica.rendering.RenderThreadContext; import com.gtnewhorizons.angelica.utils.ConcurrentTileEntityMap; @@ -9,12 +11,15 @@ import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.ChunkPosition; import net.minecraft.world.World; +import net.minecraft.world.biome.BiomeGenBase; +import net.minecraft.world.biome.WorldChunkManager; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; @@ -31,6 +36,11 @@ public abstract class MixinChunk implements IChunkTileEntityMapHolder { @Shadow public abstract void addTileEntity(TileEntity te); + @Shadow public abstract BiomeGenBase getBiomeGenForWorldCoords(int x, int z, WorldChunkManager wcm); + + @Unique private long angelica$biomeHash; + @Unique private boolean angelica$biomeHashValid; + @Override public ConcurrentTileEntityMap angelica$getConcurrentTEMap() { return (ConcurrentTileEntityMap) this.chunkTileEntityMap; @@ -116,4 +126,30 @@ public abstract class MixinChunk implements IChunkTileEntityMapHolder { } }); } + + @Inject(method = "fillChunk", at = @At("RETURN")) + private void angelica$onBiomesFilled(byte[] data, int primaryBitMask, int addBitMask, boolean groundUp, CallbackInfo ci) { + if (!groundUp || !this.worldObj.isRemote) return; + final long hash = angelica$hashBiomes(); + if (!this.angelica$biomeHashValid) { + this.angelica$biomeHashValid = true; + this.angelica$biomeHash = hash; + return; + } + if (hash == this.angelica$biomeHash) return; + this.angelica$biomeHash = hash; + ChunkBiomeDataChangedEvent.post(this.xPosition, this.zPosition); + } + + @Unique + private long angelica$hashBiomes() { + final WorldChunkManager wcm = this.worldObj.getWorldChunkManager(); + long hash = Fnv1a64.initialState(); + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + hash = Fnv1a64.hashStep(hash, getBiomeGenForWorldCoords(x, z, wcm).biomeID); + } + } + return hash; + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java index 8c7ff33bd..ea293c7d3 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/celeritas/terrain/MixinRenderGlobal.java @@ -148,7 +148,11 @@ public class MixinRenderGlobal implements IRenderGlobalExt { this.mc.entityRenderer.enableLightmap(partialTicks); final double camX = lerp(entity.lastTickPosX, entity.posX, partialTicks); - final double camY = lerp(entity.lastTickPosY, entity.posY, partialTicks); + // Minecraft's setupCameraTransform bakes -eyeHeight into the modelview, which would normally + // require feet here; CeleritasWorldRenderer.createChunkRenderMatrices compensates this by + // post-multiplying the chunk-shader modelview with translate(0, +eyeHeight, 0). + // Otherwise, we get issues with Iris shaders getting normals at a shifted y-position. + final double camY = lerp(entity.lastTickPosY, entity.posY, partialTicks) + entity.getEyeHeight(); final double camZ = lerp(entity.lastTickPosZ, entity.posZ, partialTicks); try { diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/ctm_cc/MixinTextureMap.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/ctm_cc/MixinTextureMap.java index 6ea56aa74..18f52899a 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/ctm_cc/MixinTextureMap.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/mcpatcherforge/ctm_cc/MixinTextureMap.java @@ -29,14 +29,10 @@ public abstract class MixinTextureMap extends AbstractTexture { @Final private String basePath; - @Shadow - protected abstract void registerIcons(); - @Inject( method = "loadTextureAtlas(Lnet/minecraft/client/resources/IResourceManager;)V", at = @At(value = "INVOKE", target = "Ljava/util/List;clear()V", remap = false, shift = At.Shift.AFTER)) private void modifyLoadTextureAtlas(IResourceManager manager, CallbackInfo ci) { - this.registerIcons(); TileLoader.registerIcons((TextureMap) (Object) this, this.basePath, this.mapRegisteredSprites); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/interpolatedtexturemap/MixinTextureMap.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/interpolatedtexturemap/MixinTextureMap.java index 89c51432a..1a78a16ab 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/interpolatedtexturemap/MixinTextureMap.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/interpolatedtexturemap/MixinTextureMap.java @@ -10,43 +10,46 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.resources.IResource; import net.minecraft.client.resources.SimpleResource; -import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Map; +import org.spongepowered.asm.mixin.injection.ModifyVariable; @Mixin(TextureMap.class) public abstract class MixinTextureMap extends AbstractTexture implements ITickableTextureObject, IIconRegister { @Shadow - @Final - private Map mapRegisteredSprites; + public abstract ResourceLocation completeResourceLocation(ResourceLocation p_147634_1_, int p_147634_2_); - @Shadow - protected abstract ResourceLocation completeResourceLocation(ResourceLocation p_147634_1_, int p_147634_2_); + @ModifyVariable(method = "registerIcon", at = @At(value = "STORE", ordinal = 3)) + private Object registerInterpolatedIcon(Object original){ + return createInterpolatedIcon(original); + } - @Inject(method = "registerIcon", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;(Ljava/lang/String;)V"), cancellable = true) - private void registerInterpolatedIcon(String textureName, CallbackInfoReturnable cir) { - try { - IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(completeResourceLocation(new ResourceLocation(textureName), 0)); - if (resource instanceof SimpleResource) { - //This returns IMetadataSections, which seems to already remove unused mcmeta fields in 1.7.10 - //I'm just running this to populate the mcmetaJson field more easily; this does it for us - if (resource.getMetadata("animation") != null) { - JsonObject mcmetaJson = ((SimpleResource) resource).mcmetaJson; - if (mcmetaJson.getAsJsonObject("animation").getAsJsonPrimitive("interpolate").getAsBoolean()) { - InterpolatedIcon interpolatedIcon = new InterpolatedIcon(textureName); - mapRegisteredSprites.put(textureName, interpolatedIcon); - cir.setReturnValue(interpolatedIcon); - } - } - } - } catch (Exception ignored) {/*Should quietly fail, no need to fail hard*/} - } + @ModifyVariable(method = "registerIcon", at = @At(value = "STORE", ordinal = 4)) + private Object registerInterpolatedIcon2(Object original){ + return createInterpolatedIcon(original); + } + + @Unique + private Object createInterpolatedIcon(Object original){ + TextureAtlasSprite tas = (TextureAtlasSprite) original; + String textureName = tas.getIconName(); + try { + IResource resource = Minecraft.getMinecraft().getResourceManager().getResource(completeResourceLocation(new ResourceLocation(textureName), 0)); + if (resource instanceof SimpleResource) { + //This returns IMetadataSections, which seems to already remove unused mcmeta fields in 1.7.10 + //I'm just running this to populate the mcmetaJson field more easily; this does it for us + if (resource.getMetadata("animation") != null) { + JsonObject mcmetaJson = ((SimpleResource) resource).mcmetaJson; + if (mcmetaJson.getAsJsonObject("animation").getAsJsonPrimitive("interpolate").getAsBoolean()) { + return new InterpolatedIcon(textureName); + } + } + } + } catch (Exception ignored) {/*Should quietly fail, no need to fail hard*/} + return original; + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java index 7509d6231..6e9268d5d 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinEntityRenderer.java @@ -51,6 +51,8 @@ public abstract class MixinEntityRenderer implements IResourceManagerReloadListe pipeline.set(Iris.getPipelineManager().preparePipeline(Iris.getCurrentDimensionName())); + GLStateManager.setShaderColor(1f, 1f, 1f, 1f); + pipeline.get().beginLevelRendering(); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java new file mode 100644 index 000000000..438cb3e56 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinNetHandlerPlayClient_NbtRemesh.java @@ -0,0 +1,41 @@ +package com.gtnewhorizons.angelica.mixins.early.shaders; + +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.block_rendering.NbtConditionalIdMap; +import net.minecraft.block.Block; +import net.minecraft.client.Minecraft; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(NetHandlerPlayClient.class) +public class MixinNetHandlerPlayClient_NbtRemesh { + + // Needed or TEs will be missed when meshing + @Inject(method = "handleUpdateTileEntity", at = @At("RETURN")) + private void angelica$remeshOnTileEntityUpdate(S35PacketUpdateTileEntity packet, CallbackInfo ci) { + final NbtConditionalIdMap teMap = BlockRenderingSettings.INSTANCE.getBlockNbtMap(); + if (teMap == null || teMap.isEmpty()) { + return; + } + + final World world = Minecraft.getMinecraft().theWorld; + if (world == null) { + return; + } + + final int x = packet.func_148856_c/*getX*/() ; + final int y = packet.func_148855_d/*getY*/(); + final int z = packet.func_148854_e/*getZ*/(); + final Block block = world.getBlock(x, y, z); + if (block == null || !teMap.hasConditions(block)) { + return; + } + + world.markBlockForUpdate(x, y, z); + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderDragon.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderDragon.java index 7902ca400..796fcb8ba 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderDragon.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderDragon.java @@ -1,29 +1,45 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; +import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.entity.RenderDragon; +import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.gen.Invoker; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** - * Mixin to set the entity ID to "end_crystal_beam" when rendering ender dragon healing beams. - * This allows shaders to apply special effects to the healing beams separately from the dragon itself. + * Mixin allows devs to target the ender crystal beams as a separate entity. + * Also sets the special condition "lightning" on the dragon's death beams. */ @Mixin(RenderDragon.class) -public class MixinRenderDragon { +public abstract class MixinRenderDragon { @Unique private static final NamespacedId END_CRYSTAL_BEAM = new NamespacedId("minecraft", "end_crystal_beam"); @Unique private int angelica$previousEntityId = -1; + @Unique + private boolean angelica$deathBeamsActive = false; + + @Unique + private int angelica$depthPassReplay = 0; + + @Invoker("renderEquippedItems") + protected abstract void angelica$invokeRenderEquippedItems(EntityDragon dragon, float partialTicks); + @Inject( method = "doRender(Lnet/minecraft/entity/boss/EntityDragon;DDDFF)V", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glPushMatrix()V", ordinal = 0, shift = At.Shift.AFTER, remap = false) @@ -52,4 +68,58 @@ public class MixinRenderDragon { angelica$previousEntityId = -1; } } + + /** + * We adapt the 2 pass structure that Modern Iris uses for the death beams. + * Replay like this so mixins that target the vanilla code hopefully runs too. + *

+ * Pass 1: Write the depth buffer. + * Pass 2: Write color. + */ + @Inject(method = "renderEquippedItems(Lnet/minecraft/entity/boss/EntityDragon;F)V", at = @At("HEAD")) + private void angelica$beginDeathBeamsLightningBuffer(EntityDragon dragon, float partialTicks, CallbackInfo ci) { + if (angelica$depthPassReplay > 0) return; + if (dragon.deathTicks > 0) { + GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.LIGHTNING); + angelica$deathBeamsActive = true; + + angelica$depthPassReplay++; + GLStateManager.glColorMask(false, false, false, false); + angelica$invokeRenderEquippedItems(dragon, partialTicks); + GLStateManager.glColorMask(true, true, true, true); + angelica$depthPassReplay--; + } + } + + // Don't render items twice + @WrapOperation( + method = "renderEquippedItems(Lnet/minecraft/entity/boss/EntityDragon;F)V", + at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/RenderLiving;renderEquippedItems(Lnet/minecraft/entity/EntityLivingBase;F)V") + ) + private void angelica$skipSuperDuringReplay(RenderDragon self, EntityLivingBase entity, float partialTicks, Operation original) { + if (angelica$depthPassReplay == 0) { + original.call(self, entity, partialTicks); + } + } + + // No-op the depth buffer being set to false on first pass + @WrapOperation( + method = "renderEquippedItems(Lnet/minecraft/entity/boss/EntityDragon;F)V", + at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glDepthMask(Z)V", ordinal = 0, remap = false) + ) + private void angelica$keepDepthMaskDuringReplay(boolean flag, Operation original) { + if (angelica$depthPassReplay == 0) { + original.call(flag); + } + } + + // End replay + @Inject(method = "renderEquippedItems(Lnet/minecraft/entity/boss/EntityDragon;F)V", at = @At("RETURN")) + private void angelica$endDeathBeamsLighting(EntityDragon dragon, float partialTicks, CallbackInfo ci) { + if (angelica$depthPassReplay > 0) return; + if (angelica$deathBeamsActive) { + GbufferPrograms.teardownSpecialRenderCondition(); + angelica$deathBeamsActive = false; + } + } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java index b4f47adf8..51dbd85a8 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManager.java @@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; +import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.EntityIdHelper; import net.minecraft.client.renderer.entity.Render; @@ -25,7 +27,14 @@ public class MixinRenderManager { private void iris$wrapDoRender(Render render, Entity entity, double x, double y, double z, float entityYaw, float partialTicks, Operation original) { int entityId = EntityIdHelper.getEntityId(entity); CapturedRenderingState.INSTANCE.setCurrentEntity(entityId); + final boolean lightning = EntityIdHelper.isLightningBolt(entity); + if (lightning) { + GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.LIGHTNING); + } original.call(render, entity, x, y, z, entityYaw, partialTicks); + if (lightning) { + GbufferPrograms.teardownSpecialRenderCondition(); + } CapturedRenderingState.INSTANCE.setCurrentEntity(-1); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManagerDAPI.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManagerDAPI.java index 1fdc4768a..343bcff93 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManagerDAPI.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderManagerDAPI.java @@ -2,6 +2,8 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; +import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.EntityIdHelper; import net.minecraft.client.renderer.entity.Render; @@ -23,7 +25,14 @@ public class MixinRenderManagerDAPI { private void iris$wrapDoRenderDragonAPI(Render render, Entity entity, double x, double y, double z, float entityYaw, float partialTicks, Operation original) { int entityId = EntityIdHelper.getEntityId(entity); CapturedRenderingState.INSTANCE.setCurrentEntity(entityId); + final boolean lightning = EntityIdHelper.isLightningBolt(entity); + if (lightning) { + GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.LIGHTNING); + } original.call(render, entity, x, y, z, entityYaw, partialTicks); + if (lightning) { + GbufferPrograms.teardownSpecialRenderCondition(); + } CapturedRenderingState.INSTANCE.setCurrentEntity(-1); } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java new file mode 100644 index 000000000..c42020415 --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinWorldNbtCache.java @@ -0,0 +1,17 @@ +package com.gtnewhorizons.angelica.mixins.early.shaders; + +import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(World.class) +public class MixinWorldNbtCache { + + @Inject(method = "markBlockForUpdate", at = @At("HEAD")) + private void angelica$onMarkBlockForUpdate(int x, int y, int z, CallbackInfo ci) { + BlockRenderingSettings.invalidateTeNbtCache(x, y, z); + } +} diff --git a/umbra/src/main/java/com/gtnewhorizons/umbra/loading/rfb/transformers/RFBUmbraRedirector.java b/umbra/src/main/java/com/gtnewhorizons/umbra/loading/rfb/transformers/RFBUmbraRedirector.java index bc68c73b1..42aabf6a1 100644 --- a/umbra/src/main/java/com/gtnewhorizons/umbra/loading/rfb/transformers/RFBUmbraRedirector.java +++ b/umbra/src/main/java/com/gtnewhorizons/umbra/loading/rfb/transformers/RFBUmbraRedirector.java @@ -52,12 +52,19 @@ public class RFBUmbraRedirector implements RfbClassTransformer { } @Override - public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + public boolean transformClassIfNeeded(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { final boolean changed = inner.transformClassNode(className, classNode.getNode()); if (changed) { classNode.computeMaxs(); UmbraClassDump.dumpRFBClass(className, classNode, this); } + return changed; + } + + @Override + public void transformClass(@NotNull ExtensibleClassLoader classLoader, @NotNull RfbClassTransformer.Context context, + @Nullable Manifest manifest, @NotNull String className, @NotNull ClassNodeHandle classNode) { + transformClassIfNeeded(classLoader, context, manifest, className, classNode); } }