From 6225fcd344404b5c684007a50825bb44a89803f6 Mon Sep 17 00:00:00 2001 From: Jason Mitchell Date: Sun, 22 Feb 2026 16:26:18 -0800 Subject: [PATCH] Target OpenGL 3.3 core profile * Emulates (most of) the Fixed Function Pipeline - with heavy inspiration from Mesa --- README.MD | 17 +- .../client/font/BatchingFontRenderer.java | 117 +- .../angelica/client/gui/SliderClone.java | 4 +- .../angelica/debug/ChunkDebugMinimap.java | 20 +- .../angelica/debug/F3Direction.java | 35 +- .../gtnewhorizons/angelica/debug/F3Graph.java | 103 +- .../glsm/CompatShaderTransformer.java | 232 ++++ .../angelica/glsm/CompatUniformManager.java | 230 ++++ .../angelica/glsm/DisplayListIDAllocator.java | 187 +++ .../angelica/glsm/DisplayListManager.java | 31 +- .../gtnewhorizons/angelica/glsm/Feature.java | 14 +- .../angelica/glsm/GLStateManager.java | 1000 ++++++++++++----- .../angelica/glsm/GlslTransformUtils.java | 110 ++ .../angelica/glsm/QuadConverter.java | 99 ++ .../angelica/glsm/RenderSystem.java | 14 +- .../angelica/glsm/dsa/DSAARB.java | 3 + .../angelica/glsm/ffp/FragmentKey.java | 153 +++ .../glsm/ffp/FragmentShaderGenerator.java | 167 +++ .../angelica/glsm/ffp/Program.java | 210 ++++ .../angelica/glsm/ffp/ShaderCache.java | 133 +++ .../angelica/glsm/ffp/ShaderManager.java | 175 +++ .../glsm/ffp/TessellatorStreamingDrawer.java | 195 ++++ .../angelica/glsm/ffp/Uniforms.java | 380 +++++++ .../angelica/glsm/ffp/VertexKey.java | 188 ++++ .../glsm/ffp/VertexShaderGenerator.java | 350 ++++++ .../glsm/recording/DisplayListVBO.java | 8 +- .../glsm/recording/DisplayListVBOBuilder.java | 12 +- .../glsm/recording/ImmediateModeRecorder.java | 177 ++- .../glsm/stacks/BooleanStateStack.java | 16 +- .../stacks/TextureUnitBooleanStateStack.java | 16 +- .../angelica/glsm/stacks/Vec3fStack.java | 47 + .../angelica/glsm/stacks/Vec4fStack.java | 48 + .../angelica/glsm/states/AlphaState.java | 2 +- .../angelica/glsm/states/BlendState.java | 21 +- .../angelica/glsm/states/BooleanState.java | 17 +- .../glsm/states/ClientArrayState.java | 72 ++ .../angelica/glsm/states/DepthState.java | 4 +- .../angelica/glsm/states/FogState.java | 8 +- .../angelica/glsm/states/LightModelState.java | 6 - .../angelica/glsm/states/LightState.java | 15 - .../angelica/glsm/states/MaterialState.java | 12 - .../angelica/glsm/states/MatrixMode.java | 4 +- .../angelica/glsm/states/ViewportState.java | 13 +- .../transformers/AngelicaRedirector.java | 21 +- .../gtnewhorizons/angelica/mixins/Mixins.java | 2 + .../angelica/render/CloudRenderer.java | 4 +- .../rendering/ItemRenderListManager.java | 6 +- .../celeritas/AngelicaChunkRenderer.java | 2 +- .../AngelicaRenderPassConfiguration.java | 9 +- .../CeleritasDebugScreenHandler.java | 5 + .../IrisCeleritasChunkShaderInterface.java | 17 +- .../net/coderbot/iris/gl/image/GlImage.java | 14 +- .../iris/gl/shader/StandardMacros.java | 7 +- .../coderbot/iris/gl/texture/GlTexture.java | 2 +- .../java/net/coderbot/iris/gui/GuiUtil.java | 5 +- .../iris/gui/element/IrisGuiSlot.java | 23 +- .../gui/element/widget/IrisImageButton.java | 3 +- .../net/coderbot/iris/pipeline/ClearPass.java | 4 +- .../DeferredWorldRenderingPipeline.java | 25 +- .../FixedFunctionWorldRenderingPipeline.java | 4 +- .../coderbot/iris/pipeline/HandRenderer.java | 41 +- .../iris/pipeline/HorizonRenderer.java | 12 +- .../iris/pipeline/ShadowRenderer.java | 32 +- .../transform/AttributeTransformer.java | 100 +- .../transform/CeleritasTransformer.java | 25 +- .../pipeline/transform/CommonTransformer.java | 58 +- .../transform/CompositeDepthTransformer.java | 11 +- .../transform/CoreTransformHelper.java | 58 + .../pipeline/transform/ShaderTransformer.java | 414 +------ .../iris/postprocess/CenterDepthSampler.java | 7 - .../iris/postprocess/CompositeRenderer.java | 6 +- .../iris/postprocess/FinalPassRenderer.java | 6 +- .../postprocess/FullScreenQuadRenderer.java | 72 +- .../texture/util/TextureManipulationUtil.java | 10 +- .../uniforms/ExternallyManagedUniforms.java | 1 + .../iris/uniforms/IrisInternalUniforms.java | 12 +- .../angelica/shaders/debug_graph.frag.glsl | 6 +- .../angelica/shaders/debug_graph.vert.glsl | 4 +- .../assets/angelica/shaders/fontFilter.fsh | 77 +- .../assets/angelica/shaders/fontFilter.vsh | 23 +- src/main/resources/centerDepth.fsh | 20 +- src/main/resources/centerDepth.vsh | 10 +- .../MixinForgeHooksClient_CoreProfile.java | 70 ++ .../angelica/animation/MixinTextureMap.java | 3 +- .../angelica/debug/MixinTextureManager.java | 5 +- .../ffp/MixinTessellator_CoreProfile.java | 24 + .../fontrenderer/MixinFontRenderer.java | 7 +- .../glsm/MixinSplashProgressCaching.java | 12 +- .../angelica/hudcaching/MixinRenderItem.java | 4 +- .../celeritas/terrain/MixinRenderGlobal.java | 7 - .../notfine/clouds/MixinRenderGlobal.java | 31 +- .../early/shaders/MixinRenderEndPortal.java | 8 +- .../early/shaders/MixinRenderGlobal.java | 6 +- ...ixinSkyProviderCelestial_ShaderCompat.java | 2 +- .../angelica/AngelicaExtension.java | 28 +- .../glsm/CompatShaderTransformerTest.java | 333 ++++++ .../glsm/CompatUniformManagerTest.java | 219 ++++ .../glsm/DisplayListCompilationGLSMTest.java | 41 +- .../glsm/DisplayListIdAllocatorTest.java | 239 ++++ .../glsm/GLSM_DisplayList_Nesting_Test.java | 18 +- .../glsm/GLSM_DisplayList_Stress_Test.java | 18 +- ..._DisplayList_TransformCollapsing_Test.java | 70 +- .../glsm/GLSM_MatrixStack_UnitTest.java | 9 +- .../angelica/glsm/GLSM_PushPop_UnitTest.java | 53 +- .../glsm/VertexAttribDefaultBridgeTest.java | 110 ++ .../gtnewhorizons/angelica/util/GLSMUtil.java | 194 +++- 106 files changed, 5845 insertions(+), 1489 deletions(-) create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListIDAllocator.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/TessellatorStreamingDrawer.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Vec3fStack.java create mode 100644 src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Vec4fStack.java create mode 100644 src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java create mode 100644 src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java create mode 100644 src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java diff --git a/README.MD b/README.MD index d5708cb44..594f8ce3b 100644 --- a/README.MD +++ b/README.MD @@ -12,6 +12,14 @@ * Complementary + Euphoria Patches is the primary compatibility target * Sildurs, Seus, and any other shaders might work +## Core Profile +Targets GL 3.3+ core profile +* FFP emulation via generated GLSL shaders +* Display list emulation +* Software matrix stacks and state management through GLSM +* GL_QUADS → GL_TRIANGLES conversion +* Automatic transformation of mod shaders that use compat-only GLSL builtins (`gl_ModelViewMatrix`, `texture2D`, etc.) + # Required Dependencies * [UniMixins](https://github.com/LegacyModdingMC/UniMixins/releases) >= 0.1.23 @@ -56,9 +64,9 @@ * The [Iris](https://github.com/IrisShaders/Iris) Team: coderbot, IMS212, Justsnoopy30, FoundationGames * Asek3 for the Iris Forge port [Oculus](https://github.com/Asek3/Oculus/tree/839ce8eca8cf0c4f6b7a1322b906e5c99125ca69) * Backported code under the LGPL -* Sodium +* Sodium / Celeritas * JellySquid & the CaffeineMC team, for making Sodium in the first place - * Embeddedt for [Embeddium](https://github.com/embeddedt/embeddium/tree/dc59ca357c25beefd6288f0d1d40b4cd8e670ab8) under the [LGPL 3.0](https://github.com/embeddedt/embeddium/blob/16.x/forge/LICENSE) + * Embeddedt for Celeritas used under the LGPL 3.0 * Reese's Sodium Options * FlashyReese for [Reese's Sodium Options](https://github.com/FlashyReese/reeses-sodium-options/tree/aa4ea67047cf53e54976e93c6bb1ab5ba16b142b) under the [MIT license](https://github.com/FlashyReese/reeses-sodium-options/blob/aa4ea67047cf53e54976e93c6bb1ab5ba16b142b/LICENSE.txt) * Neodymium @@ -85,3 +93,8 @@ * FalsePattern for [FalseTweaks](https://github.com/falsepattern/falsetweaks) - Item Rendering Optimizations taken from FalseTweaks under the LGPL 3.0 license * Beddium * Venn and Falsepattern for [Beddium](https://github.com/vfx-dev/Beddium) - MinimapRenderer, SafeChunkTracker, and some debug commands adapted under the LGPL 3.0 License +* [Mesa](https://gitlab.freedesktop.org/mesa/mesa) — Code ported and/or inspired from Mesa - under the MIT licensed + * Display list ID allocator ported from [util_idalloc](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/util/u_idalloc.c) (Copyright 2017 Valve Corporation) + * FFP vertex shader generation inspired by ffvertex_prog.c (Copyright 2007 VMware, Inc.) + * FFP fragment shader generation inspired by ff_fragment_shader.c (Copyright 2007, 2009 VMware, Inc. / 2010-2011 Intel Corporation) + * Fog parameter optimization inspired by st_nir_lower_fog.c (Copyright 2023 Google LLC) and prog_statevars.c (Copyright 1999-2007 Brian Paul) 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 064eaa2aa..4da3f4a15 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/font/BatchingFontRenderer.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.client.font; import com.google.common.collect.ImmutableSet; +import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizon.gtnhlib.util.font.GlyphReplacements; import com.gtnewhorizons.angelica.config.FontConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; @@ -12,8 +13,9 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; +import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import java.io.IOException; @@ -24,7 +26,13 @@ import java.nio.charset.StandardCharsets; import java.util.Comparator; import java.util.Objects; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocInt; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memByteBuffer; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memRealloc; /** * A batching replacement for {@code FontRenderer} @@ -49,8 +57,11 @@ public class BatchingFontRenderer { private final int AAMode; private final int AAStrength; - private final int texBoundAttrLocation; + private final int mvpMatrixLocation; private final int fontShaderId; + private static int fontVAO = 0; + private static int vboPositions, vboColors, vboTexCoords, vboTexBounds, vboIndices; + private static int capPositions, capColors, capTexCoords, capTexBounds, capIndices; final boolean isSGA; final boolean isSplash; @@ -95,7 +106,7 @@ public class BatchingFontRenderer { fontShaderId = FontAAShader.getProgram().getProgramId(); AAMode = GL20.glGetUniformLocation(fontShaderId, "aaMode"); AAStrength = GL20.glGetUniformLocation(fontShaderId, "strength"); - texBoundAttrLocation = GL20.glGetAttribLocation(fontShaderId, "texBounds"); + mvpMatrixLocation = GL20.glGetUniformLocation(fontShaderId, "u_MVPMatrix"); } // === Batched rendering @@ -271,9 +282,21 @@ public class BatchingFontRenderer { } } - int lastActiveProgram; - int fontAAModeLast = -1; - int fontAAStrengthLast = -1; + private static int streamUpload(int target, int vbo, long address, int bytes, int cap) { + GL15.glBindBuffer(target, vbo); + final ByteBuffer data = memByteBuffer(address, bytes); + if (bytes > cap) { + GL15.glBufferData(target, data, GL15.GL_STREAM_DRAW); + return bytes; + } + GL15.glBufferData(target, cap, GL15.GL_STREAM_DRAW); + GL15.glBufferSubData(target, 0, data); + return cap; + } + + private static final Matrix4f scratchMvp = new Matrix4f(); + private int fontAAModeLast = -1; + private int fontAAStrengthLast = -1; private void flushBatch() { final int prevProgram = GLStateManager.glGetInteger(GL20.GL_CURRENT_PROGRAM); @@ -291,11 +314,8 @@ public class BatchingFontRenderer { GLStateManager.tryBlendFuncSeparate(blendSrcRGB, blendDstRGB, GL11.GL_ONE, GL11.GL_ZERO); GLStateManager.glShadeModel(GL11.GL_FLAT); - final boolean canUseAA = FontConfig.fontAAMode != 0 && prevProgram == 0; - if (canUseAA) { - GL20.glVertexAttribPointer(texBoundAttrLocation, 4, false, 0, batchVtxTexBounds); - GL20.glEnableVertexAttribArray(texBoundAttrLocation); - lastActiveProgram = prevProgram; + final boolean useFontShader = prevProgram == 0; + if (useFontShader) { GLStateManager.glUseProgram(fontShaderId); if (FontConfig.fontAAMode != fontAAModeLast) { fontAAModeLast = FontConfig.fontAAMode; @@ -305,19 +325,56 @@ public class BatchingFontRenderer { fontAAStrengthLast = FontConfig.fontAAStrength; GL20.glUniform1f(AAStrength, FontConfig.fontAAStrength / 120.f); } + try (MemoryStack stack = stackPush()) { + final FloatBuffer mvpBuf = stack.mallocFloat(16); + GLStateManager.getProjectionMatrix().mul(GLStateManager.getModelViewMatrix(), scratchMvp); + scratchMvp.get(mvpBuf); + GL20.glUniformMatrix4(mvpMatrixLocation, false, mvpBuf); + } } - GL13.glClientActiveTexture(GL13.GL_TEXTURE0); - GL11.glTexCoordPointer(2, 0, batchVtxTexCoords); - GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); - GL11.glColorPointer(4, GL11.GL_UNSIGNED_BYTE, 0, batchVtxColors); - GL11.glEnableClientState(GL11.GL_COLOR_ARRAY); - GL11.glVertexPointer(2, 0, batchVtxPositions); - GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); + if (fontVAO == 0) { + fontVAO = org.lwjgl.opengl.GL30.glGenVertexArrays(); + vboPositions = GL15.glGenBuffers(); + vboColors = GL15.glGenBuffers(); + vboTexCoords = GL15.glGenBuffers(); + vboTexBounds = GL15.glGenBuffers(); + vboIndices = GL15.glGenBuffers(); + } + GLStateManager.glBindVertexArray(fontVAO); + + final int vtxCount = vtxWriterIndex; + + // Location 0: position (vec2, float) + batchVtxPositions.position(0).limit(vtxCount * 2); + capPositions = streamUpload(GL15.GL_ARRAY_BUFFER, vboPositions, memAddress(batchVtxPositions), batchVtxPositions.remaining() * 4, capPositions); + GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 0, 0L); + GL20.glEnableVertexAttribArray(0); + + // Location 1: color (vec4, unsigned byte normalized) + batchVtxColors.position(0).limit(vtxCount * 4); + capColors = streamUpload(GL15.GL_ARRAY_BUFFER, vboColors, memAddress(batchVtxColors), batchVtxColors.remaining(), capColors); + GL20.glVertexAttribPointer(1, 4, GL11.GL_UNSIGNED_BYTE, true, 0, 0L); + GL20.glEnableVertexAttribArray(1); + + // Location 2: texcoord0 (vec2, float) + batchVtxTexCoords.position(0).limit(vtxCount * 2); + capTexCoords = streamUpload(GL15.GL_ARRAY_BUFFER, vboTexCoords, memAddress(batchVtxTexCoords), batchVtxTexCoords.remaining() * 4, capTexCoords); + GL20.glVertexAttribPointer(2, 2, GL11.GL_FLOAT, false, 0, 0L); + GL20.glEnableVertexAttribArray(2); + + // Location 3: texbounds (vec4, float) + batchVtxTexBounds.position(0).limit(vtxCount * 4); + capTexBounds = streamUpload(GL15.GL_ARRAY_BUFFER, vboTexBounds, memAddress(batchVtxTexBounds), batchVtxTexBounds.remaining() * 4, capTexBounds); + GL20.glVertexAttribPointer(3, 4, GL11.GL_FLOAT, false, 0, 0L); + GL20.glEnableVertexAttribArray(3); + + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - GL11.glDisableClientState(GL11.GL_NORMAL_ARRAY); - GL11.glNormal3f(0.0f, 0.0f, 1.0f); + // Stream upload index buffer + batchIndices.position(0).limit(idxWriterIndex); + capIndices = streamUpload(GL15.GL_ELEMENT_ARRAY_BUFFER, vboIndices, memAddress(batchIndices), batchIndices.remaining() * 4, capIndices); // Use plain for loop to avoid allocations final FontDrawCmd[] cmdsData = batchCommands.elements(); @@ -336,19 +393,14 @@ public class BatchingFontRenderer { } lastTexture = cmd.texture; } - batchIndices.limit(cmd.startVtx + cmd.idxCount); - batchIndices.position(cmd.startVtx); - GL11.glDrawElements(GL11.GL_TRIANGLES, batchIndices); + GL11.glDrawElements(GL11.GL_TRIANGLES, cmd.idxCount, GL11.GL_UNSIGNED_INT, (long) cmd.startVtx * 4L); } - if (canUseAA) { - GLStateManager.glUseProgram(lastActiveProgram); - GL20.glDisableVertexAttribArray(texBoundAttrLocation); + if (useFontShader) { + GLStateManager.glUseProgram(prevProgram); } - GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); - GL11.glDisableClientState(GL11.GL_COLOR_ARRAY); - GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY); + GLStateManager.glBindVertexArray(0); if (isTextureEnabledBefore) { GLStateManager.glEnable(GL11.GL_TEXTURE_2D); @@ -362,8 +414,11 @@ public class BatchingFontRenderer { batchCommands.clear(); vtxWriterIndex = 0; idxWriterIndex = 0; + batchVtxPositions.limit(batchVtxPositions.capacity()); + batchVtxColors.limit(batchVtxColors.capacity()); + batchVtxTexCoords.limit(batchVtxTexCoords.capacity()); + batchVtxTexBounds.limit(batchVtxTexBounds.capacity()); batchIndices.limit(batchIndices.capacity()); - batchIndices.position(0); } // === Actual text mesh generation diff --git a/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java b/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java index 14fe5369d..13516cf84 100644 --- a/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java +++ b/src/main/java/com/gtnewhorizons/angelica/client/gui/SliderClone.java @@ -1,12 +1,12 @@ package com.gtnewhorizons.angelica.client.gui; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import lombok.AllArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; -import org.lwjgl.opengl.GL11; import java.util.function.Consumer; import java.util.function.Function; @@ -123,7 +123,7 @@ public class SliderClone extends GuiButton { this.displayString = displayStringFormatter.apply(f); } - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); this.drawTexturedModalRect(this.xPosition + (int)(this.sliderPercentage * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); } diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/ChunkDebugMinimap.java b/src/main/java/com/gtnewhorizons/angelica/debug/ChunkDebugMinimap.java index 0f3c6f996..ca8a0c1c0 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/ChunkDebugMinimap.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/ChunkDebugMinimap.java @@ -29,6 +29,7 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import lombok.Getter; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ChunkProviderClient; +import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.chunk.EmptyChunk; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.common.MinecraftForge; @@ -97,17 +98,18 @@ public class ChunkDebugMinimap { GLStateManager.enableBlend(); GLStateManager.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GLStateManager.glBegin(GL11.GL_QUADS); + final Tessellator tess = Tessellator.instance; + tess.startDrawingQuads(); final ChunkProviderClient chunkProvider = (ChunkProviderClient) mc.theWorld.getChunkProvider(); for (int x = playerChunkX - RANGE; x < playerChunkX + RANGE; x++) { for (int z = playerChunkZ - RANGE; z < playerChunkZ + RANGE; z++) { - drawChunk(x, z, playerChunkX, playerChunkZ, manager, chunkProvider); + drawChunk(tess, x, z, playerChunkX, playerChunkZ, manager, chunkProvider); } } - GL11.glEnd(); + tess.draw(); // Restore GL state GLStateManager.enableLighting(); @@ -117,7 +119,7 @@ public class ChunkDebugMinimap { GLStateManager.glPopAttrib(); } - private void drawChunk(int chunkX, int chunkZ, int playerChunkX, int playerChunkZ, AngelicaRenderSectionManager manager, ChunkProviderClient chunkProvider) { + private void drawChunk(Tessellator tess, int chunkX, int chunkZ, int playerChunkX, int playerChunkZ, AngelicaRenderSectionManager manager, ChunkProviderClient chunkProvider) { boolean initialized = false; float r = 0, g = 0, b = 0; @@ -143,16 +145,16 @@ public class ChunkDebugMinimap { } } - GL11.glColor4f(r, g, b, 0.8f); + tess.setColorRGBA_F(r, g, b, 0.8f); final int xStart = chunkX - playerChunkX; final int zStart = chunkZ - playerChunkZ; final int xEnd = xStart + 1; final int zEnd = zStart + 1; - GLStateManager.glVertex3d(xStart, zStart, 0); - GLStateManager.glVertex3d(xStart, zEnd, 0); - GLStateManager.glVertex3d(xEnd, zEnd, 0); - GLStateManager.glVertex3d(xEnd, zStart, 0); + tess.addVertex(xStart, zStart, 0); + tess.addVertex(xStart, zEnd, 0); + tess.addVertex(xEnd, zEnd, 0); + tess.addVertex(xEnd, zStart, 0); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/F3Direction.java b/src/main/java/com/gtnewhorizons/angelica/debug/F3Direction.java index c8447ec03..efc60b5e9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/F3Direction.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/F3Direction.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.debug; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.Tessellator; @@ -10,31 +11,31 @@ import org.lwjgl.opengl.GL11; public class F3Direction { public static void renderWorldDirectionsEvent(Minecraft mc, RenderGameOverlayEvent.Pre event) { if (mc.gameSettings.showDebugInfo && mc.gameSettings.thirdPersonView == 0) { - ScaledResolution scaledresolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - int width = scaledresolution.getScaledWidth(); - int height = scaledresolution.getScaledHeight(); + final ScaledResolution scaledresolution = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + final int width = scaledresolution.getScaledWidth(); + final int height = scaledresolution.getScaledHeight(); - GL11.glPushMatrix(); + GLStateManager.glPushMatrix(); - GL11.glTranslatef((float) (width / 2), (float) (height / 2), -90); + GLStateManager.glTranslatef((float) (width / 2), (float) (height / 2), -90); - Entity entity = mc.renderViewEntity; - GL11.glRotatef(entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * event.partialTicks, -1.0F, 0.0F, 0.0F); - GL11.glRotatef(entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * event.partialTicks, 0.0F, 1.0F, 0.0F); + final Entity entity = mc.renderViewEntity; + GLStateManager.glRotatef(entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * event.partialTicks, -1.0F, 0.0F, 0.0F); + GLStateManager.glRotatef(entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * event.partialTicks, 0.0F, 1.0F, 0.0F); - GL11.glScalef(-1.0F, -1.0F, -1.0F); + GLStateManager.glScalef(-1.0F, -1.0F, -1.0F); renderWorldDirections(); - GL11.glPopMatrix(); + GLStateManager.glPopMatrix(); } } public static void renderWorldDirections() { - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDepthMask(false); - Tessellator tessellator = Tessellator.instance; + GLStateManager.disableTexture(); + GLStateManager.glDepthMask(false); + final Tessellator tessellator = Tessellator.instance; - GL11.glLineWidth(2.0F); + GLStateManager.glLineWidth(2.0F); tessellator.startDrawing(GL11.GL_LINES); //X @@ -54,8 +55,8 @@ public class F3Direction { tessellator.draw(); - GL11.glLineWidth(1.0F); - GL11.glDepthMask(true); - GL11.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glLineWidth(1.0F); + GLStateManager.glDepthMask(true); + GLStateManager.enableTexture(); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java b/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java index 4ab6110d3..52b854c66 100644 --- a/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java +++ b/src/main/java/com/gtnewhorizons/angelica/debug/F3Graph.java @@ -1,44 +1,33 @@ package com.gtnewhorizons.angelica.debug; -import static org.lwjgl.opengl.GL11.GL_ALPHA_TEST; -import static org.lwjgl.opengl.GL11.GL_BLEND; -import static org.lwjgl.opengl.GL11.GL_CULL_FACE; -import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST; -import static org.lwjgl.opengl.GL11.GL_FLOAT; -import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; -import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D; -import static org.lwjgl.opengl.GL11.GL_TRIANGLE_STRIP; -import static org.lwjgl.opengl.GL11.GL_VERTEX_ARRAY; -import static org.lwjgl.opengl.GL11.glBlendFunc; -import static org.lwjgl.opengl.GL11.glColor4f; -import static org.lwjgl.opengl.GL11.glDisable; -import static org.lwjgl.opengl.GL11.glDisableClientState; -import static org.lwjgl.opengl.GL11.glDrawArrays; -import static org.lwjgl.opengl.GL11.glEnable; -import static org.lwjgl.opengl.GL11.glEnableClientState; -import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER; -import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; -import static com.gtnewhorizons.angelica.glsm.GLStateManager.glBindBuffer; -import static org.lwjgl.opengl.GL15.glBufferData; -import static org.lwjgl.opengl.GL15.glGenBuffers; -import static org.lwjgl.opengl.GL20.glDisableVertexAttribArray; -import static org.lwjgl.opengl.GL20.glEnableVertexAttribArray; -import static org.lwjgl.opengl.GL20.glUniform1; -import static org.lwjgl.opengl.GL20.glUniform1f; -import static org.lwjgl.opengl.GL20.glUniform1i; -import static org.lwjgl.opengl.GL20.glVertexAttribPointer; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*; - import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizon.gtnhlib.client.renderer.shader.ShaderProgram; -import java.nio.FloatBuffer; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.ResourceLocation; import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL30; + +import java.nio.FloatBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush; +import static com.gtnewhorizons.angelica.glsm.GLStateManager.glBindBuffer; +import static org.lwjgl.opengl.GL11.GL_FLOAT; +import static org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA; +import static org.lwjgl.opengl.GL11.GL_SRC_ALPHA; +import static org.lwjgl.opengl.GL11.GL_TRIANGLE_STRIP; +import static org.lwjgl.opengl.GL15.GL_ARRAY_BUFFER; +import static org.lwjgl.opengl.GL15.GL_STATIC_DRAW; +import static org.lwjgl.opengl.GL15.glBufferData; +import static org.lwjgl.opengl.GL15.glGenBuffers; +import static org.lwjgl.opengl.GL20.glEnableVertexAttribArray; +import static org.lwjgl.opengl.GL20.glUniform1; +import static org.lwjgl.opengl.GL20.glUniform1f; +import static org.lwjgl.opengl.GL20.glUniform1i; +import static org.lwjgl.opengl.GL20.glVertexAttribPointer; public abstract class F3Graph { private static final int NUM_SAMPLES = 240; @@ -63,6 +52,7 @@ public abstract class F3Graph { private int uHeadIdx; private int uSamples; private int vertBuf; + private int vao; private final ResourceLocation texture; private final float pxPerNs; private final boolean left; @@ -117,8 +107,8 @@ public abstract class F3Graph { "shaders/debug_graph.frag.glsl"); shader.use(); - // Register attributes - aPos = shader.getAttribLocation("pos"); + // Attribute location is declared in shader via layout(location = 0) + aPos = 0; // Register uniforms uFBWidth = shader.getUniformLocation("fbWidth"); @@ -129,7 +119,9 @@ public abstract class F3Graph { final int uPxPerNs = shader.getUniformLocation("pxPerNs"); final int uLeft = shader.getUniformLocation("left"); - // Load vertex buffer + vao = GL30.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); + vertBuf = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vertBuf); try (final MemoryStack stack = stackPush()) { @@ -146,7 +138,13 @@ public abstract class F3Graph { glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW); } + + // Configure vertex attribute in the VAO + glVertexAttribPointer(aPos, VERT_FLOATS, GL_FLOAT, false, VERT_FLOATS * 4, 0); + glEnableVertexAttribArray(aPos); + glBindBuffer(GL_ARRAY_BUFFER, 0); + GLStateManager.glBindVertexArray(0); final Minecraft mc = Minecraft.getMinecraft(); final ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); @@ -186,21 +184,21 @@ public abstract class F3Graph { // Setup GL state final Tessellator tess = Tessellator.instance; - glDisable(GL_DEPTH_TEST); - glEnable(GL_ALPHA_TEST); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + GLStateManager.disableDepthTest(); + GLStateManager.enableAlphaTest(); + GLStateManager.enableBlend(); + GLStateManager.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Draw background - glDisable(GL_TEXTURE_2D); - glColor4f(0x50 / 255.0F, 0x50 / 255.0F, 0x50 / 255.0F, 0x90 / 255.0F); + GLStateManager.disableTexture(); + GLStateManager.glColor4f(0x50 / 255.0F, 0x50 / 255.0F, 0x50 / 255.0F, 0x90 / 255.0F); tess.startDrawingQuads(); for (int i = 0; i < 4; ++i) { tess.addVertex(getVertX(sr, i), getVertY(sr, i), 0); } tess.draw(); - glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - glEnable(GL_TEXTURE_2D); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.enableTexture(); // Draw samples @@ -213,21 +211,16 @@ public abstract class F3Graph { glUniform1i(uHeadIdx, samplesHead); glUniform1(uSamples, sampleBuf); - glBindBuffer(GL_ARRAY_BUFFER, vertBuf); - glEnableVertexAttribArray(aPos); - glVertexAttribPointer(aPos, VERT_FLOATS, GL_FLOAT, false, VERT_FLOATS * 4, 0); - glEnableClientState(GL_VERTEX_ARRAY); + GLStateManager.glBindVertexArray(vao); // Left side graphs are inverted, so temporarily disable culling - if (!left) glDisable(GL_CULL_FACE); + if (!left) GLStateManager.disableCull(); - glDrawArrays(GL_TRIANGLE_STRIP, 0, VERT_COUNT); + GLStateManager.glDrawArrays(GL_TRIANGLE_STRIP, 0, VERT_COUNT); - if (!left) glEnable(GL_CULL_FACE); + if (!left) GLStateManager.enableCull(); - glDisableClientState(GL_VERTEX_ARRAY); - glDisableVertexAttribArray(aPos); - glBindBuffer(GL_ARRAY_BUFFER, 0); + GLStateManager.glBindVertexArray(0); ShaderProgram.clear(); @@ -242,9 +235,9 @@ public abstract class F3Graph { tess.draw(); // Reset GL state - glEnable(GL_DEPTH_TEST); - glDisable(GL_ALPHA_TEST); - glDisable(GL_BLEND); + GLStateManager.enableDepthTest(); + GLStateManager.disableAlphaTest(); + GLStateManager.disableBlend(); // Draw text // Ensure running counters are reset on first sample diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java new file mode 100644 index 000000000..e9caac8a1 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformer.java @@ -0,0 +1,232 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.taumc.glsl.ShaderParser; +import org.taumc.glsl.Transformer; + +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; + +/** + * Compat transformation for mod shaders running under core profile. + * + *

Handles: + *

+ */ +public class CompatShaderTransformer { + + private static final Pattern VERSION_PATTERN = + Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?"); + + /** Compat builtins that trigger AST transformation. */ + private static final Set COMPAT_BUILTINS = Set.of( + "gl_ModelView", "gl_Projection", "gl_NormalMatrix", "gl_TextureMatrix", + "gl_FragColor", "gl_Fog", "gl_FrontColor", "gl_Color", + "texture2D", "texture3D", "texelFetch2D", "texelFetch3D", "textureSize2D", + "shadow2D" + ); + + private static final Pattern NEEDS_TRANSFORM_PATTERN = Pattern.compile(String.join("|", COMPAT_BUILTINS)); + + private static final Map MATRIX_RENAMES = Map.of( + "gl_ModelViewMatrix", "angelica_ModelViewMatrix", + "gl_ModelViewMatrixInverse", "angelica_ModelViewMatrixInverse", + "gl_ProjectionMatrix", "angelica_ProjectionMatrix", + "gl_ProjectionMatrixInverse", "angelica_ProjectionMatrixInverse", + "gl_NormalMatrix", "angelica_NormalMatrix" + ); + + private static final int CACHE_SIZE = 32; + private record CacheKey(String source, boolean isFragment) {} + private static final Map cache = Collections.synchronizedMap( + new LinkedHashMap<>(32, 0.75f, true) { + @Override protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > CACHE_SIZE; + } + }); + + public static void clearCache() { + cache.clear(); + } + + /** + * Transform a mod shader source for core profile compatibility. + */ + public static String transform(String source, boolean isFragment) { + if (!needsTransformation(source)) { + return fixupVersion(source); + } + + final CacheKey key = new CacheKey(source, isFragment); + final String cached = cache.get(key); + if (cached != null) return cached; + + try { + final String result = transformInternal(source, isFragment); + cache.put(key, result); + return result; + } catch (Exception e) { + LOGGER.warn("CompatShaderTransformer: AST transformation failed, falling back to version fixup only", e); + return fixupVersion(source); + } + } + + private static boolean needsTransformation(String source) { + return NEEDS_TRANSFORM_PATTERN.matcher(source).find(); + } + + private static String transformInternal(String source, boolean isFragment) { + final Matcher versionMatcher = VERSION_PATTERN.matcher(source); + int declaredVersion = 110; + if (versionMatcher.find()) { + declaredVersion = Integer.parseInt(versionMatcher.group(1)); + } + + final int targetVersion = Math.max(declaredVersion, 330); + + // Pre-parse reserved word renaming — prevents ANTLR parse failures + source = GlslTransformUtils.replaceTexture(source); + source = GlslTransformUtils.renameReservedWords(source, targetVersion); + + final ShaderParser.ParsedShader parsedShader = ShaderParser.parseShader(source); + final Transformer transformer = new Transformer(parsedShader.full()); + + injectMatrixUniforms(transformer); + + transformFog(transformer, isFragment); + + // gl_FrontColor (vertex) → gl_Color (fragment) varying chain + if (!isFragment) { + transformer.injectVariable("out vec4 angelica_FrontColor;"); + transformer.rename("gl_FrontColor", "angelica_FrontColor"); + transformer.prependMain("angelica_FrontColor = vec4(1.0);"); + } else { + transformer.injectVariable("in vec4 angelica_FrontColor;"); + transformer.rename("gl_Color", "angelica_FrontColor"); + } + + // Fragment output handling + alpha test discard + if (isFragment) { + transformFragmentOutputs(transformer); + } + + // texture-as-variable collision handling + if (transformer.containsCall("texture") && transformer.hasVariable("texture")) { + transformer.rename("texture", "gtexture"); + } + if (transformer.hasVariable("angelica_renamed_texture")) { + transformer.rename("angelica_renamed_texture", "gtexture"); + } + + transformer.renameFunctionCall(GlslTransformUtils.TEXTURE_RENAMES); + + transformer.renameAndWrapShadow("shadow2D", "texture"); + transformer.renameAndWrapShadow("shadow2DLod", "textureLod"); + + final String versionDirective = "#version " + targetVersion + " core\n"; + final String extensions = VERSION_PATTERN.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); + final String header = versionDirective + (extensions.isEmpty() ? "" : "\n" + extensions); + final StringBuilder result = new StringBuilder(); + transformer.mutateTree(tree -> result.append(GlslTransformUtils.getFormattedShader(tree, header))); + + // Restore pre-parse renames + return GlslTransformUtils.restoreReservedWords(result.toString()); + } + + /** + * Inject matrix uniforms and rename compat builtins. + */ + private static void injectMatrixUniforms(Transformer transformer) { + transformer.injectVariable("uniform mat4 angelica_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 angelica_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat4 angelica_ProjectionMatrix;"); + transformer.injectVariable("uniform mat4 angelica_ProjectionMatrixInverse;"); + transformer.injectVariable("uniform mat3 angelica_NormalMatrix;"); + transformer.injectVariable("uniform mat4 angelica_LightmapTextureMatrix;"); + + transformer.rename(MATRIX_RENAMES); + + // Expression replacements + transformer.replaceExpression("gl_ModelViewProjectionMatrix", "(angelica_ProjectionMatrix * angelica_ModelViewMatrix)"); + transformer.replaceExpression("gl_TextureMatrix[0]", "mat4(1.0)"); + transformer.replaceExpression("gl_TextureMatrix[1]", "angelica_LightmapTextureMatrix"); + transformer.replaceExpression("gl_TextureMatrix", "mat4[8](mat4(1.0), angelica_LightmapTextureMatrix, mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0))"); + } + + /** + * Transform fragment outputs for core profile. + */ + private static void transformFragmentOutputs(Transformer transformer) { + if (transformer.containsCall("gl_FragColor")) { + transformer.replaceExpression("gl_FragColor", "gl_FragData[0]"); + } + + final Set found = new HashSet<>(); + transformer.renameArray("gl_FragData", "angelica_FragData", found); + + for (Integer i : found) { + transformer.injectVariable("layout (location = " + i + ") out vec4 angelica_FragData" + i + ";"); + } + + // Core profile: GL_ALPHA_TEST is removed - inject runtime discard using GLSM-tracked alpha reference (uploaded by CompatUniformManager). + if (found.contains(0)) { + transformer.injectVariable("uniform float angelica_currentAlphaTest;"); + transformer.appendMain("if (angelica_FragData0.a <= angelica_currentAlphaTest) discard;"); + } + } + + private static void transformFog(Transformer transformer, boolean isFragment) { + transformer.rename("gl_FogFragCoord", "angelica_FogFragCoord"); + if (!isFragment) { + transformer.injectVariable("out float angelica_FogFragCoord;"); + transformer.prependMain("angelica_FogFragCoord = 0.0f;"); + } else { + transformer.injectVariable("in float angelica_FogFragCoord;"); + } + + transformer.rename("gl_Fog", "angelica_Fog"); + transformer.injectVariable("uniform float angelica_FogDensity;"); + transformer.injectVariable("uniform float angelica_FogStart;"); + transformer.injectVariable("uniform float angelica_FogEnd;"); + transformer.injectVariable("uniform vec4 angelica_FogColor;"); + transformer.injectFunction("struct angelica_FogParameters {vec4 color;float density;float start;float end;float scale;};"); + transformer.injectFunction( + "angelica_FogParameters angelica_Fog = angelica_FogParameters(" + + "angelica_FogColor, angelica_FogDensity, angelica_FogStart, angelica_FogEnd, " + + "1.0f / (angelica_FogEnd - angelica_FogStart));"); + } + + /** Ensure #version is at least 330 core, strip 'compatibility' profile. */ + private static String fixupVersion(String source) { + final Matcher m = VERSION_PATTERN.matcher(source); + if (!m.find()) { + return "#version 330 core\n" + source; + } + + final int version = Integer.parseInt(m.group(1)); + final String profile = m.group(2); + + if (version >= 330 && !"compatibility".equals(profile)) { + if ("core".equals(profile)) return source; + return m.replaceFirst("#version " + version + " core"); + } + + final int targetVersion = Math.max(version, 330); + return m.replaceFirst("#version " + targetVersion + " core"); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java new file mode 100644 index 000000000..0f5ad6424 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/CompatUniformManager.java @@ -0,0 +1,230 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.glsm.stacks.FogStateStack; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; + +import java.nio.FloatBuffer; + +import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; + +/** + * Per-program compat uniform location cache and upload manager. + * + *

Manages {@code angelica_*} uniforms injected by {@link CompatShaderTransformer} and {@code iris_*} matrix uniforms used by Iris/celeritas shader programs. + */ +public class CompatUniformManager { + + // Uniform location indices within the cached array (package-private for tests) + static final int LOC_MODELVIEW = 0; + static final int LOC_MODELVIEW_INVERSE = 1; + static final int LOC_PROJECTION = 2; + static final int LOC_PROJECTION_INVERSE = 3; + static final int LOC_NORMAL = 4; + static final int LOC_LIGHTMAP_TEXTURE_MATRIX = 5; + static final int LOC_FOG_DENSITY = 6; + static final int LOC_FOG_START = 7; + static final int LOC_FOG_END = 8; + static final int LOC_FOG_COLOR = 9; + static final int LOC_IRIS_MODELVIEW = 10; + static final int LOC_IRIS_PROJECTION = 11; + static final int LOC_IRIS_NORMAL = 12; + static final int LOC_IRIS_LIGHTMAP_TEXTURE_MATRIX = 13; + static final int LOC_ALPHA_TEST_REF = 14; + static final int LOC_COUNT = 15; + + private static final String[] UNIFORM_NAMES = { + "angelica_ModelViewMatrix", + "angelica_ModelViewMatrixInverse", + "angelica_ProjectionMatrix", + "angelica_ProjectionMatrixInverse", + "angelica_NormalMatrix", + "angelica_LightmapTextureMatrix", + "angelica_FogDensity", + "angelica_FogStart", + "angelica_FogEnd", + "angelica_FogColor", + "iris_ModelViewMatrix", + "iris_ProjectionMatrix", + "iris_NormalMatrix", + "iris_LightmapTextureMatrix", + "angelica_currentAlphaTest", + }; + + /** Per-program cached uniform locations. Maps program ID → int[LOC_COUNT]. */ + private static final Int2ObjectOpenHashMap programLocations = new Int2ObjectOpenHashMap<>(); + + // Reusable NIO buffers for upload + private static final FloatBuffer mat4Buf = BufferUtils.createFloatBuffer(16); + private static final FloatBuffer mat3Buf = BufferUtils.createFloatBuffer(9); + private static final FloatBuffer vec4Buf = BufferUtils.createFloatBuffer(4); + private static final Matrix3f normalMatrix = new Matrix3f(); + private static final Matrix4f scratchMatrix = new Matrix4f(); + + private static final float LIGHTMAP_SCALE = 1.0f / 256.0f; + private static final FloatBuffer lightmapMatrixBuf; + static { + lightmapMatrixBuf = BufferUtils.createFloatBuffer(16); + new Matrix4f().scale(LIGHTMAP_SCALE).translate(8.0f, 8.0f, 8.0f).get(lightmapMatrixBuf); + } + + // Dirty tracking: skip uploads when state hasn't changed and program is the same + private static int lastProgram = -1; + private static int lastMatrixGen = -1; + private static int lastFragmentGen = -1; + + private CompatUniformManager() {} + + public static void onLinkProgram(int program) { + int[] locs = new int[LOC_COUNT]; + boolean hasAny = false; + + for (int i = 0; i < LOC_COUNT; i++) { + locs[i] = GL20.glGetUniformLocation(program, UNIFORM_NAMES[i]); + if (locs[i] != -1) hasAny = true; + } + + if (hasAny) { + programLocations.put(program, locs); + LOGGER.debug("CompatUniformManager: program {} has compat uniforms", program); + } + } + + public static void onUseProgram(int program) { + if (program == 0) return; + + int[] locs = programLocations.get(program); + if (locs == null) return; + + final boolean programChanged = program != lastProgram; + lastProgram = program; + + // Matrix uniforms — skip if generation unchanged and same program + final int matGen = GLStateManager.matrixGeneration; + if (programChanged || matGen != lastMatrixGen) { + lastMatrixGen = matGen; + uploadMatrices(locs); + } + + // Fragment-category uniforms (fog, alpha) — skip if generation unchanged + final int fragGen = GLStateManager.fragmentGeneration; + if (programChanged || fragGen != lastFragmentGen) { + lastFragmentGen = fragGen; + uploadFragmentUniforms(locs); + } + } + + private static void uploadMatrices(int[] locs) { + Matrix4f mv = GLStateManager.getModelViewMatrix(); + Matrix4f proj = GLStateManager.getProjectionMatrix(); + + // ModelView + if (locs[LOC_MODELVIEW] != -1 || locs[LOC_IRIS_MODELVIEW] != -1) { + mv.get(mat4Buf); + if (locs[LOC_MODELVIEW] != -1) { + GL20.glUniformMatrix4(locs[LOC_MODELVIEW], false, mat4Buf); + } + if (locs[LOC_IRIS_MODELVIEW] != -1) { + GL20.glUniformMatrix4(locs[LOC_IRIS_MODELVIEW], false, mat4Buf); + } + } + + // ModelView Inverse + if (locs[LOC_MODELVIEW_INVERSE] != -1) { + mv.invert(scratchMatrix); + scratchMatrix.get(mat4Buf); + GL20.glUniformMatrix4(locs[LOC_MODELVIEW_INVERSE], false, mat4Buf); + } + + // Projection + if (locs[LOC_PROJECTION] != -1 || locs[LOC_IRIS_PROJECTION] != -1) { + proj.get(mat4Buf); + if (locs[LOC_PROJECTION] != -1) { + GL20.glUniformMatrix4(locs[LOC_PROJECTION], false, mat4Buf); + } + if (locs[LOC_IRIS_PROJECTION] != -1) { + GL20.glUniformMatrix4(locs[LOC_IRIS_PROJECTION], false, mat4Buf); + } + } + + // Projection Inverse + if (locs[LOC_PROJECTION_INVERSE] != -1) { + proj.invert(scratchMatrix); + scratchMatrix.get(mat4Buf); + GL20.glUniformMatrix4(locs[LOC_PROJECTION_INVERSE], false, mat4Buf); + } + + // 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) { + GL20.glUniformMatrix3(locs[LOC_NORMAL], false, mat3Buf); + } + if (locs[LOC_IRIS_NORMAL] != -1) { + GL20.glUniformMatrix3(locs[LOC_IRIS_NORMAL], false, mat3Buf); + } + } + + // Iris lightmap texture matrix (constant) + if (locs[LOC_IRIS_LIGHTMAP_TEXTURE_MATRIX] != -1) { + GL20.glUniformMatrix4(locs[LOC_IRIS_LIGHTMAP_TEXTURE_MATRIX], false, lightmapMatrixBuf); + } + + // angelica_LightmapTextureMatrix — actual GLSM texture unit 1 matrix (set by enableLightmap()) + if (locs[LOC_LIGHTMAP_TEXTURE_MATRIX] != -1) { + GLStateManager.getTextures().getTextureUnitMatrix(1).get(mat4Buf); + GL20.glUniformMatrix4(locs[LOC_LIGHTMAP_TEXTURE_MATRIX], false, mat4Buf); + } + } + + private static void uploadFragmentUniforms(int[] locs) { + // Fog uniforms + FogStateStack fog = GLStateManager.getFogState(); + if (locs[LOC_FOG_DENSITY] != -1) { + GL20.glUniform1f(locs[LOC_FOG_DENSITY], Math.max(0.0f, fog.getDensity())); + } + if (locs[LOC_FOG_START] != -1) { + GL20.glUniform1f(locs[LOC_FOG_START], fog.getStart()); + } + if (locs[LOC_FOG_END] != -1) { + GL20.glUniform1f(locs[LOC_FOG_END], fog.getEnd()); + } + if (locs[LOC_FOG_COLOR] != -1) { + vec4Buf.clear(); + vec4Buf.put((float) fog.getFogColor().x).put((float) fog.getFogColor().y) + .put((float) fog.getFogColor().z).put(fog.getFogAlpha()); + vec4Buf.flip(); + GL20.glUniform4(locs[LOC_FOG_COLOR], vec4Buf); + } + + // Alpha test reference — core profile replacement for GL_ALPHA_TEST + // Return -1.0f for ALWAYS or disabled so `alpha <= ref` never discards. + if (locs[LOC_ALPHA_TEST_REF] != -1) { + final float ref; + if (!GLStateManager.getAlphaTest().isEnabled() + || GLStateManager.getAlphaState().getFunction() == GL11.GL_ALWAYS) { + ref = -1.0f; + } else { + ref = GLStateManager.getAlphaState().getReference(); + } + GL20.glUniform1f(locs[LOC_ALPHA_TEST_REF], ref); + } + } + + public static void onDeleteProgram(int program) { + programLocations.remove(program); + } + + public static boolean hasProgram(int program) { + return programLocations.containsKey(program); + } + + public static int[] getLocations(int program) { + return programLocations.get(program); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListIDAllocator.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListIDAllocator.java new file mode 100644 index 000000000..1c769cd50 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListIDAllocator.java @@ -0,0 +1,187 @@ +package com.gtnewhorizons.angelica.glsm; + +/* + * Ported from Mesa's util_idalloc (src/util/u_idalloc.c). + * + * Original copyright and license: + * + * Copyright 2017 Valve Corporation + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Original author: Samuel Pitoiset + */ + +/** + * Bitmap ID allocator for display list IDs. + * + *

Bitmap-based: each bit in the {@code data} array represents one ID. + * Bit set = allocated, bit clear = free. ID 0 is reserved (never returned). + */ +public class DisplayListIDAllocator { + + private int[] data; + private int numElements; // number of uint32 words allocated + private int numSetElements; // highest word index with any bit set + 1 + private int lowestFreeIdx; // optimization: skip fully-allocated words + + public DisplayListIDAllocator() { + this(32); // 1024 IDs initially + } + + public DisplayListIDAllocator(int initialWords) { + if (initialWords < 1) initialWords = 1; + this.data = new int[initialWords]; + this.numElements = initialWords; + this.numSetElements = 0; + this.lowestFreeIdx = 0; + // Reserve ID 0 (never returned), matching Mesa's skip_zero pattern + data[0] = 1; + numSetElements = 1; + } + + public int allocRange(int count) { + if (count <= 0) throw new IllegalArgumentException("count must be > 0"); + if (count == 1) return allocSingle(); + return allocMultiple(count); + } + + private int allocSingle() { + for (int i = lowestFreeIdx; i < numElements; i++) { + if (data[i] == 0xFFFFFFFF) continue; + + int bit = Integer.numberOfTrailingZeros(~data[i]); + data[i] |= 1 << bit; + lowestFreeIdx = i; + numSetElements = Math.max(numSetElements, i + 1); + return i * 32 + bit; + } + + // No slots available, grow. Record old end, then mark first bit there. + int oldNumElements = numElements; + resize(Math.max(numElements, 1) * 2); + lowestFreeIdx = oldNumElements; + data[oldNumElements] |= 1; + numSetElements = Math.max(numSetElements, oldNumElements + 1); + return oldNumElements * 32; + } + + private int allocMultiple(int num) { + int numWords = divRoundUp(num, 32); + int base = findFreeBlock(lowestFreeIdx); + boolean found = false; + + while (!found) { + int i; + for (i = base; i < numElements && i - base < numWords && data[i] == 0; i++) + ; + + if (i - base == numWords) { + found = true; + } else if (i == numElements) { + // Hit end — base is valid: data[base..end] are zero, resize extends the run into newly zeroed words. + resize(numElements * 2 + numWords); + found = true; + } else { + // Non-zero word at i, skip past it + base = i + 1; + } + } + + // Mark bits as used + int fullWords = num / 32; + int remainder = num % 32; + for (int i = base; i < base + fullWords; i++) { + data[i] = 0xFFFFFFFF; + } + if (remainder != 0) { + data[base + fullWords] |= (1 << remainder) - 1; + } + + if (lowestFreeIdx == base) { + lowestFreeIdx = base + num / 32; + } + numSetElements = Math.max(numSetElements, base + numWords); + + return base * 32; + } + + private int findFreeBlock(int start) { + for (int i = start; i < numElements; i++) { + if (data[i] == 0) return i; + } + return numElements; + } + + public void free(int id) { + if (id <= 0) return; // ID 0 is reserved + int idx = id / 32; + if (idx >= numElements) return; + + lowestFreeIdx = Math.min(idx, lowestFreeIdx); + data[idx] &= ~(1 << (id % 32)); + + if (numSetElements == idx + 1) { + while (numSetElements > 0 && data[numSetElements - 1] == 0) { + numSetElements--; + } + } + } + + public void freeRange(int base, int count) { + if (count <= 0 || base <= 0) return; + + int startIdx = base / 32; + if (startIdx >= numElements) return; + + int end = base + count; + for (int id = base; id < end; id++) { + int idx = id / 32; + if (idx >= numElements) break; + data[idx] &= ~(1 << (id % 32)); + } + + lowestFreeIdx = Math.min(startIdx, lowestFreeIdx); + while (numSetElements > 0 && data[numSetElements - 1] == 0) { + numSetElements--; + } + } + + public boolean isAllocated(int id) { + if (id <= 0) return false; + int idx = id / 32; + if (idx >= numSetElements) return false; + return (data[idx] & (1 << (id % 32))) != 0; + } + + private void resize(int newNumElements) { + if (newNumElements <= numElements) return; + int[] newData = new int[newNumElements]; + System.arraycopy(data, 0, newData, 0, numElements); + data = newData; + numElements = newNumElements; + } + + private static int divRoundUp(int a, int b) { + return (a + b - 1) / b; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java index 4ca3174f6..dac8b90fc 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/DisplayListManager.java @@ -27,14 +27,14 @@ import org.joml.Vector3f; import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; -import java.nio.FloatBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memGetInt; /** * VBO-based display list emulation with command recording, transform collapsing, and format-based batching. @@ -103,9 +103,6 @@ public class DisplayListManager { private static List> multMatrixSources = null; // Source ops for each MULT_MATRIX in raw buffer private static List drawRangeSources = null; // Source type for each DRAW_RANGE in final buffer - // For flushMatrix() - reusable buffer for executing collapsed transforms - private static final FloatBuffer flushMatrixBuffer = org.lwjgl.BufferUtils.createFloatBuffer(16); - // Nested compilation support - stack of parent contexts private static final Deque compilationStack = new ArrayDeque<>(); @@ -177,11 +174,8 @@ public class DisplayListManager { stateGeneration++; } - // COMPILE_AND_EXECUTE: execute now. Bypass GLSM to avoid re-entering recording path. + // COMPILE_AND_EXECUTE: apply to GLSM software stack if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { - flushMatrixBuffer.clear(); - relativeTransform.get(flushMatrixBuffer); - GL11.glMultMatrix(flushMatrixBuffer); GLStateManager.getMatrixStack().mul(relativeTransform); } @@ -619,9 +613,6 @@ public class DisplayListManager { applyTransformOp(singleTransform, x, y, z, op, rotationAxis); if (currentRecorder != null) currentRecorder.recordMultMatrix(singleTransform); if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { - flushMatrixBuffer.clear(); - singleTransform.get(flushMatrixBuffer); - GL11.glMultMatrix(flushMatrixBuffer); GLStateManager.getMatrixStack().mul(singleTransform); } return; @@ -659,9 +650,6 @@ public class DisplayListManager { } if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { - flushMatrixBuffer.clear(); - matrix.get(flushMatrixBuffer); - GL11.glMultMatrix(flushMatrixBuffer); GLStateManager.getMatrixStack().mul(matrix); } return; @@ -686,9 +674,6 @@ public class DisplayListManager { if (DEBUG_DISPLAY_LISTS) { if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp); if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { - flushMatrixBuffer.clear(); - orthoFrustumTemp.get(flushMatrixBuffer); - GL11.glMultMatrix(flushMatrixBuffer); GLStateManager.getMatrixStack().mul(orthoFrustumTemp); } return; @@ -709,9 +694,6 @@ public class DisplayListManager { if (DEBUG_DISPLAY_LISTS) { if (currentRecorder != null) currentRecorder.recordMultMatrix(orthoFrustumTemp); if (glListMode == GL11.GL_COMPILE_AND_EXECUTE) { - flushMatrixBuffer.clear(); - orthoFrustumTemp.get(flushMatrixBuffer); - GL11.glMultMatrix(flushMatrixBuffer); GLStateManager.getMatrixStack().mul(orthoFrustumTemp); } return; @@ -956,11 +938,8 @@ public class DisplayListManager { vbo.render(); } // Per OpenGL spec: if list is undefined, glCallList has no effect - } else { - // Positive IDs - fall back to native GL display lists - // This happens for lists allocated but never compiled via glNewList - GL11.glCallList(list); } + // An uncached positive-ID list = no-op (per OpenGL spec) } /** @@ -971,8 +950,6 @@ public class DisplayListManager { CompiledDisplayList compiled = displayListCache.remove(i); if (compiled != null) { compiled.delete(); - } else { - GL11.glDeleteLists(i, 1); } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java b/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java index d230c2387..a3e0e1002 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/Feature.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.glsm; import com.google.common.collect.ImmutableSet; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.stacks.BooleanStateStack; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; @@ -87,22 +88,20 @@ public class Feature { GLStateManager.alphaTest // GL_ALPHA_TEST enable bit , GLStateManager.alphaState // Alpha test function and reference value , GLStateManager.blendMode // GL_BLEND enable bit - , GLStateManager.blendState // Blending source and destination functions - // Constant blend color - // Blending equation + , GLStateManager.blendState // Blending source/destination functions, equation, blend color , GLStateManager.colorLogicOpState // GL_COLOR_LOGIC_OP enable bit , GLStateManager.ditherState // GL_DITHER enable bit , GLStateManager.drawBuffer // GL_DRAW_BUFFER setting , GLStateManager.indexLogicOpState // GL_INDEX_LOGIC_OP enable bit - // Logic op function + , GLStateManager.logicOpMode // Logic op function , GLStateManager.colorMask // Color-mode and index-mode writemasks , GLStateManager.clearColor // Color-mode and index-mode clear values )); attribToFeatures.put(GL11.GL_CURRENT_BIT, ImmutableSet.of( GLStateManager.color // Current RGBA color + , ShaderManager.getNormalStack() // Current normal vector + , ShaderManager.getTexCoordStack() // Current texture coordinates // Current color index - // Current normal vector - // Current texture coordinates // Current raster position // GL_CURRENT_RASTER_POSITION_VALID flag // RGBA color associated with current raster position @@ -300,6 +299,8 @@ public class Feature { )); final Set> textureAttribs = new HashSet<>(ImmutableSet.of( GLStateManager.activeTextureUnit // Active texture unit + , GLStateManager.texEnvMode // GL_TEXTURE_ENV_MODE + , GLStateManager.texEnvColor // GL_TEXTURE_ENV_COLOR // Enable bits for the four texture coordinates // Border color for each texture image @@ -307,7 +308,6 @@ public class Feature { // Magnification function for each texture image // Texture coordinates and wrap mode for each texture image - // Color and mode for each texture environment // Enable bits GL_TEXTURE_GEN_x, x is S, T, R, and Q // GL_TEXTURE_GEN_MODE setting for S, T, R, and Q // glTexGen plane equations for S, T, R, and Q diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java index fff33524a..fcb565897 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GLStateManager.java @@ -1,10 +1,12 @@ package com.gtnewhorizons.angelica.glsm; +import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO; import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.DisplayListManager.RecordMode; -import com.gtnewhorizons.angelica.glsm.recording.CommandRecorder; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; +import com.gtnewhorizons.angelica.glsm.ffp.TessellatorStreamingDrawer; import com.gtnewhorizons.angelica.glsm.recording.CompiledDisplayList; import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import com.gtnewhorizons.angelica.glsm.recording.commands.TexImage2DCmd; @@ -56,9 +58,9 @@ import org.joml.Matrix4f; import org.joml.Matrix4fStack; import org.joml.Vector3d; import org.joml.Vector3f; +import org.joml.Vector4f; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; -import com.gtnewhorizon.gtnhlib.client.opengl.UniversalVAO; import org.lwjgl.opengl.ARBMultitexture; import org.lwjgl.opengl.ContextCapabilities; import org.lwjgl.opengl.Display; @@ -71,7 +73,6 @@ import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; -import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GLContext; import org.lwjgl.opengl.KHRDebug; @@ -83,8 +84,11 @@ import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.function.IntSupplier; import static com.gtnewhorizons.angelica.glsm.Vendor.AMD; @@ -93,8 +97,6 @@ import static com.gtnewhorizons.angelica.glsm.Vendor.MESA; import static com.gtnewhorizons.angelica.glsm.Vendor.NVIDIA; import static com.gtnewhorizons.angelica.loading.AngelicaTweaker.LOGGER; -import static com.gtnewhorizon.gtnhlib.client.opengl.GLCaps.*; - /** * OpenGL State Manager - Provides cached state tracking and management for OpenGL operations. * @@ -120,16 +122,53 @@ public class GLStateManager { @Getter protected static boolean poppingAttributes; public static boolean BYPASS_CACHE = Boolean.parseBoolean(System.getProperty("angelica.disableGlCache", "false")); - // +2 headroom for internal operations (display list compilation) that push cache but not driver - public static final int MAX_ATTRIB_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_ATTRIB_STACK_DEPTH) + 2; - public static final int MAX_MODELVIEW_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_MODELVIEW_STACK_DEPTH) + 2; - public static final int MAX_PROJECTION_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_PROJECTION_STACK_DEPTH); - public static final int MAX_TEXTURE_STACK_DEPTH = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_STACK_DEPTH); + // Software stack depths for FFP emulation + public static final int MAX_ATTRIB_STACK_DEPTH = 16 + 2; + public static final int MAX_MODELVIEW_STACK_DEPTH = 32 + 2; + public static final int MAX_PROJECTION_STACK_DEPTH = 4; + public static final int MAX_TEXTURE_STACK_DEPTH = 4; + public static final int MAX_CLIP_PLANES = 8; public static final int MAX_TEXTURE_UNITS = GL11.glGetInteger(GL20.GL_MAX_TEXTURE_IMAGE_UNITS); - public static final int MAX_CLIP_PLANES = GL11.glGetInteger(GL11.GL_MAX_CLIP_PLANES); public static final GLFeatureSet HAS_MULTIPLE_SET = new GLFeatureSet(); + // Generation counters for FFP uniform dirty tracking. Bumped when the corresponding GLSM state changes. + public static int matrixGeneration; + public static int lightingGeneration; + public static int fragmentGeneration; // fog + alpha ref + public static int colorGeneration; // current vertex color + + // Deferred vertex attribute upload flags — set when state changes, flushed before draw + private static boolean dirtyColorAttrib; + private static boolean dirtyNormalAttrib; + private static boolean dirtyTexCoordAttrib; + private static boolean dirtyLightmapAttrib; + + /** Flush deferred vertex attribute uploads. Called before draw to ensure default attrib values are current. */ + public static void flushDeferredVertexAttribs() { + if (dirtyColorAttrib) { + GL20.glVertexAttrib4f(1, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + dirtyColorAttrib = false; + } + if (dirtyNormalAttrib) { + final var n = ShaderManager.getCurrentNormal(); + GL20.glVertexAttrib3f(4, n.x, n.y, n.z); + dirtyNormalAttrib = false; + } + if (dirtyTexCoordAttrib) { + final var tc = ShaderManager.getCurrentTexCoord(); + GL20.glVertexAttrib4f(2, tc.x, tc.y, tc.z, tc.w); + dirtyTexCoordAttrib = false; + } + if (dirtyLightmapAttrib) { + GL20.glVertexAttrib4f(3, OpenGlHelper.lastBrightnessX, OpenGlHelper.lastBrightnessY, 0.0f, 1.0f); + dirtyLightmapAttrib = false; + } + } + + // Highest texture unit index that has ever had a non-zero binding; limits onDeleteTexture scan range + private static int maxBoundTextureUnit = 0; + @Getter private static Vendor VENDOR; // This setting varies depending on driver, so it gets queried at runtime @@ -228,18 +267,24 @@ public class GLStateManager { @Getter protected static final BooleanStateStack depthTest = new BooleanStateStack(GL11.GL_DEPTH_TEST); @Getter protected static final FogStateStack fogState = new FogStateStack(); - @Getter protected static final BooleanStateStack fogMode = new BooleanStateStack(GL11.GL_FOG); + @Getter protected static final BooleanStateStack fogMode = new BooleanStateStack(GL11.GL_FOG, false, true); @Getter protected static final Color4Stack color = new Color4Stack(); @Getter protected static final Color4Stack clearColor = new Color4Stack(new Color4(0.0F, 0.0F, 0.0F, 0.0F)); @Getter protected static final ColorMaskStack colorMask = new ColorMaskStack(); @Getter protected static final IntegerStateStack drawBuffer = new IntegerStateStack(DEFAULT_DRAW_BUFFER); + @Getter protected static final IntegerStateStack logicOpMode = new IntegerStateStack(GL11.GL_COPY); @Getter protected static final BooleanStateStack cullState = new BooleanStateStack(GL11.GL_CULL_FACE); @Getter protected static final AlphaStateStack alphaState = new AlphaStateStack(); - @Getter protected static final BooleanStateStack alphaTest = new BooleanStateStack(GL11.GL_ALPHA_TEST); + @Getter protected static final BooleanStateStack alphaTest = new BooleanStateStack(GL11.GL_ALPHA_TEST, false, true); - @Getter protected static final BooleanStateStack lightingState = new BooleanStateStack(GL11.GL_LIGHTING); - @Getter protected static final BooleanStateStack rescaleNormalState = new BooleanStateStack(GL12.GL_RESCALE_NORMAL); - @Getter protected static final BooleanStateStack normalizeState = new BooleanStateStack(GL11.GL_NORMALIZE); + // Texture environment mode (GL_MODULATE default per OpenGL spec) + @Getter protected static final IntegerStateStack texEnvMode = new IntegerStateStack(GL11.GL_MODULATE); + // Texture environment color (used by GL_BLEND mode) + @Getter protected static final Color4Stack texEnvColor = new Color4Stack(new Color4(0.0f, 0.0f, 0.0f, 0.0f)); + + @Getter protected static final BooleanStateStack lightingState = new BooleanStateStack(GL11.GL_LIGHTING, false, true); + @Getter protected static final BooleanStateStack rescaleNormalState = new BooleanStateStack(GL12.GL_RESCALE_NORMAL, false, true); + @Getter protected static final BooleanStateStack normalizeState = new BooleanStateStack(GL11.GL_NORMALIZE, false, true); // Additional enable bit states tracked by GL_ENABLE_BIT @Getter protected static final BooleanStateStack ditherState = new BooleanStateStack(GL11.GL_DITHER, true); // Defaults to true per OpenGL spec @@ -264,6 +309,10 @@ public class GLStateManager { // Line state (GL_LINE_BIT) @Getter protected static final LineStateStack lineState = new LineStateStack(); + // Line width range queried at init from GL_ALIASED_LINE_WIDTH_RANGE + static float lineWidthMin = 1.0f; + static float lineWidthMax = 1.0f; + // Point state (GL_POINT_BIT) @Getter protected static final PointStateStack pointState = new PointStateStack(); @@ -272,8 +321,8 @@ public class GLStateManager { // Stencil state (GL_STENCIL_BUFFER_BIT) @Getter protected static final StencilStateStack stencilState = new StencilStateStack(); + private static int stencilBitMask = 0xFFFFFFFF; - // Evaluator states @Getter protected static final BooleanStateStack autoNormalState = new BooleanStateStack(GL11.GL_AUTO_NORMAL); @Getter protected static final BooleanStateStack map1Color4State = new BooleanStateStack(GL11.GL_MAP1_COLOR_4); @Getter protected static final BooleanStateStack map1IndexState = new BooleanStateStack(GL11.GL_MAP1_INDEX); @@ -303,7 +352,7 @@ public class GLStateManager { @Getter protected static final BooleanStateStack[] lightStates = new BooleanStateStack[8]; @Getter protected static final LightStateStack[] lightDataStates = new LightStateStack[8]; - @Getter protected static final BooleanStateStack colorMaterial = new BooleanStateStack(GL11.GL_COLOR_MATERIAL); + @Getter protected static final BooleanStateStack colorMaterial = new BooleanStateStack(GL11.GL_COLOR_MATERIAL, false, true); @Getter protected static final IntegerStateStack colorMaterialFace = new IntegerStateStack(GL11.GL_FRONT_AND_BACK); @Getter protected static final IntegerStateStack colorMaterialParameter = new IntegerStateStack(GL11.GL_AMBIENT_AND_DIFFUSE); @Getter protected static final LightModelStateStack lightModel = new LightModelStateStack(); @@ -315,7 +364,7 @@ public class GLStateManager { static { for (int i = 0; i < lightStates.length; i ++) { - lightStates[i] = new BooleanStateStack(GL11.GL_LIGHT0 + i); + lightStates[i] = new BooleanStateStack(GL11.GL_LIGHT0 + i, false, true); lightDataStates[i] = new LightStateStack(GL11.GL_LIGHT0 + i); } @@ -416,10 +465,24 @@ public class GLStateManager { final String glVendor = GL11.glGetString(GL11.GL_VENDOR); VENDOR = Vendor.getVendor(glVendor.toLowerCase()); - if (vendorIsAMD()) { - // AMD Drivers seem to default to 0 for the matrix mode, so we need to set it to the default - GL11.glMatrixMode(GL11.GL_MODELVIEW); - } + // Compute stencil bit mask — driver clamps stencil masks to buffer depth + final int stencilBits = GL11.glGetInteger(GL11.GL_STENCIL_BITS); + stencilBitMask = stencilBits >= 32 ? 0xFFFFFFFF : (1 << stencilBits) - 1; + + // Initialize stencil masks from computed bit mask + stencilState.setValueMaskFront(stencilBitMask); + stencilState.setValueMaskBack(stencilBitMask); + stencilState.setWriteMaskFront(stencilBitMask); + stencilState.setWriteMaskBack(stencilBitMask); + + final FloatBuffer lwRange = BufferUtils.createFloatBuffer(16); + GL11.glGetFloat(GL12.GL_ALIASED_LINE_WIDTH_RANGE, lwRange); + lineWidthMin = lwRange.get(0); + lineWidthMax = lwRange.get(1); + + // Sync default vertex attribs with GLSM cache initial values. + GL20.glVertexAttrib4f(1, 1.0f, 1.0f, 1.0f, 1.0f); // COLOR = white + GL20.glVertexAttrib3f(4, 0.0f, 0.0f, 1.0f); // NORMAL = +Z final Minecraft mc = Minecraft.getMinecraft(); if (mc != null) { @@ -775,6 +838,8 @@ public class GLStateManager { case GL11.GL_TEXTURE_GEN_T -> textures.getTexGenTStates(activeTextureUnit.getValue()).isEnabled(); case GL11.GL_TEXTURE_GEN_R -> textures.getTexGenRStates(activeTextureUnit.getValue()).isEnabled(); case GL11.GL_TEXTURE_GEN_Q -> textures.getTexGenQStates(activeTextureUnit.getValue()).isEnabled(); + case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.localViewer != 0.0f; + case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.twoSide != 0.0f; default -> GL11.glGetBoolean(pname); }; } @@ -826,10 +891,26 @@ public class GLStateManager { case GL11.GL_MODELVIEW_STACK_DEPTH -> getMatrixStackDepth(modelViewMatrix); case GL11.GL_PROJECTION_STACK_DEPTH -> getMatrixStackDepth(projectionMatrix); + case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.colorControl; + case GL14.GL_BLEND_DST_ALPHA -> blendState.getDstAlpha(); case GL14.GL_BLEND_DST_RGB -> blendState.getDstRgb(); case GL14.GL_BLEND_SRC_ALPHA -> blendState.getSrcAlpha(); case GL14.GL_BLEND_SRC_RGB -> blendState.getSrcRgb(); + case GL14.GL_BLEND_EQUATION -> blendState.getEquationRgb(); + case GL20.GL_BLEND_EQUATION_ALPHA -> blendState.getEquationAlpha(); + + case GL11.GL_LOGIC_OP_MODE -> logicOpMode.getValue(); + case GL11.GL_DRAW_BUFFER -> drawBuffer.getValue(); + + case GL11.GL_STENCIL_FUNC -> stencilState.getFuncFront(); + case GL11.GL_STENCIL_REF -> stencilState.getRefFront(); + case GL11.GL_STENCIL_VALUE_MASK -> stencilState.getValueMaskFront(); + case GL11.GL_STENCIL_FAIL -> stencilState.getFailOpFront(); + case GL11.GL_STENCIL_PASS_DEPTH_FAIL -> stencilState.getZFailOpFront(); + case GL11.GL_STENCIL_PASS_DEPTH_PASS -> stencilState.getZPassOpFront(); + case GL11.GL_STENCIL_WRITEMASK -> stencilState.getWriteMaskFront(); + case GL11.GL_STENCIL_CLEAR_VALUE -> stencilState.getClearValue(); case GL15.GL_ARRAY_BUFFER_BINDING -> boundVBO; @@ -837,7 +918,14 @@ public class GLStateManager { case GL30.GL_VERTEX_ARRAY_BINDING -> boundVAO; - default -> GL11.glGetInteger(pname); + default -> { + yield switch (pname) { + case GL11.GL_FOG_MODE -> fogState.getFogMode(); + case GL11.GL_LINE_STIPPLE_PATTERN -> lineState.getStipplePattern() & 0xFFFF; + case GL11.GL_LINE_STIPPLE_REPEAT -> lineState.getStippleFactor(); + default -> GL11.glGetInteger(pname); + }; + } }; } @@ -860,11 +948,6 @@ public class GLStateManager { } public static void glGetMaterial(int face, int pname, FloatBuffer params) { - if (shouldBypassCache()) { - GL11.glGetMaterial(face, pname, params); - return; - } - final MaterialStateStack state; if (face == GL11.GL_FRONT) { state = frontMaterial; @@ -881,16 +964,11 @@ public class GLStateManager { case GL11.GL_EMISSION -> state.emission.get(0, params); case GL11.GL_SHININESS -> params.put(state.shininess); case GL11.GL_COLOR_INDEXES -> state.colorIndexes.get(0, params); - default -> GL11.glGetMaterial(face, pname, params); + default -> {} } } public static void glGetLight(int light, int pname, FloatBuffer params) { - if (shouldBypassCache()) { - GL11.glGetLight(light, pname, params); - return; - } - final LightStateStack state = lightDataStates[light - GL11.GL_LIGHT0]; switch (pname) { case GL11.GL_AMBIENT -> state.ambient.get(0, params); @@ -903,7 +981,7 @@ public class GLStateManager { case GL11.GL_CONSTANT_ATTENUATION -> params.put(state.constantAttenuation); case GL11.GL_LINEAR_ATTENUATION -> params.put(state.linearAttenuation); case GL11.GL_QUADRATIC_ATTENUATION -> params.put(state.quadraticAttenuation); - default -> GL11.glGetLight(light, pname, params); + default -> {} } } @@ -916,9 +994,30 @@ public class GLStateManager { switch (pname) { case GL11.GL_MODELVIEW_MATRIX -> modelViewMatrix.get(0, params); case GL11.GL_PROJECTION_MATRIX -> projectionMatrix.get(0, params); -// case GL11.GL_TEXTURE_MATRIX -> textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params); + case GL11.GL_TEXTURE_MATRIX -> textures.getTextureUnitMatrix(getActiveTextureUnit()).get(0, params); case GL11.GL_COLOR_CLEAR_VALUE -> clearColor.get(params); case GL11.GL_CURRENT_COLOR -> color.get(params); + case GL11.GL_DEPTH_RANGE -> { + params.put((float) viewportState.depthRangeNear); + params.put((float) viewportState.depthRangeFar); + } + case GL14.GL_BLEND_COLOR -> { + params.put(blendState.getBlendColorR()).put(blendState.getBlendColorG()) + .put(blendState.getBlendColorB()).put(blendState.getBlendColorA()); + } + case GL11.GL_CURRENT_NORMAL -> { + final Vector3f normal = ShaderManager.getCurrentNormal(); + params.put(normal.x).put(normal.y).put(normal.z); + } + case GL11.GL_CURRENT_TEXTURE_COORDS -> { + final Vector4f tc = ShaderManager.getCurrentTexCoord(); + params.put(tc.x).put(tc.y).put(tc.z).put(tc.w); + } + case GL11.GL_FOG_COLOR -> { + final FloatBuffer fogBuf = fogState.getFogColorBuffer(); + params.put(fogBuf.get(0)).put(fogBuf.get(1)).put(fogBuf.get(2)).put(fogBuf.get(3)); + } + case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.ambient.get(0, params); default -> { if(!HAS_MULTIPLE_SET.contains(pname)) { params.put(0, glGetFloat(pname)); @@ -930,7 +1029,16 @@ public class GLStateManager { } public static float glGetFloat(int pname) { - return GL11.glGetFloat(pname); + return switch (pname) { + case GL11.GL_ALPHA_TEST_REF -> alphaState.getReference(); + case GL11.GL_FOG_DENSITY -> fogState.getDensity(); + case GL11.GL_FOG_START -> fogState.getStart(); + case GL11.GL_FOG_END -> fogState.getEnd(); + case GL11.GL_DEPTH_CLEAR_VALUE -> (float) depthState.getClearValue(); + case GL11.GL_LINE_WIDTH -> lineState.getWidth(); + case GL11.GL_POINT_SIZE -> pointState.getSize(); + default -> GL11.glGetFloat(pname); + }; } // GLStateManager Functions @@ -943,7 +1051,18 @@ public class GLStateManager { return; } } - GL14.glBlendColor(red, green, blue, alpha); + final boolean caching = isCachingEnabled(); + final boolean bypass = BYPASS_CACHE || !caching; + if (bypass || red != blendState.getBlendColorR() || green != blendState.getBlendColorG() + || blue != blendState.getBlendColorB() || alpha != blendState.getBlendColorA()) { + if (caching) { + blendState.setBlendColorR(red); + blendState.setBlendColorG(green); + blendState.setBlendColorB(blue); + blendState.setBlendColorA(alpha); + } + GL14.glBlendColor(red, green, blue, alpha); + } } public static void enableBlend() { @@ -1024,8 +1143,9 @@ public class GLStateManager { return; } final boolean bypass = BYPASS_CACHE || !caching; - if (bypass || blendState.getSrcRgb() != srcFactor || blendState.getDstRgb() != dstFactor) { - if (caching) blendState.setSrcDstRgb(srcFactor, dstFactor); + if (bypass || blendState.getSrcRgb() != srcFactor || blendState.getDstRgb() != dstFactor + || blendState.getSrcAlpha() != srcFactor || blendState.getDstAlpha() != dstFactor) { + if (caching) blendState.setAll(srcFactor, dstFactor, srcFactor, dstFactor); GL11.glBlendFunc(srcFactor, dstFactor); } } @@ -1034,14 +1154,30 @@ public class GLStateManager { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glBlendEquation in display lists not yet implemented - if you see this, please report!"); } - GL14.glBlendEquation(mode); + final boolean caching = isCachingEnabled(); + final boolean bypass = BYPASS_CACHE || !caching; + if (bypass || blendState.getEquationRgb() != mode || blendState.getEquationAlpha() != mode) { + if (caching) { + blendState.setEquationRgb(mode); + blendState.setEquationAlpha(mode); + } + GL14.glBlendEquation(mode); + } } public static void glBlendEquationSeparate(int modeRGB, int modeAlpha) { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glBlendEquationSeparate in display lists not yet implemented - if you see this, please report!"); } - GL20.glBlendEquationSeparate(modeRGB, modeAlpha); + final boolean caching = isCachingEnabled(); + final boolean bypass = BYPASS_CACHE || !caching; + if (bypass || blendState.getEquationRgb() != modeRGB || blendState.getEquationAlpha() != modeAlpha) { + if (caching) { + blendState.setEquationRgb(modeRGB); + blendState.setEquationAlpha(modeAlpha); + } + GL20.glBlendEquationSeparate(modeRGB, modeAlpha); + } } public static void tryBlendFuncSeparate(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { @@ -1084,32 +1220,39 @@ public class GLStateManager { // Currently only used inside of display lists public static void glNormal3b(byte nx, byte ny, byte nz) { - if (DisplayListManager.isRecording()) { - ImmediateModeRecorder.setNormal(b2f(nx), b2f(ny), b2f(nz)); + final float fnx = b2f(nx), fny = b2f(ny), fnz = b2f(nz); + ShaderManager.setCurrentNormal(fnx, fny, fnz); + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { + ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - GL11.glNormal3b(nx, ny, nz); + dirtyNormalAttrib = true; } public static void glNormal3d(double nx, double ny, double nz) { - if (DisplayListManager.isRecording()) { - ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz); + final float fnx = (float) nx, fny = (float) ny, fnz = (float) nz; + ShaderManager.setCurrentNormal(fnx, fny, fnz); + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { + ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - GL11.glNormal3d(nx, ny, nz); + dirtyNormalAttrib = true; } public static void glNormal3f(float nx, float ny, float nz) { - if (DisplayListManager.isRecording()) { + ShaderManager.setCurrentNormal(nx, ny, nz); + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setNormal(nx, ny, nz); return; } - GL11.glNormal3f(nx, ny, nz); + dirtyNormalAttrib = true; } public static void glNormal3i(int nx, int ny, int nz) { - if (DisplayListManager.isRecording()) { - ImmediateModeRecorder.setNormal((float) nx, (float) ny, (float) nz); + final float fnx = nx / 2147483647.0f, fny = ny / 2147483647.0f, fnz = nz / 2147483647.0f; + ShaderManager.setCurrentNormal(fnx, fny, fnz); + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { + ImmediateModeRecorder.setNormal(fnx, fny, fnz); return; } - GL11.glNormal3i(nx, ny, nz); + dirtyNormalAttrib = true; } public static void glDepthFunc(int func) { @@ -1149,7 +1292,7 @@ public class GLStateManager { } public static void glEdgeFlag(boolean flag) { - GL11.glEdgeFlag(flag); + // No-op: edge flags are removed in GL 3.3 core profile and have no equivalent } public static void glColor4f(float red, float green, float blue, float alpha) { @@ -1160,9 +1303,7 @@ public class GLStateManager { return; } } - if (changeColor(red, green, blue, alpha)) { - GL11.glColor4f(red, green, blue, alpha); - } + changeColor(red, green, blue, alpha); } public static void glColor4d(double red, double green, double blue, double alpha) { @@ -1173,9 +1314,7 @@ public class GLStateManager { return; } } - if (changeColor((float) red, (float) green, (float) blue, (float) alpha)) { - GL11.glColor4d(red, green, blue, alpha); - } + changeColor((float) red, (float) green, (float) blue, (float) alpha); } public static void glColor4b(byte red, byte green, byte blue, byte alpha) { @@ -1186,9 +1325,7 @@ public class GLStateManager { return; } } - if (changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha))) { - GL11.glColor4b(red, green, blue, alpha); - } + changeColor(b2f(red), b2f(green), b2f(blue), b2f(alpha)); } public static void glColor4ub(byte red, byte green, byte blue, byte alpha) { @@ -1199,9 +1336,7 @@ public class GLStateManager { return; } } - if (changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha))) { - GL11.glColor4ub(red, green, blue, alpha); - } + changeColor(ub2f(red), ub2f(green), ub2f(blue), ub2f(alpha)); } public static void glColor3f(float red, float green, float blue) { @@ -1212,9 +1347,7 @@ public class GLStateManager { return; } } - if (changeColor(red, green, blue, 1.0F)) { - GL11.glColor3f(red, green, blue); - } + changeColor(red, green, blue, 1.0F); } public static void glColor3d(double red, double green, double blue) { @@ -1225,9 +1358,7 @@ public class GLStateManager { return; } } - if (changeColor((float) red, (float) green, (float) blue, 1.0F)) { - GL11.glColor3d(red, green, blue); - } + changeColor((float) red, (float) green, (float) blue, 1.0F); } public static void glColor3b(byte red, byte green, byte blue) { @@ -1238,9 +1369,7 @@ public class GLStateManager { return; } } - if (changeColor(b2f(red), b2f(green), b2f(blue), 1.0F)) { - GL11.glColor3b(red, green, blue); - } + changeColor(b2f(red), b2f(green), b2f(blue), 1.0F); } public static void glColor3ub(byte red, byte green, byte blue) { @@ -1251,9 +1380,7 @@ public class GLStateManager { return; } } - if (changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F)) { - GL11.glColor3ub(red, green, blue); - } + changeColor(ub2f(red), ub2f(green), ub2f(blue), 1.0F); } private static float ub2f(byte b) { @@ -1275,7 +1402,12 @@ public class GLStateManager { color.setGreen(green); color.setBlue(blue); color.setAlpha(alpha); + colorGeneration++; } + if (ImmediateModeRecorder.isDrawing()) { + ImmediateModeRecorder.setColor(red, green, blue, alpha); + } + dirtyColorAttrib = true; return true; } return false; @@ -1339,6 +1471,7 @@ public class GLStateManager { return; } } + if (isCachingEnabled()) depthState.setClearValue(depth); GL11.glClearDepth(depth); } @@ -1394,8 +1527,8 @@ public class GLStateManager { if (isCachingEnabled()) { alphaState.setFunction(function); alphaState.setReference(reference); + fragmentGeneration++; } - GL11.glAlphaFunc(function, reference); } // Textures @@ -1466,6 +1599,9 @@ public class GLStateManager { if (cachedBinding != texture) { GL11.glBindTexture(target, texture); textureUnit.setBinding(texture); + if (texture != 0 && activeUnit > maxBoundTextureUnit) { + maxBoundTextureUnit = activeUnit; + } TextureTracker.INSTANCE.onBindTexture(texture); } } @@ -1541,60 +1677,68 @@ public class GLStateManager { } public static void glTexCoord1f(float s) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord(s, 0.0f); return; } - GL11.glTexCoord1f(s); + ShaderManager.setCurrentTexCoord(s, 0.0f, 0.0f, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord1d(double s) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord((float) s, 0.0f); return; } - GL11.glTexCoord1d(s); + ShaderManager.setCurrentTexCoord((float) s, 0.0f, 0.0f, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord2f(float s, float t) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord(s, t); return; } - GL11.glTexCoord2f(s, t); + ShaderManager.setCurrentTexCoord(s, t, 0.0f, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord2d(double s, double t) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } - GL11.glTexCoord2d(s, t); + ShaderManager.setCurrentTexCoord((float) s, (float) t, 0.0f, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord3f(float s, float t, float r) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord(s, t); // Only track s,t for 2D textures return; } - GL11.glTexCoord3f(s, t, r); + ShaderManager.setCurrentTexCoord(s, t, r, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord3d(double s, double t, double r) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } - GL11.glTexCoord3d(s, t, r); + ShaderManager.setCurrentTexCoord((float) s, (float) t, (float) r, 1.0f); + dirtyTexCoordAttrib = true; } public static void glTexCoord4f(float s, float t, float r, float q) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord(s, t); return; } - GL11.glTexCoord4f(s, t, r, q); + ShaderManager.setCurrentTexCoord(s, t, r, q); + dirtyTexCoordAttrib = true; } public static void glTexCoord4d(double s, double t, double r, double q) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.setTexCoord((float) s, (float) t); return; } - GL11.glTexCoord4d(s, t, r, q); + ShaderManager.setCurrentTexCoord((float) s, (float) t, (float) r, (float) q); + dirtyTexCoordAttrib = true; } public static void glDeleteTextures(int id) { @@ -1665,55 +1809,27 @@ public class GLStateManager { textures.getTextureUnitStates(textureUnit).disable(); } - public static void glRasterPos2f(float x, float y) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos2f(x, y); - } - public static void glRasterPos2d(double x, double y) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos2d(x, y); - } - public static void glRasterPos2i(int x, int y) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos2i(x, y); - } - public static void glRasterPos3f(float x, float y, float z) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos3f(x, y, z); - } - public static void glRasterPos3d(double x, double y, double z) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos3d(x, y, z); - } - public static void glRasterPos3i(int x, int y, int z) { - if (DisplayListManager.isRecording()) { - throw new UnsupportedOperationException("glRasterPos in display lists not yet implemented"); - } - GL11.glRasterPos3i(x, y, z); - } - public static void glRasterPos4f(float x, float y, float z, float w) { - checkCompiling("glRasterPos"); - GL11.glRasterPos4f(x, y, z, w); - } - public static void glRasterPos4d(double x, double y, double z, double w) { - checkCompiling("glRasterPos"); - GL11.glRasterPos4d(x, y, z, w); - } - public static void glRasterPos4i(int x, int y, int z, int w) { - checkCompiling("glRasterPos"); - GL11.glRasterPos4i(x, y, z, w); + private static final String PIXELTRANSFER_MSG = "glPixelTransfer is not available in GL 3.3 core profile."; + + public static void glPixelTransferf(int pname, float param) { + guardUnsupportedFFP("glPixelTransfer", PIXELTRANSFER_MSG); } + public static void glPixelTransferi(int pname, int param) { + guardUnsupportedFFP("glPixelTransfer", PIXELTRANSFER_MSG); + } + + private static final String RASTERPOS_MSG = "glRasterPos is not available in GL 3.3 core profile."; + + public static void glRasterPos2f(float x, float y) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos2d(double x, double y) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos2i(int x, int y) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos3f(float x, float y, float z) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos3d(double x, double y, double z) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos3i(int x, int y, int z) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos4f(float x, float y, float z, float w) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos4d(double x, double y, double z, double w) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } + public static void glRasterPos4i(int x, int y, int z, int w) { guardUnsupportedFFP("glRasterPos", RASTERPOS_MSG); } public static void setFilter(boolean bilinear, boolean mipmap) { final int i, j; @@ -1730,65 +1846,55 @@ public class GLStateManager { public static void glBegin(int mode) { if (DisplayListManager.isRecording()) { - // Record to immediate mode recorder ImmediateModeRecorder.begin(mode); - return; // Don't call actual GL during recording + return; } - GL11.glBegin(mode); + ImmediateModeRecorder.beginLive(mode); } public static void glEnd() { if (DisplayListManager.isRecording()) { - // Record to immediate mode recorder and flush geometry immediately final DirectTessellator result = ImmediateModeRecorder.end(); if (result != null) { - // Add draw at current command position for correct interleaving DisplayListManager.addImmediateModeDraw(result); } - return; // Don't call actual GL during recording - } - GL11.glEnd(); - } - - // Vertex methods for display list recording - private static boolean loggedVertex = false; - public static void glVertex2f(float x, float y) { - final boolean recording = DisplayListManager.isRecording(); - if (recording) { - ImmediateModeRecorder.vertex(x, y, 0.0f); return; } - GL11.glVertex2f(x, y); + final DirectTessellator result = ImmediateModeRecorder.end(); + if (result != null) { + TessellatorStreamingDrawer.drawDirect(result); + } + } + + // Vertex methods for display list recording and live immediate mode + public static void glVertex2f(float x, float y) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { + ImmediateModeRecorder.vertex(x, y, 0.0f); + } } public static void glVertex2d(double x, double y) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.vertex((float) x, (float) y, 0.0f); - return; } - GL11.glVertex2d(x, y); } public static void glVertex3f(float x, float y, float z) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.vertex(x, y, z); - return; } - GL11.glVertex3f(x, y, z); } public static void glVertex3d(double x, double y, double z) { - if (DisplayListManager.isRecording()) { + if (DisplayListManager.isRecording() || ImmediateModeRecorder.isDrawing()) { ImmediateModeRecorder.vertex((float) x, (float) y, (float) z); - return; } - GL11.glVertex3d(x, y, z); } public static void glDrawElements(int mode, ByteBuffer indices) { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); } - BlendModeStorage.flushDeferredBlend(); + ShaderManager.getInstance().preDraw(); GL11.glDrawElements(mode, indices); } @@ -1796,7 +1902,7 @@ public class GLStateManager { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); } - BlendModeStorage.flushDeferredBlend(); + ShaderManager.getInstance().preDraw(); GL11.glDrawElements(mode, indices); } @@ -1804,7 +1910,7 @@ public class GLStateManager { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); } - BlendModeStorage.flushDeferredBlend(); + ShaderManager.getInstance().preDraw(); GL11.glDrawElements(mode, indices); } @@ -1812,7 +1918,7 @@ public class GLStateManager { if (DisplayListManager.isRecording()) { throw new UnsupportedOperationException("glDrawElements in display lists not yet implemented - if you see this, please report!"); } - BlendModeStorage.flushDeferredBlend(); + ShaderManager.getInstance().preDraw(); GL11.glDrawElements(mode, count, type, indices); } @@ -1828,7 +1934,7 @@ public class GLStateManager { return; } } - BlendModeStorage.flushDeferredBlend(); + ShaderManager.getInstance().preDraw(); GL11.glDrawElements(mode, indices_count, type, indices_buffer_offset); } @@ -1840,6 +1946,7 @@ public class GLStateManager { return; } } + if (isCachingEnabled()) drawBuffer.setValue(mode); GL11.glDrawBuffer(mode); } @@ -1855,8 +1962,12 @@ public class GLStateManager { } return; } - BlendModeStorage.flushDeferredBlend(); - GL11.glDrawArrays(mode, first, count); + ShaderManager.getInstance().preDraw(); + if (mode == GL11.GL_QUADS) { + QuadConverter.drawQuadsAsTriangles(first, count); + } else { + GL11.glDrawArrays(mode, first, count); + } } // Client array state interception methods (for glDrawArrays conversion) @@ -1866,14 +1977,12 @@ public class GLStateManager { if (!isVAOBound()) { clientArrayState.setVertexPointer(size, GL11.GL_FLOAT, stride, pointer); } - GL11.glVertexPointer(size, stride, pointer); } public static void glVertexPointer(int size, int type, int stride, ByteBuffer pointer) { if (!isVAOBound()) { clientArrayState.setVertexPointer(size, type, stride, pointer); } - GL11.glVertexPointer(size, type, stride, pointer); } public static void glVertexPointer(int size, int type, int stride, long pointer_buffer_offset) { @@ -1881,21 +1990,18 @@ public class GLStateManager { // VBO offset - can't track buffer reference, clear it clientArrayState.setVertexPointer(size, type, stride, null); } - GL11.glVertexPointer(size, type, stride, pointer_buffer_offset); } public static void glColorPointer(int size, int stride, FloatBuffer pointer) { if (!isVAOBound()) { clientArrayState.setColorPointer(size, GL11.GL_FLOAT, stride, pointer); } - GL11.glColorPointer(size, stride, pointer); } public static void glColorPointer(int size, int type, int stride, ByteBuffer pointer) { if (!isVAOBound()) { clientArrayState.setColorPointer(size, type, stride, pointer); } - GL11.glColorPointer(size, type, stride, pointer); } public static void glColorPointer(int size, boolean unsigned, int stride, ByteBuffer pointer) { @@ -1903,7 +2009,6 @@ public class GLStateManager { final int type = unsigned ? GL11.GL_UNSIGNED_BYTE : GL11.GL_BYTE; clientArrayState.setColorPointer(size, type, stride, pointer); } - GL11.glColorPointer(size, unsigned, stride, pointer); } public static void glColorPointer(int size, int type, int stride, long pointer_buffer_offset) { @@ -1911,23 +2016,64 @@ public class GLStateManager { // VBO offset - can't track buffer reference, clear it clientArrayState.setColorPointer(size, type, stride, null); } - GL11.glColorPointer(size, type, stride, pointer_buffer_offset); + } + + public static void glNormalPointer(int type, int stride, ByteBuffer pointer) { + if (!isVAOBound()) clientArrayState.setNormalPointer(type, stride, pointer); + } + + public static void glNormalPointer(int type, int stride, FloatBuffer pointer) { + if (!isVAOBound()) clientArrayState.setNormalPointer(GL11.GL_FLOAT, stride, pointer); + } + + public static void glNormalPointer(int type, int stride, ShortBuffer pointer) { + if (!isVAOBound()) clientArrayState.setNormalPointer(GL11.GL_SHORT, stride, pointer); + } + + public static void glNormalPointer(int type, int stride, IntBuffer pointer) { + if (!isVAOBound()) clientArrayState.setNormalPointer(GL11.GL_INT, stride, pointer); + } + + public static void glNormalPointer(int type, int stride, long pointer_buffer_offset) { + if (!isVAOBound()) clientArrayState.setNormalPointer(type, stride, null); + } + + public static void glTexCoordPointer(int size, int type, int stride, ByteBuffer pointer) { + if (!isVAOBound()) clientArrayState.setTexCoordPointer(size, type, stride, pointer); + } + + public static void glTexCoordPointer(int size, int type, int stride, FloatBuffer pointer) { + if (!isVAOBound()) clientArrayState.setTexCoordPointer(size, GL11.GL_FLOAT, stride, pointer); + } + + public static void glTexCoordPointer(int size, int type, int stride, ShortBuffer pointer) { + if (!isVAOBound()) clientArrayState.setTexCoordPointer(size, GL11.GL_SHORT, stride, pointer); + } + + public static void glTexCoordPointer(int size, int type, int stride, IntBuffer pointer) { + if (!isVAOBound()) clientArrayState.setTexCoordPointer(size, GL11.GL_INT, stride, pointer); + } + + public static void glTexCoordPointer(int size, int type, int stride, long pointer_buffer_offset) { + if (!isVAOBound()) clientArrayState.setTexCoordPointer(size, type, stride, null); } public static void glEnableClientState(int cap) { if (!isVAOBound()) { if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(true); else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(true); + else if (cap == GL11.GL_NORMAL_ARRAY) clientArrayState.setNormalArrayEnabled(true); + else if (cap == GL11.GL_TEXTURE_COORD_ARRAY) clientArrayState.setTexCoordArrayEnabled(true); } - GL11.glEnableClientState(cap); } public static void glDisableClientState(int cap) { if (!isVAOBound()) { if (cap == GL11.GL_VERTEX_ARRAY) clientArrayState.setVertexArrayEnabled(false); else if (cap == GL11.GL_COLOR_ARRAY) clientArrayState.setColorArrayEnabled(false); + else if (cap == GL11.GL_NORMAL_ARRAY) clientArrayState.setNormalArrayEnabled(false); + else if (cap == GL11.GL_TEXTURE_COORD_ARRAY) clientArrayState.setTexCoordArrayEnabled(false); } - GL11.glDisableClientState(cap); } public static void glLogicOp(int opcode) { @@ -1938,6 +2084,7 @@ public class GLStateManager { return; } } + if (isCachingEnabled()) logicOpMode.setValue(opcode); GL11.glLogicOp(opcode); } @@ -2020,10 +2167,10 @@ public class GLStateManager { } } colorMaterial.enable(); - float r = getColor().getRed(); - float g = getColor().getGreen(); - float b = getColor().getBlue(); - float a = getColor().getAlpha(); + final float r = getColor().getRed(); + final float g = getColor().getGreen(); + final float b = getColor().getBlue(); + final float a = getColor().getAlpha(); if (colorMaterialFace.getValue() == GL11.GL_FRONT || colorMaterialFace.getValue() == GL11.GL_FRONT_AND_BACK) { switch (colorMaterialParameter.getValue()) { case GL11.GL_AMBIENT_AND_DIFFUSE -> { @@ -2137,8 +2284,6 @@ public class GLStateManager { } // TODO: Iris Notifier if (HAS_MULTIPLE_SET.contains(pname)) { - GL11.glFog(pname, param); - if (pname == GL11.GL_FOG_COLOR && isCachingEnabled()) { final float red = param.get(0); final float green = param.get(1); @@ -2148,6 +2293,7 @@ public class GLStateManager { fogState.setFogAlpha(param.get(3)); fogState.getFogColorBuffer().clear(); fogState.getFogColorBuffer().put((FloatBuffer) param.position(0)).flip(); + fragmentGeneration++; } } else { GLStateManager.glFogf(pname, param.get(0)); @@ -2158,7 +2304,6 @@ public class GLStateManager { return fogState.getFogColor(); } - private static final FloatBuffer fogColorTempBuffer = BufferUtils.createFloatBuffer(4); public static void fogColor(float red, float green, float blue, float alpha) { final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || red != fogState.getFogColor().x || green != fogState.getFogColor().y || blue != fogState.getFogColor().z || alpha != fogState.getFogAlpha()) { @@ -2167,12 +2312,7 @@ public class GLStateManager { fogState.setFogAlpha(alpha); fogState.getFogColorBuffer().clear(); fogState.getFogColorBuffer().put(red).put(green).put(blue).put(alpha).flip(); - GL11.glFog(GL11.GL_FOG_COLOR, fogState.getFogColorBuffer()); - } else { - // Use temp buffer for non-main thread to avoid corrupting shared state - fogColorTempBuffer.clear(); - fogColorTempBuffer.put(red).put(green).put(blue).put(alpha).flip(); - GL11.glFog(GL11.GL_FOG_COLOR, fogColorTempBuffer); + fragmentGeneration++; } } } @@ -2185,14 +2325,13 @@ public class GLStateManager { return; } } - GL11.glFogf(pname, param); - // Note: Does not handle GL_FOG_INDEX - // Only update cached state when caching is enabled + // Update cached state (FFP shader reads from cache) if (isCachingEnabled()) { switch (pname) { - case GL11.GL_FOG_DENSITY -> fogState.setDensity(param); - case GL11.GL_FOG_START -> fogState.setStart(param); - case GL11.GL_FOG_END -> fogState.setEnd(param); + case GL11.GL_FOG_DENSITY -> { fogState.setDensity(param); fragmentGeneration++; } + case GL11.GL_FOG_START -> { fogState.setStart(param); fragmentGeneration++; } + case GL11.GL_FOG_END -> { fogState.setEnd(param); fragmentGeneration++; } + case GL11.GL_FOG_MODE -> { fogState.setFogMode((int) param); fragmentGeneration++; } } } } @@ -2205,10 +2344,10 @@ public class GLStateManager { return; } } - GL11.glFogi(pname, param); - // Only update cached state when caching is enabled + // Update cached state (FFP shader reads from cache) if (isCachingEnabled() && pname == GL11.GL_FOG_MODE) { fogState.setFogMode(param); + fragmentGeneration++; } } @@ -2232,7 +2371,6 @@ public class GLStateManager { if (caching) { shadeModelState.setValue(mode); } - GL11.glShadeModel(mode); } } @@ -2246,7 +2384,7 @@ public class GLStateManager { // Only update cached texture bindings on main thread if (isCachingEnabled()) { - for (int i = 0; i < GLStateManager.MAX_TEXTURE_UNITS; i++) { + for (int i = 0; i <= maxBoundTextureUnit; i++) { if (textures.getTextureUnitBindings(i).getBinding() == id) { textures.getTextureUnitBindings(i).setBinding(0); } @@ -2314,10 +2452,21 @@ public class GLStateManager { return DisplayListManager.getRecordingListId(); } + private static final DisplayListIDAllocator displayListIdAllocator = new DisplayListIDAllocator(); + + public static int glGenLists(int range) { + return displayListIdAllocator.allocRange(range); + } + + public static boolean glIsList(int list) { + return displayListIdAllocator.isAllocated(list); + } + /** * Delete display lists and free their VBO resources. */ public static void glDeleteLists(int list, int range) { + displayListIdAllocator.freeRange(list, range); DisplayListManager.glDeleteLists(list, range); } @@ -2372,6 +2521,78 @@ public class GLStateManager { for (IStateStack stack : nonBooleanStacks) { stack.popDepth(); } + + // Third: apply restored state to the GL driver. BooleanStateStacks already issue GL calls via setEnabled(); non-boolean stacks are pure data + // containers, so we must explicitly drive GL here. + applyRestoredState(mask); + } + + /** + * After popping GLSM stacks, apply restored state to the GL driver. + */ + private static void applyRestoredState(int mask) { + if ((mask & GL11.GL_DEPTH_BUFFER_BIT) != 0) { + GL11.glDepthFunc(depthState.getFunc()); + GL11.glDepthMask(depthState.isEnabled()); + GL11.glClearDepth(depthState.getClearValue()); + } + if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) { + GL14.glBlendFuncSeparate(blendState.getSrcRgb(), blendState.getDstRgb(), blendState.getSrcAlpha(), blendState.getDstAlpha()); + GL20.glBlendEquationSeparate(blendState.getEquationRgb(), blendState.getEquationAlpha()); + GL14.glBlendColor(blendState.getBlendColorR(), blendState.getBlendColorG(), blendState.getBlendColorB(), blendState.getBlendColorA()); + GL11.glColorMask(colorMask.red, colorMask.green, colorMask.blue, colorMask.alpha); + GL11.glClearColor(clearColor.getRed(), clearColor.getGreen(), clearColor.getBlue(), clearColor.getAlpha()); + // Draw buffer is per-framebuffer state; only restore on the default framebuffer + if (drawFramebuffer == 0) { + GL11.glDrawBuffer(drawBuffer.getValue()); + } + GL11.glLogicOp(logicOpMode.getValue()); + } + if ((mask & GL11.GL_STENCIL_BUFFER_BIT) != 0) { + GL20.glStencilFuncSeparate(GL11.GL_FRONT, stencilState.getFuncFront(), stencilState.getRefFront(), stencilState.getValueMaskFront()); + GL20.glStencilFuncSeparate(GL11.GL_BACK, stencilState.getFuncBack(), stencilState.getRefBack(), stencilState.getValueMaskBack()); + GL20.glStencilOpSeparate(GL11.GL_FRONT, stencilState.getFailOpFront(), stencilState.getZFailOpFront(), stencilState.getZPassOpFront()); + GL20.glStencilOpSeparate(GL11.GL_BACK, stencilState.getFailOpBack(), stencilState.getZFailOpBack(), stencilState.getZPassOpBack()); + GL20.glStencilMaskSeparate(GL11.GL_FRONT, stencilState.getWriteMaskFront()); + GL20.glStencilMaskSeparate(GL11.GL_BACK, stencilState.getWriteMaskBack()); + GL11.glClearStencil(stencilState.getClearValue()); + } + if ((mask & GL11.GL_VIEWPORT_BIT) != 0) { + GL11.glViewport(viewportState.x, viewportState.y, viewportState.width, viewportState.height); + GL11.glDepthRange(viewportState.depthRangeNear, viewportState.depthRangeFar); + } + if ((mask & GL11.GL_LINE_BIT) != 0) { + GL11.glLineWidth(lineState.getWidth()); + } + if ((mask & GL11.GL_POINT_BIT) != 0) { + GL11.glPointSize(pointState.getSize()); + } + if ((mask & GL11.GL_POLYGON_BIT) != 0) { + // Core profile only supports GL_FRONT_AND_BACK; use frontMode (front/back are always kept in sync since glPolygonMode also forces GL_FRONT_AND_BACK) + GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, polygonState.getFrontMode()); + GL11.glPolygonOffset(polygonState.getOffsetFactor(), polygonState.getOffsetUnits()); + GL11.glCullFace(polygonState.getCullFaceMode()); + GL11.glFrontFace(polygonState.getFrontFace()); + } + if ((mask & GL11.GL_TEXTURE_BIT) != 0) { + // Restore texture bindings for all units, then restore active unit. activeTextureUnit stores the 0-based index, glActiveTexture needs GL_TEXTURE0 + index. + for (int i = 0; i < MAX_TEXTURE_UNITS; i++) { + GL13.glActiveTexture(GL13.GL_TEXTURE0 + i); + GL11.glBindTexture(GL11.GL_TEXTURE_2D, textures.getTextureUnitBindings(i).getBinding()); + } + GL13.glActiveTexture(GL13.GL_TEXTURE0 + activeTextureUnit.getValue()); + } + + // Bump generation counters so FFP shader re-uploads restored uniforms + if ((mask & GL11.GL_LIGHTING_BIT) != 0) lightingGeneration++; + if ((mask & GL11.GL_FOG_BIT) != 0) fragmentGeneration++; + if ((mask & GL11.GL_COLOR_BUFFER_BIT) != 0) fragmentGeneration++; // alpha ref + if ((mask & GL11.GL_TRANSFORM_BIT) != 0) matrixGeneration++; + if ((mask & GL11.GL_CURRENT_BIT) != 0) { + colorGeneration++; + ShaderManager.bumpNormalGeneration(); + ShaderManager.bumpTexCoordGeneration(); + } } public static void glClear(int mask) { @@ -2393,10 +2614,7 @@ public class GLStateManager { } } GLDebug.pushGroup("pushState"); - GL11.glPushAttrib(mask); - if (isCachingEnabled()) { - pushState(mask); - } + pushState(mask); } public static void glPopAttrib() { @@ -2407,15 +2625,12 @@ public class GLStateManager { return; } } - GL11.glPopAttrib(); GLDebug.popGroup(); - if (isCachingEnabled()) { - poppingAttributes = true; - GLDebug.pushGroup("popState"); - popState(); - GLDebug.popGroup(); - poppingAttributes = false; - } + poppingAttributes = true; + GLDebug.pushGroup("popState"); + popState(); + GLDebug.popGroup(); + poppingAttributes = false; } // Matrix Operations @@ -2428,7 +2643,6 @@ public class GLStateManager { return; } } - GL11.glMatrixMode(mode); matrixMode.setMode(mode); } @@ -2444,8 +2658,7 @@ public class GLStateManager { return; } } - if (isCachingEnabled()) getMatrixStack().set(m); - GL11.glLoadMatrix(m); + if (isCachingEnabled()) { getMatrixStack().set(m); matrixGeneration++; } } public static void glLoadMatrix(DoubleBuffer m) { @@ -2466,8 +2679,8 @@ public class GLStateManager { if (isCachingEnabled()) { conversionMatrix4d.set(m); getMatrixStack().set(conversionMatrix4d); + matrixGeneration++; } - GL11.glLoadMatrix(m); } public static Matrix4fStack getMatrixStack() { @@ -2495,8 +2708,7 @@ public class GLStateManager { return; } } - GL11.glLoadIdentity(); - if (isCachingEnabled()) getMatrixStack().identity(); + if (isCachingEnabled()) { getMatrixStack().identity(); matrixGeneration++; } } public static void glTranslatef(float x, float y, float z) { @@ -2505,8 +2717,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.TRANSLATE, null); return; } - GL11.glTranslatef(x, y, z); - if (isCachingEnabled()) getMatrixStack().translate(x, y, z); + if (isCachingEnabled()) { getMatrixStack().translate(x, y, z); matrixGeneration++; } } public static void glTranslated(double x, double y, double z) { @@ -2515,8 +2726,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.TRANSLATE, null); return; } - GL11.glTranslated(x, y, z); - if (isCachingEnabled()) getMatrixStack().translate((float) x, (float) y, (float) z); + if (isCachingEnabled()) { getMatrixStack().translate((float) x, (float) y, (float) z); matrixGeneration++; } } public static void glScalef(float x, float y, float z) { @@ -2525,8 +2735,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform(x, y, z, DisplayListManager.TransformOp.SCALE, null); return; } - GL11.glScalef(x, y, z); - if (isCachingEnabled()) getMatrixStack().scale(x, y, z); + if (isCachingEnabled()) { getMatrixStack().scale(x, y, z); matrixGeneration++; } } public static void glScaled(double x, double y, double z) { @@ -2535,8 +2744,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform((float) x, (float) y, (float) z, DisplayListManager.TransformOp.SCALE, null); return; } - GL11.glScaled(x, y, z); - if (isCachingEnabled()) getMatrixStack().scale((float) x, (float) y, (float) z); + if (isCachingEnabled()) { getMatrixStack().scale((float) x, (float) y, (float) z); matrixGeneration++; } } private static final Matrix4f multMatrix = new Matrix4f(); @@ -2549,8 +2757,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform(multMatrix); return; } - GL11.glMultMatrix(floatBuffer); - if (isCachingEnabled()) getMatrixStack().mul(multMatrix); + if (isCachingEnabled()) { getMatrixStack().mul(multMatrix); matrixGeneration++; } } public static final Matrix4d conversionMatrix4d = new Matrix4d(); @@ -2564,8 +2771,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform(conversionMatrix4f); return; } - GL11.glMultMatrix(matrix); - if (isCachingEnabled()) getMatrixStack().mul(conversionMatrix4f); + if (isCachingEnabled()) { getMatrixStack().mul(conversionMatrix4f); matrixGeneration++; } } private static final Vector3f rotation = new Vector3f(); @@ -2576,10 +2782,10 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform(angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); return; } - GL11.glRotatef(angle, x, y, z); if (isCachingEnabled()) { rotation.set(x, y, z).normalize(); getMatrixStack().rotate((float)Math.toRadians(angle), rotation); + matrixGeneration++; } } @@ -2590,10 +2796,10 @@ public class GLStateManager { DisplayListManager.updateRelativeTransform((float) angle, 0, 0, DisplayListManager.TransformOp.ROTATE, rotation); return; } - GL11.glRotated(angle, x, y, z); if (isCachingEnabled()) { rotation.set((float) x, (float) y, (float) z).normalize(); getMatrixStack().rotate((float)Math.toRadians(angle), rotation); + matrixGeneration++; } } @@ -2603,8 +2809,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransformOrtho(left, right, bottom, top, zNear, zFar); return; // Transform accumulated, will be emitted at barriers } - GL11.glOrtho(left, right, bottom, top, zNear, zFar); - if (isCachingEnabled()) getMatrixStack().ortho((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); + if (isCachingEnabled()) { getMatrixStack().ortho((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); matrixGeneration++; } } public static void glFrustum(double left, double right, double bottom, double top, double zNear, double zFar) { @@ -2613,8 +2818,7 @@ public class GLStateManager { DisplayListManager.updateRelativeTransformFrustum(left, right, bottom, top, zNear, zFar); return; // Transform accumulated, will be emitted at barriers } - GL11.glFrustum(left, right, bottom, top, zNear, zFar); - if (isCachingEnabled()) getMatrixStack().frustum((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); + if (isCachingEnabled()) { getMatrixStack().frustum((float)left, (float)right, (float)bottom, (float)top, (float)zNear, (float)zFar); matrixGeneration++; } } public static void glPushMatrix() { final RecordMode mode = DisplayListManager.getRecordMode(); @@ -2624,7 +2828,6 @@ public class GLStateManager { return; } } - GL11.glPushMatrix(); // Only track stack on main thread (splash thread has separate GL context) if (isCachingEnabled()) { try { @@ -2644,11 +2847,11 @@ public class GLStateManager { return; } } - GL11.glPopMatrix(); // Only track stack on main thread (splash thread has separate GL context) if (isCachingEnabled()) { try { getMatrixStack().popMatrix(); + matrixGeneration++; } catch(IllegalStateException ignored) { if(AngelicaMod.lwjglDebug) AngelicaTweaker.LOGGER.warn("Matrix stack underflow ", new Throwable()); @@ -2732,6 +2935,11 @@ public class GLStateManager { public static void glTexParameter(int target, int pname, IntBuffer params) { + if (params.remaining() >= 1) { + final int val = params.get(params.position()); + final int remapped = remapTexClamp(pname, val); + if (remapped != val) params.put(params.position(), remapped); + } if (target != GL11.GL_TEXTURE_2D || params.remaining() != 1 ) { GL11.glTexParameter(target, pname, params); return; @@ -2742,6 +2950,11 @@ public class GLStateManager { } public static void glTexParameter(int target, int pname, FloatBuffer params) { + if (params.remaining() >= 1) { + final float val = params.get(params.position()); + final float remapped = remapTexClamp(pname, val); + if (remapped != val) params.put(params.position(), remapped); + } if (target != GL11.GL_TEXTURE_2D || params.remaining() != 1 ) { GL11.glTexParameter(target, pname, params); return; @@ -2752,6 +2965,7 @@ public class GLStateManager { } public static void glTexParameteri(int target, int pname, int param) { + param = remapTexClamp(pname, param); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordTexParameteri(target, pname, param); @@ -2791,6 +3005,7 @@ public class GLStateManager { } public static void glTexParameterf(int target, int pname, float param) { + param = remapTexClamp(pname, param); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordTexParameterf(target, pname, param); @@ -2977,6 +3192,7 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } + lightingGeneration++; } public static void glMaterial(int face, int pname, IntBuffer params) { @@ -2990,7 +3206,7 @@ public class GLStateManager { floatParams[i] = GLStateManager.i2f(params.get()); } params.reset(); - DisplayListManager.recordMaterial(face, pname, java.nio.FloatBuffer.wrap(floatParams)); + DisplayListManager.recordMaterial(face, pname, FloatBuffer.wrap(floatParams)); if (mode == RecordMode.COMPILE) { return; } @@ -3005,6 +3221,7 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } + lightingGeneration++; } public static void glMaterialf(int face, int pname, float val) { @@ -3030,6 +3247,7 @@ public class GLStateManager { } else { throw new RuntimeException("Unsupported face value for glMaterial: " + face); } + lightingGeneration++; } public static void glMateriali(int face, int pname, int val) { @@ -3058,8 +3276,9 @@ public class GLStateManager { case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params); case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params); case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params); - default -> GL11.glLight(light, pname, params); + default -> {} } + lightingGeneration++; } public static void glLight(int light, int pname, IntBuffer params) { @@ -3073,7 +3292,7 @@ public class GLStateManager { floatParams[i] = GLStateManager.i2f(params.get()); } params.reset(); - DisplayListManager.recordLight(light, pname, java.nio.FloatBuffer.wrap(floatParams)); + DisplayListManager.recordLight(light, pname, FloatBuffer.wrap(floatParams)); if (mode == RecordMode.COMPILE) { return; } @@ -3090,8 +3309,9 @@ public class GLStateManager { case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(params); case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(params); case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(params); - default -> GL11.glLight(light, pname, params); + default -> {} } + lightingGeneration++; } public static void glLightf(int light, int pname, float param) { @@ -3109,8 +3329,9 @@ public class GLStateManager { case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param); case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param); case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param); - default -> GL11.glLightf(light, pname, param); + default -> {} } + lightingGeneration++; } public static void glLighti(int light, int pname, int param) { @@ -3128,8 +3349,9 @@ public class GLStateManager { case GL11.GL_CONSTANT_ATTENUATION -> lightState.setConstantAttenuation(param); case GL11.GL_LINEAR_ATTENUATION -> lightState.setLinearAttenuation(param); case GL11.GL_QUADRATIC_ATTENUATION -> lightState.setQuadraticAttenuation(param); - default -> GL11.glLighti(light, pname, param); + default -> {} } + lightingGeneration++; } public static void glLightModel(int pname, FloatBuffer params) { @@ -3144,8 +3366,9 @@ public class GLStateManager { case GL11.GL_LIGHT_MODEL_AMBIENT -> lightModel.setAmbient(params); case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params); case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params); - default -> GL11.glLightModel(pname, params); + default -> {} } + lightingGeneration++; } public static void glLightModel(int pname, IntBuffer params) { // For IntBuffer version, we need to convert to float for recording @@ -3158,7 +3381,7 @@ public class GLStateManager { floatParams[i] = GLStateManager.i2f(params.get()); } params.reset(); - DisplayListManager.recordLightModel(pname, java.nio.FloatBuffer.wrap(floatParams)); + DisplayListManager.recordLightModel(pname, FloatBuffer.wrap(floatParams)); if (mode == RecordMode.COMPILE) { return; } @@ -3168,8 +3391,9 @@ public class GLStateManager { case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(params); case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(params); case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(params); - default -> GL11.glLightModel(pname, params); + default -> {} } + lightingGeneration++; } public static void glLightModelf(int pname, float param) { final RecordMode mode = DisplayListManager.getRecordMode(); @@ -3184,10 +3408,9 @@ public class GLStateManager { switch (pname) { case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param); case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param); - default -> GL11.glLightModelf(pname, param); + default -> {} } - } else { - GL11.glLightModelf(pname, param); + lightingGeneration++; } } public static void glLightModeli(int pname, int param) { @@ -3204,10 +3427,9 @@ public class GLStateManager { case GL12.GL_LIGHT_MODEL_COLOR_CONTROL -> lightModel.setColorControl(param); case GL11.GL_LIGHT_MODEL_LOCAL_VIEWER -> lightModel.setLocalViewer(param); case GL11.GL_LIGHT_MODEL_TWO_SIDE -> lightModel.setTwoSide(param); - default -> GL11.glLightModeli(pname, param); + default -> {} } - } else { - GL11.glLightModeli(pname, param); + lightingGeneration++; } } @@ -3224,12 +3446,13 @@ public class GLStateManager { if (caching) { colorMaterialFace.setValue(face); colorMaterialParameter.setValue(mode); + lightingGeneration++; } - GL11.glColorMaterial(face, mode); } } public static void glDepthRange(double near, double far) { + if (isCachingEnabled()) viewportState.setDepthRange(near, far); GL11.glDepthRange(near, far); } @@ -3241,6 +3464,22 @@ public class GLStateManager { return; } } + + final ShaderManager ffp = ShaderManager.getInstance(); + if (program == 0 && ffp.isEnabled()) { + final boolean caching = isCachingEnabled(); + if (caching) { + activeProgram = 0; // Track that FFP was requested + } + ffp.activate(); + return; + } + + // Non-zero program or FFP emulation not enabled + if (ffp.isActive()) { + ffp.deactivate(); + } + final boolean caching = isCachingEnabled(); if (BYPASS_CACHE || !caching || program != activeProgram) { if (caching) { @@ -3251,6 +3490,7 @@ public class GLStateManager { GLDebug.debugMessage("Activating Program - " + program + ":" + programName); } GL20.glUseProgram(program); + CompatUniformManager.onUseProgram(program); } } @@ -3277,6 +3517,7 @@ public class GLStateManager { } public static void glLineWidth(float width) { + width = Math.max(lineWidthMin, Math.min(lineWidthMax, width)); final RecordMode mode = DisplayListManager.getRecordMode(); if (mode != RecordMode.NONE) { DisplayListManager.recordLineWidth(width); @@ -3293,6 +3534,39 @@ public class GLStateManager { } } + public static void glShaderSource(int shader, CharSequence source) { + String src = source.toString(); + if (ShaderManager.getInstance().isEnabled()) { + src = CompatShaderTransformer.transform(src, isFragmentShader(shader)); + } + GL20.glShaderSource(shader, src); + } + + public static void glShaderSource(int shader, ByteBuffer source) { + final byte[] bytes = new byte[source.remaining()]; + final int pos = source.position(); + source.get(bytes); + source.position(pos); + glShaderSource(shader, new String(bytes, StandardCharsets.UTF_8)); + } + + public static void glShaderSource(int shader, CharSequence[] sources) { + if (ShaderManager.getInstance().isEnabled()) { + int totalLen = 0; + for (CharSequence s : sources) totalLen += s.length(); + final StringBuilder sb = new StringBuilder(totalLen); + for (CharSequence s : sources) sb.append(s); + GL20.glShaderSource(shader, CompatShaderTransformer.transform(sb.toString(), isFragmentShader(shader))); + return; + } + GL20.glShaderSource(shader, sources); + } + + /** Check shader type to determine if fragment output transformation is needed. */ + private static boolean isFragmentShader(int shader) { + return GL20.glGetShaderi(shader, GL20.GL_SHADER_TYPE) == GL20.GL_FRAGMENT_SHADER; + } + // Texture commands public static void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, ByteBuffer pixels) { final RecordMode mode = DisplayListManager.getRecordMode(); @@ -3431,14 +3705,12 @@ public class GLStateManager { return; } } - final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || lineState.getStippleFactor() != factor || lineState.getStipplePattern() != pattern) { - if (caching) { - lineState.setStippleFactor(factor); - lineState.setStipplePattern(pattern); - } - GL11.glLineStipple(factor, pattern); + if (isCachingEnabled()) { + lineState.setStippleFactor(factor); + lineState.setStipplePattern(pattern); } + if (guardUnsupportedFFP("glLineStipple", "glLineStipple is not available in GL 3.3 core profile.")) return; + GL11.glLineStipple(factor, pattern); } public static void glPointSize(float size) { @@ -3466,6 +3738,7 @@ public class GLStateManager { return; } } + // Track front/back separately in cache (Mesa compat semantics), but always issue GL_FRONT_AND_BACK to the driver (core profile constraint). final boolean caching = isCachingEnabled(); final boolean needsUpdate; if (face == GL11.GL_FRONT) { @@ -3482,7 +3755,7 @@ public class GLStateManager { } } if (needsUpdate) { - GL11.glPolygonMode(face, polygonMode); + GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, polygonMode); } } @@ -3526,12 +3799,13 @@ public class GLStateManager { return; } } + final int clampedMask = mask & stencilBitMask; final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != mask) { + if (BYPASS_CACHE || !caching || stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != clampedMask) { if (caching) { - stencilState.setFunc(func, ref, mask); + stencilState.setFunc(func, ref, clampedMask); } - GL11.glStencilFunc(func, ref, mask); + GL11.glStencilFunc(func, ref, clampedMask); } } @@ -3543,12 +3817,13 @@ public class GLStateManager { return; } } + final int clampedMask = mask & stencilBitMask; final boolean caching = isCachingEnabled(); - if (BYPASS_CACHE || !caching || stencilState.getWriteMaskFront() != mask) { + if (BYPASS_CACHE || !caching || stencilState.getWriteMaskFront() != clampedMask) { if (caching) { - stencilState.setWriteMask(mask); + stencilState.setWriteMask(clampedMask); } - GL11.glStencilMask(mask); + GL11.glStencilMask(clampedMask); } } @@ -3675,14 +3950,15 @@ public class GLStateManager { return; } } + final int clampedMask = mask & stencilBitMask; final boolean caching = isCachingEnabled(); boolean needsUpdate = BYPASS_CACHE || !caching; if (!needsUpdate) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - needsUpdate = stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != mask; + needsUpdate = stencilState.getFuncFront() != func || stencilState.getRefFront() != ref || stencilState.getValueMaskFront() != clampedMask; } if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) { - needsUpdate = stencilState.getFuncBack() != func || stencilState.getRefBack() != ref || stencilState.getValueMaskBack() != mask; + needsUpdate = stencilState.getFuncBack() != func || stencilState.getRefBack() != ref || stencilState.getValueMaskBack() != clampedMask; } } if (needsUpdate) { @@ -3690,15 +3966,15 @@ public class GLStateManager { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { stencilState.setFuncFront(func); stencilState.setRefFront(ref); - stencilState.setValueMaskFront(mask); + stencilState.setValueMaskFront(clampedMask); } if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { stencilState.setFuncBack(func); stencilState.setRefBack(ref); - stencilState.setValueMaskBack(mask); + stencilState.setValueMaskBack(clampedMask); } } - GL20.glStencilFuncSeparate(face, func, ref, mask); + GL20.glStencilFuncSeparate(face, func, ref, clampedMask); } } @@ -3710,26 +3986,27 @@ public class GLStateManager { return; } } + final int clampedMask = mask & stencilBitMask; final boolean caching = isCachingEnabled(); boolean needsUpdate = BYPASS_CACHE || !caching; if (!needsUpdate) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - needsUpdate = stencilState.getWriteMaskFront() != mask; + needsUpdate = stencilState.getWriteMaskFront() != clampedMask; } if (!needsUpdate && (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK)) { - needsUpdate = stencilState.getWriteMaskBack() != mask; + needsUpdate = stencilState.getWriteMaskBack() != clampedMask; } } if (needsUpdate) { if (caching) { if (face == GL11.GL_FRONT || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setWriteMaskFront(mask); + stencilState.setWriteMaskFront(clampedMask); } if (face == GL11.GL_BACK || face == GL11.GL_FRONT_AND_BACK) { - stencilState.setWriteMaskBack(mask); + stencilState.setWriteMaskBack(clampedMask); } } - GL20.glStencilMaskSeparate(face, mask); + GL20.glStencilMaskSeparate(face, clampedMask); } } @@ -3856,11 +4133,24 @@ public class GLStateManager { glActiveTexture(textureUnit); } + public static void glMultiTexCoord2f(int target, float s, float t) { + if (target == GL13.GL_TEXTURE0) { + ShaderManager.setCurrentTexCoord(s, t, 0.0f, 1.0f); + dirtyTexCoordAttrib = true; + } else if (target == GL13.GL_TEXTURE1) { + setLightmapTextureCoords(target, s, t); + } + } + + public static void glMultiTexCoord2s(int target, short s, short t) { + glMultiTexCoord2f(target, s, t); + } + public static void setLightmapTextureCoords(int unit, float x, float y) { - GL13.glMultiTexCoord2f(unit, x, y); if (unit == GL13.GL_TEXTURE1) { OpenGlHelper.lastBrightnessX = x; OpenGlHelper.lastBrightnessY = y; + dirtyLightmapAttrib = true; } } @@ -3874,4 +4164,140 @@ public class GLStateManager { return OpenGlHelper.framebufferSupported && Minecraft.getMinecraft().gameSettings.fboEnable; } + private static final boolean FFP_WARN_ON_UNSUPPORTED = Boolean.parseBoolean( + System.getProperty("angelica.ffp.warnOnUnsupported", "false")); + + private static final Set warnedFFPFunctions = new HashSet<>(); + + /** + * Guards against FFP features not supported in core profile. + * Default: throws UnsupportedOperationException. + * With {@code -Dangelica.ffp.warnOnUnsupported=true}: warns once per function (diagnostic mode). + * @return true (always — caller should skip the GL call) + */ + private static boolean guardUnsupportedFFP(String function, String explanation) { + if (!FFP_WARN_ON_UNSUPPORTED) { + throw new UnsupportedOperationException(function + ": " + explanation); + } + if (warnedFFPFunctions.add(function)) { + LOGGER.warn("{}: {}", function, explanation, new Throwable("Stack trace")); + } + return true; + } + + /** + * In core profile, GL_CLAMP (0x2900) is removed. Remap to GL_CLAMP_TO_EDGE for wrap modes. + * Semantically equivalent when texture border is not used (border textures are also removed in core). + */ + public static int remapTexClamp(int pname, int param) { + if (param == GL11.GL_CLAMP && (pname == GL11.GL_TEXTURE_WRAP_S || pname == GL11.GL_TEXTURE_WRAP_T || pname == GL12.GL_TEXTURE_WRAP_R)) { + return GL12.GL_CLAMP_TO_EDGE; + } + return param; + } + + public static float remapTexClamp(int pname, float param) { + if ((int) param == GL11.GL_CLAMP + && (pname == GL11.GL_TEXTURE_WRAP_S || pname == GL11.GL_TEXTURE_WRAP_T || pname == GL12.GL_TEXTURE_WRAP_R)) { + return (float) GL12.GL_CLAMP_TO_EDGE; + } + return param; + } + + public static void remapTexClampBuffer(int pname, IntBuffer params) { + if (params.remaining() >= 1) { + final int val = params.get(params.position()); + final int remapped = remapTexClamp(pname, val); + if (remapped != val) params.put(params.position(), remapped); + } + } + + private static final String TEXENV_COMBINE_MSG = "Texture environment combine mode is not supported in FFP emulation."; + + public static void glTexEnvi(int target, int pname, int param) { + handleTexEnvScalar(target, pname, param); + } + + public static void glTexEnvf(int target, int pname, float param) { + handleTexEnvScalar(target, pname, param); + } + + public static void glTexEnv(int target, int pname, FloatBuffer params) { + if (target == GL11.GL_TEXTURE_ENV && pname == GL11.GL_TEXTURE_ENV_COLOR && params.remaining() >= 4) { + final int pos = params.position(); + texEnvColor.setRed(params.get(pos)); + texEnvColor.setGreen(params.get(pos + 1)); + texEnvColor.setBlue(params.get(pos + 2)); + texEnvColor.setAlpha(params.get(pos + 3)); + fragmentGeneration++; + return; + } + guardTexEnvTarget(target, "glTexEnv"); + } + + public static void glTexEnv(int target, int pname, IntBuffer params) { + guardTexEnvTarget(target, "glTexEnv"); + } + + /** + * Scalar glTexEnvi/glTexEnvf dispatch. glTexEnv is removed in core profile. + * GL_TEXTURE_FILTER_CONTROL (LOD bias) is remapped to glTexParameterf. + * GL_TEXTURE_ENV_MODE values (MODULATE, REPLACE, ADD, DECAL, BLEND) are tracked in cache. + */ + private static void handleTexEnvScalar(int target, int pname, float param) { + if (target == GL14.GL_TEXTURE_FILTER_CONTROL) { + // LOD bias via legacy glTexEnv path — remap to core-profile glTexParameterf + glTexParameterf(GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, param); + return; + } + if (target == GL11.GL_TEXTURE_ENV && pname == GL11.GL_TEXTURE_ENV_MODE) { + final int mode = (int) param; + if (mode == GL11.GL_MODULATE || mode == GL11.GL_REPLACE + || mode == GL11.GL_ADD || mode == GL11.GL_DECAL || mode == GL11.GL_BLEND) { + texEnvMode.setValue(mode); + fragmentGeneration++; + return; + } + } + guardUnsupportedFFP("glTexEnv", TEXENV_COMBINE_MSG); + } + + /** + * Guard for buffer glTexEnv variants. glTexEnv is removed in core profile. + */ + private static void guardTexEnvTarget(int target, String function) { + if (target == GL14.GL_TEXTURE_FILTER_CONTROL) { + guardUnsupportedFFP(function, "LOD bias via buffer glTexEnv is not supported; use glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, value) instead."); + return; + } + guardUnsupportedFFP(function, TEXENV_COMBINE_MSG); + } + + private static final String TEXGEN_MSG = "glTexGen is not implemented in FFP emulation."; + + public static void glTexGeni(int coord, int pname, int param) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + public static void glTexGenf(int coord, int pname, float param) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + public static void glTexGend(int coord, int pname, double param) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + public static void glTexGen(int coord, int pname, FloatBuffer params) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + public static void glTexGen(int coord, int pname, DoubleBuffer params) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + public static void glTexGen(int coord, int pname, IntBuffer params) { guardUnsupportedFFP("glTexGen", TEXGEN_MSG); } + + public static void glPolygonStipple(ByteBuffer pattern) { + guardUnsupportedFFP("glPolygonStipple", "glPolygonStipple is not available in GL 3.3 core profile."); + } + + public static void glAccum(int op, float value) { + guardUnsupportedFFP("glAccum", "The accumulation buffer is not available in GL 3.3 core profile."); + } + + public static void glLinkProgram(int program) { + GL20.glLinkProgram(program); + CompatUniformManager.onLinkProgram(program); + } + + public static void glDeleteProgram(int program) { + CompatUniformManager.onDeleteProgram(program); + GL20.glDeleteProgram(program); + } + } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java b/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java new file mode 100644 index 000000000..00e0ae378 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/GlslTransformUtils.java @@ -0,0 +1,110 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; + +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Shared GLSL shader transformation utilities. + */ +public class GlslTransformUtils { + + private static final String RENAMED_PREFIX = "angelica_renamed_"; + + /** Texture function renames */ + public static final Map TEXTURE_RENAMES = Map.ofEntries( + Map.entry("texture2D", "texture"), + Map.entry("texture3D", "texture"), + Map.entry("texture2DLod", "textureLod"), + Map.entry("texture3DLod", "textureLod"), + Map.entry("texture2DProj", "textureProj"), + Map.entry("texture3DProj", "textureProj"), + Map.entry("texture2DGrad", "textureGrad"), + Map.entry("texture2DGradARB", "textureGrad"), + Map.entry("texture3DGrad", "textureGrad"), + Map.entry("texelFetch2D", "texelFetch"), + Map.entry("texelFetch3D", "texelFetch"), + Map.entry("textureSize2D", "textureSize") + ); + + private static final Pattern TEXTURE_PATTERN = Pattern.compile("\\btexture\\s*\\(|(\\btexture\\b)"); + + /** Reserved words added in later GLSL versions that may appear as identifiers in older shaders. */ + private static final Map> VERSIONED_RESERVED_WORDS = Map.of( + 400, List.of("sample") + ); + + public static String replaceTexture(String input) { + final Matcher matcher = TEXTURE_PATTERN.matcher(input); + final StringBuilder builder = new StringBuilder(); + while (matcher.find()) { + if (matcher.group(1) != null) { + matcher.appendReplacement(builder, RENAMED_PREFIX + "texture"); + } else { + matcher.appendReplacement(builder, Matcher.quoteReplacement(matcher.group(0))); + } + } + matcher.appendTail(builder); + return builder.toString(); + } + + public static String renameReservedWords(String source, int targetVersion) { + for (var entry : VERSIONED_RESERVED_WORDS.entrySet()) { + if (targetVersion < entry.getKey()) { + for (String reservedWord : entry.getValue()) { + source = source.replaceAll("\\b" + reservedWord + "\\b", RENAMED_PREFIX + reservedWord); + } + } + } + return source; + } + + public static String restoreReservedWords(String source) { + source = source.replace(RENAMED_PREFIX + "texture", "texture"); + source = source.replace(RENAMED_PREFIX + "sample", "sample"); + return source; + } + + public static String getFormattedShader(ParseTree tree, String header) { + final StringBuilder sb = new StringBuilder(header + "\n"); + final String[] tabHolder = {""}; + getFormattedShader(tree, sb, tabHolder); + return sb.toString(); + } + + private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder) { + if (tree instanceof TerminalNode) { + final String text = tree.getText(); + if (text.equals("")) { + return; + } + if (text.equals("#")) { + stringBuilder.append("\n#"); + return; + } + stringBuilder.append(text); + if (text.equals("{")) { + stringBuilder.append(" \n\t"); + tabHolder[0] = "\t"; + } + + if (text.equals("}")) { + if (stringBuilder.length() >= 2) { + stringBuilder.deleteCharAt(stringBuilder.length() - 2); + } + tabHolder[0] = ""; + stringBuilder.append(" \n"); + } else { + stringBuilder.append(text.equals(";") ? " \n" + tabHolder[0] : " "); + } + } else { + for (int i = 0; i < tree.getChildCount(); ++i) { + getFormattedShader(tree.getChild(i), stringBuilder, tabHolder); + } + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java b/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java new file mode 100644 index 000000000..799e818c8 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/QuadConverter.java @@ -0,0 +1,99 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memPutInt; + +/** + * Shared quad-to-triangle EBO for core profile GL_QUADS emulation. + * + *

Maintains a single growable element buffer with pre-computed indices mapping + * GL_QUADS vertex order to GL_TRIANGLES: {@code (0,1,3, 1,2,3)} per quad. + * Uses {@code GL_LAST_VERTEX_CONVENTION} winding (Mesa {@code do_quad} LAST path) + * so both emitted triangles share the quad's provoking vertex (v3). + */ +public final class QuadConverter { + public static final int INDEX_TYPE = GL11.GL_UNSIGNED_INT; + + private static int eboId; + private static int maxQuads; + + private QuadConverter() {} + + private static void ensureCapacity(int quadCount) { + if (quadCount <= maxQuads) return; + + // Round up to power of 2 for amortized growth + int newMaxQuads = Math.max(256, maxQuads); + while (newMaxQuads < quadCount) { + newMaxQuads *= 2; + } + + if (eboId == 0) { + eboId = GL15.glGenBuffers(); + } + + // Generate index data: 6 ints per quad + final ByteBuffer indexData = memAlloc(newMaxQuads * 6 * 4); + long ptr = memAddress0(indexData); + for (int i = 0; i < newMaxQuads; i++) { + final int base = i * 4; + // GL_LAST_VERTEX_CONVENTION: both triangles share v3 as provoking vertex + // Triangle 1: 0, 1, 3 + memPutInt(ptr, base); + memPutInt(ptr + 4, base + 1); + memPutInt(ptr + 8, base + 3); + // Triangle 2: 1, 2, 3 + memPutInt(ptr + 12, base + 1); + memPutInt(ptr + 16, base + 2); + memPutInt(ptr + 20, base + 3); + ptr += 24; + } + + GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId); + GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexData, GL15.GL_STATIC_DRAW); + + memFree(indexData); + maxQuads = newMaxQuads; + } + + /** Get the EBO id. Populated after the first {@link #drawQuadsAsTriangles} call. */ + public static int getEboId() { + return eboId; + } + + /** + * Convert a GL_QUADS glDrawArrays call to indexed GL_TRIANGLES. + * Binds the shared EBO to the current VAO and issues glDrawElements. + * + * @param first first vertex index (must be aligned to quad boundary, i.e. multiple of 4) + * @param vertexCount number of vertices (must be multiple of 4) + */ + public static void drawQuadsAsTriangles(int first, int vertexCount) { + assert first % 4 == 0 : "QuadConverter: first (" + first + ") must be a multiple of 4"; + assert vertexCount % 4 == 0 : "QuadConverter: vertexCount (" + vertexCount + ") must be a multiple of 4"; + final int quadCount = vertexCount / 4; + ensureCapacity(first / 4 + quadCount); + GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId); + // Index offset: first vertex / 4 quads * 6 indices * 4 bytes per int + final long indexOffset = (long) (first / 4) * 6 * 4; + GL11.glDrawElements(GL11.GL_TRIANGLES, quadCount * 6, INDEX_TYPE, indexOffset); + } + + /** + * Clean up the shared EBO. + */ + public static void destroy() { + if (eboId != 0) { + GL15.glDeleteBuffers(eboId); + eboId = 0; + maxQuads = 0; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java b/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java index 6aca02514..3c9d777a4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/RenderSystem.java @@ -4,7 +4,9 @@ import com.gtnewhorizons.angelica.glsm.dsa.DSAARB; import com.gtnewhorizons.angelica.glsm.dsa.DSAAccess; import com.gtnewhorizons.angelica.glsm.dsa.DSACore; import com.gtnewhorizons.angelica.glsm.dsa.DSAUnsupported; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; +import net.coderbot.iris.gl.shader.StandardMacros; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable; @@ -22,6 +24,7 @@ import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; +import org.lwjgl.opengl.GL32; import org.lwjgl.opengl.GL33; import org.lwjgl.opengl.GL40; import org.lwjgl.opengl.GL42; @@ -29,8 +32,6 @@ import org.lwjgl.opengl.GL43; import org.lwjgl.opengl.GL44; import org.lwjgl.opengl.NVXGpuMemoryInfo; -import net.coderbot.iris.gl.shader.StandardMacros; - import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; @@ -124,6 +125,15 @@ public class RenderSystem { LOGGER.info("Image Load/Store: {}, Max Image Units: {}", supportsImageLoadStore, maxImageUnits); LOGGER.info("SSBO: {}, Max SSBO Bindings: {}", supportsSSBO, maxSSBOBindings); LOGGER.info("Buffer Storage: {}, Clear Texture: {}, Sampler Objects: {}", supportsBufferStorage, supportsClearTexture, supportsSamplerObjects); + + if (GLStateManager.capabilities.OpenGL32) { + final int profileMask = GL11.glGetInteger(GL32.GL_CONTEXT_PROFILE_MASK); + if ((profileMask & GL32.GL_CONTEXT_CORE_PROFILE_BIT) != 0) { + LOGGER.info("GL 3.3 core profile detected, enabling FFP shader emulation."); + ShaderManager.getInstance().enable(); + GLStateManager.lineWidthMax = 1.0f; + } + } } public static void generateMipmaps(int texture, int mipmapTarget) { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java index 935edd18f..3e8434992 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/dsa/DSAARB.java @@ -40,6 +40,7 @@ public class DSAARB extends DSAUnsupported { @Override public void texParameteri(int texture, int target, int pname, int param) { + param = GLStateManager.remapTexClamp(pname, param); if(!GLStateManager.updateTexParameteriCache(target, texture, pname, param)) return; ARBDirectStateAccess.glTextureParameteri(texture, pname, param); @@ -47,6 +48,7 @@ public class DSAARB extends DSAUnsupported { @Override public void texParameterf(int texture, int target, int pname, float param) { + param = GLStateManager.remapTexClamp(pname, param); if(!GLStateManager.updateTexParameterfCache(target, texture, pname, param)) return; ARBDirectStateAccess.glTextureParameterf(texture, pname, param); @@ -54,6 +56,7 @@ public class DSAARB extends DSAUnsupported { @Override public void texParameteriv(int texture, int target, int pname, IntBuffer params) { + GLStateManager.remapTexClampBuffer(pname, params); ARBDirectStateAccess.glTextureParameter(texture, pname, params); } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java new file mode 100644 index 000000000..fb20a0f86 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentKey.java @@ -0,0 +1,153 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/** + * Compact key capturing the fragment shader permutation axes for FFP emulation. + * Packed into a single long for fast hash/compare. + */ +public final class FragmentKey { + + private final long packed; + + private static final int BIT_FOG_MODE = 0; + private static final int BIT_ALPHA_TEST = 2; + private static final int BIT_ALPHA_FUNC = 3; + private static final int BIT_SEPARATE_SPECULAR = 6; + private static final int BIT_TEXTURE = 7; + private static final int BIT_LIGHTMAP = 8; + private static final int BIT_TEX_ENV_MODE = 9; // 3 bits: 0=MODULATE, 1=REPLACE, 2=ADD, 3=DECAL, 4=BLEND + + public static final int FOG_NONE = 0; + public static final int FOG_LINEAR = 1; + public static final int FOG_EXP = 2; + public static final int FOG_EXP2 = 3; + + private FragmentKey(long packed) { + this.packed = packed; + } + + public long pack() { return packed; } + + public int fogMode() { return (int)(packed & 0x3); } + public boolean alphaTestEnabled() { return ((packed >> BIT_ALPHA_TEST) & 1) != 0; } + public int alphaTestFunc() { return (int)((packed >> BIT_ALPHA_FUNC) & 0x7); } + public boolean separateSpecular() { return ((packed >> BIT_SEPARATE_SPECULAR) & 1) != 0; } + public boolean textureEnabled() { return ((packed >> BIT_TEXTURE) & 1) != 0; } + public boolean lightmapEnabled() { return ((packed >> BIT_LIGHTMAP) & 1) != 0; } + public int texEnvMode() { return (int)((packed >> BIT_TEX_ENV_MODE) & 0x7); } + + public static final int TEX_ENV_MODULATE = 0; + public static final int TEX_ENV_REPLACE = 1; + public static final int TEX_ENV_ADD = 2; + public static final int TEX_ENV_DECAL = 3; + public static final int TEX_ENV_BLEND = 4; + + public static long packFromState() { + long bits = 0; + + // Fog + if (GLStateManager.getFogMode().isEnabled()) { + final int glFogMode = GLStateManager.getFogState().getFogMode(); + final int fogMode = switch (glFogMode) { + case GL11.GL_LINEAR -> FOG_LINEAR; + case GL11.GL_EXP -> FOG_EXP; + case GL11.GL_EXP2 -> FOG_EXP2; + default -> FOG_NONE; + }; + bits |= ((long) fogMode & 0x3); + } + + // Alpha test + if (GLStateManager.getAlphaTest().isEnabled()) { + bits |= (1L << BIT_ALPHA_TEST); + final int func = encodeAlphaFunc(GLStateManager.getAlphaState().getFunction()); + bits |= ((long) func & 0x7) << BIT_ALPHA_FUNC; + } + + // Separate specular + if (GLStateManager.getLightingState().isEnabled() + && GLStateManager.getLightModel().colorControl == GL12.GL_SEPARATE_SPECULAR_COLOR) { + bits |= (1L << BIT_SEPARATE_SPECULAR); + } + + // Texture unit 0 + if (GLStateManager.getTextures().getTextureUnitStates(0).isEnabled()) { + bits |= (1L << BIT_TEXTURE); + + // Tex env mode only matters when texture is enabled + final int envMode = encodeTexEnvMode(GLStateManager.getTexEnvMode().getValue()); + bits |= ((long) envMode & 0x7) << BIT_TEX_ENV_MODE; + } + // Texture unit 1 (lightmap) + if (GLStateManager.getTextures().getTextureUnitStates(1).isEnabled()) { + bits |= (1L << BIT_LIGHTMAP); + } + + return bits; + } + + public static FragmentKey fromState() { + return new FragmentKey(packFromState()); + } + + static FragmentKey fromPacked(long packed) { + return new FragmentKey(packed); + } + + private static int encodeAlphaFunc(int glFunc) { + return glFunc & 0x7; + } + + private static int encodeTexEnvMode(int glMode) { + return switch (glMode) { + case GL11.GL_MODULATE -> TEX_ENV_MODULATE; + case GL11.GL_REPLACE -> TEX_ENV_REPLACE; + case GL11.GL_ADD -> TEX_ENV_ADD; + case GL11.GL_DECAL -> TEX_ENV_DECAL; + case GL11.GL_BLEND -> TEX_ENV_BLEND; + default -> TEX_ENV_MODULATE; + }; + } + + public static int decodeAlphaFunc(int encoded) { + return 0x0200 | encoded; + } + + @Override + public int hashCode() { + return Long.hashCode(packed); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof FragmentKey other)) return false; + return packed == other.packed; + } + + @Override + public String toString() { + final String fogName = switch (fogMode()) { + case FOG_NONE -> "NONE"; + case FOG_LINEAR -> "LINEAR"; + case FOG_EXP -> "EXP"; + case FOG_EXP2 -> "EXP2"; + default -> "?"; + }; + final String envName = switch (texEnvMode()) { + case TEX_ENV_MODULATE -> "MOD"; + case TEX_ENV_REPLACE -> "REPL"; + case TEX_ENV_ADD -> "ADD"; + case TEX_ENV_DECAL -> "DEC"; + case TEX_ENV_BLEND -> "BL"; + default -> "?"; + }; + return String.format("FFPFragmentKey[0x%03X: fog=%s alpha=%b(%s) specSep=%b tex=%b(env=%s) lm=%b]", + packed, fogName, alphaTestEnabled(), + alphaTestEnabled() ? String.format("0x%04X", decodeAlphaFunc(alphaTestFunc())) : "-", + separateSpecular(), textureEnabled(), envName, lightmapEnabled()); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java new file mode 100644 index 000000000..89eb0ee68 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/FragmentShaderGenerator.java @@ -0,0 +1,167 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import org.lwjgl.opengl.GL11; + +/** + * Generates GLSL 330 core fragment shaders for FFP emulation. + * Follows Mesa's ff_fragment_shader.c and st_nir_lower_fog.c. + */ +public final class FragmentShaderGenerator { + + private FragmentShaderGenerator() {} + + public static String generate(FragmentKey key) { + final StringBuilder sb = new StringBuilder(1024); + sb.append("#version 330 core\n\n"); + + emitInputs(sb, key); + emitUniforms(sb, key); + sb.append("out vec4 fragColor;\n\n"); + + sb.append("void main() {\n"); + emitTextureSampling(sb, key); + emitColorCombine(sb, key); + emitSpecularAdd(sb, key); + emitAlphaTest(sb, key); + emitFog(sb, key); + sb.append(" fragColor = color;\n"); + sb.append("}\n"); + + return sb.toString(); + } + + private static void emitInputs(StringBuilder sb, FragmentKey key) { + sb.append("// Inputs from vertex shader\n"); + sb.append("in vec4 v_Color;\n"); + if (key.separateSpecular()) { + sb.append("in vec3 v_SpecularColor;\n"); + } + if (key.textureEnabled()) { + sb.append("in vec2 v_TexCoord0;\n"); + } + if (key.lightmapEnabled()) { + sb.append("in vec2 v_TexCoord1;\n"); + } + if (key.fogMode() != FragmentKey.FOG_NONE) { + sb.append("in float v_FogCoord;\n"); + } + sb.append('\n'); + } + + private static void emitUniforms(StringBuilder sb, FragmentKey key) { + if (key.textureEnabled()) { + sb.append("uniform sampler2D u_Sampler0;\n"); + } + if (key.lightmapEnabled()) { + sb.append("uniform sampler2D u_Sampler1;\n"); + } + if (key.alphaTestEnabled()) { + sb.append("uniform float u_AlphaRef;\n"); + } + if (key.textureEnabled() && key.texEnvMode() == FragmentKey.TEX_ENV_BLEND) { + sb.append("uniform vec4 u_TexEnvColor;\n"); + } + if (key.fogMode() != FragmentKey.FOG_NONE) { + sb.append("uniform vec4 u_FogParams;\n"); + sb.append("uniform vec4 u_FogColor;\n"); + } + sb.append('\n'); + } + + private static void emitTextureSampling(StringBuilder sb, FragmentKey key) { + if (key.textureEnabled()) { + sb.append(" vec4 texColor = texture(u_Sampler0, v_TexCoord0);\n"); + } + if (key.lightmapEnabled()) { + sb.append(" vec4 lightmapColor = texture(u_Sampler1, v_TexCoord1);\n"); + } + } + + private static void emitColorCombine(StringBuilder sb, FragmentKey key) { + if (!key.textureEnabled()) { + sb.append(" // No texture — vertex color only\n"); + sb.append(" vec4 color = v_Color;\n"); + } else { + final int envMode = key.texEnvMode(); + switch (envMode) { + case FragmentKey.TEX_ENV_REPLACE -> { + sb.append(" // Color combine (REPLACE)\n"); + sb.append(" vec4 color = texColor;\n"); + } + case FragmentKey.TEX_ENV_ADD -> { + sb.append(" // Color combine (ADD)\n"); + sb.append(" vec4 color = vec4(clamp(v_Color.rgb + texColor.rgb, 0.0, 1.0), v_Color.a * texColor.a);\n"); + } + case FragmentKey.TEX_ENV_DECAL -> { + sb.append(" // Color combine (DECAL)\n"); + sb.append(" vec4 color = vec4(mix(v_Color.rgb, texColor.rgb, texColor.a), v_Color.a);\n"); + } + case FragmentKey.TEX_ENV_BLEND -> { + sb.append(" // Color combine (BLEND)\n"); + sb.append(" vec4 color = vec4(v_Color.rgb * (vec3(1.0) - texColor.rgb) + u_TexEnvColor.rgb * texColor.rgb, v_Color.a * texColor.a);\n"); + } + default -> { + sb.append(" // Color combine (MODULATE)\n"); + sb.append(" vec4 color = v_Color * texColor;\n"); + } + } + } + if (key.lightmapEnabled()) { + sb.append(" color *= lightmapColor;\n"); + } + } + + private static void emitSpecularAdd(StringBuilder sb, FragmentKey key) { + if (key.separateSpecular()) { + sb.append(" // Add separate specular\n"); + sb.append(" color.rgb += v_SpecularColor;\n"); + } + } + + private static void emitAlphaTest(StringBuilder sb, FragmentKey key) { + if (!key.alphaTestEnabled()) return; + + sb.append(" // Alpha test\n"); + final int func = FragmentKey.decodeAlphaFunc(key.alphaTestFunc()); + + switch (func) { + case GL11.GL_NEVER -> + sb.append(" discard;\n"); + case GL11.GL_LESS -> + sb.append(" if (color.a >= u_AlphaRef) discard;\n"); + case GL11.GL_EQUAL -> + sb.append(" if (color.a != u_AlphaRef) discard;\n"); + case GL11.GL_LEQUAL -> + sb.append(" if (color.a > u_AlphaRef) discard;\n"); + case GL11.GL_GREATER -> + sb.append(" if (color.a <= u_AlphaRef) discard;\n"); + case GL11.GL_NOTEQUAL -> + sb.append(" if (color.a == u_AlphaRef) discard;\n"); + case GL11.GL_GEQUAL -> + sb.append(" if (color.a < u_AlphaRef) discard;\n"); + case GL11.GL_ALWAYS -> {} + } + } + + private static void emitFog(StringBuilder sb, FragmentKey key) { + final int fogMode = key.fogMode(); + if (fogMode == FragmentKey.FOG_NONE) return; + + sb.append(" // Fog\n"); + sb.append(" float f;\n"); + + switch (fogMode) { + case FragmentKey.FOG_LINEAR -> + sb.append(" f = v_FogCoord * u_FogParams.x + u_FogParams.y;\n"); + case FragmentKey.FOG_EXP -> + sb.append(" f = exp2(-(v_FogCoord * u_FogParams.z));\n"); + case FragmentKey.FOG_EXP2 -> { + sb.append(" float fogTmp = v_FogCoord * u_FogParams.w;\n"); + sb.append(" f = exp2(-(fogTmp * fogTmp));\n"); + } + } + + sb.append(" f = clamp(f, 0.0, 1.0);\n"); + sb.append(" color.rgb = mix(u_FogColor.rgb, color.rgb, f);\n"); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java new file mode 100644 index 000000000..c7d0a5db1 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Program.java @@ -0,0 +1,210 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLDebug; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.RenderSystem; +import lombok.Getter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.KHRDebug; + +/** + * A compiled and linked FFP emulation program (vertex + fragment shader pair). Owns the GL program handle and caches uniform locations. + */ +public class Program { + + private static final Logger LOGGER = LogManager.getLogger("FFPProgram"); + + @Getter private final int programId; + @Getter private final VertexKey vertexKey; + @Getter private final FragmentKey fragmentKey; + + // Uniform locations (-1 = not present in this variant) + // Matrices + public int locModelViewMatrix = -1; + public int locProjectionMatrix = -1; + public int locMVPMatrix = -1; + public int locNormalMatrix = -1; + public int locTextureMatrix0 = -1; + + // Current state defaults + public int locCurrentNormal = -1; + public int locCurrentColor = -1; + public int locCurrentTexCoord = -1; + public int locCurrentLightmapCoord = -1; + public int locLightmapTextureMatrix = -1; + + // Lighting - color material path (raw values) + public int locLightModelAmbient = -1; + public int locMaterialEmission = -1; + public int locMaterialAmbient = -1; + public int locMaterialDiffuse = -1; + public int locMaterialSpecular = -1; + public int locMaterialShininess = -1; + public int locLight0Ambient = -1; + public int locLight0Diffuse = -1; + public int locLight0Specular = -1; + public int locLight1Ambient = -1; + public int locLight1Diffuse = -1; + public int locLight1Specular = -1; + + // Lighting - pre-computed path + public int locSceneColor = -1; + public int locLightProd0Ambient = -1; + public int locLightProd0Diffuse = -1; + public int locLightProd0Specular = -1; + public int locLightProd1Ambient = -1; + public int locLightProd1Diffuse = -1; + public int locLightProd1Specular = -1; + + // Light positions + public int locLight0Position = -1; + public int locLight1Position = -1; + + // Normal scale (for rescale normals) + public int locNormalScale = -1; + + // Fragment uniforms + public int locSampler0 = -1; + public int locSampler1 = -1; + public int locAlphaRef = -1; + public int locTexEnvColor = -1; + public int locFogParams = -1; + public int locFogColor = -1; + + Program(int programId, VertexKey vertexKey, FragmentKey fragmentKey) { + this.programId = programId; + this.vertexKey = vertexKey; + this.fragmentKey = fragmentKey; + resolveLocations(); + } + + private void resolveLocations() { + locModelViewMatrix = loc("u_ModelViewMatrix"); + locProjectionMatrix = loc("u_ProjectionMatrix"); + locMVPMatrix = loc("u_MVPMatrix"); + locNormalMatrix = loc("u_NormalMatrix"); + locTextureMatrix0 = loc("u_TextureMatrix0"); + + locCurrentNormal = loc("u_CurrentNormal"); + locCurrentColor = loc("u_CurrentColor"); + locCurrentTexCoord = loc("u_CurrentTexCoord"); + locCurrentLightmapCoord = loc("u_CurrentLightmapCoord"); + locLightmapTextureMatrix = loc("u_LightmapTextureMatrix"); + + // Color material path + locLightModelAmbient = loc("u_LightModelAmbient"); + locMaterialEmission = loc("u_MaterialEmission"); + locMaterialAmbient = loc("u_MaterialAmbient"); + locMaterialDiffuse = loc("u_MaterialDiffuse"); + locMaterialSpecular = loc("u_MaterialSpecular"); + locMaterialShininess = loc("u_MaterialShininess"); + locLight0Ambient = loc("u_Light0Ambient"); + locLight0Diffuse = loc("u_Light0Diffuse"); + locLight0Specular = loc("u_Light0Specular"); + locLight1Ambient = loc("u_Light1Ambient"); + locLight1Diffuse = loc("u_Light1Diffuse"); + locLight1Specular = loc("u_Light1Specular"); + + // Pre-computed path + locSceneColor = loc("u_SceneColor"); + locLightProd0Ambient = loc("u_LightProd0Ambient"); + locLightProd0Diffuse = loc("u_LightProd0Diffuse"); + locLightProd0Specular = loc("u_LightProd0Specular"); + locLightProd1Ambient = loc("u_LightProd1Ambient"); + locLightProd1Diffuse = loc("u_LightProd1Diffuse"); + locLightProd1Specular = loc("u_LightProd1Specular"); + + // Light positions + locLight0Position = loc("u_Light0Position"); + locLight1Position = loc("u_Light1Position"); + + locNormalScale = loc("u_NormalScale"); + + // Fragment + locSampler0 = loc("u_Sampler0"); + locSampler1 = loc("u_Sampler1"); + locAlphaRef = loc("u_AlphaRef"); + locTexEnvColor = loc("u_TexEnvColor"); + locFogParams = loc("u_FogParams"); + locFogColor = loc("u_FogColor"); + } + + private int loc(String name) { + return GL20.glGetUniformLocation(programId, name); + } + + public void destroy() { + GL20.glDeleteProgram(programId); + } + + /** + * Compile a shader, link it into a program, and return the FFPProgram. + */ + static Program create(VertexKey vk, FragmentKey fk, String vertSrc, String fragSrc) { + final int vs = compileShader(GL20.GL_VERTEX_SHADER, vertSrc, "ffp_v_" + Long.toHexString(vk.pack())); + final int fs = compileShader(GL20.GL_FRAGMENT_SHADER, fragSrc, "ffp_f_" + Long.toHexString(fk.pack())); + + final int program = GL20.glCreateProgram(); + GL20.glAttachShader(program, vs); + GL20.glAttachShader(program, fs); + GL20.glLinkProgram(program); + + final String log = RenderSystem.getProgramInfoLog(program); + if (!log.isEmpty()) { + LOGGER.warn("FFP program link log (vk=0x{}, fk=0x{}): {}", Long.toHexString(vk.pack()), Long.toHexString(fk.pack()), log); + } + + final int linkStatus = GL20.glGetProgrami(program, GL20.GL_LINK_STATUS); + if (linkStatus != GL11.GL_TRUE) { + GL20.glDeleteProgram(program); + GL20.glDeleteShader(vs); + GL20.glDeleteShader(fs); + throw new RuntimeException("FFP shader link failed (vk=0x" + Long.toHexString(vk.pack()) + ", fk=0x" + Long.toHexString(fk.pack()) + "): " + log); + } + + final String debugName = "FFP(v=0x" + Long.toHexString(vk.pack()) + ",f=0x" + Long.toHexString(fk.pack()) + ")"; + GLDebug.nameObject(KHRDebug.GL_PROGRAM, program, debugName); + + // Detach and delete individual shaders — they're linked into the program + GL20.glDetachShader(program, vs); + GL20.glDetachShader(program, fs); + GL20.glDeleteShader(vs); + GL20.glDeleteShader(fs); + + final Program ffpProgram = new Program(program, vk, fk); + + final int previousProgram = GLStateManager.getActiveProgram(); + GL20.glUseProgram(program); + if (ffpProgram.locSampler0 != -1) GL20.glUniform1i(ffpProgram.locSampler0, 0); + if (ffpProgram.locSampler1 != -1) GL20.glUniform1i(ffpProgram.locSampler1, 1); + GL20.glUseProgram(previousProgram); + + return ffpProgram; + } + + private static int compileShader(int type, String src, String name) { + final int shader = GL20.glCreateShader(type); + GL20.glShaderSource(shader, src); + GL20.glCompileShader(shader); + + final String typeName = (type == GL20.GL_VERTEX_SHADER) ? "vertex" : "fragment"; + GLDebug.nameObject(KHRDebug.GL_SHADER, shader, name + "(" + typeName + ")"); + + final String log = RenderSystem.getShaderInfoLog(shader); + if (!log.isEmpty()) { + LOGGER.warn("FFP {} shader compilation log for {}: {}", typeName, name, log); + } + + final int result = GL20.glGetShaderi(shader, GL20.GL_COMPILE_STATUS); + if (result != GL11.GL_TRUE) { + LOGGER.error("FFP {} shader source:\n{}", typeName, src); + GL20.glDeleteShader(shader); + throw new RuntimeException("FFP " + typeName + " shader compilation failed for " + name + ": " + log); + } + + return shader; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java new file mode 100644 index 000000000..d06bab92c --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderCache.java @@ -0,0 +1,133 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import lombok.Setter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Cache for FFP shader program variants. Keyed on (vertexKey, fragmentKey) pairs. + */ +public class ShaderCache { + private static final Logger LOGGER = LogManager.getLogger("FFPShaderCache"); + + private final Long2ObjectOpenHashMap vertexSourceCache = new Long2ObjectOpenHashMap<>(); + private final Long2ObjectOpenHashMap fragmentSourceCache = new Long2ObjectOpenHashMap<>(); + private final Long2ObjectOpenHashMap programCache = new Long2ObjectOpenHashMap<>(); + + private long lastCombinedKey = Long.MIN_VALUE; + private Program lastProgram = null; + + @Setter private Path dumpDir = null; + + /** + * Get or create an FFP program for the given packed state keys. + */ + public Program getOrCreate(long vkPacked, long fkPacked) { + final long combinedKey = (fkPacked << 32) | (vkPacked & 0xFFFFFFFFL); + + if (combinedKey == lastCombinedKey && lastProgram != null) { + return lastProgram; + } + + Program program = programCache.get(combinedKey); + if (program != null) { + lastCombinedKey = combinedKey; + lastProgram = program; + + return program; + } + + final VertexKey vk = VertexKey.fromPacked(vkPacked); + final FragmentKey fk = FragmentKey.fromPacked(fkPacked); + + final String vertSrc = getOrGenerateVertex(vk); + final String fragSrc = getOrGenerateFragment(fk); + + program = Program.create(vk, fk, vertSrc, fragSrc); + programCache.put(combinedKey, program); + lastCombinedKey = combinedKey; + lastProgram = program; + + LOGGER.debug("FFP variant compiled: {} + {} (total: {} programs)", vk, fk, programCache.size()); + + // Debug dump + if (dumpDir != null) { + dumpShader(vkPacked, ".vert.glsl", vertSrc); + dumpShader(fkPacked, ".frag.glsl", fragSrc); + } + + return program; + } + + private String getOrGenerateVertex(VertexKey vk) { + return vertexSourceCache.computeIfAbsent(vk.pack(), k -> VertexShaderGenerator.generate(vk)); + } + + private String getOrGenerateFragment(FragmentKey fk) { + return fragmentSourceCache.computeIfAbsent(fk.pack(), k -> FragmentShaderGenerator.generate(fk)); + } + + private void dumpShader(long key, String suffix, String source) { + if (dumpDir == null) return; + try { + Files.createDirectories(dumpDir); + final Path file = dumpDir.resolve("ffp_" + Long.toHexString(key) + suffix); + if (!Files.exists(file)) { + Files.writeString(file, source, StandardCharsets.UTF_8); + } + } catch (IOException e) { + LOGGER.warn("Failed to dump FFP shader to {}: {}", dumpDir, e.getMessage()); + } + } + + /** + * Dump all cached shaders to disk. Useful for debugging. + */ + public void dumpAll(Path outputDir) { + try { + Files.createDirectories(outputDir); + for (var entry : vertexSourceCache.entrySet()) { + dumpShader(entry.getKey(), ".vert.glsl", entry.getValue()); + } + for (var entry : fragmentSourceCache.entrySet()) { + dumpShader(entry.getKey(), ".frag.glsl", entry.getValue()); + } + LOGGER.info("Dumped {} vertex and {} fragment FFP shader sources to {}", vertexSourceCache.size(), fragmentSourceCache.size(), outputDir); + } catch (IOException e) { + LOGGER.warn("Failed to dump FFP shaders: {}", e.getMessage()); + } + } + + /** + * Destroy all cached programs and clear caches. + */ + public void destroy() { + for (Program program : programCache.values()) { + program.destroy(); + } + programCache.clear(); + vertexSourceCache.clear(); + fragmentSourceCache.clear(); + lastProgram = null; + lastCombinedKey = Long.MIN_VALUE; + LOGGER.debug("FFP shader cache cleared"); + } + + public int getProgramCount() { + return programCache.size(); + } + + public int getVertexVariantCount() { + return vertexSourceCache.size(); + } + + public int getFragmentVariantCount() { + return fragmentSourceCache.size(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java new file mode 100644 index 000000000..78b44fa33 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/ShaderManager.java @@ -0,0 +1,175 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.glsm.CompatUniformManager; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.stacks.Vec3fStack; +import com.gtnewhorizons.angelica.glsm.stacks.Vec4fStack; +import lombok.Getter; +import net.coderbot.iris.gl.blending.BlendModeStorage; +import net.minecraft.launchwrapper.Launch; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.joml.Vector3f; +import org.joml.Vector4f; +import org.lwjgl.opengl.GL20; + +import java.nio.file.Paths; + +/** + * FFP shader manager + */ +public class ShaderManager { + private static final Logger LOGGER = LogManager.getLogger("FFPShaderManager"); + + private static final class Holder { static final ShaderManager INSTANCE = new ShaderManager(); } + + private final ShaderCache cache = new ShaderCache(); + private final Uniforms uniforms = new Uniforms(); + + @Getter + private boolean active = false; + private Program currentProgram = null; + private long currentVertexKeyPacked = Long.MIN_VALUE; + private long currentFragmentKeyPacked = Long.MIN_VALUE; + + @Getter private static final Vector3f currentNormal = new Vector3f(0.0f, 0.0f, 1.0f); + @Getter private static final Vector4f currentTexCoord = new Vector4f(0.0f, 0.0f, 0.0f, 1.0f); + @Getter private static final Vec3fStack normalStack = new Vec3fStack(currentNormal); + @Getter private static final Vec4fStack texCoordStack = new Vec4fStack(currentTexCoord); + @Getter private static int normalGeneration; + @Getter private static int texCoordGeneration; + @Getter private boolean enabled = false; + private int currentVertexFlags = VertexFlags.TEXTURE_BIT | VertexFlags.COLOR_BIT | VertexFlags.NORMAL_BIT; + + private ShaderManager() { + boolean isDev = false; + try { + final Object deobfEnv = Launch.blackboard != null ? Launch.blackboard.get("fml.deobfuscatedEnvironment") : null; + isDev = Boolean.TRUE.equals(deobfEnv); + } catch (Exception ignored) {} + if (isDev || Boolean.parseBoolean(System.getProperty("angelica.ffp.dumpShaders", "false"))) { + cache.setDumpDir(Paths.get("ffp_shaders")); + } + } + + public static ShaderManager getInstance() { + return Holder.INSTANCE; + } + + public void enable() { + enabled = true; + + VertexFormat.registerSetupBufferStateOverride((format, offset) -> { + currentVertexFlags = format.getVertexFlags(); + return false; + }); + + LOGGER.info("FFP shader emulation enabled"); + } + + public void disable() { + enabled = false; + } + + public void activate() { + active = true; + updateVariant(true, true, true, true); + uploadUniforms(); + } + + public void deactivate() { + active = false; + currentProgram = null; + currentVertexKeyPacked = Long.MIN_VALUE; + currentFragmentKeyPacked = Long.MIN_VALUE; + } + + public void preDraw(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { + GLStateManager.flushDeferredVertexAttribs(); + BlendModeStorage.flushDeferredBlend(); + + if (!active) { + if (enabled) { + final int currentProgramId = GLStateManager.getActiveProgram(); + if (currentProgramId != 0) { + CompatUniformManager.onUseProgram(currentProgramId); + return; + } + active = true; + } else { + return; + } + } + + final long vkPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap); + final long fkPacked = FragmentKey.packFromState(); + + if (vkPacked != currentVertexKeyPacked || fkPacked != currentFragmentKeyPacked) { + currentVertexKeyPacked = vkPacked; + currentFragmentKeyPacked = fkPacked; + + currentProgram = cache.getOrCreate(vkPacked, fkPacked); + GL20.glUseProgram(currentProgram.getProgramId()); + } + + uploadUniforms(); + } + + public void preDraw(int vertexFlags) { + currentVertexFlags = vertexFlags; + preDraw( + (vertexFlags & VertexFlags.COLOR_BIT) != 0, + (vertexFlags & VertexFlags.NORMAL_BIT) != 0, + (vertexFlags & VertexFlags.TEXTURE_BIT) != 0, + (vertexFlags & VertexFlags.BRIGHTNESS_BIT) != 0 + ); + } + + public void preDraw() { + preDraw(currentVertexFlags); + } + + private void updateVariant(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { + currentVertexKeyPacked = VertexKey.packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap); + currentFragmentKeyPacked = FragmentKey.packFromState(); + + currentProgram = cache.getOrCreate(currentVertexKeyPacked, currentFragmentKeyPacked); + GL20.glUseProgram(currentProgram.getProgramId()); + } + + private void uploadUniforms() { + if (currentProgram != null) { + uniforms.upload(currentProgram); + } + } + + public static void setCurrentNormal(float x, float y, float z) { + currentNormal.set(x, y, z); + normalGeneration++; + } + + public static void setCurrentTexCoord(float s, float t, float r, float q) { + currentTexCoord.set(s, t, r, q); + texCoordGeneration++; + } + + public static void bumpNormalGeneration() { normalGeneration++; } + public static void bumpTexCoordGeneration() { texCoordGeneration++; } + + public void destroy() { + cache.destroy(); + uniforms.destroy(); + TessellatorStreamingDrawer.destroy(); + com.gtnewhorizons.angelica.glsm.QuadConverter.destroy(); + active = false; + currentProgram = null; + } + + public String getDebugInfo() { + return String.format("FFP: %d programs (%d vert, %d frag variants)", + cache.getProgramCount(), cache.getVertexVariantCount(), cache.getFragmentVariantCount()); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/TessellatorStreamingDrawer.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/TessellatorStreamingDrawer.java new file mode 100644 index 000000000..582284d8e --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/TessellatorStreamingDrawer.java @@ -0,0 +1,195 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFlags; +import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.QuadConverter; +import net.minecraft.client.renderer.Tessellator; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL30; + +import java.nio.ByteBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; + +/** + * Replaces the vanilla Tessellator's FFP client-array draw path with a streaming VBO+VAO approach for GL 3.3 core profile compatibility. + *

+ * Maintains a cached VAO+VBO pair per vertex format (up to 16 combinations). Data is repacked from vanilla's 32-byte/vertex stride into the optimal + * VertexFormat, then stream-uploaded to the VBO and drawn via the VAO. + */ +public class TessellatorStreamingDrawer { + + private static final int FORMAT_COUNT = VertexFlags.BITSET_SIZE; // 16 + private static final int[] vboIds = new int[FORMAT_COUNT]; + private static final int[] vaoIds = new int[FORMAT_COUNT]; + private static final int[] vboCapacities = new int[FORMAT_COUNT]; // track allocated capacity + + private static ByteBuffer repackBuffer; + private static long repackAddress; + private static int repackCapacity; + + + static { + // Initial repack buffer: 64KB + repackCapacity = 0x10000; + repackBuffer = memAlloc(repackCapacity); + repackAddress = memAddress0(repackBuffer); + } + + /** + * Draw the vanilla Tessellator's data using streaming VBO+VAO instead of FFP client arrays. + */ + public static int draw(Tessellator tess) { + if (!tess.isDrawing) { + throw new IllegalStateException("Not tesselating!"); + } + + tess.isDrawing = false; + + final int vertexCount = tess.vertexCount; + if (vertexCount == 0) { + final int result = tess.rawBufferIndex * 4; + tess.reset(); + return result; + } + + // Determine the optimal vertex format from the tessellator's flags + final int flags = VertexFlags.convertToFlags(tess.hasTexture, tess.hasColor, tess.hasNormals, tess.hasBrightness); + final VertexFormat format = DefaultVertexFormat.ALL_FORMATS[flags]; + final int vertexSize = format.getVertexSize(); + + final int requiredBytes = vertexCount * vertexSize; + ensureRepackCapacity(requiredBytes); + + long writePtr = format.writeToBuffer0(repackAddress, tess.rawBuffer, tess.rawBufferIndex); + repackBuffer.position(0); + repackBuffer.limit((int)(writePtr - repackAddress)); + + ensureVAO(flags, format); + GLStateManager.glBindVertexArray(vaoIds[flags]); + + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboIds[flags]); + streamUpload(flags, repackBuffer, requiredBytes); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + ShaderManager.getInstance().preDraw(flags); + drawWithQuadConversion(tess.drawMode, vertexCount); + + GLStateManager.glBindVertexArray(0); + + // Shrink rawBuffer if oversized + if (tess.rawBufferSize > 0x20000 && tess.rawBufferIndex < (tess.rawBufferSize << 3)) { + tess.rawBufferSize = 0x10000; + tess.rawBuffer = new int[tess.rawBufferSize]; + } + + final int result = tess.rawBufferIndex * 4; + tess.reset(); + return result; + } + + /** + * Draw DirectTessellator data via streaming VBO+VAO. Used for live immediate mode emulation. + */ + public static void drawDirect(DirectTessellator dt) { + final VertexFormat format = dt.getVertexFormat(); + if (format == null) return; + + final int vertexCount = dt.getVertexCount(); + if (vertexCount == 0) return; + + final int drawMode = dt.getDrawMode(); + final int flags = format.getVertexFlags(); + + // getWriteBuffer() returns the internal buffer directly — no allocation or copy. + final ByteBuffer buffer = dt.getWriteBuffer(); + final int requiredBytes = buffer.remaining(); + + ensureVAO(flags, format); + GLStateManager.glBindVertexArray(vaoIds[flags]); + + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboIds[flags]); + streamUpload(flags, buffer, requiredBytes); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + ShaderManager.getInstance().preDraw(flags); + drawWithQuadConversion(drawMode, vertexCount); + + GLStateManager.glBindVertexArray(0); + } + + private static void streamUpload(int flags, ByteBuffer data, int requiredBytes) { + if (requiredBytes > vboCapacities[flags]) { + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, data, GL15.GL_STREAM_DRAW); + vboCapacities[flags] = requiredBytes; + } else { + // Orphan + upload for streaming (avoids sync) + GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vboCapacities[flags], GL15.GL_STREAM_DRAW); + GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, data); + } + } + + private static void drawWithQuadConversion(int drawMode, int vertexCount) { + if (drawMode == GL11.GL_QUADS) { + QuadConverter.drawQuadsAsTriangles(0, vertexCount); + } else { + GL11.glDrawArrays(drawMode, 0, vertexCount); + } + } + + private static void ensureRepackCapacity(int requiredBytes) { + if (requiredBytes <= repackCapacity) return; + + int newCapacity = repackCapacity; + while (newCapacity < requiredBytes) { + newCapacity *= 2; + } + + memFree(repackBuffer); + repackBuffer = memAlloc(newCapacity); + repackAddress = memAddress0(repackBuffer); + repackCapacity = newCapacity; + } + + private static void ensureVAO(int flags, VertexFormat format) { + if (vaoIds[flags] != 0) return; + + // Create VBO + vboIds[flags] = GL15.glGenBuffers(); + + // Create VAO and configure vertex attributes + vaoIds[flags] = GL30.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vaoIds[flags]); + + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboIds[flags]); + format.setupBufferState(0L); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + + GLStateManager.glBindVertexArray(0); + + vboCapacities[flags] = 0; + } + + /** + * Clean up all VAOs, VBOs, and the repack buffer. + */ + public static void destroy() { + for (int i = 0; i < FORMAT_COUNT; i++) { + if (vaoIds[i] != 0) { GL30.glDeleteVertexArrays(vaoIds[i]); vaoIds[i] = 0; } + if (vboIds[i] != 0) { GL15.glDeleteBuffers(vboIds[i]); vboIds[i] = 0; } + vboCapacities[i] = 0; + } + if (repackBuffer != null) { + memFree(repackBuffer); + repackBuffer = null; + repackAddress = 0; + repackCapacity = 0; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java new file mode 100644 index 000000000..a3aa41f41 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/Uniforms.java @@ -0,0 +1,380 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.states.FogState; +import com.gtnewhorizons.angelica.glsm.states.LightState; +import com.gtnewhorizons.angelica.glsm.states.MaterialState; +import net.minecraft.client.renderer.OpenGlHelper; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.joml.Vector4f; +import org.lwjgl.opengl.GL20; + +import java.nio.FloatBuffer; + +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAllocFloat; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; + +/** + * Uploads GLSM cached state to the active FFP program's uniforms. + * + * Follows Mesa's prog_statevars.c patterns: + * - Pre-computed derived state (light products, scene color) when material is static + * - Raw light/material values when color material is active + * - Optimized fog params (pre-divided for single MAD in shader) + */ +public class Uniforms { + // Reusable temp buffers for uniform upload + private final FloatBuffer mat4Buf = memAllocFloat(16); + private final FloatBuffer mat3Buf = memAllocFloat(9); + private final FloatBuffer vec4Buf = memAllocFloat(4); + private final FloatBuffer vec3Buf = memAllocFloat(3); + + // Derived matrices (computed on CPU) + private final Matrix4f mvpMatrix = new Matrix4f(); + private final Matrix3f normalMatrix = new Matrix3f(); + + // Temp vectors for light product and normal scale computation + private final Vector4f tempVec4 = new Vector4f(); + private final org.joml.Vector3f tempVec3 = new org.joml.Vector3f(); + + // Pre-computed constants for fog params (Mesa STATE_FOG_PARAMS_OPTIMIZED) + private static final double LN2 = Math.log(2.0); + private static final double SQRT_LN2 = Math.sqrt(LN2); + + // Dirty tracking: last-uploaded generation per category + program ID. + // Program change forces full re-upload since uniform locations differ. + private int lastProgramId = -1; + private int lastMatrixGen = -1; + private int lastLightingGen = -1; + private int lastFragmentGen = -1; + private int lastColorGen = -1; + private int lastNormalGen = -1; + private int lastTexCoordGen = -1; + private float lastLightmapX = Float.NaN; + private float lastLightmapY = Float.NaN; + + /** + * Upload all relevant uniforms to the given FFP program based on current GLSM state. + * Uses generation counters to skip categories that haven't changed since last upload. + */ + public void upload(Program program) { + final boolean programChanged = program.getProgramId() != lastProgramId; + lastProgramId = program.getProgramId(); + + final int matGen = GLStateManager.matrixGeneration; + if (programChanged || matGen != lastMatrixGen) { + uploadMatrices(program); + lastMatrixGen = matGen; + } + + if (program.getVertexKey().lightingEnabled()) { + final int litGen = GLStateManager.lightingGeneration; + if (programChanged || litGen != lastLightingGen) { + uploadLighting(program); + lastLightingGen = litGen; + } + } + + // Current color/normal/texcoord — skip if generation unchanged + if (!program.getVertexKey().hasVertexColor()) { + final int colorGen = GLStateManager.colorGeneration; + if (programChanged || colorGen != lastColorGen) { + uploadCurrentColor(program); + lastColorGen = colorGen; + } + } + + if (!program.getVertexKey().hasVertexNormal() && program.getVertexKey().lightingEnabled()) { + final int normalGen = ShaderManager.getNormalGeneration(); + if (programChanged || normalGen != lastNormalGen) { + uploadCurrentNormal(program); + lastNormalGen = normalGen; + } + } + + if (!program.getVertexKey().hasVertexTexCoord() && program.getVertexKey().textureEnabled()) { + final int texGen = ShaderManager.getTexCoordGeneration(); + if (programChanged || texGen != lastTexCoordGen) { + uploadCurrentTexCoord(program); + lastTexCoordGen = texGen; + } + } + + if (program.getVertexKey().lightmapEnabled() && !program.getVertexKey().hasVertexLightmap()) { + if (programChanged || OpenGlHelper.lastBrightnessX != lastLightmapX || OpenGlHelper.lastBrightnessY != lastLightmapY) { + uploadCurrentLightmapCoord(program); + lastLightmapX = OpenGlHelper.lastBrightnessX; + lastLightmapY = OpenGlHelper.lastBrightnessY; + } + } + + final int fragGen = GLStateManager.fragmentGeneration; + if (programChanged || fragGen != lastFragmentGen) { + uploadFragmentUniforms(program); + lastFragmentGen = fragGen; + } + } + + private void uploadMatrices(Program program) { + final Matrix4f mv = GLStateManager.getModelViewMatrix(); + final Matrix4f proj = GLStateManager.getProjectionMatrix(); + + // ModelView + if (program.locModelViewMatrix != -1) { + mv.get(mat4Buf); + GL20.glUniformMatrix4(program.locModelViewMatrix, false, mat4Buf); + } + + // Projection + if (program.locProjectionMatrix != -1) { + proj.get(mat4Buf); + GL20.glUniformMatrix4(program.locProjectionMatrix, false, mat4Buf); + } + + // MVP = Projection * ModelView + if (program.locMVPMatrix != -1) { + proj.mul(mv, mvpMatrix); + mvpMatrix.get(mat4Buf); + GL20.glUniformMatrix4(program.locMVPMatrix, false, mat4Buf); + } + + // Normal matrix = inverse transpose of upper-left 3x3 of ModelView + if (program.locNormalMatrix != -1 || program.locNormalScale != -1) { + mv.normal(normalMatrix); + } + if (program.locNormalMatrix != -1) { + normalMatrix.get(mat3Buf); + GL20.glUniformMatrix3(program.locNormalMatrix, false, mat3Buf); + } + + // Normal scale (for GL_RESCALE_NORMAL without GL_NORMALIZE) + if (program.locNormalScale != -1) { + // Scale factor = 1/length of first column of normal matrix + final float scale = 1.0f / normalMatrix.getColumn(0, tempVec3).length(); + GL20.glUniform1f(program.locNormalScale, scale); + } + + // Texture matrix unit 0 + if (program.locTextureMatrix0 != -1) { + final Matrix4f texMat = GLStateManager.getTextures().getTextureUnitMatrix(0); + texMat.get(mat4Buf); + GL20.glUniformMatrix4(program.locTextureMatrix0, false, mat4Buf); + } + + // Texture matrix unit 1 (lightmap) + if (program.locLightmapTextureMatrix != -1) { + final Matrix4f lmTexMat = GLStateManager.getTextures().getTextureUnitMatrix(1); + lmTexMat.get(mat4Buf); + GL20.glUniformMatrix4(program.locLightmapTextureMatrix, false, mat4Buf); + } + } + + private void uploadLighting(Program program) { + final VertexKey vk = program.getVertexKey(); + + if (vk.colorMaterialEnabled()) { + uploadLightingColorMaterial(program, vk); + } else { + uploadLightingPreComputed(program, vk); + } + } + + /** + * Color material active: upload raw light and material values. + * The shader multiplies them with vertex color at runtime. + */ + private void uploadLightingColorMaterial(Program program, VertexKey vk) { + final MaterialState mat = GLStateManager.getFrontMaterial(); + + uploadVec4(program.locLightModelAmbient, GLStateManager.getLightModel().ambient); + uploadVec4(program.locMaterialEmission, mat.emission); + uploadVec4(program.locMaterialAmbient, mat.ambient); + uploadVec4(program.locMaterialDiffuse, mat.diffuse); + uploadVec4(program.locMaterialSpecular, mat.specular); + if (program.locMaterialShininess != -1) { + GL20.glUniform1f(program.locMaterialShininess, mat.shininess); + } + + if (vk.light0Enabled()) { + final LightState light0 = GLStateManager.getLightDataStates()[0]; + uploadVec4(program.locLight0Ambient, light0.ambient); + uploadVec4(program.locLight0Diffuse, light0.diffuse); + uploadVec4(program.locLight0Specular, light0.specular); + uploadVec4(program.locLight0Position, light0.position); + } + if (vk.light1Enabled()) { + final LightState light1 = GLStateManager.getLightDataStates()[1]; + uploadVec4(program.locLight1Ambient, light1.ambient); + uploadVec4(program.locLight1Diffuse, light1.diffuse); + uploadVec4(program.locLight1Specular, light1.specular); + uploadVec4(program.locLight1Position, light1.position); + } + } + + /** + * No color material: upload pre-computed light products and scene color. + * Fewer shader multiplies since material is static. + */ + private void uploadLightingPreComputed(Program program, VertexKey vk) { + final MaterialState mat = GLStateManager.getFrontMaterial(); + + // Scene color = emission + ambient * lightModel.ambient + // Alpha = material.diffuse.a + if (program.locSceneColor != -1) { + tempVec4.set( + mat.emission.x + mat.ambient.x * GLStateManager.getLightModel().ambient.x, + mat.emission.y + mat.ambient.y * GLStateManager.getLightModel().ambient.y, + mat.emission.z + mat.ambient.z * GLStateManager.getLightModel().ambient.z, + mat.diffuse.w // alpha from diffuse + ); + uploadVec4(program.locSceneColor, tempVec4); + } + + if (program.locMaterialShininess != -1) { + GL20.glUniform1f(program.locMaterialShininess, mat.shininess); + } + + // Per-light products + if (vk.light0Enabled()) { + final LightState light0 = GLStateManager.getLightDataStates()[0]; + uploadVec4(program.locLight0Position, light0.position); + uploadLightProduct(program.locLightProd0Ambient, light0.ambient, mat.ambient); + uploadLightProduct(program.locLightProd0Diffuse, light0.diffuse, mat.diffuse); + uploadLightProduct(program.locLightProd0Specular, light0.specular, mat.specular); + } + if (vk.light1Enabled()) { + final LightState light1 = GLStateManager.getLightDataStates()[1]; + uploadVec4(program.locLight1Position, light1.position); + uploadLightProduct(program.locLightProd1Ambient, light1.ambient, mat.ambient); + uploadLightProduct(program.locLightProd1Diffuse, light1.diffuse, mat.diffuse); + uploadLightProduct(program.locLightProd1Specular, light1.specular, mat.specular); + } + } + + /** + * Upload pre-multiplied light product: light.X * material.X (RGB only). + */ + private void uploadLightProduct(int loc, Vector4f lightVal, Vector4f materialVal) { + if (loc == -1) return; + vec3Buf.clear(); + vec3Buf.put(lightVal.x * materialVal.x); + vec3Buf.put(lightVal.y * materialVal.y); + vec3Buf.put(lightVal.z * materialVal.z); + vec3Buf.flip(); + GL20.glUniform3(loc, vec3Buf); + } + + private void uploadCurrentColor(Program program) { + if (program.locCurrentColor == -1) return; + // Upload the current color from GLSM + final var color = GLStateManager.getColor(); + vec4Buf.clear(); + vec4Buf.put(color.getRed()); + vec4Buf.put(color.getGreen()); + vec4Buf.put(color.getBlue()); + vec4Buf.put(color.getAlpha()); + vec4Buf.flip(); + GL20.glUniform4(program.locCurrentColor, vec4Buf); + } + + private void uploadCurrentTexCoord(Program program) { + if (program.locCurrentTexCoord == -1) return; + final var tc = ShaderManager.getCurrentTexCoord(); + uploadVec4(program.locCurrentTexCoord, tc); + } + + private void uploadCurrentLightmapCoord(Program program) { + if (program.locCurrentLightmapCoord == -1) return; + GL20.glUniform2f(program.locCurrentLightmapCoord, + OpenGlHelper.lastBrightnessX, OpenGlHelper.lastBrightnessY); + } + + private void uploadCurrentNormal(Program program) { + if (program.locCurrentNormal == -1) return; + // Upload current normal from FFPShaderManager's tracked normal + final var normal = ShaderManager.getCurrentNormal(); + vec3Buf.clear(); + vec3Buf.put(normal.x); + vec3Buf.put(normal.y); + vec3Buf.put(normal.z); + vec3Buf.flip(); + GL20.glUniform3(program.locCurrentNormal, vec3Buf); + } + + private void uploadFragmentUniforms(Program program) { + final FragmentKey fk = program.getFragmentKey(); + + // Alpha test reference + if (fk.alphaTestEnabled() && program.locAlphaRef != -1) { + GL20.glUniform1f(program.locAlphaRef, GLStateManager.getAlphaState().getReference()); + } + + // Tex env color (only used by GL_BLEND mode) + if (program.locTexEnvColor != -1) { + final var envColor = GLStateManager.getTexEnvColor(); + vec4Buf.clear(); + vec4Buf.put(envColor.getRed()); + vec4Buf.put(envColor.getGreen()); + vec4Buf.put(envColor.getBlue()); + vec4Buf.put(envColor.getAlpha()); + vec4Buf.flip(); + GL20.glUniform4(program.locTexEnvColor, vec4Buf); + } + + // Fog + if (fk.fogMode() != FragmentKey.FOG_NONE) { + uploadFog(program); + } + } + + /** + * Upload optimized fog params (following Mesa's STATE_FOG_PARAMS_OPTIMIZED): + */ + private void uploadFog(Program program) { + final FogState fog = GLStateManager.getFogState(); + + if (program.locFogParams != -1) { + final float start = fog.getStart(); + final float end = fog.getEnd(); + final float density = fog.getDensity(); + final float range = end - start; + + vec4Buf.clear(); + vec4Buf.put(range != 0.0f ? -1.0f / range : 0.0f); // [0]: -1/(end-start) + vec4Buf.put(range != 0.0f ? end / range : 1.0f); // [1]: end/(end-start) + vec4Buf.put((float)(density / LN2)); // [2]: density/ln(2) + vec4Buf.put((float)(density / SQRT_LN2)); // [3]: density/sqrt(ln(2)) + vec4Buf.flip(); + GL20.glUniform4(program.locFogParams, vec4Buf); + } + + if (program.locFogColor != -1) { + vec4Buf.clear(); + vec4Buf.put((float) fog.getFogColor().x); + vec4Buf.put((float) fog.getFogColor().y); + vec4Buf.put((float) fog.getFogColor().z); + vec4Buf.put(fog.getFogAlpha()); + vec4Buf.flip(); + GL20.glUniform4(program.locFogColor, vec4Buf); + } + } + + private void uploadVec4(int loc, Vector4f v) { + if (loc == -1) return; + vec4Buf.clear(); + vec4Buf.put(v.x); + vec4Buf.put(v.y); + vec4Buf.put(v.z); + vec4Buf.put(v.w); + vec4Buf.flip(); + GL20.glUniform4(loc, vec4Buf); + } + + public void destroy() { + memFree(mat4Buf); + memFree(mat3Buf); + memFree(vec4Buf); + memFree(vec3Buf); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java new file mode 100644 index 000000000..e15a0eb54 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexKey.java @@ -0,0 +1,188 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +import com.gtnewhorizons.angelica.glsm.DisplayListManager; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + +/** + * Compact key capturing the vertex shader permutation axes for FFP emulation. + * Packed into a single long for fast hash/compare. + */ +public final class VertexKey { + + private final long packed; + + private static final int BIT_LIGHTING = 0; + private static final int BIT_LIGHT0 = 1; + private static final int BIT_LIGHT1 = 2; + private static final int BIT_LIGHT0_DIR = 3; + private static final int BIT_LIGHT1_DIR = 4; + private static final int BIT_COLOR_MATERIAL = 5; + private static final int BIT_SEPARATE_SPECULAR = 6; + private static final int BIT_FOG = 7; + private static final int BIT_FOG_DIST_MODE = 8; + private static final int BIT_NORMALIZE = 10; + private static final int BIT_RESCALE_NORMAL = 11; + private static final int BIT_TEXTURE = 12; + private static final int BIT_LIGHTMAP = 13; + private static final int BIT_TEX_MATRIX = 14; + private static final int BIT_HAS_VERTEX_COLOR = 15; + private static final int BIT_HAS_VERTEX_NORMAL = 16; + private static final int BIT_HAS_VERTEX_TEX = 17; + private static final int BIT_HAS_VERTEX_LIGHTMAP = 18; + private static final int BIT_COLOR_MAT_MODE = 19; + + public static final int CM_AMBIENT = 0; + public static final int CM_DIFFUSE = 1; + public static final int CM_SPECULAR = 2; + public static final int CM_EMISSION = 3; + public static final int CM_AMBIENT_AND_DIFFUSE = 4; + + private VertexKey(long packed) { + this.packed = packed; + } + + public long pack() { return packed; } + + public boolean lightingEnabled() { return bit(BIT_LIGHTING); } + public boolean light0Enabled() { return bit(BIT_LIGHT0); } + public boolean light1Enabled() { return bit(BIT_LIGHT1); } + public boolean light0Directional() { return bit(BIT_LIGHT0_DIR); } + public boolean light1Directional() { return bit(BIT_LIGHT1_DIR); } + public boolean colorMaterialEnabled() { return bit(BIT_COLOR_MATERIAL); } + public boolean separateSpecular() { return bit(BIT_SEPARATE_SPECULAR); } + public boolean fogEnabled() { return bit(BIT_FOG); } + public int fogDistanceMode() { return (int)((packed >> BIT_FOG_DIST_MODE) & 0x3); } + public boolean normalizeEnabled() { return bit(BIT_NORMALIZE); } + public boolean rescaleNormalsEnabled() { return bit(BIT_RESCALE_NORMAL); } + public boolean textureEnabled() { return bit(BIT_TEXTURE); } + public boolean lightmapEnabled() { return bit(BIT_LIGHTMAP); } + public boolean textureMatrixEnabled() { return bit(BIT_TEX_MATRIX); } + public boolean hasVertexColor() { return bit(BIT_HAS_VERTEX_COLOR); } + public boolean hasVertexNormal() { return bit(BIT_HAS_VERTEX_NORMAL); } + public boolean hasVertexTexCoord() { return bit(BIT_HAS_VERTEX_TEX); } + public boolean hasVertexLightmap() { return bit(BIT_HAS_VERTEX_LIGHTMAP); } + /** Color material mode (CM_AMBIENT, CM_DIFFUSE, CM_SPECULAR, CM_EMISSION, CM_AMBIENT_AND_DIFFUSE). Only meaningful when colorMaterialEnabled(). */ + public int colorMaterialMode() { return (int)((packed >> BIT_COLOR_MAT_MODE) & 0x7); } + + /** Whether vertex color replaces material ambient in this variant. */ + public boolean cmReplacesAmbient() { final int m = colorMaterialMode(); return m == CM_AMBIENT || m == CM_AMBIENT_AND_DIFFUSE; } + /** Whether vertex color replaces material diffuse in this variant. */ + public boolean cmReplacesDiffuse() { final int m = colorMaterialMode(); return m == CM_DIFFUSE || m == CM_AMBIENT_AND_DIFFUSE; } + /** Whether vertex color replaces material specular in this variant. */ + public boolean cmReplacesSpecular() { return colorMaterialMode() == CM_SPECULAR; } + /** Whether vertex color replaces material emission in this variant. */ + public boolean cmReplacesEmission() { return colorMaterialMode() == CM_EMISSION; } + + private boolean bit(int pos) { return ((packed >> pos) & 1) != 0; } + + static int encodeColorMaterialMode(int glMode) { + return switch (glMode) { + case GL11.GL_AMBIENT -> CM_AMBIENT; + case GL11.GL_DIFFUSE -> CM_DIFFUSE; + case GL11.GL_SPECULAR -> CM_SPECULAR; + case GL11.GL_EMISSION -> CM_EMISSION; + case GL11.GL_AMBIENT_AND_DIFFUSE -> CM_AMBIENT_AND_DIFFUSE; + default -> CM_AMBIENT_AND_DIFFUSE; + }; + } + + public static long packFromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { + long bits = 0; + + final boolean lighting = GLStateManager.getLightingState().isEnabled(); + if (lighting) { + bits |= (1L << BIT_LIGHTING); + + if (GLStateManager.getLightStates()[0].isEnabled()) { + bits |= (1L << BIT_LIGHT0); + // position.w == 0 means directional + if (GLStateManager.getLightDataStates()[0].position.w == 0.0f) { + bits |= (1L << BIT_LIGHT0_DIR); + } + } + if (GLStateManager.getLightStates()[1].isEnabled()) { + bits |= (1L << BIT_LIGHT1); + if (GLStateManager.getLightDataStates()[1].position.w == 0.0f) { + bits |= (1L << BIT_LIGHT1_DIR); + } + } + + if (GLStateManager.getColorMaterial().isEnabled()) { + bits |= (1L << BIT_COLOR_MATERIAL); + final int cmMode = encodeColorMaterialMode(GLStateManager.getColorMaterialParameter().getValue()); + bits |= ((long) cmMode & 0x7) << BIT_COLOR_MAT_MODE; + } + + if (GLStateManager.getLightModel().colorControl == GL12.GL_SEPARATE_SPECULAR_COLOR) { + bits |= (1L << BIT_SEPARATE_SPECULAR); + } + } + + if (GLStateManager.getFogMode().isEnabled()) { + bits |= (1L << BIT_FOG); + final int fogDistMode = GLStateManager.getFogState().getFogDistanceMode(); + bits |= ((long) fogDistMode & 0x3) << BIT_FOG_DIST_MODE; + } + + if (GLStateManager.getNormalizeState().isEnabled()) { + bits |= (1L << BIT_NORMALIZE); + } + if (GLStateManager.getRescaleNormalState().isEnabled()) { + bits |= (1L << BIT_RESCALE_NORMAL); + } + + // Texture unit 0 (base texture) + if (GLStateManager.getTextures().getTextureUnitStates(0).isEnabled()) { + bits |= (1L << BIT_TEXTURE); + } + // Texture unit 1 (lightmap) + if (GLStateManager.getTextures().getTextureUnitStates(1).isEnabled()) { + bits |= (1L << BIT_LIGHTMAP); + } + + // Check if texture matrix unit 0 is non-identity + final Matrix4f texMat = GLStateManager.getTextures().getTextureUnitMatrix(0); + if (!DisplayListManager.isIdentity(texMat)) { + bits |= (1L << BIT_TEX_MATRIX); + } + + // Vertex format flags + if (hasColor) bits |= (1L << BIT_HAS_VERTEX_COLOR); + if (hasNormal) bits |= (1L << BIT_HAS_VERTEX_NORMAL); + if (hasTexCoord) bits |= (1L << BIT_HAS_VERTEX_TEX); + if (hasLightmap) bits |= (1L << BIT_HAS_VERTEX_LIGHTMAP); + + return bits; + } + + public static VertexKey fromState(boolean hasColor, boolean hasNormal, boolean hasTexCoord, boolean hasLightmap) { + return new VertexKey(packFromState(hasColor, hasNormal, hasTexCoord, hasLightmap)); + } + + static VertexKey fromPacked(long packed) { + return new VertexKey(packed); + } + + @Override + public int hashCode() { + return Long.hashCode(packed); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof VertexKey other)) return false; + return packed == other.packed; + } + + @Override + public String toString() { + return String.format("FFPVertexKey[0x%05X: lit=%b l0=%b l1=%b cm=%b fog=%b tex=%b lm=%b col=%b nrm=%b vtex=%b vlm=%b]", + packed, lightingEnabled(), light0Enabled(), light1Enabled(), + colorMaterialEnabled(), fogEnabled(), textureEnabled(), lightmapEnabled(), + hasVertexColor(), hasVertexNormal(), hasVertexTexCoord(), hasVertexLightmap()); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java new file mode 100644 index 000000000..9c1db0b4e --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/ffp/VertexShaderGenerator.java @@ -0,0 +1,350 @@ +package com.gtnewhorizons.angelica.glsm.ffp; + +/** + * Generates GLSL 330 core vertex shaders for FFP emulation. + * Follows Mesa's ffvertex_prog.c build order. + * + * Attribute locations + * 0 = a_Position (vec3) + * 1 = a_Color (vec4, ubyte4 normalized) + * 2 = a_TexCoord0 (vec2) + * 3 = a_TexCoord1 (vec2, lightmap) + * 4 = a_Normal (vec3, byte3 normalized) + */ +public final class VertexShaderGenerator { + + private VertexShaderGenerator() {} + + public static String generate(VertexKey key) { + final StringBuilder sb = new StringBuilder(2048); + sb.append("#version 330 core\n\n"); + + emitAttributes(sb, key); + emitUniforms(sb, key); + emitOutputs(sb, key); + + sb.append("void main() {\n"); + emitPositionTransform(sb, key); + if (key.lightingEnabled()) { + emitNormalTransform(sb, key); + emitLighting(sb, key); + } else { + emitColorPassthrough(sb, key); + } + emitTexCoordPassthrough(sb, key); + if (key.fogEnabled()) { + emitFogDistance(sb, key); + } + sb.append("}\n"); + + return sb.toString(); + } + + private static void emitAttributes(StringBuilder sb, VertexKey key) { + sb.append("// Vertex attributes\n"); + sb.append("layout(location = 0) in vec3 a_Position;\n"); + if (key.hasVertexColor()) { + sb.append("layout(location = 1) in vec4 a_Color;\n"); + } + if (key.hasVertexTexCoord()) { + sb.append("layout(location = 2) in vec2 a_TexCoord0;\n"); + } + if (key.hasVertexLightmap()) { + sb.append("layout(location = 3) in vec2 a_TexCoord1;\n"); + } + if (key.hasVertexNormal()) { + sb.append("layout(location = 4) in vec3 a_Normal;\n"); + } + sb.append('\n'); + } + + private static void emitUniforms(StringBuilder sb, VertexKey key) { + sb.append("// Matrices\n"); + sb.append("uniform mat4 u_ModelViewMatrix;\n"); + sb.append("uniform mat4 u_ProjectionMatrix;\n"); + sb.append("uniform mat4 u_MVPMatrix;\n"); + + if (key.lightingEnabled()) { + sb.append("uniform mat3 u_NormalMatrix;\n"); + } + + if (key.textureMatrixEnabled()) { + sb.append("uniform mat4 u_TextureMatrix0;\n"); + } + + if (!key.hasVertexNormal() && key.lightingEnabled()) { + sb.append("uniform vec3 u_CurrentNormal;\n"); + } + + if (!key.hasVertexColor()) { + sb.append("uniform vec4 u_CurrentColor;\n"); + } + + if (!key.hasVertexTexCoord() && key.textureEnabled()) { + sb.append("uniform vec4 u_CurrentTexCoord;\n"); + } + + if (key.lightmapEnabled() && !key.hasVertexLightmap()) { + sb.append("uniform vec2 u_CurrentLightmapCoord;\n"); + } + + if (key.lightmapEnabled()) { + sb.append("uniform mat4 u_LightmapTextureMatrix;\n"); + } + + if (key.lightingEnabled()) { + emitLightingUniforms(sb, key); + } + + if (key.lightingEnabled() && (key.normalizeEnabled() || key.rescaleNormalsEnabled())) { + // normalize is done in shader; rescale uses normalScale + if (key.rescaleNormalsEnabled() && !key.normalizeEnabled()) { + sb.append("uniform float u_NormalScale;\n"); + } + } + + sb.append('\n'); + } + + private static void emitLightingUniforms(StringBuilder sb, VertexKey key) { + sb.append("\n// Lighting\n"); + + if (key.colorMaterialEnabled()) { + // When color material is active, we can't pre-compute light products so we upload raw light and material values + sb.append("uniform vec4 u_LightModelAmbient;\n"); + sb.append("uniform vec4 u_MaterialEmission;\n"); + sb.append("uniform vec4 u_MaterialAmbient;\n"); + sb.append("uniform vec4 u_MaterialDiffuse;\n"); + sb.append("uniform vec4 u_MaterialSpecular;\n"); + sb.append("uniform float u_MaterialShininess;\n"); + + if (key.light0Enabled()) { + sb.append("uniform vec4 u_Light0Ambient;\n"); + sb.append("uniform vec4 u_Light0Diffuse;\n"); + sb.append("uniform vec4 u_Light0Specular;\n"); + sb.append("uniform vec4 u_Light0Position;\n"); + } + if (key.light1Enabled()) { + sb.append("uniform vec4 u_Light1Ambient;\n"); + sb.append("uniform vec4 u_Light1Diffuse;\n"); + sb.append("uniform vec4 u_Light1Specular;\n"); + sb.append("uniform vec4 u_Light1Position;\n"); + } + } else { + // Pre-computed: sceneColor + lightProducts + sb.append("uniform vec4 u_SceneColor;\n"); + + if (key.light0Enabled()) { + sb.append("uniform vec4 u_Light0Position;\n"); + sb.append("uniform vec3 u_LightProd0Ambient;\n"); + sb.append("uniform vec3 u_LightProd0Diffuse;\n"); + sb.append("uniform vec3 u_LightProd0Specular;\n"); + } + if (key.light1Enabled()) { + sb.append("uniform vec4 u_Light1Position;\n"); + sb.append("uniform vec3 u_LightProd1Ambient;\n"); + sb.append("uniform vec3 u_LightProd1Diffuse;\n"); + sb.append("uniform vec3 u_LightProd1Specular;\n"); + } + sb.append("uniform float u_MaterialShininess;\n"); + } + } + + private static void emitOutputs(StringBuilder sb, VertexKey key) { + sb.append("// Outputs\n"); + sb.append("out vec4 v_Color;\n"); + if (key.separateSpecular()) { + sb.append("out vec3 v_SpecularColor;\n"); + } + if (key.textureEnabled() || key.hasVertexTexCoord()) { + sb.append("out vec2 v_TexCoord0;\n"); + } + if (key.lightmapEnabled()) { + sb.append("out vec2 v_TexCoord1;\n"); + } + if (key.fogEnabled()) { + sb.append("out float v_FogCoord;\n"); + } + sb.append('\n'); + } + + private static void emitPositionTransform(StringBuilder sb, VertexKey key) { + sb.append(" // Position transform\n"); + sb.append(" vec4 pos4 = vec4(a_Position, 1.0);\n"); + sb.append(" gl_Position = u_MVPMatrix * pos4;\n"); + + // Eye position needed for lighting and fog + if (key.lightingEnabled() || key.fogEnabled()) { + sb.append(" vec4 eyePos = u_ModelViewMatrix * pos4;\n"); + } + sb.append('\n'); + } + + private static void emitNormalTransform(StringBuilder sb, VertexKey key) { + sb.append(" // Normal transform\n"); + if (key.hasVertexNormal()) { + sb.append(" vec3 normal = u_NormalMatrix * a_Normal;\n"); + } else { + sb.append(" vec3 normal = u_NormalMatrix * u_CurrentNormal;\n"); + } + + if (key.normalizeEnabled()) { + sb.append(" normal = normalize(normal);\n"); + } else if (key.rescaleNormalsEnabled()) { + sb.append(" normal *= u_NormalScale;\n"); + } + sb.append('\n'); + } + + private static void emitLighting(StringBuilder sb, VertexKey key) { + sb.append(" // Gouraud lighting\n"); + + if (key.colorMaterialEnabled()) { + // Color material: vertex color replaces specific material properties per glColorMaterial mode (Mesa ffvertex_prog.c get_material() bitmask approach) + sb.append(" vec4 matColor = "); + sb.append(key.hasVertexColor() ? "a_Color" : "u_CurrentColor"); + sb.append(";\n"); + + // Emission source: vertex color for CM_EMISSION, else material uniform + final String emSrc = key.cmReplacesEmission() ? "matColor.rgb" : "u_MaterialEmission.rgb"; + // Ambient source for scene color: vertex color for CM_AMBIENT / CM_AMBIENT_AND_DIFFUSE + final String amSrc = key.cmReplacesAmbient() ? "matColor.rgb" : "u_MaterialAmbient.rgb"; + sb.append(" vec3 sceneColor = ").append(emSrc).append(" + ").append(amSrc).append(" * u_LightModelAmbient.rgb;\n"); + + // Alpha from diffuse source (per GL spec) + sb.append(" float outAlpha = ").append(key.cmReplacesDiffuse() ? "matColor.a" : "u_MaterialDiffuse.a").append(";\n"); + } else { + // Pre-computed scene color + sb.append(" vec3 sceneColor = u_SceneColor.rgb;\n"); + sb.append(" float outAlpha = u_SceneColor.a;\n"); + } + + sb.append(" vec3 color0 = sceneColor;\n"); + if (key.separateSpecular()) { + sb.append(" vec3 specAccum = vec3(0.0);\n"); + } + + // Per-light accumulation + if (key.light0Enabled()) { + emitLightContribution(sb, key, 0); + } + if (key.light1Enabled()) { + emitLightContribution(sb, key, 1); + } + + sb.append(" v_Color = vec4(clamp(color0, 0.0, 1.0), outAlpha);\n"); + if (key.separateSpecular()) { + sb.append(" v_SpecularColor = clamp(specAccum, 0.0, 1.0);\n"); + } + sb.append('\n'); + } + + private static void emitLightContribution(StringBuilder sb, VertexKey key, int lightIndex) { + final String li = String.valueOf(lightIndex); + final boolean directional = (lightIndex == 0) ? key.light0Directional() : key.light1Directional(); + final String posUniform = "u_Light" + li + "Position"; + + sb.append(" { // Light ").append(li).append('\n'); + + // Light vector + if (directional) { + // Directional: position is already normalized direction + sb.append(" vec3 VPpli = normalize(").append(posUniform).append(".xyz);\n"); + } else { + // Positional light + sb.append(" vec3 VPpli = ").append(posUniform).append(".xyz - eyePos.xyz;\n"); + sb.append(" VPpli = normalize(VPpli);\n"); + } + + // Dot products + sb.append(" float NdotVP = max(dot(normal, VPpli), 0.0);\n"); + + // Half vector for specular (infinite viewer: H = normalize(L + (0,0,1))) + sb.append(" vec3 halfVec = normalize(VPpli + vec3(0.0, 0.0, 1.0));\n"); + sb.append(" float NdotHV = max(dot(normal, halfVec), 0.0);\n"); + + // Specular power + sb.append(" float spec = (NdotVP > 0.0 && u_MaterialShininess > 0.0) ? pow(NdotHV, u_MaterialShininess) : 0.0;\n"); + + // Accumulate — per-property source depends on color material mode + if (key.colorMaterialEnabled()) { + final String ambU = "u_Light" + li + "Ambient"; + final String difU = "u_Light" + li + "Diffuse"; + final String speU = "u_Light" + li + "Specular"; + // Ambient product: light.ambient * (vertex color or material) + final String ambMat = key.cmReplacesAmbient() ? "matColor.rgb" : "u_MaterialAmbient.rgb"; + sb.append(" vec3 ambient = ").append(ambU).append(".rgb * ").append(ambMat).append(";\n"); + // Diffuse product + final String difMat = key.cmReplacesDiffuse() ? "matColor.rgb" : "u_MaterialDiffuse.rgb"; + sb.append(" vec3 diffuse = ").append(difU).append(".rgb * ").append(difMat).append(";\n"); + // Specular product + final String speMat = key.cmReplacesSpecular() ? "matColor.rgb" : "u_MaterialSpecular.rgb"; + sb.append(" vec3 specular = ").append(speU).append(".rgb * ").append(speMat).append(";\n"); + } else { + sb.append(" vec3 ambient = u_LightProd").append(li).append("Ambient;\n"); + sb.append(" vec3 diffuse = u_LightProd").append(li).append("Diffuse;\n"); + sb.append(" vec3 specular = u_LightProd").append(li).append("Specular;\n"); + } + + sb.append(" color0 += ambient + NdotVP * diffuse;\n"); + if (key.separateSpecular()) { + sb.append(" specAccum += spec * specular;\n"); + } else { + sb.append(" color0 += spec * specular;\n"); + } + + sb.append(" }\n"); + } + + private static void emitColorPassthrough(StringBuilder sb, VertexKey key) { + sb.append(" // Color passthrough (no lighting)\n"); + if (key.hasVertexColor()) { + sb.append(" v_Color = a_Color;\n"); + } else { + sb.append(" v_Color = u_CurrentColor;\n"); + } + sb.append('\n'); + } + + private static void emitTexCoordPassthrough(StringBuilder sb, VertexKey key) { + if (key.textureEnabled() || key.hasVertexTexCoord()) { + sb.append(" // Texture coordinates\n"); + if (key.hasVertexTexCoord()) { + if (key.textureMatrixEnabled()) { + sb.append(" v_TexCoord0 = (u_TextureMatrix0 * vec4(a_TexCoord0, 0.0, 1.0)).st;\n"); + } else { + sb.append(" v_TexCoord0 = a_TexCoord0;\n"); + } + } else { + if (key.textureMatrixEnabled()) { + sb.append(" v_TexCoord0 = (u_TextureMatrix0 * u_CurrentTexCoord).st;\n"); + } else { + sb.append(" v_TexCoord0 = u_CurrentTexCoord.st;\n"); + } + } + } + if (key.lightmapEnabled()) { + if (key.hasVertexLightmap()) { + sb.append(" v_TexCoord1 = (u_LightmapTextureMatrix * vec4(a_TexCoord1, 0.0, 1.0)).st;\n"); + } else { + sb.append(" v_TexCoord1 = (u_LightmapTextureMatrix * vec4(u_CurrentLightmapCoord, 0.0, 1.0)).st;\n"); + } + } + } + + private static void emitFogDistance(StringBuilder sb, VertexKey key) { + sb.append(" // Fog distance\n"); + // Mesa ffvertex_prog.c build_fog(): FDM_EYE_RADIAL/EYE_PLANE/EYE_PLANE_ABS + final int fogDistMode = key.fogDistanceMode(); + switch (fogDistMode) { + case 0 -> // FDM_EYE_RADIAL: Euclidean distance + sb.append(" v_FogCoord = length(eyePos.xyz);\n"); + case 1 -> // FDM_EYE_PLANE: raw Z (can be negative, clamped by fog factor) + sb.append(" v_FogCoord = eyePos.z;\n"); + case 2 -> // FDM_EYE_PLANE_ABS: absolute Z + sb.append(" v_FogCoord = abs(eyePos.z);\n"); + default -> + sb.append(" v_FogCoord = abs(eyePos.z);\n"); + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java index 87a539641..343501b78 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBO.java @@ -1,8 +1,7 @@ package com.gtnewhorizons.angelica.glsm.recording; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; -import org.lwjgl.opengl.GL15; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; /** * A class that stores multiple vertex formats & their corresponding buffers. @@ -35,12 +34,14 @@ public final class DisplayListVBO { private final int drawMode; private final int start; private final int count; + private final int vertexFlags; - public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count) { + public SubVBO(IVertexArrayObject vao, int drawMode, int start, int count, int vertexFlags) { this.vao = vao; this.drawMode = drawMode; this.start = start; this.count = count; + this.vertexFlags = vertexFlags; } public void delete() { @@ -48,6 +49,7 @@ public final class DisplayListVBO { } public void render() { + ShaderManager.getInstance().preDraw(vertexFlags); vao.bind(); vao.draw(drawMode, start, count); vao.unbind(); diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java index b30cacdbe..85688ec82 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/DisplayListVBOBuilder.java @@ -14,7 +14,11 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.*; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAddress0; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memAlloc; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memCopy; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.memFree; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities.nmemFree; /** * Compiles multiple ByteBuffers of the same Vertex format into a VBO. Any buffer added to the builder will be freed afterward. @@ -69,10 +73,10 @@ public final class DisplayListVBOBuilder { vertexCount = format.getVertexCount(size); } if (data.drawMode == GL11.GL_QUADS) { - IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount)); - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6); + final IVertexArrayObject indexedVAO = new IndexedVAO(vbo, IndexBuffer.convertQuadsToTrigs(start, start + vertexCount)); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(indexedVAO, GL11.GL_TRIANGLES, 0, vertexCount / 4 * 6, i); } else { - vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount); + vbos[data.drawIndex] = new DisplayListVBO.SubVBO(vao, data.drawMode, start, vertexCount, i); } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java index fb9bf85c1..ebd9297e7 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/recording/ImmediateModeRecorder.java @@ -4,8 +4,6 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.ClientArrayState; -import net.minecraft.client.renderer.Tessellator; -import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import java.nio.Buffer; @@ -16,28 +14,49 @@ import java.nio.IntBuffer; import java.nio.ShortBuffer; /** - * Records immediate mode GL calls (glBegin/glEnd/glVertex) during display list compilation. - * Converts immediate mode geometry to ByteBuffer directly via {@link DirectTessellator} - *

- * Currently only used for display list compilation, should be perfectly usable outside of display lists too though. + * Records immediate mode GL calls (glBegin/glEnd/glVertex) via {@link DirectTessellator}. + * Used both during display list compilation and for live immediate mode emulation in core profile. */ public final class ImmediateModeRecorder { private static final DirectTessellator tessellator = new DirectTessellator(TessellatorManager.DEFAULT_BUFFER_SIZE); + /** Separate tessellator for the splash thread. Nulled after splash completes. */ + private static DirectTessellator splashTessellator; + private ImmediateModeRecorder() { } - public static DirectTessellator getInternalTessellator() { + public static void initSplashTessellator() { + splashTessellator = new DirectTessellator(TessellatorManager.DEFAULT_BUFFER_SIZE); + } + + public static void destroySplashTessellator() { + splashTessellator = null; + } + + private static DirectTessellator tessellator() { + final DirectTessellator splash = splashTessellator; + if (splash != null && Thread.currentThread() != GLStateManager.getMainThread()) { + return splash; + } return tessellator; } + public static DirectTessellator getInternalTessellator() { + return tessellator(); + } + + public static boolean isDrawing() { + return tessellator().isDrawing; + } + /** * Set the current texture coordinate. * Called by GLStateManager.glTexCoord*. */ public static void setTexCoord(float s, float t) { - tessellator.setTextureUV(s, t); + tessellator().setTextureUV(s, t); } /** @@ -45,14 +64,39 @@ public final class ImmediateModeRecorder { * Called by GLStateManager.glNormal*. */ public static void setNormal(float x, float y, float z) { - tessellator.setNormal(x, y, z); + tessellator().setNormal(x, y, z); + } + + /** + * Set the current color on the internal tessellator. + * Called by GLStateManager.glColor* when inside a glBegin/glEnd block. + */ + public static void setColor(float r, float g, float b, float a) { + tessellator().setColorRGBA((int) (r * 255.0f), (int) (g * 255.0f), (int) (b * 255.0f), (int) (a * 255.0f)); } /** * Start recording a new primitive. + * Resets the tessellator to clear any data from the previous draw. + * + * @param primitiveType GL primitive type (GL_QUADS, GL_TRIANGLES, etc.) */ public static void begin(int primitiveType) { - tessellator.startDrawing(primitiveType); + final DirectTessellator t = tessellator(); + t.reset(); + t.startDrawing(primitiveType); + } + + /** + * Start recording a new primitive with initial color sync from GLSM cache. + * Used for live immediate mode emulation only (not display list recording). + */ + public static void beginLive(int primitiveType) { + final DirectTessellator t = tessellator(); + t.reset(); + t.startDrawing(primitiveType); + final var c = GLStateManager.getColor(); + t.setColorRGBA((int) (c.getRed() * 255.0f), (int) (c.getGreen() * 255.0f), (int) (c.getBlue() * 255.0f), (int) (c.getAlpha() * 255.0f)); } /** @@ -62,15 +106,16 @@ public final class ImmediateModeRecorder { * @return Result containing quads, lines, and flags, or null if no geometry was produced */ public static DirectTessellator end() { - if (!tessellator.isDrawing) { + final DirectTessellator t = tessellator(); + if (!t.isDrawing) { throw new IllegalStateException("glEnd called without glBegin"); } - tessellator.isDrawing = false; + t.isDrawing = false; - if (tessellator.isEmpty()) return null; + if (t.isEmpty()) return null; - return tessellator; + return t; } /** @@ -78,10 +123,11 @@ public final class ImmediateModeRecorder { * Color is read from GLStateManager at call time. */ public static void vertex(float x, float y, float z) { - if (!tessellator.isDrawing) { + final DirectTessellator t = tessellator(); + if (!t.isDrawing) { throw new IllegalStateException("glVertex called outside glBegin/glEnd"); } - tessellator.addVertex(x, y, z); + t.addVertex(x, y, z); } /** @@ -92,7 +138,7 @@ public final class ImmediateModeRecorder { * where primitives might fail to convert (e.g., incomplete quads). */ public static boolean hasGeometry() { - return tessellator.vertexCount != 0; + return tessellator().vertexCount != 0; } /** @@ -100,7 +146,7 @@ public final class ImmediateModeRecorder { * Called when starting a new display list. */ public static void reset() { - tessellator.reset(); + tessellator().reset(); } /** @@ -116,13 +162,19 @@ public final class ImmediateModeRecorder { final ClientArrayState cas = GLStateManager.getClientArrayState(); final Buffer vertexPointer = cas.isVertexArrayEnabled() ? cas.getVertexPointer() : null; final Buffer colorPointer = cas.isColorArrayEnabled() ? cas.getColorPointer() : null; + final Buffer normalPointer = cas.isNormalArrayEnabled() ? cas.getNormalPointer() : null; + final Buffer texCoordPointer = cas.isTexCoordArrayEnabled() ? cas.getTexCoordPointer() : null; return convertClientArrays( mode, first, count, vertexPointer, cas.getVertexPointerType(), cas.getVertexPointerSize(), cas.getVertexPointerStride(), colorPointer, - cas.getColorPointerType(), cas.getColorPointerSize(), cas.getColorPointerStride() + cas.getColorPointerType(), cas.getColorPointerSize(), cas.getColorPointerStride(), + normalPointer, + cas.getNormalPointerType(), cas.getNormalPointerStride(), + texCoordPointer, + cas.getTexCoordPointerType(), cas.getTexCoordPointerSize(), cas.getTexCoordPointerStride() ); } @@ -130,33 +182,23 @@ public final class ImmediateModeRecorder { * Convert client array data to immediate mode. * Called by glDrawArrays during display list recording. * Like Mesa's save_DrawArrays, reads vertex data from arrays and emits as immediate mode. - * - * @param mode Primitive type (GL_QUADS, GL_LINES, etc.) - * @param first Starting index in arrays - * @param count Number of vertices - * @param vertexPointer Vertex position buffer (or null if not enabled) - * @param vertexType GL type (GL_FLOAT, GL_DOUBLE, etc.) - * @param vertexSize Size of vertex (2, 3, or 4) - * @param vertexStride Stride in bytes (0 for tightly packed) - * @param colorPointer Color buffer (or null if not enabled) - * @param colorType GL type (GL_FLOAT, GL_UNSIGNED_BYTE, etc.) - * @param colorSize Size of color (3 or 4) - * @param colorStride Stride in bytes (0 for tightly packed) - * @return Result containing converted geometry, or null if no geometry produced */ public static DirectTessellator convertClientArrays( int mode, int first, int count, java.nio.Buffer vertexPointer, int vertexType, int vertexSize, int vertexStride, - java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride + java.nio.Buffer colorPointer, int colorType, int colorSize, int colorStride, + java.nio.Buffer normalPointer, int normalType, int normalStride, + java.nio.Buffer texCoordPointer, int texCoordType, int texCoordSize, int texCoordStride ) { begin(mode); + final DirectTessellator t = tessellator(); // Hoist type checks and stride calculations outside the loop for performance. // Mesa's algorithm: offset_bytes = index * effective_stride // effective_stride = (stride == 0) ? (numComponents * sizeof(element)) : stride - // Determine color reader (hoisted out of loop) - final ColorReader colorReader; + // Determine color reader + final ArrayReader colorReader; if (colorPointer == null) { colorReader = null; } else if (colorType == GL11.GL_FLOAT && colorPointer instanceof FloatBuffer fb) { @@ -185,8 +227,46 @@ public final class ImmediateModeRecorder { colorReader = (idx) -> GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); } - // Determine vertex reader (hoisted out of loop) - final VertexReader vertexReader; + // Determine normal reader + final ArrayReader normalReader; + if (normalPointer == null) { + normalReader = null; + } else if (normalType == GL11.GL_FLOAT && normalPointer instanceof FloatBuffer fb) { + final int effectiveStride = (normalStride == 0) ? 3 * 4 : normalStride; + final int strideInFloats = effectiveStride / 4; + normalReader = (idx) -> { + final int offset = idx * strideInFloats; + setNormal(fb.get(offset), fb.get(offset + 1), fb.get(offset + 2)); + }; + } else if (normalType == GL11.GL_BYTE && normalPointer instanceof ByteBuffer bb) { + final int effectiveStride = (normalStride == 0) ? 3 : normalStride; + normalReader = (idx) -> { + final int offset = idx * effectiveStride; + setNormal(bb.get(offset) / 127.0f, bb.get(offset + 1) / 127.0f, bb.get(offset + 2) / 127.0f); + }; + } else { + normalReader = null; + } + + // Determine texcoord reader + final ArrayReader texCoordReader; + if (texCoordPointer == null) { + texCoordReader = null; + } else if (texCoordType == GL11.GL_FLOAT && texCoordPointer instanceof FloatBuffer fb) { + final int effectiveStride = (texCoordStride == 0) ? texCoordSize * 4 : texCoordStride; + final int strideInFloats = effectiveStride / 4; + texCoordReader = (idx) -> { + final int offset = idx * strideInFloats; + final float s = fb.get(offset); + final float tt = (texCoordSize >= 2) ? fb.get(offset + 1) : 0.0f; + setTexCoord(s, tt); + }; + } else { + texCoordReader = null; + } + + // Determine vertex reader + final ArrayReader vertexReader; if (vertexPointer == null) { vertexReader = null; } else if (vertexType == GL11.GL_FLOAT && vertexPointer instanceof FloatBuffer fb) { @@ -197,7 +277,7 @@ public final class ImmediateModeRecorder { final float x = fb.get(offset); final float y = fb.get(offset + 1); final float z = (vertexSize >= 3) ? fb.get(offset + 2) : 0.0f; - vertex(x, y, z); + t.addVertex(x, y, z); }; } else if (vertexType == GL11.GL_DOUBLE && vertexPointer instanceof DoubleBuffer db) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 8 : vertexStride; @@ -207,7 +287,7 @@ public final class ImmediateModeRecorder { final float x = (float) db.get(offset); final float y = (float) db.get(offset + 1); final float z = (vertexSize >= 3) ? (float) db.get(offset + 2) : 0.0f; - vertex(x, y, z); + t.addVertex(x, y, z); }; } else if (vertexType == GL11.GL_INT && vertexPointer instanceof IntBuffer ib) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 4 : vertexStride; @@ -217,7 +297,7 @@ public final class ImmediateModeRecorder { final float x = ib.get(offset); final float y = ib.get(offset + 1); final float z = (vertexSize >= 3) ? ib.get(offset + 2) : 0.0f; - vertex(x, y, z); + t.addVertex(x, y, z); }; } else if (vertexType == GL11.GL_SHORT && vertexPointer instanceof ShortBuffer sb) { final int effectiveStride = (vertexStride == 0) ? vertexSize * 2 : vertexStride; @@ -227,7 +307,7 @@ public final class ImmediateModeRecorder { final float x = sb.get(offset); final float y = sb.get(offset + 1); final float z = (vertexSize >= 3) ? sb.get(offset + 2) : 0.0f; - vertex(x, y, z); + t.addVertex(x, y, z); }; } else { // Unsupported vertex type @@ -236,6 +316,12 @@ public final class ImmediateModeRecorder { // Main loop - no type checks, just function calls for (int i = first; i < first + count; i++) { + if (normalReader != null) { + normalReader.read(i); + } + if (texCoordReader != null) { + texCoordReader.read(i); + } if (colorReader != null) { colorReader.read(i); } @@ -247,15 +333,8 @@ public final class ImmediateModeRecorder { return end(); } - - @FunctionalInterface - private interface ColorReader { - void read(int index); - } - - @FunctionalInterface - private interface VertexReader { + private interface ArrayReader { void read(int index); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BooleanStateStack.java b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BooleanStateStack.java index aca76cfcc..9b28122ba 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BooleanStateStack.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/BooleanStateStack.java @@ -22,8 +22,7 @@ public class BooleanStateStack extends BooleanState implements IStateStack { + + private final Vector3f value; + private final float[][] stack; + private int pointer; + + public Vec3fStack(Vector3f value) { + this.value = value; + stack = new float[GLStateManager.MAX_ATTRIB_STACK_DEPTH][3]; + } + + @Override + public Vec3fStack push() { + if (pointer == stack.length) { + throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); + } + stack[pointer][0] = value.x; + stack[pointer][1] = value.y; + stack[pointer][2] = value.z; + pointer++; + return this; + } + + @Override + public Vec3fStack pop() { + if (pointer == 0) { + throw new IllegalStateException("Stack underflow"); + } + pointer--; + value.set(stack[pointer][0], stack[pointer][1], stack[pointer][2]); + return this; + } + + @Override + public boolean isEmpty() { + return pointer == 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Vec4fStack.java b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Vec4fStack.java new file mode 100644 index 000000000..e7fbca872 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/stacks/Vec4fStack.java @@ -0,0 +1,48 @@ +package com.gtnewhorizons.angelica.glsm.stacks; + +import com.gtnewhorizon.gtnhlib.client.renderer.stacks.IStateStack; +import com.gtnewhorizons.angelica.glsm.GLStateManager; +import org.joml.Vector4f; + +/** + * Stack for a Vector4f value (e.g. current texture coordinates). + */ +public class Vec4fStack implements IStateStack { + + private final Vector4f value; + private final float[][] stack; + private int pointer; + + public Vec4fStack(Vector4f value) { + this.value = value; + stack = new float[GLStateManager.MAX_ATTRIB_STACK_DEPTH][4]; + } + + @Override + public Vec4fStack push() { + if (pointer == stack.length) { + throw new IllegalStateException("Stack overflow size " + (pointer + 1) + " reached"); + } + stack[pointer][0] = value.x; + stack[pointer][1] = value.y; + stack[pointer][2] = value.z; + stack[pointer][3] = value.w; + pointer++; + return this; + } + + @Override + public Vec4fStack pop() { + if (pointer == 0) { + throw new IllegalStateException("Stack underflow"); + } + pointer--; + value.set(stack[pointer][0], stack[pointer][1], stack[pointer][2], stack[pointer][3]); + return this; + } + + @Override + public boolean isEmpty() { + return pointer == 0; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaState.java index a7bf4679a..923e96619 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/AlphaState.java @@ -7,7 +7,7 @@ import org.lwjgl.opengl.GL11; @Getter public class AlphaState implements ISettableState { @Setter protected int function = GL11.GL_ALWAYS; - @Setter protected float reference = -1.0F; + @Setter protected float reference = 0.0F; @Override public AlphaState set(AlphaState state) { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BlendState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BlendState.java index fc6a88db9..c66ad7a1e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BlendState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BlendState.java @@ -3,6 +3,7 @@ package com.gtnewhorizons.angelica.glsm.states; import lombok.Getter; import lombok.Setter; import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL14; @Getter @Setter @@ -11,6 +12,12 @@ public class BlendState implements ISettableState { protected int dstRgb = GL11.GL_ZERO; protected int srcAlpha = GL11.GL_ONE; protected int dstAlpha = GL11.GL_ZERO; + protected int equationRgb = GL14.GL_FUNC_ADD; + protected int equationAlpha = GL14.GL_FUNC_ADD; + protected float blendColorR = 0.0f; + protected float blendColorG = 0.0f; + protected float blendColorB = 0.0f; + protected float blendColorA = 0.0f; public BlendState() {} @@ -39,6 +46,12 @@ public class BlendState implements ISettableState { this.dstRgb = state.dstRgb; this.srcAlpha = state.srcAlpha; this.dstAlpha = state.dstAlpha; + this.equationRgb = state.equationRgb; + this.equationAlpha = state.equationAlpha; + this.blendColorR = state.blendColorR; + this.blendColorG = state.blendColorG; + this.blendColorB = state.blendColorB; + this.blendColorA = state.blendColorA; return this; } @@ -46,7 +59,13 @@ public class BlendState implements ISettableState { public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof BlendState blendState)) return false; - return srcRgb == blendState.srcRgb && dstRgb == blendState.dstRgb && srcAlpha == blendState.srcAlpha && dstAlpha == blendState.dstAlpha; + return srcRgb == blendState.srcRgb && dstRgb == blendState.dstRgb + && srcAlpha == blendState.srcAlpha && dstAlpha == blendState.dstAlpha + && equationRgb == blendState.equationRgb && equationAlpha == blendState.equationAlpha + && Float.compare(blendColorR, blendState.blendColorR) == 0 + && Float.compare(blendColorG, blendState.blendColorG) == 0 + && Float.compare(blendColorB, blendState.blendColorB) == 0 + && Float.compare(blendColorA, blendState.blendColorA) == 0; } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java index 2a80c1884..1f8a6fda0 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/BooleanState.java @@ -6,12 +6,18 @@ import org.lwjgl.opengl.GL11; public class BooleanState implements ISettableState { protected final int glCap; + protected final boolean ffpStateOnly; @Getter protected boolean enabled; protected boolean stateUnknown; public BooleanState(int glCap) { + this(glCap, false); + } + + public BooleanState(int glCap, boolean ffpStateOnly) { this.glCap = glCap; + this.ffpStateOnly = ffpStateOnly; } public void setUnknownState() { @@ -33,11 +39,12 @@ public class BooleanState implements ISettableState { if (!bypass) { this.enabled = enabled; } - // Always call GL - the calling method controls whether we reach here based on recording mode - if (enabled) { - GL11.glEnable(this.glCap); - } else { - GL11.glDisable(this.glCap); + if (!ffpStateOnly) { + if (enabled) { + GL11.glEnable(this.glCap); + } else { + GL11.glDisable(this.glCap); + } } } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java index 10cb8b397..b9b11c9d7 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ClientArrayState.java @@ -60,6 +60,19 @@ public class ClientArrayState { return vertexPointerStride; } + // Normal array state + private boolean normalArrayEnabled = false; + private Buffer normalPointer = null; + private int normalPointerType = GL11.GL_FLOAT; + private int normalPointerStride = 0; + + // TexCoord array state + private boolean texCoordArrayEnabled = false; + private Buffer texCoordPointer = null; + private int texCoordPointerSize = 4; + private int texCoordPointerType = GL11.GL_FLOAT; + private int texCoordPointerStride = 0; + // Color array methods public void setColorPointer(int size, int type, int stride, Buffer pointer) { this.colorPointerSize = size; @@ -91,4 +104,63 @@ public class ClientArrayState { public int getColorPointerStride() { return colorPointerStride; } + + // Normal array methods + public void setNormalPointer(int type, int stride, Buffer pointer) { + this.normalPointerType = type; + this.normalPointerStride = stride; + this.normalPointer = pointer; + } + + public boolean isNormalArrayEnabled() { + return normalArrayEnabled; + } + + public void setNormalArrayEnabled(boolean enabled) { + this.normalArrayEnabled = enabled; + } + + public Buffer getNormalPointer() { + return normalPointer; + } + + public int getNormalPointerType() { + return normalPointerType; + } + + public int getNormalPointerStride() { + return normalPointerStride; + } + + // TexCoord array methods + public void setTexCoordPointer(int size, int type, int stride, Buffer pointer) { + this.texCoordPointerSize = size; + this.texCoordPointerType = type; + this.texCoordPointerStride = stride; + this.texCoordPointer = pointer; + } + + public boolean isTexCoordArrayEnabled() { + return texCoordArrayEnabled; + } + + public void setTexCoordArrayEnabled(boolean enabled) { + this.texCoordArrayEnabled = enabled; + } + + public Buffer getTexCoordPointer() { + return texCoordPointer; + } + + public int getTexCoordPointerSize() { + return texCoordPointerSize; + } + + public int getTexCoordPointerType() { + return texCoordPointerType; + } + + public int getTexCoordPointerStride() { + return texCoordPointerStride; + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/DepthState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/DepthState.java index c83a4c495..b8521986b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/DepthState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/DepthState.java @@ -8,11 +8,13 @@ import org.lwjgl.opengl.GL11; public class DepthState implements ISettableState { protected boolean enabled = true; protected int func = GL11.GL_LESS; + protected double clearValue = 1.0; @Override public DepthState set(DepthState state) { this.enabled = state.enabled; this.func = state.func; + this.clearValue = state.clearValue; return this; } @@ -20,7 +22,7 @@ public class DepthState implements ISettableState { public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof DepthState depthState)) return false; - return enabled == depthState.enabled && func == depthState.func; + return enabled == depthState.enabled && func == depthState.func && Double.compare(clearValue, depthState.clearValue) == 0; } @Override public DepthState copy() { diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/FogState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/FogState.java index 638dff827..5ed3c0332 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/FogState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/FogState.java @@ -16,6 +16,8 @@ public class FogState implements ISettableState { protected float density = 1.0F; protected float start; protected float end = 1.0F; + /** Fog distance computation mode: 0=EYE_RADIAL, 1=EYE_PLANE, 2=EYE_PLANE_ABS */ + protected int fogDistanceMode = 2; @Override public FogState set(FogState state) { @@ -23,16 +25,20 @@ public class FogState implements ISettableState { this.fogColor.set(state.fogColor); this.fogAlpha = state.fogAlpha; this.fogColorBuffer.put(0, state.fogColorBuffer.get(0)); + this.fogColorBuffer.put(1, state.fogColorBuffer.get(1)); + this.fogColorBuffer.put(2, state.fogColorBuffer.get(2)); + this.fogColorBuffer.put(3, state.fogColorBuffer.get(3)); this.density = state.density; this.start = state.start; this.end = state.end; + this.fogDistanceMode = state.fogDistanceMode; return this; } @Override public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof FogState fogState)) return false; - return fogMode == fogState.fogMode && Float.compare(fogState.fogAlpha, fogAlpha) == 0 && Float.compare(fogState.density, density) == 0 && Float.compare(fogState.start, start) == 0 && Float.compare(fogState.end, end) == 0 && fogColor.equals(fogState.fogColor); + return fogMode == fogState.fogMode && fogDistanceMode == fogState.fogDistanceMode && Float.compare(fogState.fogAlpha, fogAlpha) == 0 && Float.compare(fogState.density, density) == 0 && Float.compare(fogState.start, start) == 0 && Float.compare(fogState.end, end) == 0 && fogColor.equals(fogState.fogColor); } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java index 66e12b6e1..1aac2e658 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightModelState.java @@ -3,7 +3,6 @@ package com.gtnewhorizons.angelica.glsm.states; import com.gtnewhorizons.angelica.glsm.GLStateManager; import org.joml.Vector4f; import org.joml.Vector4i; -import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.nio.FloatBuffer; @@ -32,7 +31,6 @@ public class LightModelState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer); } } @@ -41,14 +39,12 @@ public class LightModelState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glLightModel(GL11.GL_LIGHT_MODEL_AMBIENT, newBuffer); } } public void setColorControl(int val) { if (GLStateManager.shouldBypassCache() || this.colorControl != val) { this.colorControl = val; - GL11.glLightModeli(GL12.GL_LIGHT_MODEL_COLOR_CONTROL, val); } } @@ -59,7 +55,6 @@ public class LightModelState implements ISettableState { public void setLocalViewer(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.localViewer, val) != 0) { this.localViewer = val; - GL11.glLightModelf(GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, val); } } @@ -78,7 +73,6 @@ public class LightModelState implements ISettableState { public void setTwoSide(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.twoSide, val) != 0) { this.twoSide = val; - GL11.glLightModelf(GL11.GL_LIGHT_MODEL_TWO_SIDE, val); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java index 6ae1c7425..91c46d4a4 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/LightState.java @@ -76,7 +76,6 @@ public class LightState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer); } } @@ -85,7 +84,6 @@ public class LightState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glLight(this.light, GL11.GL_AMBIENT, newBuffer); } } @@ -93,7 +91,6 @@ public class LightState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); - GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer); } } @@ -102,7 +99,6 @@ public class LightState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); - GL11.glLight(this.light, GL11.GL_DIFFUSE, newBuffer); } } @@ -110,7 +106,6 @@ public class LightState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); - GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer); } } @@ -119,7 +114,6 @@ public class LightState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); - GL11.glLight(this.light, GL11.GL_SPECULAR, newBuffer); } } @@ -129,14 +123,12 @@ public class LightState implements ISettableState { // with and the untransformed coordinates in addition to the final transformation. this.position.set(newBuffer); this.position.mul(GLStateManager.getModelViewMatrix()); - GL11.glLight(this.light, GL11.GL_POSITION, newBuffer); } public void setPosition(IntBuffer newBuffer) { vector4i.set(newBuffer); this.position.set((float) vector4i.x, (float) vector4i.y, (float) vector4i.z, (float) vector4i.w); this.position.mul(GLStateManager.getModelViewMatrix()); - GL11.glLight(this.light, GL11.GL_POSITION, newBuffer); } public void setSpotDirection(FloatBuffer newBuffer) { @@ -146,7 +138,6 @@ public class LightState implements ISettableState { GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.set(newBuffer); this.spotDirection.mul(matrix3f); - GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer); } public void setSpotDirection(IntBuffer newBuffer) { @@ -154,7 +145,6 @@ public class LightState implements ISettableState { GLStateManager.getModelViewMatrix().get3x3(matrix3f); this.spotDirection.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z); this.spotDirection.mul(matrix3f); - GL11.glLight(this.light, GL11.GL_SPOT_DIRECTION, newBuffer); } public void setSpotExponent(FloatBuffer newBuffer) { @@ -172,7 +162,6 @@ public class LightState implements ISettableState { public void setSpotExponent(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotExponent) != 0) { this.spotExponent = f; - GL11.glLightf(this.light, GL11.GL_SPOT_EXPONENT, f); } } @@ -191,7 +180,6 @@ public class LightState implements ISettableState { public void setSpotCutoff(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.spotCutoff) != 0) { this.spotCutoff = f; - GL11.glLightf(this.light, GL11.GL_SPOT_CUTOFF, f); } } @@ -210,7 +198,6 @@ public class LightState implements ISettableState { public void setConstantAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.constantAttenuation) != 0) { this.constantAttenuation = f; - GL11.glLightf(this.light, GL11.GL_CONSTANT_ATTENUATION, f); } } @@ -229,7 +216,6 @@ public class LightState implements ISettableState { public void setLinearAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.linearAttenuation) != 0) { this.linearAttenuation = f; - GL11.glLightf(this.light, GL11.GL_LINEAR_ATTENUATION, f); } } @@ -248,7 +234,6 @@ public class LightState implements ISettableState { public void setQuadraticAttenuation(float f) { if (GLStateManager.shouldBypassCache() || Float.compare(f, this.quadraticAttenuation) != 0) { this.quadraticAttenuation = f; - GL11.glLightf(this.light, GL11.GL_QUADRATIC_ATTENUATION, f); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java index f0bf06330..fa1af275e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/MaterialState.java @@ -5,7 +5,6 @@ import org.joml.Vector3f; import org.joml.Vector3i; import org.joml.Vector4f; import org.joml.Vector4i; -import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; import java.nio.IntBuffer; @@ -42,7 +41,6 @@ public class MaterialState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer); } } @@ -51,7 +49,6 @@ public class MaterialState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.ambient.equals(vector4f)) { this.ambient.set(vector4f); - GL11.glMaterial(face, GL11.GL_AMBIENT, newBuffer); } } @@ -59,7 +56,6 @@ public class MaterialState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); - GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer); } } @@ -68,7 +64,6 @@ public class MaterialState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.diffuse.equals(vector4f)) { this.diffuse.set(vector4f); - GL11.glMaterial(face, GL11.GL_DIFFUSE, newBuffer); } } @@ -76,7 +71,6 @@ public class MaterialState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); - GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer); } } @@ -85,7 +79,6 @@ public class MaterialState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.specular.equals(vector4f)) { this.specular.set(vector4f); - GL11.glMaterial(face, GL11.GL_SPECULAR, newBuffer); } } @@ -93,7 +86,6 @@ public class MaterialState implements ISettableState { vector4f.set(newBuffer); if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); - GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer); } } @@ -102,14 +94,12 @@ public class MaterialState implements ISettableState { vector4f.set(i2f(vector4i.x), i2f(vector4i.y), i2f(vector4i.z), i2f(vector4i.w)); if (GLStateManager.shouldBypassCache() || !this.emission.equals(vector4f)) { this.emission.set(vector4f); - GL11.glMaterial(face, GL11.GL_EMISSION, newBuffer); } } public void setShininess(float val) { if (GLStateManager.shouldBypassCache() || Float.compare(this.shininess, val) != 0) { this.shininess = val; - GL11.glMaterialf(face, GL11.GL_SHININESS, val); } } @@ -132,7 +122,6 @@ public class MaterialState implements ISettableState { if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); - GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer); } } @@ -141,7 +130,6 @@ public class MaterialState implements ISettableState { vector3f.set((float) vector3i.x, (float) vector3i.y, (float) vector3i.z); if (GLStateManager.shouldBypassCache() || !this.colorIndexes.equals(vector3f)) { this.colorIndexes.set(vector3f); - GL11.glMaterial(face, GL11.GL_COLOR_INDEXES, newBuffer); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java index 138d0f19f..5713881ef 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/MatrixMode.java @@ -10,8 +10,7 @@ public class MatrixMode implements ISettableState { public void setMode(int mode) { if(mode != GL11.GL_MODELVIEW && mode != GL11.GL_PROJECTION && mode != GL11.GL_TEXTURE && mode != GL11.GL_COLOR) { - // Invalid mode, do nothing on the cache, but pass it along to OGL - GL11.glMatrixMode(mode); + // Invalid mode, do nothing on the cache return; } @@ -20,7 +19,6 @@ public class MatrixMode implements ISettableState { if (!bypass) { this.mode = mode; } - GL11.glMatrixMode(mode); } } diff --git a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java index 6acb2aa13..977e2b8f9 100644 --- a/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java +++ b/src/main/java/com/gtnewhorizons/angelica/glsm/states/ViewportState.java @@ -7,6 +7,8 @@ public class ViewportState implements ISettableState { public int y; public int width; public int height; + public double depthRangeNear = 0.0; + public double depthRangeFar = 1.0; public void setViewPort(int x, int y, int width, int height) { this.x = x; @@ -15,6 +17,11 @@ public class ViewportState implements ISettableState { this.height = height; } + public void setDepthRange(double near, double far) { + this.depthRangeNear = near; + this.depthRangeFar = far; + } + public void get(IntBuffer params) { params.put(0, x); params.put(1, y); @@ -28,6 +35,8 @@ public class ViewportState implements ISettableState { this.y = state.y; this.width = state.width; this.height = state.height; + this.depthRangeNear = state.depthRangeNear; + this.depthRangeFar = state.depthRangeFar; return this; } @@ -36,7 +45,9 @@ public class ViewportState implements ISettableState { public boolean sameAs(Object state) { if (this == state) return true; if (!(state instanceof ViewportState viewportState)) return false; - return x == viewportState.x && y == viewportState.y && width == viewportState.width && height == viewportState.height; + return x == viewportState.x && y == viewportState.y && width == viewportState.width && height == viewportState.height + && Double.compare(depthRangeNear, viewportState.depthRangeNear) == 0 + && Double.compare(depthRangeFar, viewportState.depthRangeFar) == 0; } @Override diff --git a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java index 93061fc76..1a9647538 100644 --- a/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java +++ b/src/main/java/com/gtnewhorizons/angelica/loading/shared/transformers/AngelicaRedirector.java @@ -15,7 +15,6 @@ import org.objectweb.asm.tree.MethodNode; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Set; @@ -103,6 +102,8 @@ public final class AngelicaRedirector { .add("glColorMask") .add("glColorMaterial") .add("glDeleteLists") + .add("glGenLists") + .add("glIsList") .add("glDeleteTextures") .add("glDepthFunc") .add("glDepthMask") @@ -175,6 +176,13 @@ public final class AngelicaRedirector { .add("glTexCoord3f") .add("glTexCoord4d") .add("glTexCoord4f") + .add("glTexEnvi") + .add("glTexEnvf") + .add("glTexEnv") + .add("glTexGeni") + .add("glTexGenf") + .add("glTexGend") + .add("glTexGen") .add("glTexImage1D") .add("glTexImage2D") .add("glTexImage3D") @@ -186,6 +194,8 @@ public final class AngelicaRedirector { .add("glCopyTexSubImage2D") .add("glPixelStoref") .add("glPixelStorei") + .add("glPixelTransferf") + .add("glPixelTransferi") .add("glTexParameter") .add("glTexParameterf") .add("glTexParameteri") @@ -198,6 +208,8 @@ public final class AngelicaRedirector { .add("glPointSize") .add("glPolygonMode") .add("glPolygonOffset") + .add("glPolygonStipple") + .add("glAccum") .add("glReadBuffer") .add("glSampleCoverage") .add("glScissor") @@ -215,6 +227,8 @@ public final class AngelicaRedirector { .add("glVertex3f") .add("glVertexPointer") .add("glColorPointer") + .add("glNormalPointer") + .add("glTexCoordPointer") .add("glEnableClientState") .add("glDisableClientState") .add("glViewport") @@ -227,6 +241,8 @@ public final class AngelicaRedirector { methodRedirects.put(GL13, RedirectMap.newMap() .add("glActiveTexture") .add("glSampleCoverage") + .add("glMultiTexCoord2f") + .add("glMultiTexCoord2s") ); methodRedirects.put(GL14, RedirectMap.newMap() .add("glBlendFuncSeparate", "tryBlendFuncSeparate") @@ -243,6 +259,9 @@ public final class AngelicaRedirector { .add("glStencilMaskSeparate") .add("glStencilOpSeparate") .add("glUseProgram") + .add("glShaderSource") + .add("glLinkProgram") + .add("glDeleteProgram") ); methodRedirects.put(GL30, RedirectMap.newMap() .add("glBindVertexArray") diff --git a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java index 7604a86af..b7362379e 100644 --- a/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java +++ b/src/main/java/com/gtnewhorizons/angelica/mixins/Mixins.java @@ -29,6 +29,7 @@ public enum Mixins implements IMixins { .addClientMixins( "angelica.MixinActiveRenderInfo" , "angelica.MixinEntityRenderer" + , "angelica.MixinForgeHooksClient_CoreProfile" , "angelica.MixinGameSettings" , "angelica.MixinMinecraft" , "angelica.MixinMinecraftServer" @@ -37,6 +38,7 @@ public enum Mixins implements IMixins { , "angelica.bugfixes.MixinRenderGlobal_DestroyBlock" , "angelica.glsm.MixinSplashProgressCaching" , "angelica.debug.MixinMinecraft_FPSCap" + , "angelica.ffp.MixinTessellator_CoreProfile" ) ), diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java index 82f9d196e..76d2ac75f 100644 --- a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java @@ -25,13 +25,11 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import jss.notfine.core.Settings; import jss.notfine.gui.options.named.GraphicsQualityOff; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; -import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.resources.IReloadableResourceManager; @@ -374,7 +372,7 @@ public class CloudRenderer implements IResourceManagerReloadListener { // Wireframe for debug. if (WIREFRAME) { GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); - GL11.glLineWidth(2.0F); + GLStateManager.glLineWidth(2.0F); GLStateManager.disableTexture(); GLStateManager.glDepthMask(false); GLStateManager.disableFog(); diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java b/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java index 2f069dfca..37b964f91 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/ItemRenderListManager.java @@ -29,11 +29,10 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexBuffer; -import com.gtnewhorizon.gtnhlib.client.renderer.vao.IndexedVAO; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VAOManager; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.config.AngelicaConfig; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import lombok.Data; import lombok.NoArgsConstructor; @@ -92,6 +91,7 @@ public class ItemRenderListManager { public static void post(DirectTessellator tessellator, CachedVBO vbo) { vbo.allocate(tessellator); TessellatorManager.stopCapturingDirect(); + ShaderManager.getInstance().preDraw(CachedVBO.VERTEX_FLAGS); vbo.vertexBuffer.render(); } @@ -100,6 +100,7 @@ public class ItemRenderListManager { } public static final class CachedVBO { + private static final int VERTEX_FLAGS = DefaultVertexFormat.POSITION_TEXTURE_NORMAL.getVertexFlags(); private final IVertexArrayObject vertexBuffer; private final IndexBuffer ebo; private int expiry; @@ -118,6 +119,7 @@ public class ItemRenderListManager { } private void render(int elapsedTicks) { + ShaderManager.getInstance().preDraw(VERTEX_FLAGS); vertexBuffer.render(); expiry = elapsedTicks + EXPIRY_TICKS; } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java index 53a6a3d80..7d4606124 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaChunkRenderer.java @@ -4,9 +4,9 @@ import com.gtnewhorizons.angelica.AngelicaMod; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProvider; import com.gtnewhorizons.angelica.rendering.celeritas.api.IrisShaderProviderHolder; +import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import org.embeddedt.embeddium.impl.gl.device.RenderDevice; import org.embeddedt.embeddium.impl.gl.shader.GlProgram; -import me.jellysquid.mods.sodium.client.gui.options.named.MultiDrawMode; import org.embeddedt.embeddium.impl.render.chunk.DefaultChunkRenderer; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.multidraw.DirectMultiDrawEmitter; diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java index 4211c4c5d..377970e2b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/AngelicaRenderPassConfiguration.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.rendering.celeritas; import com.google.common.collect.ImmutableListMultimap; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; import org.embeddedt.embeddium.impl.render.chunk.RenderPassConfiguration; import org.embeddedt.embeddium.impl.render.chunk.compile.sorting.QuadPrimitiveType; @@ -21,17 +22,17 @@ public class AngelicaRenderPassConfiguration { @Override public void setup() { if (pass == 0) { - GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F); + GLStateManager.glAlphaFunc(GL11.GL_GREATER, 0.1F); } if (disableAlphaTest) { - GL11.glDisable(GL11.GL_ALPHA_TEST); + GLStateManager.disableAlphaTest(); } } @Override public void clear() { if (disableAlphaTest) { - GL11.glEnable(GL11.GL_ALPHA_TEST); + GLStateManager.enableAlphaTest(); } } } @@ -40,7 +41,7 @@ public class AngelicaRenderPassConfiguration { return TerrainRenderPass.builder() .pipelineState(new AngelicaPipelineState(pass, disableAlphaTest)) .vertexType(vertexType) - .primitiveType(QuadPrimitiveType.DIRECT); + .primitiveType(QuadPrimitiveType.TRIANGULATED); } public static RenderPassConfiguration build(ChunkVertexType vertexType) { diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java index 11d0531b4..25d8897ef 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/celeritas/CeleritasDebugScreenHandler.java @@ -4,6 +4,7 @@ import com.gtnewhorizons.angelica.Tags; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.dynamiclights.DynamicLights; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.ffp.ShaderManager; import com.gtnewhorizons.angelica.glsm.states.FogState; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; @@ -42,6 +43,10 @@ public class CeleritasDebugScreenHandler { event.right.add(""); event.right.add(EnumChatFormatting.GREEN + "Angelica " + Tags.VERSION + " [Celeritas Renderer]"); event.right.addAll(renderer.getDebugStrings()); + final ShaderManager sm = ShaderManager.getInstance(); + if (sm != null) { + event.right.add(sm.getDebugInfo()); + } event.right.add(""); } diff --git a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java index bb642f444..4ca493048 100644 --- a/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java +++ b/src/main/java/net/coderbot/iris/celeritas/IrisCeleritasChunkShaderInterface.java @@ -6,18 +6,15 @@ import net.coderbot.iris.Iris; import net.coderbot.iris.gl.blending.BlendModeOverride; import net.coderbot.iris.gl.blending.BufferBlendOverride; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.samplers.IrisSamplers; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.DynamicTexture; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL13; import net.coderbot.iris.gl.program.ProgramImages; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; +import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.coderbot.iris.samplers.IrisSamplers; import net.coderbot.iris.shadows.ShadowRenderingState; import net.coderbot.iris.uniforms.custom.CustomUniforms; -import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.DynamicTexture; import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat3v; import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix3f; @@ -30,6 +27,10 @@ import org.jetbrains.annotations.Nullable; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Matrix4fc; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL13; + +import java.util.List; public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { @Nullable @@ -129,7 +130,7 @@ public class IrisCeleritasChunkShaderInterface implements ChunkShaderInterface { @Override public GlPrimitiveType getPrimitiveType() { - return GlPrimitiveType.QUADS; + return GlPrimitiveType.TRIANGLES; } @Override diff --git a/src/main/java/net/coderbot/iris/gl/image/GlImage.java b/src/main/java/net/coderbot/iris/gl/image/GlImage.java index da1982f60..4f2f296a3 100644 --- a/src/main/java/net/coderbot/iris/gl/image/GlImage.java +++ b/src/main/java/net/coderbot/iris/gl/image/GlImage.java @@ -34,18 +34,18 @@ public class GlImage extends GlObject { GLDebug.nameObject(GL11.GL_TEXTURE, handle(), name); - GL11.glBindTexture(target.getGlType(), handle()); + GLStateManager.glBindTexture(target.getGlType(), handle()); target.apply(handle(), width, height, depth, internalFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null); - int texture = handle(); + final int texture = handle(); setup(texture, width, height, depth); - GL11.glBindTexture(target.getGlType(), 0); + GLStateManager.glBindTexture(target.getGlType(), 0); } protected void setup(int texture, int width, int height, int depth) { - boolean isInteger = internalTextureFormat.getPixelFormat().isInteger(); + final boolean isInteger = internalTextureFormat.getPixelFormat().isInteger(); RenderSystem.texParameteri(texture, target.getGlType(), GL11.GL_TEXTURE_MIN_FILTER, isInteger ? GL11.GL_NEAREST : GL11.GL_LINEAR); RenderSystem.texParameteri(texture, target.getGlType(), GL11.GL_TEXTURE_MAG_FILTER, isInteger ? GL11.GL_NEAREST : GL11.GL_LINEAR); RenderSystem.texParameteri(texture, target.getGlType(), GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); @@ -139,14 +139,14 @@ public class GlImage extends GlObject { @Override public void updateNewSize(int width, int height) { - GL11.glBindTexture(target.getGlType(), handle()); + GLStateManager.glBindTexture(target.getGlType(), handle()); target.apply(handle(), (int) (width * relativeWidth), (int) (height * relativeHeight), 0, internalTextureFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null); - int texture = handle(); + final int texture = handle(); setup(texture, width, height, 0); - GL11.glBindTexture(target.getGlType(), 0); + GLStateManager.glBindTexture(target.getGlType(), 0); } } } 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 d24a10f48..645054f02 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java +++ b/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java @@ -15,6 +15,7 @@ import net.minecraft.world.biome.BiomeGenBase; import org.lwjgl.LWJGLUtil; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL30; import java.util.ArrayList; import java.util.Arrays; @@ -262,7 +263,11 @@ public class StandardMacros { * @see Optifine Doc */ public static Set getGlExtensions() { - String[] extensions = Objects.requireNonNull(GL11.glGetString(GL11.GL_EXTENSIONS)).split("\\s+"); + int numExtensions = GL11.glGetInteger(GL30.GL_NUM_EXTENSIONS); + String[] extensions = new String[numExtensions]; + for (int i = 0; i < numExtensions; i++) { + extensions[i] = GL30.glGetStringi(GL11.GL_EXTENSIONS, i); + } // TODO note that we do not add extensions based on if the shader uses them and if they are supported // see https://github.com/sp614x/optifine/blob/master/OptiFineDoc/doc/shaders.txt#L738 diff --git a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java b/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java index de23eeb1c..156537fdb 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java +++ b/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java @@ -54,7 +54,7 @@ public class GlTexture extends GlObject implements TextureAccess { } public static void bindTextureForSetup(int glType, int glId) { - GL11.glBindTexture(glType, glId); + GLStateManager.glBindTexture(glType, glId); } public TextureType getTarget() { diff --git a/src/main/java/net/coderbot/iris/gui/GuiUtil.java b/src/main/java/net/coderbot/iris/gui/GuiUtil.java index 66e6fdfd4..b7c5024be 100644 --- a/src/main/java/net/coderbot/iris/gui/GuiUtil.java +++ b/src/main/java/net/coderbot/iris/gui/GuiUtil.java @@ -8,7 +8,6 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL14; /** * Class serving as abstraction and @@ -59,7 +58,7 @@ public final class GuiUtil { final int vOffset = disabled ? 46 : hovered ? 86 : 66; // Sets RenderSystem to use solid white as the tint color for blend mode, and enables blend mode - GL14.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); GLStateManager.enableBlend(); // Sets RenderSystem to be able to use textures when drawing @@ -194,7 +193,7 @@ public final class GuiUtil { */ public void draw(int x, int y) { // Sets RenderSystem to use solid white as the tint color for blend mode, and enables blend mode - GL14.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); GLStateManager.enableBlend(); // Sets RenderSystem to be able to use textures when drawing diff --git a/src/main/java/net/coderbot/iris/gui/element/IrisGuiSlot.java b/src/main/java/net/coderbot/iris/gui/element/IrisGuiSlot.java index a7c47cc64..fd73c38f1 100644 --- a/src/main/java/net/coderbot/iris/gui/element/IrisGuiSlot.java +++ b/src/main/java/net/coderbot/iris/gui/element/IrisGuiSlot.java @@ -1,5 +1,6 @@ package net.coderbot.iris.gui.element; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import lombok.Getter; import lombok.Setter; import net.minecraft.client.Minecraft; @@ -129,8 +130,8 @@ public abstract class IrisGuiSlot extends GuiSlot { this.bindAmountScrolled(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_FOG); + GLStateManager.glDisable(GL11.GL_LIGHTING); + GLStateManager.glDisable(GL11.GL_FOG); final Tessellator tessellator = Tessellator.instance; drawContainerBackground(tessellator); final int elementRight = this.left + this.width / 2 - this.getListWidth() / 2 + 2; @@ -141,14 +142,14 @@ public abstract class IrisGuiSlot extends GuiSlot { } this.drawSelectionBox(elementRight, relativeY, mouseX, mouseY); - GL11.glDisable(GL11.GL_DEPTH_TEST); + GLStateManager.glDisable(GL11.GL_DEPTH_TEST); this.overlayBackground(0, this.top, 255, 255); this.overlayBackground(this.bottom, this.height, 255, 255); - GL11.glEnable(GL11.GL_BLEND); + GLStateManager.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(770, 771, 0, 1); - GL11.glDisable(GL11.GL_ALPHA_TEST); - GL11.glShadeModel(GL11.GL_SMOOTH); - GL11.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glDisable(GL11.GL_ALPHA_TEST); + GLStateManager.glShadeModel(GL11.GL_SMOOTH); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); tessellator.startDrawingQuads(); tessellator.setColorRGBA_I(0, 0); tessellator.addVertexWithUV(this.left, (this.top + offset), 0.0D, 0.0D, 1.0D); @@ -209,9 +210,9 @@ public abstract class IrisGuiSlot extends GuiSlot { tessellator.draw(); } - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glShadeModel(GL11.GL_FLAT); - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glDisable(GL11.GL_BLEND); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glShadeModel(GL11.GL_FLAT); + GLStateManager.glEnable(GL11.GL_ALPHA_TEST); + GLStateManager.glDisable(GL11.GL_BLEND); } } diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/IrisImageButton.java b/src/main/java/net/coderbot/iris/gui/element/widget/IrisImageButton.java index 2361e6cdc..1d74a842a 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/IrisImageButton.java +++ b/src/main/java/net/coderbot/iris/gui/element/widget/IrisImageButton.java @@ -4,7 +4,6 @@ import com.gtnewhorizons.angelica.glsm.GLStateManager; import cpw.mods.fml.client.config.GuiUtils; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL14; import java.util.function.Consumer; @@ -37,7 +36,7 @@ public class IrisImageButton extends IrisButton { } // Sets RenderSystem to use solid white as the tint color for blend mode, and enables blend mode - GL14.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glBlendColor(1.0f, 1.0f, 1.0f, 1.0f); GLStateManager.enableBlend(); // Sets RenderSystem to be able to use textures when drawing diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java b/src/main/java/net/coderbot/iris/pipeline/ClearPass.java index e02edbd42..ad0521716 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java +++ b/src/main/java/net/coderbot/iris/pipeline/ClearPass.java @@ -34,8 +34,8 @@ public class ClearPass { color = this.color; } - GL11.glClearColor(color.x, color.y, color.z, color.w); - GL11.glClear(clearFlags); + GLStateManager.glClearColor(color.x, color.y, color.z, color.w); + GLStateManager.glClear(clearFlags); if (Minecraft.isRunningOnMac) { GL11.glGetError(); } diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java index 444e6c494..85740e3f7 100644 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java @@ -288,12 +288,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // Initialize custom images this.customImages = new HashSet<>(); final var customImageInfos = programs.getPack().getCustomImages(); - Iris.logger.debug("[CustomImages] Found {} custom image definitions from shader pack", customImageInfos.size()); final List clearList = new ArrayList<>(); for (var entry : customImageInfos.object2ObjectEntrySet()) { - ImageInformation info = entry.getValue(); - Iris.logger.debug("[CustomImages] Creating GlImage: {} with info: {}", entry.getKey(), info); - GlImage image; + final ImageInformation info = entry.getValue(); + final GlImage image; if (info.isRelative()) { image = new GlImage.Relative(info.name(), info.samplerName(), info.format(), info.internalTextureFormat(), info.type(), info.clear(), info.relativeWidth(), info.relativeHeight(), @@ -302,14 +300,12 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R image = new GlImage(info.name(), info.samplerName(), info.target(), info.format(), info.internalTextureFormat(), info.type(), info.clear(), info.width(), info.height(), info.depth()); } - Iris.logger.debug("[CustomImages] Created GlImage: {} with texture ID: {}", entry.getKey(), image.getId()); customImages.add(image); if (image.shouldClear()) { clearList.add(image); } } this.imagesToClear = clearList.toArray(new GlImage[0]); - Iris.logger.debug("[CustomImages] Total GlImages created: {}, images to clear: {}", customImages.size(), imagesToClear.length); // Initialize SSBOs final var bufferObjectInfos = programs.getPack().getBufferObjects(); @@ -747,7 +743,10 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R return; } - beginPass(table.match(getCondition(getPhase()), inputs)); + final RenderCondition condition = getCondition(getPhase()); + final Pass matched = table.match(condition, inputs); + + beginPass(matched); } public void beginPass(Pass pass) { @@ -1117,7 +1116,7 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R } else { // Clear depth first, regardless of any color clearing. shadowRenderTargets.getDepthSourceFb().bind(); - GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); + GLStateManager.glClear(GL11.GL_DEPTH_BUFFER_BIT); if (Minecraft.isRunningOnMac) { GL11.glGetError(); } @@ -1467,16 +1466,16 @@ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, R // DimensionSpecialEffects.SkyType skyType = Minecraft.getMinecraft().theWorld.effects().skyType(); if (true/*skyType == DimensionSpecialEffects.SkyType.NORMAL*/) { - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glDepthMask(false); + GLStateManager.glDisable(GL11.GL_TEXTURE_2D); + GLStateManager.glDepthMask(false); final Vector3d fogColor = GLStateManager.getFogColor(); - GL11.glColor4f((float) fogColor.x, (float) fogColor.y, (float) fogColor.z, 1.0F); + GLStateManager.glColor4f((float) fogColor.x, (float) fogColor.y, (float) fogColor.z, 1.0F); horizonRenderer.renderHorizon(RenderingState.INSTANCE.getModelViewBuffer()); - GL11.glDepthMask(true); - GL11.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.glDepthMask(true); + GLStateManager.glEnable(GL11.GL_TEXTURE_2D); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java index 3dece81cf..5f255e898 100644 --- a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java +++ b/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java @@ -1,6 +1,7 @@ package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.compat.mojang.Camera; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; import net.coderbot.iris.block_rendering.BlockRenderingSettings; @@ -17,7 +18,6 @@ import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; -import org.lwjgl.opengl.GL20; import java.util.List; import java.util.OptionalInt; @@ -35,7 +35,7 @@ public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeli public void beginLevelRendering() { // Use the default Minecraft framebuffer and ensure that no programs are in use Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); - GL20.glUseProgram(0); + GLStateManager.glUseProgram(0); } @Override diff --git a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java b/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java index adab076b3..c9c0f1ab9 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java @@ -20,6 +20,8 @@ import org.lwjgl.util.glu.Project; import java.util.Map; + + public class HandRenderer { public static final HandRenderer INSTANCE = new HandRenderer(); @@ -30,30 +32,30 @@ public class HandRenderer { private void setupGlState(RenderGlobal gameRenderer, Camera camera, float tickDelta) { final Minecraft mc = Minecraft.getMinecraft(); - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); // We need to scale the matrix by 0.125 so the hand doesn't clip through blocks. - GL11.glScalef(1.0F, 1.0F, DEPTH); + GLStateManager.glScalef(1.0F, 1.0F, DEPTH); // TODO: Anaglyph /*if (this.mc.gameSettings.anaglyph) { - GL11.glTranslatef((float) (-(anaglyphChannel * 2 - 1)) * 0.07F, 0.0F, 0.0F); + GLStateManager.glTranslatef((float) (-(anaglyphChannel * 2 - 1)) * 0.07F, 0.0F, 0.0F); }*/ if (mc.entityRenderer.cameraZoom != 1.0D) { - GL11.glTranslatef((float) mc.entityRenderer.cameraYaw, (float) (-mc.entityRenderer.cameraPitch), 0.0F); - GL11.glScaled(mc.entityRenderer.cameraZoom, mc.entityRenderer.cameraZoom, 1.0D); + GLStateManager.glTranslatef((float) mc.entityRenderer.cameraYaw, (float) (-mc.entityRenderer.cameraPitch), 0.0F); + GLStateManager.glScaled(mc.entityRenderer.cameraZoom, mc.entityRenderer.cameraZoom, 1.0D); } Project.gluPerspective(mc.entityRenderer.getFOVModifier(tickDelta, false), (float) mc.displayWidth / (float) mc.displayHeight, 0.05F, mc.entityRenderer.farPlaneDistance * 2.0F); if (mc.playerController.enableEverythingIsScrewedUpMode()) { - GL11.glScalef(1.0F, 2 / 3f, 1.0F); + GLStateManager.glScalef(1.0F, 2 / 3f, 1.0F); } - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glLoadIdentity(); // TODO: Anaglyph /*if (mc.gameSettings.anaglyph) { @@ -106,8 +108,8 @@ public class HandRenderer { pipeline.setPhase(WorldRenderingPhase.HAND_SOLID); - GL11.glPushMatrix(); - GL11.glDepthMask(true); // actually write to the depth buffer, it's normally disabled at this point + GLStateManager.glPushMatrix(); + GLStateManager.glDepthMask(true); // actually write to the depth buffer, it's normally disabled at this point mc.mcProfiler.startSection("iris_hand"); @@ -116,13 +118,14 @@ public class HandRenderer { GbufferPrograms.setBlockEntityDefaults(); renderingSolid = true; + mc.entityRenderer.enableLightmap(tickDelta); mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta); mc.entityRenderer.disableLightmap(tickDelta); GLStateManager.defaultBlendFunc(); - GL11.glDepthMask(false); - GL11.glPopMatrix(); + GLStateManager.glDepthMask(false); + GLStateManager.glPopMatrix(); mc.mcProfiler.endSection(); @@ -146,7 +149,7 @@ public class HandRenderer { pipeline.setPhase(WorldRenderingPhase.HAND_TRANSLUCENT); - GL11.glPushMatrix(); + GLStateManager.glPushMatrix(); mc.mcProfiler.startSection("iris_hand_translucent"); @@ -158,7 +161,7 @@ public class HandRenderer { mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta); mc.entityRenderer.disableLightmap(tickDelta); - GL11.glPopMatrix(); + GLStateManager.glPopMatrix(); resetProjectionMatrix(); @@ -170,10 +173,10 @@ public class HandRenderer { } private void resetProjectionMatrix() { - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glLoadIdentity(); - GL11.glMultMatrix(RenderingState.INSTANCE.getProjectionBuffer()); - GL11.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glLoadIdentity(); + GLStateManager.glMultMatrix(RenderingState.INSTANCE.getProjectionBuffer()); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); } public boolean isActive() { diff --git a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java b/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java index dd4f03821..ed490cb85 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java @@ -4,12 +4,10 @@ import com.gtnewhorizon.gtnhlib.client.renderer.DirectTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject; import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType; -import com.gtnewhorizon.gtnhlib.client.renderer.vbo.IVertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; - +import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; -import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; @@ -157,15 +155,15 @@ public class HorizonRenderer { rebuildBuffer(); } - GL11.glPushMatrix(); - GL11.glLoadIdentity(); - GL11.glMultMatrix(matrix); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); + GLStateManager.glMultMatrix(matrix); vao.bind(); vao.draw(); vao.unbind(); - GL11.glPopMatrix(); + GLStateManager.glPopMatrix(); } public void destroy() { diff --git a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java index 5c9b577ca..39bff8b85 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java +++ b/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java @@ -2,25 +2,20 @@ package net.coderbot.iris.pipeline; import com.google.common.collect.ImmutableList; import com.gtnewhorizons.angelica.compat.mojang.Camera; +import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.rendering.RenderingState; import com.gtnewhorizons.angelica.rendering.celeritas.CeleritasWorldRenderer; -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Objects; import net.coderbot.iris.Iris; -import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.gui.option.IrisVideoSettings; +import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.ShadowCullState; import net.coderbot.iris.shaderpack.PackShadowDirectives; import net.coderbot.iris.shaderpack.ProgramSource; +import net.coderbot.iris.shaderpack.ShadowCullState; import net.coderbot.iris.shadow.ShadowMatrices; import net.coderbot.iris.shadows.CullingDataCache; import net.coderbot.iris.shadows.ShadowCompositeRenderer; @@ -32,7 +27,6 @@ import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum; import net.coderbot.iris.shadows.frustum.advanced.SafeZoneCullingFrustum; import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum; import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; -import net.coderbot.iris.uniforms.CameraUniforms; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.CelestialUniforms; import net.minecraft.client.Minecraft; @@ -47,7 +41,6 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; -import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import org.embeddedt.embeddium.impl.render.viewport.ViewportProvider; import org.joml.Matrix4f; import org.joml.Vector3d; @@ -60,6 +53,13 @@ import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + public class ShadowRenderer { public static final Matrix4f MODELVIEW = new Matrix4f(); public static final FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16); @@ -485,14 +485,14 @@ public class ShadowRenderer { GLStateManager.glEnable(GL11.GL_POLYGON_OFFSET_FILL); GLStateManager.glPolygonOffset(1.0f, 1.0f); - GL11.glPushMatrix(); + GLStateManager.glPushMatrix(); MODELVIEW_BUFFER.clear().rewind(); modelView.peek().getModel().get(MODELVIEW_BUFFER); - GL11.glLoadMatrix(MODELVIEW_BUFFER); + GLStateManager.glLoadMatrix(MODELVIEW_BUFFER); } private void teardownEntityShadowState() { - GL11.glPopMatrix(); + GLStateManager.glPopMatrix(); GLStateManager.glDisable(GL11.GL_POLYGON_OFFSET_FILL); GLStateManager.glPolygonOffset(0.0f, 0.0f); @@ -553,7 +553,7 @@ public class ShadowRenderer { } int brightness = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, (float) brightness % 65536, (float) brightness / 65536); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); TileEntityRendererDispatcher.instance.renderTileEntityAt(tile, (double)tile.xCoord - cameraX, (double)tile.yCoord - cameraY, @@ -573,10 +573,10 @@ public class ShadowRenderer { culler.setPosition(cameraX, cameraY, cameraZ); } - GL11.glPushMatrix(); + GLStateManager.glPushMatrix(); MODELVIEW_BUFFER.clear().rewind(); modelView.peek().getModel().get(MODELVIEW_BUFFER); - GL11.glLoadMatrix(MODELVIEW_BUFFER); + GLStateManager.glLoadMatrix(MODELVIEW_BUFFER); GbufferPrograms.beginBlockEntities(); GbufferPrograms.setBlockEntityDefaults(); 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 27897c9aa..070e6b574 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -12,73 +12,59 @@ import java.util.Map; * transformation methods. */ class AttributeTransformer { - public static void transform(Transformer transformer, AttributeParameters parameters, String profile, int version) { - boolean isCore = profile.equals("core") || (version > 140 && !profile.equals("compatibility")); - - // Common patches (compatibility profile) - CommonTransformer.transform(transformer, parameters, isCore, version); + public static void transform(Transformer transformer, AttributeParameters parameters, int version) { + // Always core profile — minimum GLSL version is 330 (see ShaderTransformer.getStageMinimumVersion) + CommonTransformer.transform(transformer, parameters, true, version); // Entity ID and overlay color patching (uniform path) EntityPatcher.patchEntityId(transformer, parameters); EntityPatcher.patchOverlayColor(transformer, parameters); - if (isCore) { - if (parameters.type == ShaderType.VERTEX) { - throw new IllegalStateException("Vertex shaders must be in the compatibility profile to run properly!"); + transformCore(transformer, parameters); + } + + private static void transformCore(Transformer transformer, AttributeParameters parameters) { + CoreTransformHelper.injectMatrixUniforms(transformer); + + if (parameters.type == ShaderType.VERTEX) { + transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); + transformer.injectVariable("layout(location = 1) in vec4 iris_Color;"); + transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;"); + transformer.injectVariable("layout(location = 3) in vec4 iris_MultiTexCoord1;"); + transformer.injectVariable("layout(location = 4) in vec3 iris_Normal;"); + + transformer.rename("gl_Vertex", "iris_Vertex"); + transformer.rename("gl_Color", "iris_Color"); + transformer.rename("gl_Normal", "iris_Normal"); + + // ftransform() = gl_ModelViewProjectionMatrix * gl_Vertex + transformer.renameFunctionCall("ftransform", "iris_ftransform"); + transformer.injectFunction("vec4 iris_ftransform() { return (iris_ProjectionMatrix * iris_ModelViewMatrix) * iris_Vertex; }"); + + // gl_MultiTexCoord1 and gl_MultiTexCoord2 are both lightmap + if (parameters.inputs.lightmap) { + transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); } - return; - } - // gl_MultiTexCoord1 and gl_MultiTexCoord2 are both ways to refer to the - // lightmap texture coordinate. - // See https://github.com/IrisShaders/Iris/issues/1149 - if (parameters.inputs.lightmap) { - transformer.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); - } + Map texCoordReplacements = new HashMap<>(); + if (!parameters.inputs.lightmap) { + texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)"); + texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)"); + } + if (!parameters.inputs.texture) { + texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)"); + } + texCoordReplacements.forEach(transformer::replaceExpression); - Map texCoordReplacements = new HashMap<>(); - if (!parameters.inputs.lightmap) { - texCoordReplacements.put("gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)"); - texCoordReplacements.put("gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)"); - } - if (!parameters.inputs.texture) { - texCoordReplacements.put("gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)"); - } - texCoordReplacements.forEach(transformer::replaceExpression); + // Rename remaining gl_MultiTexCoord references to iris_ versions + transformer.rename("gl_MultiTexCoord0", "iris_MultiTexCoord0"); + transformer.rename("gl_MultiTexCoord1", "iris_MultiTexCoord1"); - patchTextureMatrices(transformer, parameters.inputs.lightmap); - - if (parameters.type == ShaderType.VERTEX && transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) { - transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord"); - transformer.injectVariable("attribute vec4 mc_midTexCoord;"); + if (transformer.hasVariable("gl_MultiTexCoord3") && !transformer.hasVariable("mc_midTexCoord")) { + transformer.rename("gl_MultiTexCoord3", "mc_midTexCoord"); + transformer.injectVariable("in vec4 mc_midTexCoord;"); + } } } - private static void patchTextureMatrices(Transformer transformer, boolean hasLightmap) { - transformer.rename("gl_TextureMatrix", "iris_TextureMatrix"); - - transformer.injectVariable("float iris_ONE_OVER_256 = 0.00390625;"); - transformer.injectVariable("float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;"); - - if (hasLightmap) { - transformer.injectVariable("mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];"); - } else { - transformer.injectVariable("mat4 iris_LightmapTextureMatrix =" + - "mat4(iris_ONE_OVER_256, 0.0, 0.0, 0.0," + - " 0.0, iris_ONE_OVER_256, 0.0, 0.0," + - " 0.0, 0.0, iris_ONE_OVER_256, 0.0," + - " iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_32, iris_ONE_OVER_256);"); - } - - transformer.injectVariable("mat4 iris_TextureMatrix[8] = mat4[8](" + - "gl_TextureMatrix[0]," + - "iris_LightmapTextureMatrix," + - "mat4(1.0)," + - "mat4(1.0)," + - "mat4(1.0)," + - "mat4(1.0)," + - "mat4(1.0)," + - "mat4(1.0)" + - ");"); - } } 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 23b66d5a7..f15754d67 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CeleritasTransformer.java @@ -1,6 +1,5 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; @@ -9,7 +8,8 @@ import java.util.Map; class CeleritasTransformer { public static void transform(Transformer transformer, Parameters parameters, int glslVersion) { - CommonTransformer.transform(transformer, parameters, false, glslVersion); + // Always core profile — minimum GLSL version is 330 (see ShaderTransformer.getStageMinimumVersion) + CommonTransformer.transform(transformer, parameters, true, glslVersion); switch (parameters.type) { case FRAGMENT: @@ -60,25 +60,6 @@ class CeleritasTransformer { } private static void transformShared(Transformer transformer, Parameters parameters) { - transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); - transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); - transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;"); - transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;"); - transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); - transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;"); - - final Map renames = new HashMap<>(); - renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix"); - renames.put("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse"); - renames.put("gl_ProjectionMatrix", "iris_ProjectionMatrix"); - renames.put("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse"); - renames.put("gl_NormalMatrix", "iris_NormalMatrix"); - transformer.rename(renames); - - final Map sharedReplacements = new HashMap<>(); - sharedReplacements.put("gl_TextureMatrix[0]", "mat4(1.0)"); - sharedReplacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); - sharedReplacements.put("gl_ModelViewProjectionMatrix", "(iris_ProjectionMatrix * iris_ModelViewMatrix)"); - sharedReplacements.forEach(transformer::replaceExpression); + 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 306b2c6bd..ec280e2e5 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CommonTransformer.java @@ -1,29 +1,15 @@ package net.coderbot.iris.pipeline.transform; -import net.coderbot.iris.gl.blending.AlphaTest; +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; -import java.util.Map; +import java.util.HashSet; +import java.util.Set; public class CommonTransformer { - private static final Map COMMON_TEXTURE_RENAMES = Map.ofEntries( - Map.entry("texture2D", "texture"), - Map.entry("texture3D", "texture"), - Map.entry("texture2DLod", "textureLod"), - Map.entry("texture3DLod", "textureLod"), - Map.entry("texture2DProj", "textureProj"), - Map.entry("texture3DProj", "textureProj"), - Map.entry("texture2DGrad", "textureGrad"), - Map.entry("texture2DGradARB", "textureGrad"), - Map.entry("texture3DGrad", "textureGrad"), - Map.entry("texelFetch2D", "texelFetch"), - Map.entry("texelFetch3D", "texelFetch"), - Map.entry("textureSize2D", "textureSize") - ); - public static void transform(Transformer root, Parameters parameters, boolean core, int glslVersion) { root.rename("gl_FogFragCoord", "iris_FogFragCoord"); if (parameters.type == ShaderType.VERTEX) { @@ -34,8 +20,12 @@ public class CommonTransformer { } if (parameters.type == ShaderType.VERTEX) { - root.injectVariable("vec4 iris_FrontColor;"); + root.injectVariable("out vec4 iris_FrontColor;"); root.rename("gl_FrontColor", "iris_FrontColor"); + root.prependMain("iris_FrontColor = vec4(1.0);"); + } else if (parameters.type == ShaderType.FRAGMENT) { + root.injectVariable("in vec4 iris_FrontColor;"); + root.rename("gl_Color", "iris_FrontColor"); } if (parameters.type == ShaderType.FRAGMENT) { @@ -43,10 +33,21 @@ public class CommonTransformer { root.replaceExpression("gl_FragColor", "gl_FragData[0]"); } - // Note: In compatibility profile, gl_FragData is a built-in array. - if (!core && parameters.getAlphaTest() != AlphaTest.ALWAYS) { - root.injectVariable("uniform float iris_currentAlphaTest;"); - root.appendMain(parameters.getAlphaTest().toExpression("gl_FragData[0].a", "iris_currentAlphaTest", "")); + if (core) { + // Core profile: gl_FragData doesn't exist. Flatten gl_FragData[N] → iris_FragDataN with layout-qualified out declarations. + Set found = new HashSet<>(); + root.renameArray("gl_FragData", "iris_FragData", found); + + for (Integer i : found) { + root.injectVariable("layout (location = " + i + ") out vec4 iris_FragData" + i + ";"); + } + + // Core profile: GL_ALPHA_TEST is removed. 1.7.10 engine relies on alpha test to discard transparent fragments. Inject + // runtime discard using the GLSM-tracked alpha reference value. + if (found.contains(0) && parameters.patch != Patch.COMPOSITE && parameters.patch != Patch.COMPUTE) { + root.injectVariable("uniform float iris_currentAlphaTest;"); + root.appendMain("if (iris_FragData0.a <= iris_currentAlphaTest) discard;"); + } } } @@ -54,8 +55,8 @@ public class CommonTransformer { root.rename("texture", "gtexture"); } - if (root.hasVariable("iris_renamed_texture")) { - root.rename("iris_renamed_texture", "gtexture"); + if (root.hasVariable("angelica_renamed_texture")) { + root.rename("angelica_renamed_texture", "gtexture"); } if (root.containsCall("gcolor") && root.hasVariable("gcolor")) { @@ -70,11 +71,8 @@ public class CommonTransformer { root.injectFunction("struct iris_FogParameters {vec4 color;float density;float start;float end;float scale;};"); root.injectFunction("iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, iris_FogStart, iris_FogEnd, 1.0f / (iris_FogEnd - iris_FogStart));"); - // GLSL 120 natively uses texture2D/shadow2D etc. Ttexture/textureLod don't exist in 120, so only rename for versions that support them. - if (glslVersion > 120) { - root.renameFunctionCall(COMMON_TEXTURE_RENAMES); - root.renameAndWrapShadow("shadow2D", "texture"); - root.renameAndWrapShadow("shadow2DLod", "textureLod"); - } + root.renameFunctionCall(GlslTransformUtils.TEXTURE_RENAMES); + root.renameAndWrapShadow("shadow2D", "texture"); + root.renameAndWrapShadow("shadow2DLod", "textureLod"); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java index 209391fcd..0a4746289 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java @@ -1,14 +1,21 @@ package net.coderbot.iris.pipeline.transform; +import net.coderbot.iris.gl.shader.ShaderType; import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.taumc.glsl.Transformer; class CompositeDepthTransformer { public static void transform(Transformer transformer, Parameters parameters, int glslVersion) { - CommonTransformer.transform(transformer, parameters, false, glslVersion); + CommonTransformer.transform(transformer, parameters, true, glslVersion); - int type = transformer.findType("centerDepthSmooth"); + CoreTransformHelper.injectMatrixUniforms(transformer); + + if (parameters.type == ShaderType.VERTEX) { + CoreTransformHelper.injectCompositeVertexAttributes(transformer); + } + + final int type = transformer.findType("centerDepthSmooth"); if (type != 0) { transformer.injectVariable("uniform sampler2D iris_centerDepthSmooth;"); transformer.replaceExpression("centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java new file mode 100644 index 000000000..926aeacf5 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CoreTransformHelper.java @@ -0,0 +1,58 @@ +package net.coderbot.iris.pipeline.transform; + +import org.taumc.glsl.Transformer; + +import java.util.HashMap; +import java.util.Map; + +/** + * Shared core-profile transformation logic for matrix uniforms, texture matrices, and vertex attribute replacement. + */ +class CoreTransformHelper { + + /** + * Inject matrix uniforms and rename FFP matrix builtins to iris_* equivalents. + * Handles: ModelView, ModelViewInverse, Projection, ProjectionInverse, NormalMatrix, ModelViewProjectionMatrix, TextureMatrix[0..1], and LightmapTextureMatrix. + */ + static void injectMatrixUniforms(Transformer transformer) { + transformer.injectVariable("uniform mat4 iris_ModelViewMatrix;"); + transformer.injectVariable("uniform mat4 iris_ModelViewMatrixInverse;"); + transformer.injectVariable("uniform mat4 iris_ProjectionMatrix;"); + transformer.injectVariable("uniform mat4 iris_ProjectionMatrixInverse;"); + transformer.injectVariable("uniform mat3 iris_NormalMatrix;"); + transformer.injectVariable("uniform mat4 iris_LightmapTextureMatrix;"); + + final Map renames = new HashMap<>(); + renames.put("gl_ModelViewMatrix", "iris_ModelViewMatrix"); + renames.put("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse"); + renames.put("gl_ProjectionMatrix", "iris_ProjectionMatrix"); + renames.put("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse"); + renames.put("gl_NormalMatrix", "iris_NormalMatrix"); + transformer.rename(renames); + + final Map replacements = new HashMap<>(); + replacements.put("gl_ModelViewProjectionMatrix", "(iris_ProjectionMatrix * iris_ModelViewMatrix)"); + replacements.put("gl_TextureMatrix[0]", "mat4(1.0)"); + replacements.put("gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); + replacements.forEach(transformer::replaceExpression); + + // Catch any remaining gl_TextureMatrix references (e.g. [2]-[7]) + transformer.replaceExpression("gl_TextureMatrix", "mat4[8](mat4(1.0), iris_LightmapTextureMatrix, mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0), mat4(1.0))"); + } + + /** + * Inject vertex attributes and ftransform() replacement for composite/depth shaders. Uses locations matching FullScreenQuadRenderer's POSITION_TEXTURE VAO layout. + */ + static void injectCompositeVertexAttributes(Transformer transformer) { + transformer.injectVariable("layout(location = 0) in vec4 iris_Vertex;"); + transformer.injectVariable("layout(location = 2) in vec4 iris_MultiTexCoord0;"); + + transformer.rename("gl_Vertex", "iris_Vertex"); + transformer.rename("gl_MultiTexCoord0", "iris_MultiTexCoord0"); + + transformer.renameFunctionCall("ftransform", "iris_ftransform"); + transformer.injectFunction("vec4 iris_ftransform() { return (iris_ProjectionMatrix * iris_ModelViewMatrix) * iris_Vertex; }"); + + ShaderTransformer.applyIntelHd4000Workaround(transformer); + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java index 01510730b..b1ffee396 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java @@ -1,33 +1,24 @@ package net.coderbot.iris.pipeline.transform; import com.google.common.base.Stopwatch; +import com.gtnewhorizons.angelica.glsm.GlslTransformUtils; +import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.rendering.celeritas.iris.IrisExtendedChunkVertexType; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; -import org.antlr.v4.runtime.CommonToken; -import org.antlr.v4.runtime.tree.ParseTree; -import org.antlr.v4.runtime.tree.ParseTreeWalker; -import org.antlr.v4.runtime.tree.TerminalNode; +import net.coderbot.iris.pipeline.transform.parameter.Parameters; import org.embeddedt.embeddium.impl.gl.shader.ShaderConstants; import org.embeddedt.embeddium.impl.render.shader.ShaderLoader; import org.taumc.glsl.ShaderParser; -import org.taumc.glsl.StorageCollector; import org.taumc.glsl.Transformer; import org.taumc.glsl.grammar.GLSLLexer; -import org.taumc.glsl.grammar.GLSLParser; -import com.gtnewhorizons.angelica.glsm.RenderSystem; - -import java.util.ArrayList; import java.util.EnumMap; -import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -37,11 +28,6 @@ import java.util.regex.Pattern; public class ShaderTransformer { private static final Pattern versionPattern = Pattern.compile("#version\\s+(\\d+)(?:\\s+(\\w+))?"); - private static final Pattern inOutVaryingPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in|out)(\\s+)"); - private static final Pattern inPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(in)(\\s+)"); - private static final Pattern outPattern = Pattern.compile("(?m)^(\\s*(?:(?:flat|smooth|noperspective)\\s+)?)(out)(\\s+)"); - private static final Pattern texturePattern = Pattern.compile("\\btexture\\s*\\(|(\\btexture\\b)"); - private static final Pattern unsignedSuffixPattern = Pattern.compile("(\\b(?:\\d+|0[xX][0-9a-fA-F]+))[uU]\\b"); private static final int CACHE_SIZE = 100; private static final Object2ObjectLinkedOpenHashMap, Map> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>(); @@ -57,26 +43,6 @@ public class ShaderTransformer { loggedNegotiations.clear(); } - private static final Map> versionedReservedWords = new HashMap<>(); - - private static String replaceTexture(String input) { - final var matcher = texturePattern.matcher(input); - final StringBuilder builder = new StringBuilder(); - while (matcher.find()) { - if (matcher.group(1) != null) { - matcher.appendReplacement(builder, "iris_renamed_texture"); - } else { - matcher.appendReplacement(builder, Matcher.quoteReplacement(matcher.group(0))); - } - } - matcher.appendTail(builder); - return builder.toString(); - } - - static { - // sample was added as a keyword in GLSL 400, many shaders use it - versionedReservedWords.put(400, List.of("sample")); - } private record VersionRequirement(String keyword, int minVersion, BooleanSupplier supported) {} @@ -97,68 +63,13 @@ public class ShaderTransformer { }; - private record DowngradeRule( - int fromVersion, - int toVersion, - BooleanSupplier supported, - List extensions, - Map defines, - List preprocessorDefines, - boolean convertStorageQualifiers - ) {} - - private static final DowngradeRule[] DOWNGRADE_RULES = { - new DowngradeRule(130, 120, - RenderSystem::supportsGpuShader4, - List.of("GL_EXT_gpu_shader4"), - Map.of("texture", "texture2D"), - List.of( - // Preprocessor defines - "#define uint int", - "#define uvec2 ivec2", - "#define uvec3 ivec3", - "#define uvec4 ivec4", - "#define isnan(x) ((x) != (x))", - "#define isinf(x) ((x) == (1.0/0.0) || (x) == (-1.0/0.0))", - "#define trunc(x) (sign(x) * floor(abs(x)))", - "#define round(x) (floor((x) + 0.5))", - "#define texelFetch texelFetch2D", - "#define textureSize textureSize2D", - "#define modf iris_modf", - // Function definitions - "GLSL_FUNC:float iris_modf(float x, out float i) { i = sign(x) * floor(abs(x)); return x - i; }", - "GLSL_FUNC:vec2 iris_modf(vec2 x, out vec2 i) { i = sign(x) * floor(abs(x)); return x - i; }", - "GLSL_FUNC:vec3 iris_modf(vec3 x, out vec3 i) { i = sign(x) * floor(abs(x)); return x - i; }", - "GLSL_FUNC:vec4 iris_modf(vec4 x, out vec4 i) { i = sign(x) * floor(abs(x)); return x - i; }", - "GLSL_FUNC:vec2 mix(vec2 a, vec2 b, bvec2 sel) { return vec2(sel.x ? b.x : a.x, sel.y ? b.y : a.y); }", - "GLSL_FUNC:vec3 mix(vec3 a, vec3 b, bvec3 sel) { return vec3(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z); }", - "GLSL_FUNC:vec4 mix(vec4 a, vec4 b, bvec4 sel) { return vec4(sel.x ? b.x : a.x, sel.y ? b.y : a.y, sel.z ? b.z : a.z, sel.w ? b.w : a.w); }", - "GLSL_FUNC:bool any(bool b) { return b; }", - "GLSL_FUNC:bool all(bool b) { return b; }" - ), - true - ) - }; - - record NegotiationResult( - int targetVersion, - String profile, - List extensions, - Map defines, - List preprocessorDefines, - boolean convertStorageQualifiers, - String error - ) { - static NegotiationResult success(int targetVersion, String profile, List extensions, Map defines, List preprocessorDefines, boolean convertStorageQualifiers) { - return new NegotiationResult(targetVersion, profile, extensions, defines, preprocessorDefines, convertStorageQualifiers, null); - } - + record NegotiationResult(int targetVersion, String profile, String error) { static NegotiationResult error(String message) { - return new NegotiationResult(-1, "", List.of(), Map.of(), List.of(), false, message); + return new NegotiationResult(-1, "", message); } static NegotiationResult noop(int version, String profile) { - return new NegotiationResult(version, profile, List.of(), Map.of(), List.of(), false, null); + return new NegotiationResult(version, profile, null); } boolean isError() { return error != null; } @@ -168,8 +79,8 @@ public class ShaderTransformer { return switch (stage) { case COMPUTE -> 330; case TESS_CONTROL, TESS_EVAL -> 400; - case GEOMETRY -> 150; - default -> 110; + case GEOMETRY -> 330; + default -> 330; }; } @@ -177,17 +88,7 @@ public class ShaderTransformer { final int maxGlsl = RenderSystem.getMaxGlslVersion(); if (effectiveVersion <= maxGlsl) { - if (effectiveVersion <= 120 && RenderSystem.supportsGpuShader4()) { - final String profile = ""; - for (DowngradeRule rule : DOWNGRADE_RULES) { - if (rule.fromVersion == 130 && rule.toVersion == 120) { - final List definesOnly = rule.preprocessorDefines.stream().filter(d -> !d.startsWith("GLSL_FUNC:")).toList(); - return NegotiationResult.success(effectiveVersion, profile, rule.extensions, rule.defines, definesOnly, true); - } - } - return NegotiationResult.success(effectiveVersion, profile, List.of("GL_EXT_gpu_shader4"), Map.of(), List.of(), true); - } - return NegotiationResult.noop(effectiveVersion, effectiveVersion >= 150 ? "compatibility" : ""); + return NegotiationResult.noop(effectiveVersion, effectiveVersion >= 150 ? "core" : ""); } final int stageMin = getStageMinimumVersion(stage); @@ -195,44 +96,7 @@ public class ShaderTransformer { return NegotiationResult.error("Hardware GLSL " + maxGlsl + " below stage minimum " + stageMin + " for " + stage.name()); } - // Walk downgrade rules from effectiveVersion toward maxGlsl - final List accExtensions = new ArrayList<>(); - final Map accDefines = new HashMap<>(); - final List accPreprocessorDefines = new ArrayList<>(); - boolean accConvertQualifiers = false; - int currentVersion = effectiveVersion; - - while (currentVersion > maxGlsl) { - DowngradeRule matched = null; - for (DowngradeRule rule : DOWNGRADE_RULES) { - if (rule.fromVersion == currentVersion) { - matched = rule; - break; - } - } - - if (matched == null) { - return NegotiationResult.error("No downgrade rule from GLSL " + currentVersion + " (hardware max: " + maxGlsl + ", shader requires: " + effectiveVersion + ")"); - } - - // Verify rule's required extensions are supported - if (!matched.supported.getAsBoolean()) { - return NegotiationResult.error("Downgrade from " + matched.fromVersion + " to " + matched.toVersion + " requires extensions " + matched.extensions + " which are not supported"); - } - - accExtensions.addAll(matched.extensions); - accDefines.putAll(matched.defines); - accPreprocessorDefines.addAll(matched.preprocessorDefines); - accConvertQualifiers |= matched.convertStorageQualifiers; - currentVersion = matched.toVersion; - } - - if (currentVersion < stageMin) { - return NegotiationResult.error("Downgrade reached GLSL " + currentVersion + " which is below stage minimum " + stageMin + " for " + stage.name()); - } - - final String profile = currentVersion >= 150 ? "compatibility" : ""; - return NegotiationResult.success(currentVersion, profile, accExtensions, accDefines, accPreprocessorDefines, accConvertQualifiers); + return NegotiationResult.error("Shader requires GLSL " + effectiveVersion + " but hardware max is " + maxGlsl); } private static Pattern hoistPattern; @@ -433,39 +297,26 @@ public class ShaderTransformer { versionString = String.valueOf(versionInt); } - String profileString = "#version " + versionString + " core\n"; + final String profileString = "#version " + versionString + " core\n"; - // Rename reserved words - String input = replaceTexture(compute); - for (int version : versionedReservedWords.keySet()) { - if (versionInt < version) { - for (String reservedWord : versionedReservedWords.get(version)) { - final String newName = "iris_renamed_" + reservedWord; - input = input.replaceAll("\\b" + reservedWord + "\\b", newName); - } - } - } + // Pre-parse reserved word renaming + String input = GlslTransformUtils.replaceTexture(compute); + input = GlslTransformUtils.renameReservedWords(input, versionInt); final var parsedShader = ShaderParser.parseShader(input); final var transformer = new Transformer(parsedShader.full()); - doTransform(transformer, patchType, parameters, "core", versionInt); + doTransform(transformer, patchType, parameters, versionInt); // Extract extensions - final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); + final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); final String finalHeader = profileString + (extensions.isEmpty() ? "" : "\n" + extensions); final StringBuilder formattedShaderBuilder = new StringBuilder(); - transformer.mutateTree(tree -> { - formattedShaderBuilder.append(getFormattedShader(tree, finalHeader)); - }); + transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader))); - String formattedShader = formattedShaderBuilder.toString(); - - // Restore identifiers that were temporarily renamed - formattedShader = formattedShader.replace("iris_renamed_texture", "texture"); - formattedShader = formattedShader.replace("iris_renamed_sample", "sample"); + String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString()); result.put(PatchShaderType.COMPUTE, formattedShader); @@ -478,8 +329,6 @@ public class ShaderTransformer { final EnumMap result = new EnumMap<>(PatchShaderType.class); final EnumMap types = new EnumMap<>(PatchShaderType.class); final EnumMap prepatched = new EnumMap<>(PatchShaderType.class); - final EnumMap negotiations = new EnumMap<>(PatchShaderType.class); - final EnumMap needsTextureLodExtension = new EnumMap<>(PatchShaderType.class); final Stopwatch watch = Stopwatch.createStarted(); @@ -501,7 +350,6 @@ public class ShaderTransformer { continue; } - String profile = ""; int versionInt = Integer.parseInt(versionString); // Include celeritas header in scan — it's injected post-negotiation but contains uint/uvec3 @@ -513,62 +361,35 @@ public class ShaderTransformer { versionString = String.valueOf(versionInt); } - // Negotiate version downgrade if needed + // Ensure minimum version for this stage (330 for most, 400 for tessellation) + final int stageMin = getStageMinimumVersion(type); + if (versionInt < stageMin) { + versionInt = stageMin; + versionString = String.valueOf(versionInt); + } + + // Negotiate version if needed (error if hardware can't support) final NegotiationResult negotiation = negotiateVersion(versionInt, type); if (negotiation.isError()) { throw new RuntimeException("Shader version negotiation failed for " + type.name() + ": " + negotiation.error()); } - if (negotiation.targetVersion() != versionInt) { - String negotiationKey = type.name() + "_" + versionInt + "_" + negotiation.targetVersion(); - if (loggedNegotiations.add(negotiationKey)) { - Iris.logger.info("Negotiated {} shader from GLSL {} to {} (extensions: {}, polyfills: {})", type.name(), versionInt, negotiation.targetVersion(), negotiation.extensions(), negotiation.preprocessorDefines().size()); - } - versionInt = negotiation.targetVersion(); - versionString = String.valueOf(versionInt); - profile = negotiation.profile(); - } else { - if (versionInt >= 150) { - profile = matcher.group(2); - if (profile == null) { - profile = "compatibility"; - } - } - } - negotiations.put(type, negotiation); + // All stages >= 330 use core profile + final String profile = "core"; + final String profileString = "#version " + versionString + " " + profile + "\n"; - final String profileString = "#version " + versionString + (profile.isEmpty() ? "" : " " + profile) + "\n"; - - input = replaceTexture(input); - // The primary reason we rename words here using regex, is because if the words cause invalid - // GLSL, regardless of the version being used, it will cause glsl-transformation-lib to fail - // so we need to rename them prior to passing the shader input to glsl-transformation-lib. - for (int version : versionedReservedWords.keySet()) { - if (versionInt < version) { - for (String reservedWord : versionedReservedWords.get(version)) { - final String newName = "iris_renamed_" + reservedWord; - input = input.replaceAll("\\b" + reservedWord + "\\b", newName); - } - } - } + // Pre-parse reserved word renaming — prevents ANTLR parse failures + input = GlslTransformUtils.replaceTexture(input); + input = GlslTransformUtils.renameReservedWords(input, versionInt); final var parsedShader = ShaderParser.parseShader(input); final var transformer = new Transformer(parsedShader.full()); - if (parameters.type == ShaderType.VERTEX || parameters.type == ShaderType.FRAGMENT) { - upgradeStorageQualifiers(transformer, parameters); - } - - doTransform(transformer, patchType, parameters, profile, versionInt); - - // Check if we need to patch in texture LOD extension enabling - if (versionInt <= 120 && (transformer.containsCall("texture2DLod") || transformer.containsCall("texture3DLod") || transformer.containsCall("texture2DGradARB"))) { - needsTextureLodExtension.put(type, true); - } + doTransform(transformer, patchType, parameters, versionInt); // Extract extensions from the pre-parsed content (version + extensions before main code) // This preserves #extension directives that the shader pack declares - final var extensions = versionPattern.matcher(getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); + final var extensions = versionPattern.matcher(GlslTransformUtils.getFormattedShader(parsedShader.pre(), "")).replaceFirst("").trim(); types.put(type, transformer); prepatched.put(type, profileString + (extensions.isEmpty() ? "" : "\n" + extensions)); @@ -578,7 +399,6 @@ public class ShaderTransformer { final PatchShaderType shaderType = entry.getKey(); final Transformer transformer = entry.getValue(); String header = prepatched.get(shaderType); - final NegotiationResult negotiation = negotiations.get(shaderType); // For Celeritas terrain vertex shaders, inject chunk_vertex.glsl header if (patchType == Patch.CELERITAS_TERRAIN && shaderType == PatchShaderType.VERTEX) { @@ -588,46 +408,9 @@ public class ShaderTransformer { final String finalHeader = header; final StringBuilder formattedShaderBuilder = new StringBuilder(); - transformer.mutateTree(tree -> { - formattedShaderBuilder.append(getFormattedShader(tree, finalHeader)); - }); + transformer.mutateTree(tree -> formattedShaderBuilder.append(GlslTransformUtils.getFormattedShader(tree, finalHeader))); - String formattedShader = formattedShaderBuilder.toString(); - - // Restore identifiers that were temporarily renamed to dodge GLSL reserved keywords. - formattedShader = formattedShader.replace("iris_renamed_texture", "texture"); - formattedShader = formattedShader.replace("iris_renamed_sample", "sample"); - - // Inject texture LOD extension if needed - if (needsTextureLodExtension.containsKey(shaderType)) { - final String[] parts = formattedShader.split("\n", 2); - parts[1] = "#extension GL_ARB_shader_texture_lod : require\n" + parts[1]; - formattedShader = parts[0] + "\n" + parts[1]; - } - - if (negotiation != null && (!negotiation.extensions().isEmpty() || !negotiation.preprocessorDefines().isEmpty())) { - formattedShader = injectGlslPreamble(formattedShader, negotiation.extensions(), negotiation.preprocessorDefines()); - } - - if (negotiation != null && !negotiation.defines().isEmpty()) { - for (var defineEntry : negotiation.defines().entrySet()) { - formattedShader = formattedShader.replaceAll("\\b" + Pattern.quote(defineEntry.getKey()) + "\\b", Matcher.quoteReplacement(defineEntry.getValue())); - } - } - - // Convert storage qualifiers for downgraded shaders or native 120 shaders - if (negotiation != null && (negotiation.convertStorageQualifiers() || negotiation.targetVersion() <= 120)) { - if (shaderType == PatchShaderType.VERTEX) { - final Matcher inMatcher = inPattern.matcher(formattedShader); - formattedShader = inMatcher.replaceAll("$1attribute$3"); - final Matcher outMatcher = outPattern.matcher(formattedShader); - formattedShader = outMatcher.replaceAll("$1varying$3"); - } else { - final Matcher inOutVaryingMatcher = inOutVaryingPattern.matcher(formattedShader); - formattedShader = inOutVaryingMatcher.replaceAll("$1varying$3"); - } - formattedShader = unsignedSuffixPattern.matcher(formattedShader).replaceAll("$1"); - } + String formattedShader = GlslTransformUtils.restoreReservedWords(formattedShaderBuilder.toString()); result.put(shaderType, formattedShader); } @@ -636,7 +419,7 @@ public class ShaderTransformer { return result; } - private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, String profile, int versionInt) { + private static void doTransform(Transformer transformer, Patch patchType, Parameters parameters, int versionInt) { switch (patchType) { case CELERITAS_TERRAIN: CeleritasTransformer.transform(transformer, parameters, versionInt); @@ -649,7 +432,7 @@ public class ShaderTransformer { CompositeDepthTransformer.transform(transformer, parameters, versionInt); break; case ATTRIBUTES: - AttributeTransformer.transform(transformer, (AttributeParameters) parameters, profile, versionInt); + AttributeTransformer.transform(transformer, (AttributeParameters) parameters, versionInt); break; case COMPUTE: ComputeTransformer.transform(transformer, parameters, versionInt); @@ -729,126 +512,5 @@ public class ShaderTransformer { return "\n\n" + chunkVertexHeader + "\n\n"; } - /** - * Converts GLSL 120 storage qualifiers (varying/attribute) to modern in/out tokens so downstream AST transforms (e.g. CompatibilityTransformer) can find them. - * The hacky120Patches regex pass converts them back for the final output. - */ - public static void upgradeStorageQualifiers(Transformer root, Parameters parameters) { - final List tokens = new ArrayList<>(); - root.mutateTree(tree -> ParseTreeWalker.DEFAULT.walk(new StorageCollector(tokens), tree)); - - for (TerminalNode node : tokens) { - if (!(node.getSymbol() instanceof CommonToken token)) { - return; - } - if (token.getType() == GLSLParser.ATTRIBUTE) { - token.setType(GLSLParser.IN); - token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", "")); - } else if (token.getType() == GLSLParser.VARYING) { - if (parameters.type == ShaderType.VERTEX) { - token.setType(GLSLParser.OUT); - token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.OUT).replace("'", "")); - } else { - token.setType(GLSLParser.IN); - token.setText(GLSLParser.VOCABULARY.getLiteralName(GLSLParser.IN).replace("'", "")); - } - } - } - } - - private static String injectGlslPreamble(String shader, List extensions, List preprocessorDefines) { - final StringBuilder extensionBlock = new StringBuilder(); - final StringBuilder defineBlock = new StringBuilder(); - final StringBuilder functionBlock = new StringBuilder(); - - for (String ext : extensions) { - extensionBlock.append("#extension ").append(ext).append(" : require\n"); - } - for (String define : preprocessorDefines) { - if (define.startsWith("GLSL_FUNC:")) { - functionBlock.append(define.substring(10)).append("\n"); - } else { - defineBlock.append(define).append("\n"); - } - } - - // Find where preprocessor section ends and code begins - final String[] lines = shader.split("\n"); - final StringBuilder shaderResult = new StringBuilder(); - boolean extensionsInjected = false, definesInjected = false, functionsInjected = false; - - for (String line : lines) { - final String trimmed = line.trim(); - final boolean isPreprocessor = trimmed.startsWith("#"); - final boolean isExtension = trimmed.startsWith("#extension"); - final boolean isVersion = trimmed.startsWith("#version"); - - // Inject our extensions right after #version - if (isVersion) { - shaderResult.append(line).append("\n"); - shaderResult.append(extensionBlock); - extensionsInjected = true; - continue; - } - - // Inject our defines after the last #extension line (before other preprocessor or code) - if (!definesInjected && extensionsInjected && !isExtension && !trimmed.isEmpty()) { - shaderResult.append(defineBlock); - definesInjected = true; - } - - // Inject our functions after all preprocessor lines - if (!functionsInjected && definesInjected && !isPreprocessor && !trimmed.isEmpty()) { - shaderResult.append(functionBlock); - functionsInjected = true; - } - - shaderResult.append(line).append("\n"); - } - - if (!definesInjected) shaderResult.append(defineBlock); - if (!functionsInjected) shaderResult.append(functionBlock); - - return shaderResult.toString(); - } - - public static String getFormattedShader(ParseTree tree, String string) { - final StringBuilder sb = new StringBuilder(string + "\n"); - final String[] tabHolder = {""}; - getFormattedShader(tree, sb, tabHolder); - return sb.toString(); - } - - private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder, String[] tabHolder) { - if (tree instanceof TerminalNode) { - final String text = tree.getText(); - if (text.equals("")) { - return; - } - if (text.equals("#")) { - stringBuilder.append("\n#"); - return; - } - stringBuilder.append(text); - if (text.equals("{")) { - stringBuilder.append(" \n\t"); - tabHolder[0] = "\t"; - } - - if (text.equals("}")) { - if (stringBuilder.length() >= 2) { - stringBuilder.deleteCharAt(stringBuilder.length() - 2); - } - tabHolder[0] = ""; - stringBuilder.append(" \n"); - } else { - stringBuilder.append(text.equals(";") ? " \n" + tabHolder[0] : " "); - } - } else { - for (int i = 0; i < tree.getChildCount(); ++i) { - getFormattedShader(tree.getChild(i), stringBuilder, tabHolder); - } - } - } } diff --git a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java b/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java index 9e3c54cd9..b13872ce3 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java +++ b/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java @@ -49,13 +49,6 @@ public class CenterDepthSampler { try { String fsh = new String(IOUtils.toByteArray(Objects.requireNonNull(getClass().getResourceAsStream("/centerDepth.fsh"))), StandardCharsets.UTF_8); - - if (GLStateManager.capabilities.OpenGL32) { - fsh = fsh.replace("VERSIONPLACEHOLDER", "150 compatibility"); - } else { - fsh = fsh.replace("#define IS_GL3", ""); - fsh = fsh.replace("VERSIONPLACEHOLDER", "120"); - } String vsh = new String(IOUtils.toByteArray(Objects.requireNonNull(getClass().getResourceAsStream("/centerDepth.vsh"))), StandardCharsets.UTF_8); builder = ProgramBuilder.begin("centerDepthSmooth", vsh, null, fsh, ImmutableSet.of(0, 1, 2)); diff --git a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java index 06f8fbb72..b30e69e38 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java @@ -17,6 +17,7 @@ import net.coderbot.iris.gl.program.ProgramBuilder; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.gl.sampler.SamplerLimits; +import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.gl.texture.TextureAccess; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.WorldRenderingPipeline; @@ -32,7 +33,6 @@ import net.coderbot.iris.shaderpack.ProgramDirectives; import net.coderbot.iris.shaderpack.ProgramSource; import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.shadows.ShadowRenderTargets; -import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.uniforms.CommonUniforms; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; @@ -42,7 +42,6 @@ import net.minecraft.client.shader.Framebuffer; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; @@ -291,6 +290,7 @@ public class CompositeRenderer { renderPass.program.use(); this.customUniforms.push(renderPass.program); + FullScreenQuadRenderer.uploadCompositeMatrices(); FullScreenQuadRenderer.INSTANCE.renderQuad(); } @@ -302,7 +302,7 @@ public class CompositeRenderer { Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); - GL20.glUseProgram(0); + GLStateManager.glUseProgram(0); // NB: Unbinding all of these textures is necessary for proper shaderpack reloading. for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { diff --git a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java index 5ef6f1463..4e37129c0 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java @@ -15,6 +15,7 @@ import net.coderbot.iris.gl.program.ProgramBuilder; import net.coderbot.iris.gl.program.ProgramSamplers; import net.coderbot.iris.gl.program.ProgramUniforms; import net.coderbot.iris.gl.sampler.SamplerLimits; +import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.gl.texture.TextureAccess; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.WorldRenderingPipeline; @@ -31,7 +32,6 @@ import net.coderbot.iris.shaderpack.ProgramSet; import net.coderbot.iris.shaderpack.ProgramSource; import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.shadows.ShadowRenderTargets; -import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.uniforms.CommonUniforms; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; @@ -41,7 +41,6 @@ import net.minecraft.client.shader.Framebuffer; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL42; @@ -237,6 +236,7 @@ public class FinalPassRenderer { finalPass.program.use(); this.customUniforms.push(finalPass.program); + FullScreenQuadRenderer.uploadCompositeMatrices(); FullScreenQuadRenderer.INSTANCE.renderQuad(); @@ -284,7 +284,7 @@ public class FinalPassRenderer { main.bindFramebuffer(true); ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); - GL20.glUseProgram(0); + GLStateManager.glUseProgram(0); for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { // Unbind all textures that we may have used. diff --git a/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java b/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java index 5b76e2afa..56d10156a 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java +++ b/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java @@ -4,9 +4,11 @@ package net.coderbot.iris.postprocess; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; +import org.lwjgl.opengl.GL20; import java.nio.FloatBuffer; @@ -15,11 +17,18 @@ import java.nio.FloatBuffer; */ public class FullScreenQuadRenderer { private final int quadBuffer; + private final int vao; public static final FullScreenQuadRenderer INSTANCE = new FullScreenQuadRenderer(); private FullScreenQuadRenderer() { + this.vao = org.lwjgl.opengl.GL30.glGenVertexArrays(); + GLStateManager.glBindVertexArray(vao); this.quadBuffer = createQuad(); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, quadBuffer); + DefaultVertexFormat.POSITION_TEXTURE.setupBufferState(0L); + GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glBindVertexArray(0); } public void render() { @@ -33,21 +42,20 @@ public class FullScreenQuadRenderer { public void begin() { GLStateManager.disableDepthTest(); - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); // scale the quad from [0, 1] to [-1, 1] - GL11.glTranslatef(-1.0F, -1.0F, 0.0F); - GL11.glScalef(2.0F, 2.0F, 0.0F); + GLStateManager.glTranslatef(-1.0F, -1.0F, 0.0F); + GLStateManager.glScalef(2.0F, 2.0F, 1.0F); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPushMatrix(); - GL11.glLoadIdentity(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glPushMatrix(); + GLStateManager.glLoadIdentity(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, quadBuffer); - DefaultVertexFormat.POSITION_TEXTURE.setupBufferState(0L); + GLStateManager.glBindVertexArray(vao); } public void renderQuad() { @@ -55,15 +63,45 @@ public class FullScreenQuadRenderer { } public static void end() { - DefaultVertexFormat.POSITION_TEXTURE.clearBufferState(); - GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); + GLStateManager.glBindVertexArray(0); GLStateManager.enableDepthTest(); - GL11.glMatrixMode(GL11.GL_PROJECTION); - GL11.glPopMatrix(); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_PROJECTION); + GLStateManager.glPopMatrix(); + GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); + GLStateManager.glPopMatrix(); + } + + private static final FloatBuffer matBuf = BufferUtils.createFloatBuffer(16); + + /** Per-program cached uniform locations: [mvLoc, projLoc]. Populated on first miss. */ + private static final Int2ObjectOpenHashMap compositeLocCache = new Int2ObjectOpenHashMap<>(); + + public static void uploadCompositeMatrices() { + final int program = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM); + if (program == 0) return; + + int[] locs = compositeLocCache.get(program); + if (locs == null) { + locs = new int[] { + GL20.glGetUniformLocation(program, "iris_ModelViewMatrix"), + GL20.glGetUniformLocation(program, "iris_ProjectionMatrix") + }; + compositeLocCache.put(program, locs); + } + + if (locs[0] != -1) { + GLStateManager.getModelViewMatrix().get(matBuf); + matBuf.rewind(); + GL20.glUniformMatrix4(locs[0], false, matBuf); + } + + if (locs[1] != -1) { + GLStateManager.getProjectionMatrix().get(matBuf); + matBuf.rewind(); + GL20.glUniformMatrix4(locs[1], false, matBuf); + } } /** diff --git a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java b/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java index ad89b3088..645190afa 100644 --- a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java +++ b/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java @@ -1,7 +1,5 @@ package net.coderbot.iris.texture.util; -import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*; - import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.Minecraft; @@ -12,6 +10,8 @@ import org.lwjgl.opengl.GL30; import java.nio.FloatBuffer; import java.nio.IntBuffer; +import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.stackPush; + public class TextureManipulationUtil { private static int colorFillFBO = -1; @@ -29,7 +29,7 @@ public class TextureManipulationUtil { GL11.glGetInteger(GL11.GL_VIEWPORT, previousViewportBuffer); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, colorFillFBO); - GL11.glClearColor( + GLStateManager.glClearColor( (rgba >> 24 & 0xFF) / 255.0f, (rgba >> 16 & 0xFF) / 255.0f, (rgba >> 8 & 0xFF) / 255.0f, @@ -45,7 +45,7 @@ public class TextureManipulationUtil { GL11.GL_TEXTURE_2D, textureId, level); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); + GLStateManager.glClear(GL11.GL_COLOR_BUFFER_BIT); if (Minecraft.isRunningOnMac) { GL11.glGetError(); } @@ -59,7 +59,7 @@ public class TextureManipulationUtil { } OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, previousFramebufferId); - GL11.glClearColor( + GLStateManager.glClearColor( previousClearColorBuffer.get(0), previousClearColorBuffer.get(1), previousClearColorBuffer.get(2), diff --git a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java b/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java index 1a9b6e0ca..8d0852e51 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java @@ -10,6 +10,7 @@ public class ExternallyManagedUniforms { public static void addExternallyManagedUniforms(UniformHolder uniformHolder) { addMat4(uniformHolder, "iris_ModelViewMatrix"); + addMat4(uniformHolder, "iris_ProjectionMatrix"); addMat4(uniformHolder, "u_ModelViewProjectionMatrix"); addMat4(uniformHolder, "iris_NormalMatrix"); uniformHolder.externallyManagedUniform("heavyFog", UniformType.BOOL); diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java index 35804e1f1..52bcb3fbb 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java +++ b/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java @@ -5,6 +5,7 @@ import net.coderbot.iris.gl.state.FogMode; import net.coderbot.iris.gl.uniform.DynamicUniformHolder; import org.joml.Vector3d; import org.joml.Vector4f; +import org.lwjgl.opengl.GL11; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; @@ -14,6 +15,13 @@ public class IrisInternalUniforms { private IrisInternalUniforms() { } + private static float getEffectiveAlphaRef() { + if (!GLStateManager.getAlphaTest().isEnabled() || GLStateManager.getAlphaState().getFunction() == GL11.GL_ALWAYS) { + return -1.0f; + } + return GLStateManager.getAlphaState().getReference(); + } + public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode) { uniforms.uniform4f(PER_FRAME, "iris_FogColor", () -> { final Vector3d color = GLStateManager.getFogState().getFogColor(); @@ -26,7 +34,7 @@ public class IrisInternalUniforms { .uniform1f(PER_FRAME, "iris_FogDensity", () -> Math.max(0.0F, GLStateManager.getFogState().getDensity())); uniforms - .uniform1f(PER_FRAME, "iris_currentAlphaTest", () -> GLStateManager.getAlphaState().getReference()) - .uniform1f(PER_FRAME, "alphaTestRef", () -> GLStateManager.getAlphaState().getReference()); + .uniform1f(PER_FRAME, "iris_currentAlphaTest", IrisInternalUniforms::getEffectiveAlphaRef) + .uniform1f(PER_FRAME, "alphaTestRef", IrisInternalUniforms::getEffectiveAlphaRef); } } diff --git a/src/main/resources/assets/angelica/shaders/debug_graph.frag.glsl b/src/main/resources/assets/angelica/shaders/debug_graph.frag.glsl index 72876c9ee..7e4a2130c 100644 --- a/src/main/resources/assets/angelica/shaders/debug_graph.frag.glsl +++ b/src/main/resources/assets/angelica/shaders/debug_graph.frag.glsl @@ -1,4 +1,4 @@ -#version 120 +#version 330 core uniform int headIdx; uniform float scaleFactor; @@ -7,6 +7,8 @@ uniform float pxPerNs; uniform bool left; uniform float fbWidth; +out vec4 fragColor; + void main() { // Get position - gl_FragCoord starts from the lower left and returns the position of the center of the pixel // i.e. the lower-left-most pixel is (0.5, 0.5). Shift if we're on the right side of the screen. @@ -31,5 +33,5 @@ void main() { float g = 1.0 - clamp((time - midNs) / midNs, 0.0, 1.0); if (dy <= height) color = vec4(r, g, 0.0, 1.0); - gl_FragColor = color; + fragColor = color; } diff --git a/src/main/resources/assets/angelica/shaders/debug_graph.vert.glsl b/src/main/resources/assets/angelica/shaders/debug_graph.vert.glsl index 87c578a3c..ad976ae9d 100644 --- a/src/main/resources/assets/angelica/shaders/debug_graph.vert.glsl +++ b/src/main/resources/assets/angelica/shaders/debug_graph.vert.glsl @@ -1,6 +1,6 @@ -#version 120 +#version 330 core -attribute vec2 pos; +layout(location = 0) in vec2 pos; uniform float fbWidth; uniform float fbHeight; diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.fsh b/src/main/resources/assets/angelica/shaders/fontFilter.fsh index b6be624a3..8d0f8c2cf 100644 --- a/src/main/resources/assets/angelica/shaders/fontFilter.fsh +++ b/src/main/resources/assets/angelica/shaders/fontFilter.fsh @@ -1,11 +1,14 @@ -#version 120 +#version 330 core uniform sampler2D sampler; uniform int aaMode; uniform float strength; -varying vec4 color; -varying vec4 tB; +in vec4 color; +in vec4 tB; +in vec2 texCoord; + +out vec4 fragColor; /* Hacky MSAA and anisotropic filtering. Cursed beyond belief. There _may_ have been simpler means of @@ -23,45 +26,49 @@ float txSample(vec2 uv, float du, float dv, float factorU, float factorV) { if (finalU < tB.x || finalU > tB.y || finalV < tB.z || finalV > tB.w) { return 0.0f; } - return weight * texture2D(sampler, vec2(finalU, finalV)).a; + return weight * texture(sampler, vec2(finalU, finalV)).a; } void main() { - vec2 texCoords = gl_TexCoord[0].st; - vec2 texScaled = texCoords * strength; vec4 col = color; float original_alpha = col.a; - if (texCoords.s != 0 || texCoords.t != 0) { - float res = 0; - float fu = abs(dFdx(texScaled.x)) + abs(dFdy(texScaled.x)); - float fv = abs(dFdx(texScaled.y)) + abs(dFdy(texScaled.y)); - totalWt = 0; - if (aaMode == 1) { - res += txSample(texCoords, 2, 6, fu, fv); - res += txSample(texCoords, 6, -2, fu, fv); - res += txSample(texCoords, -2, -6, fu, fv); - res += txSample(texCoords, -6, 2, fu, fv); + if (texCoord.s != 0 || texCoord.t != 0) { + if (aaMode == 0) { + // No AA — single texture sample + col.a = original_alpha * texture(sampler, texCoord).a; } else { - res += txSample(texCoords, 1, 1, fu, fv); - res += txSample(texCoords, -1, -3, fu, fv); - res += txSample(texCoords, -3, 2, fu, fv); - res += txSample(texCoords, 4, -1, fu, fv); - res += txSample(texCoords, -5, -2, fu, fv); - res += txSample(texCoords, 2, 5, fu, fv); - res += txSample(texCoords, 5, 3, fu, fv); - res += txSample(texCoords, 3, -5, fu, fv); - res += txSample(texCoords, -2, 6, fu, fv); - res += txSample(texCoords, 0, -7, fu, fv); - res += txSample(texCoords, -4, -6, fu, fv); - res += txSample(texCoords, -6, 4, fu, fv); - res += txSample(texCoords, -8, 0, fu, fv); - res += txSample(texCoords, 7, -4, fu, fv); - res += txSample(texCoords, 6, 7, fu, fv); - res += txSample(texCoords, -7, -8, fu, fv); + vec2 texScaled = texCoord * strength; + float res = 0; + float fu = abs(dFdx(texScaled.x)) + abs(dFdy(texScaled.x)); + float fv = abs(dFdx(texScaled.y)) + abs(dFdy(texScaled.y)); + totalWt = 0; + if (aaMode == 1) { + res += txSample(texCoord, 2, 6, fu, fv); + res += txSample(texCoord, 6, -2, fu, fv); + res += txSample(texCoord, -2, -6, fu, fv); + res += txSample(texCoord, -6, 2, fu, fv); + } else { + res += txSample(texCoord, 1, 1, fu, fv); + res += txSample(texCoord, -1, -3, fu, fv); + res += txSample(texCoord, -3, 2, fu, fv); + res += txSample(texCoord, 4, -1, fu, fv); + res += txSample(texCoord, -5, -2, fu, fv); + res += txSample(texCoord, 2, 5, fu, fv); + res += txSample(texCoord, 5, 3, fu, fv); + res += txSample(texCoord, 3, -5, fu, fv); + res += txSample(texCoord, -2, 6, fu, fv); + res += txSample(texCoord, 0, -7, fu, fv); + res += txSample(texCoord, -4, -6, fu, fv); + res += txSample(texCoord, -6, 4, fu, fv); + res += txSample(texCoord, -8, 0, fu, fv); + res += txSample(texCoord, 7, -4, fu, fv); + res += txSample(texCoord, 6, 7, fu, fv); + res += txSample(texCoord, -7, -8, fu, fv); + } + res /= totalWt; + col.a = original_alpha * res; } - res /= totalWt; - col.a = original_alpha * res; } - gl_FragColor = col; + fragColor = col; } diff --git a/src/main/resources/assets/angelica/shaders/fontFilter.vsh b/src/main/resources/assets/angelica/shaders/fontFilter.vsh index 09b0a9ff2..86de3be35 100644 --- a/src/main/resources/assets/angelica/shaders/fontFilter.vsh +++ b/src/main/resources/assets/angelica/shaders/fontFilter.vsh @@ -1,12 +1,19 @@ -#version 120 +#version 330 core -attribute vec4 texBounds; -varying vec4 tB; -varying vec4 color; +layout(location = 0) in vec2 a_Position; +layout(location = 1) in vec4 a_Color; +layout(location = 2) in vec2 a_TexCoord0; +layout(location = 3) in vec4 a_TexBounds; + +uniform mat4 u_MVPMatrix; + +out vec4 tB; +out vec4 color; +out vec2 texCoord; void main() { - gl_Position = ftransform(); - gl_TexCoord[0] = gl_MultiTexCoord0; - color = gl_Color; - tB = texBounds; + gl_Position = u_MVPMatrix * vec4(a_Position, 0.0, 1.0); + texCoord = a_TexCoord0; + color = a_Color; + tB = a_TexBounds; } diff --git a/src/main/resources/centerDepth.fsh b/src/main/resources/centerDepth.fsh index edf76e80a..4039c7016 100644 --- a/src/main/resources/centerDepth.fsh +++ b/src/main/resources/centerDepth.fsh @@ -1,32 +1,20 @@ -#version VERSIONPLACEHOLDER - -// This will be removed by Iris if the system does not support GL3. -#define IS_GL3 +#version 330 core uniform sampler2D depth; uniform sampler2D altDepth; uniform float lastFrameTime; uniform float decay; -#ifdef IS_GL3 out float oculus_fragColor; -#endif void main() { - float currentDepth = texture2D(depth, vec2(0.5)).r; + float currentDepth = texture(depth, vec2(0.5)).r; float decay2 = 1.0 - exp(-decay * lastFrameTime); - float oldDepth = texture2D(altDepth, vec2(0.5)).r; + float oldDepth = texture(altDepth, vec2(0.5)).r; - #ifdef IS_GL3 if (isnan(oldDepth)) { oldDepth = currentDepth; } oculus_fragColor = mix(oldDepth, currentDepth, decay2); - #else - if (oldDepth != oldDepth) { // cheap isNaN - oldDepth = currentDepth; - } - gl_FragColor = vec4(mix(texture2D(altDepth, vec2(0.5)).r, currentDepth, decay2), 0, 0, 0); - #endif -} \ No newline at end of file +} diff --git a/src/main/resources/centerDepth.vsh b/src/main/resources/centerDepth.vsh index ce81abb06..6c45b62bb 100644 --- a/src/main/resources/centerDepth.vsh +++ b/src/main/resources/centerDepth.vsh @@ -1,2 +1,8 @@ -#version 120 -void main() { gl_Position = ftransform(); } +#version 330 core + +layout(location = 0) in vec3 a_Position; + +void main() { + // Full-screen quad vertices are in [0,1] range, map to [-1,1] clip space + gl_Position = vec4(a_Position.xyz * 2.0 - 1.0, 1.0); +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java new file mode 100644 index 000000000..041f8e1df --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/MixinForgeHooksClient_CoreProfile.java @@ -0,0 +1,70 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica; + +import net.minecraftforge.client.ForgeHooksClient; +import org.lwjgl.LWJGLException; +import org.lwjgl.opengl.ContextAttribs; +import org.lwjgl.opengl.Display; +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.PixelFormat; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; + +import javax.imageio.ImageIO; + +/** + * Requests a GL 3.3 core profile context + */ +@Mixin(value = ForgeHooksClient.class, remap = false) +public abstract class MixinForgeHooksClient_CoreProfile { + + @Shadow static int stencilBits; + + /** + * @author Angelica + * @reason Request GL 3.3 core profile context + */ + @Overwrite + public static void createDisplay() throws LWJGLException { + ImageIO.setUseCache(false); + final PixelFormat format = new PixelFormat().withDepthBits(24); + final ContextAttribs attribs = new ContextAttribs(3, 3) + .withProfileCore(true) + .withForwardCompatible(true); + + // Preserve vanilla Forge stencil support -- enabled via -Dforge.forceDisplayStencil=true by users/modpacks + final boolean wantStencil = Boolean.parseBoolean(System.getProperty("forge.forceDisplayStencil", "false")); + + if (!wantStencil) { + try { + Display.create(format, attribs); + } catch (LWJGLException e) { + reportContextFailure(e); + throw e; + } + stencilBits = 0; + return; + } + + try { + Display.create(format.withStencilBits(8), attribs); + stencilBits = 8; + } catch (LWJGLException e) { + try { + Display.create(format, attribs); + stencilBits = 0; + } catch (LWJGLException e2) { + reportContextFailure(e2); + throw e2; + } + } + } + + private static void reportContextFailure(LWJGLException e) { + System.err.println("[Angelica] FATAL: Failed to create OpenGL 3.3 core profile context."); + System.err.println("[Angelica] Error: " + e.getMessage()); + try { + System.err.println("[Angelica] GPU: " + GL11.glGetString(GL11.GL_RENDERER) + ", Driver: " + GL11.glGetString(GL11.GL_VERSION)); + } catch (Exception ignored) {} + } +} diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/animation/MixinTextureMap.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/animation/MixinTextureMap.java index 647cab559..e2da8d2f3 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/animation/MixinTextureMap.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/animation/MixinTextureMap.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.animation; import com.gtnewhorizons.angelica.AngelicaMod; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.interfaces.IPatchedTextureAtlasSprite; import com.gtnewhorizons.angelica.utils.AnimationMode; import net.minecraft.client.Minecraft; @@ -37,7 +38,7 @@ public abstract class MixinTextureMap extends AbstractTexture { final boolean renderVisible = AngelicaMod.animationsMode.is(AnimationMode.VISIBLE_ONLY); mc.mcProfiler.startSection("updateAnimations"); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, this.getGlTextureId()); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, this.getGlTextureId()); final int size = listAnimatedSprites.size(); for (int i = 0; i < size; i++) { diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinTextureManager.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinTextureManager.java index 126661adb..b0336042c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinTextureManager.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/debug/MixinTextureManager.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.debug; import com.gtnewhorizons.angelica.glsm.GLDebug; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; @@ -17,9 +18,9 @@ public class MixinTextureManager { private void onTextureLoad(ResourceLocation resource, ITextureObject texture, CallbackInfoReturnable cir) { if(texture != null && texture != TextureUtil.missingTexture) { final int curId = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getGlTextureId()); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, texture.getGlTextureId()); GLDebug.nameObject(GL11.GL_TEXTURE, texture.getGlTextureId(), resource.toString()); - GL11.glBindTexture(GL11.GL_TEXTURE_2D, curId); + GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, curId); } } } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java new file mode 100644 index 000000000..62f9d16dd --- /dev/null +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/ffp/MixinTessellator_CoreProfile.java @@ -0,0 +1,24 @@ +package com.gtnewhorizons.angelica.mixins.early.angelica.ffp; + +import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; +import com.gtnewhorizons.angelica.glsm.ffp.TessellatorStreamingDrawer; +import net.minecraft.client.renderer.Tessellator; +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.CallbackInfoReturnable; + +/** + * Intercepts Tessellator.draw() to use streaming VBO+VAO for core profile rendering, + * except when GTNHLib needs to intercept (display list compilation, DirectTessellator capture). + */ +@Mixin(Tessellator.class) +public class MixinTessellator_CoreProfile { + + @Inject(method = "draw", at = @At("HEAD"), cancellable = true) + private void angelica$coreProfileDraw(CallbackInfoReturnable cir) { + // Let GTNHLib handle display list compilation and DirectTessellator capture + if (TessellatorManager.shouldInterceptDraw((Tessellator)(Object)this)) return; + cir.setReturnValue(TessellatorStreamingDrawer.draw((Tessellator)(Object)this)); + } +} 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 11bd90b00..33b9ef058 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 @@ -8,17 +8,16 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; 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.Constant; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyConstant; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.ModifyConstant; -import org.spongepowered.asm.mixin.injection.Constant; import java.util.Random; @@ -173,7 +172,7 @@ public abstract class MixinFontRenderer implements FontRendererAccessor, IFontPa this.blue = (float)(argb >> 8 & 255) / 255.0F; this.green = (float)(argb & 255) / 255.0F; this.alpha = (float)(argb >> 24 & 255) / 255.0F; - GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); this.posX = (float)x; this.posY = (float)y; return (int) angelica$batcher.drawString(x, y, argb, dropShadow, unicodeFlag, text, 0, text.length()); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java index 27100bb3a..a50f6440f 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/glsm/MixinSplashProgressCaching.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.glsm; import com.gtnewhorizons.angelica.glsm.GLStateManager; +import com.gtnewhorizons.angelica.glsm.recording.ImmediateModeRecorder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; @@ -27,10 +28,19 @@ public class MixinSplashProgressCaching { private static final Logger LOGGER = LogManager.getLogger("Angelica"); /** - * On return from finish() - mark splash complete + * Before splash starts, create a separate DirectTessellator for the splash thread. + */ + @Inject(method = "start", at = @At("HEAD")) + private static void angelica$initSplashTessellator(CallbackInfo ci) { + ImmediateModeRecorder.initSplashTessellator(); + } + + /** + * On return from finish() - destroy splash tessellator and mark splash complete */ @Inject(method = "finish", at = @At("RETURN")) private static void angelica$enableCachingOnFinish(CallbackInfo ci) { + ImmediateModeRecorder.destroySplashTessellator(); GLStateManager.markSplashComplete(); LOGGER.info("Splash Complete"); } diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/hudcaching/MixinRenderItem.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/hudcaching/MixinRenderItem.java index 0418164cb..8092cf03a 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/hudcaching/MixinRenderItem.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/angelica/hudcaching/MixinRenderItem.java @@ -1,10 +1,10 @@ package com.gtnewhorizons.angelica.mixins.early.angelica.hudcaching; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.mixins.dummy.DummyTessellator; import com.llamalad7.mixinextras.injector.ModifyExpressionValue; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderItem; -import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -32,7 +32,7 @@ public class MixinRenderItem { ) ) private void angelica$neuterGlDisable(int cap) { - if (cap == GL_LIGHTING) GL11.glDisable(cap); + if (cap == GL_LIGHTING) GLStateManager.glDisable(cap); } @Redirect( 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 fb7d79c4f..8c7ff33bd 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 @@ -111,19 +111,12 @@ public class MixinRenderGlobal implements IRenderGlobalExt { this.celeritas$renderer.scheduleTerrainUpdate(); } - @Unique - private static boolean sortAndRenderLogged = false; - /** * @author celeritas * @reason Redirect to our renderer with Iris phase support */ @Overwrite public int sortAndRender(EntityLivingBase entity, int pass, double partialTicks) { - if (!sortAndRenderLogged && ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { - Iris.logger.info("[SHADOW DEBUG] sortAndRender called! pass={}", pass); - sortAndRenderLogged = true; - } final WorldRenderingPipeline pipeline; if (!Iris.enabled) { diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/clouds/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/clouds/MixinRenderGlobal.java index 7fdb20883..df1c36786 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/clouds/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/notfine/clouds/MixinRenderGlobal.java @@ -1,5 +1,6 @@ package com.gtnewhorizons.angelica.mixins.early.notfine.clouds; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import jss.notfine.core.Settings; import jss.notfine.gui.options.named.GraphicsQualityOff; import net.minecraft.client.Minecraft; @@ -50,8 +51,8 @@ public abstract class MixinRenderGlobal { @Overwrite public void renderCloudsFancy(float partialTicks) { Tessellator tessellator = Tessellator.instance; - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); + GLStateManager.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(770, 771, 1, 0); renderEngine.bindTexture(locationCloudsPng); @@ -89,19 +90,19 @@ public abstract class MixinRenderGlobal { float cloudWidth = 8f; int renderRadius = (int)((int)Settings.RENDER_DISTANCE_CLOUDS.option.getStore() / (cloudScale * 2f)); float edgeOverlap = 0.0001f;//0.001F; - GL11.glScalef(cloudInteriorWidth, 1.0F, cloudInteriorWidth); + GLStateManager.glScalef(cloudInteriorWidth, 1.0F, cloudInteriorWidth); for (int loop = 0; loop < 2; ++loop) { if (loop == 0) { - GL11.glColorMask(false, false, false, false); + GLStateManager.glColorMask(false, false, false, false); } else if (mc.gameSettings.anaglyph) { if (EntityRenderer.anaglyphField == 0) { - GL11.glColorMask(false, true, true, true); + GLStateManager.glColorMask(false, true, true, true); } else { - GL11.glColorMask(true, false, false, true); + GLStateManager.glColorMask(true, false, false, true); } } else { - GL11.glColorMask(true, true, true, true); + GLStateManager.glColorMask(true, true, true, true); } for(int chunkX = -renderRadius + 1; chunkX <= renderRadius; ++chunkX) { @@ -184,15 +185,15 @@ public abstract class MixinRenderGlobal { } } - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_CULL_FACE); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glEnable(GL11.GL_CULL_FACE); } public void renderCloudsFast(float partialTicks) { Tessellator tessellator = Tessellator.instance; - GL11.glDisable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_BLEND); + GLStateManager.glDisable(GL11.GL_CULL_FACE); + GLStateManager.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(770, 771, 1, 0); renderEngine.bindTexture(locationCloudsPng); @@ -238,9 +239,9 @@ public abstract class MixinRenderGlobal { tessellator.addVertexWithUV(neg, cameraRelativeY, neg, startXUv, startZUv); tessellator.draw(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_CULL_FACE); + GLStateManager.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GLStateManager.glDisable(GL11.GL_BLEND); + GLStateManager.glEnable(GL11.GL_CULL_FACE); } @Shadow @Final diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderEndPortal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderEndPortal.java index 316ffc3b0..a5d42631c 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderEndPortal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderEndPortal.java @@ -1,13 +1,12 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; -import net.coderbot.iris.Iris; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.coderbot.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.tileentity.RenderEndPortal; import net.minecraft.tileentity.TileEntityEndPortal; import net.minecraft.util.ResourceLocation; -import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -28,8 +27,7 @@ public class MixinRenderEndPortal { @Inject(method = "renderTileEntityAt(Lnet/minecraft/tileentity/TileEntityEndPortal;DDDF)V", at = @At("HEAD"), cancellable = true) private void iris$renderShaderPortal(TileEntityEndPortal te, double x, double y, double z, float partialTicks, CallbackInfo ci) { - if (!Iris.getCurrentPack().isPresent()) return; - + // Always use shader-based portal rendering — eliminates glTexGen dependency for core profile ci.cancel(); float progress = (SystemTimeUniforms.TIMER.getFrameTimeCounter() * 0.01f) % 1.0f; @@ -42,7 +40,7 @@ public class MixinRenderEndPortal { float bottom = (float) y + iris$BOTTOM; Minecraft.getMinecraft().getTextureManager().bindTexture(iris$END_PORTAL_TEXTURE); - GL11.glEnable(GL11.GL_TEXTURE_2D); + GLStateManager.enableTexture(); Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java index c9012c777..1d6660826 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/early/shaders/MixinRenderGlobal.java @@ -1,10 +1,11 @@ package com.gtnewhorizons.angelica.mixins.early.shaders; +import com.gtnewhorizon.gtnhlib.client.renderer.ITessellatorInstance; +import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Share; import com.llamalad7.mixinextras.sugar.ref.LocalRef; -import com.gtnewhorizon.gtnhlib.client.renderer.ITessellatorInstance; import net.coderbot.iris.Iris; import net.coderbot.iris.layer.GbufferPrograms; import net.coderbot.iris.pipeline.WorldRenderingPhase; @@ -17,7 +18,6 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MovingObjectPosition; -import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -62,7 +62,7 @@ public class MixinRenderGlobal { @Inject(method = "renderSky", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/WorldClient;getCelestialAngle(F)F"), slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/WorldClient;getRainStrength(F)F"))) private void iris$renderSky$tiltSun(float p_72714_1_, CallbackInfo ci, @Share("pipeline") LocalRef pipeline) { - GL11.glRotatef(pipeline.get().getSunPathRotation(), 0.0F, 0.0F, 1.0F); + GLStateManager.glRotatef(pipeline.get().getSunPathRotation(), 0.0F, 0.0F, 1.0F); } // Sky disc: wrap the glCallList(glSkyList) call — the first glCallList in the surface world branch diff --git a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/ntmSpace/MixinSkyProviderCelestial_ShaderCompat.java b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/ntmSpace/MixinSkyProviderCelestial_ShaderCompat.java index 6019bdd4d..c87a39953 100644 --- a/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/ntmSpace/MixinSkyProviderCelestial_ShaderCompat.java +++ b/src/mixin/java/com/gtnewhorizons/angelica/mixins/late/client/ntmSpace/MixinSkyProviderCelestial_ShaderCompat.java @@ -238,7 +238,7 @@ public class MixinSkyProviderCelestial_ShaderCompat { @Inject(method = "render", at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glRotatef(FFFF)V", ordinal = 2), remap = false) private void iris$renderSky$tiltSun(CallbackInfo ci, @Share("pipeline") LocalRef pipeline) { if(pipeline.get() != null) - GL11.glRotatef(pipeline.get().getSunPathRotation(), 0.0F, 0.0F, 1.0F); + GLStateManager.glRotatef(pipeline.get().getSunPathRotation(), 0.0F, 0.0F, 1.0F); } @Inject(method = "renderSun", at = @At(value = "FIELD", target = "Lcom/hbm/dim/CelestialBody;texture:Lnet/minecraft/util/ResourceLocation;"), remap = false) diff --git a/src/test/java/com/gtnewhorizons/angelica/AngelicaExtension.java b/src/test/java/com/gtnewhorizons/angelica/AngelicaExtension.java index f2422ce29..5365a5727 100644 --- a/src/test/java/com/gtnewhorizons/angelica/AngelicaExtension.java +++ b/src/test/java/com/gtnewhorizons/angelica/AngelicaExtension.java @@ -12,8 +12,6 @@ import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.PixelFormat; -import org.lwjgl.util.glu.GLU; - import sun.misc.Unsafe; import java.lang.reflect.Field; @@ -29,7 +27,6 @@ public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, public static String glRenderer; public static String glVersion; - // Expected stack depths (1 = just the base matrix, no pushes) private static final int EXPECTED_MODELVIEW_STACK_DEPTH = 1; private static final int EXPECTED_PROJECTION_STACK_DEPTH = 1; @@ -45,14 +42,12 @@ public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, final PixelFormat format = new PixelFormat().withDepthBits(24).withStencilBits(8); Display.create(format); - // Set MainThread to the current test thread (the one with the GL context) setMainThread(Thread.currentThread()); - // Warm-up State Manager features GLStateManager.preInit(); - GLStateManager.setRunningSplash(false); // So we don't bypass the cache - GLStateManager.markSplashComplete(); // Enable caching for tests - GLStateManager.BYPASS_CACHE = false; // Just to be sure + GLStateManager.setRunningSplash(false); + GLStateManager.markSplashComplete(); + GLStateManager.BYPASS_CACHE = false; RenderSystem.initRenderer(); context.getRoot().getStore(GLOBAL).put("AngelicaExtension", this); glVendor = GL11.glGetString(GL11.GL_VENDOR); @@ -88,12 +83,8 @@ public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, @Override public void beforeEach(ExtensionContext context) throws Exception { - // Clear any pending GL errors from previous tests - while (GL11.glGetError() != GL11.GL_NO_ERROR) { - // drain errors - } + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} - // Reset matrix stacks to known state by popping until we're at base level GL11.glMatrixMode(GL11.GL_MODELVIEW); while (GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH) > EXPECTED_MODELVIEW_STACK_DEPTH) { GL11.glPopMatrix(); @@ -106,23 +97,17 @@ public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, } GL11.glLoadIdentity(); - // Reset to MODELVIEW mode (typical default) GL11.glMatrixMode(GL11.GL_MODELVIEW); - // Clear any errors from cleanup - while (GL11.glGetError() != GL11.GL_NO_ERROR) { - // drain errors - } + while (GL11.glGetError() != GL11.GL_NO_ERROR) {} } @Override public void afterEach(ExtensionContext context) throws Exception { - // Check for GL errors first int error = GL11.glGetError(); assertEquals(GL11.GL_NO_ERROR, error, - () -> "GL Error: " + GLU.gluErrorString(error)); + () -> "GL Error: 0x" + Integer.toHexString(error)); - // Check matrix stack depths - unbalanced push/pop is a common bug int modelviewDepth = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); int projectionDepth = GL11.glGetInteger(GL11.GL_PROJECTION_STACK_DEPTH); @@ -131,7 +116,6 @@ public class AngelicaExtension implements BeforeAllCallback, BeforeEachCallback, assertEquals(EXPECTED_PROJECTION_STACK_DEPTH, projectionDepth, "PROJECTION stack depth mismatch - unbalanced glPushMatrix/glPopMatrix"); - // Check matrix mode is reset to MODELVIEW int matrixMode = GL11.glGetInteger(GL11.GL_MATRIX_MODE); assertEquals(GL11.GL_MODELVIEW, matrixMode, () -> "Matrix mode not reset to MODELVIEW, was: " + GLDebug.getMatrixModeName(matrixMode)); diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java new file mode 100644 index 000000000..3a445fc7c --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/CompatShaderTransformerTest.java @@ -0,0 +1,333 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CompatShaderTransformerTest { + + @Test + void testModelViewMatrixReplacement() { + String src = """ + #version 120 + void main() { + vec4 pos = gl_ModelViewMatrix * gl_Vertex; + gl_Position = gl_ProjectionMatrix * pos; + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertTrue(result.contains("angelica_ModelViewMatrix")); + assertTrue(result.contains("angelica_ProjectionMatrix")); + assertFalse(result.contains("gl_ModelViewMatrix")); + assertFalse(result.contains("gl_ProjectionMatrix")); + assertTrue(result.contains("#version 330 core")); + } + + @Test + void testNormalMatrixReplacement() { + String src = """ + #version 120 + void main() { + vec3 n = gl_NormalMatrix * gl_Normal; + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertTrue(result.contains("uniform mat3 angelica_NormalMatrix")); + assertFalse(result.contains("gl_NormalMatrix")); + } + + @Test + void testModelViewProjectionMatrixExpression() { + String src = """ + #version 120 + void main() { + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertFalse(result.contains("gl_ModelViewProjectionMatrix")); + assertTrue(result.contains("angelica_ProjectionMatrix")); + } + + @Test + void testTextureFunctionRenames() { + String src = """ + #version 120 + uniform sampler2D tex; + void main() { + vec4 color = texture2D(tex, vec2(0.0)); + } + """; + + String result = CompatShaderTransformer.transform(src, false); + // texture2D → texture + assertFalse(result.contains("texture2D")); + assertTrue(result.contains("texture")); + } + + @Test + void testFragColorHandling() { + String src = """ + #version 120 + void main() { + gl_FragColor = vec4(1.0); + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertFalse(result.contains("gl_FragColor")); + // Should have layout-qualified output declaration + assertTrue(result.contains("angelica_FragData0")); + assertTrue(result.contains("layout")); + } + + @Test + void testVersionUpgradeTo330() { + String src = """ + #version 110 + void main() { + gl_FragColor = vec4(1.0); + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertTrue(result.contains("#version 330 core")); + assertFalse(result.contains("#version 110")); + } + + @Test + void testCompatibilityProfileStripped() { + String src = """ + #version 330 compatibility + void main() { + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertTrue(result.contains("#version 330 core")); + assertFalse(result.contains("compatibility")); + } + + @Test + void testPassthroughUnchangedShader() { + String src = """ + #version 330 core + in vec3 position; + uniform mat4 mvp; + void main() { + gl_Position = mvp * vec4(position, 1.0); + } + """; + + String result = CompatShaderTransformer.transform(src, false); + // Source should be returned as-is (passthrough) + assertEquals(src, result); + } + + @Test + void testCombinedBuiltinsInSingleShader() { + String src = """ + #version 120 + uniform sampler2D tex; + void main() { + vec3 n = gl_NormalMatrix * gl_Normal; + vec4 pos = gl_ModelViewMatrix * gl_Vertex; + gl_Position = gl_ProjectionMatrix * pos; + vec4 color = texture2D(tex, vec2(0.0)); + gl_FragColor = color; + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertTrue(result.contains("angelica_ModelViewMatrix")); + assertTrue(result.contains("angelica_ProjectionMatrix")); + assertTrue(result.contains("angelica_NormalMatrix")); + assertFalse(result.contains("gl_ModelViewMatrix")); + assertFalse(result.contains("gl_ProjectionMatrix")); + assertFalse(result.contains("gl_NormalMatrix")); + assertFalse(result.contains("texture2D")); + assertFalse(result.contains("gl_FragColor")); + assertTrue(result.contains("#version 330 core")); + } + + @Test + void testInverseMatrixReplacement() { + String src = """ + #version 120 + void main() { + vec4 pos = gl_ModelViewMatrixInverse * vec4(0.0, 0.0, 0.0, 1.0); + vec4 proj = gl_ProjectionMatrixInverse * vec4(0.0, 0.0, -1.0, 1.0); + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertFalse(result.contains("gl_ModelViewMatrixInverse")); + assertFalse(result.contains("gl_ProjectionMatrixInverse")); + } + + @Test + void testTextureMatrixReplacement() { + String src = """ + #version 120 + void main() { + vec4 lmCoord = gl_TextureMatrix[1] * gl_MultiTexCoord1; + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertFalse(result.contains("gl_TextureMatrix")); + } + + @Test + void testFogStructAccess() { + String src = """ + #version 120 + void main() { + vec4 c = gl_Fog.color; + float d = gl_Fog.density; + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertTrue(result.contains("angelica_Fog"), "gl_Fog should be renamed to angelica_Fog"); + assertFalse(result.contains("gl_Fog"), "gl_Fog should not remain in output"); + assertTrue(result.contains("angelica_FogParameters"), "Fog struct should be injected"); + assertTrue(result.contains("uniform float angelica_FogDensity"), "Fog density uniform should be injected"); + assertTrue(result.contains("uniform vec4 angelica_FogColor"), "Fog color uniform should be injected"); + } + + @Test + void testFogFragCoordVertex() { + String src = """ + #version 120 + void main() { + gl_FogFragCoord = length(gl_ModelViewMatrix * gl_Vertex); + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertTrue(result.contains("out float angelica_FogFragCoord"), "Vertex shader should get 'out' declaration"); + assertTrue(result.contains("angelica_FogFragCoord"), "gl_FogFragCoord should be renamed"); + assertFalse(result.contains("gl_FogFragCoord"), "gl_FogFragCoord should not remain"); + } + + @Test + void testFogFragCoordFragment() { + String src = """ + #version 120 + void main() { + float f = gl_FogFragCoord; + gl_FragColor = vec4(f); + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertTrue(result.contains("in float angelica_FogFragCoord"), "Fragment shader should get 'in' declaration"); + assertFalse(result.contains("gl_FogFragCoord"), "gl_FogFragCoord should not remain"); + } + + @Test + void testGlFrontColorVertex() { + String src = """ + #version 120 + void main() { + gl_FrontColor = vec4(1.0, 0.0, 0.0, 1.0); + } + """; + + String result = CompatShaderTransformer.transform(src, false); + assertTrue(result.contains("vec4 angelica_FrontColor"), "gl_FrontColor should become a local vec4"); + assertFalse(result.contains("gl_FrontColor"), "gl_FrontColor should not remain"); + } + + @Test + void testShadow2DRename() { + String src = """ + #version 120 + uniform sampler2DShadow shadowMap; + void main() { + float s = shadow2D(shadowMap, vec3(0.0)).r; + gl_FragColor = vec4(s); + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertFalse(result.contains("shadow2D("), "shadow2D should be renamed"); + // shadow2D → texture with vec4 wrapping + assertTrue(result.contains("texture"), "shadow2D should be renamed to texture"); + } + + @Test + void testReservedWordTextureAsVariable() { + // Shader declares 'texture' as a sampler variable — this is valid in GLSL 120 + // but 'texture' is a reserved word in GLSL 330+, causing parse failures without pre-rename + String src = """ + #version 120 + uniform sampler2D texture; + void main() { + gl_FragColor = texture2D(texture, vec2(0.5)); + } + """; + + // Should not throw — the pre-parse replaceTexture handles this + String result = CompatShaderTransformer.transform(src, true); + assertNotNull(result); + assertTrue(result.contains("#version 330 core")); + // The variable named 'texture' should have been renamed to gtexture (matching CommonTransformer convention) + assertTrue(result.contains("gtexture"), "Variable 'texture' should be renamed to gtexture"); + } + + @Test + void testCacheHit() { + String src = """ + #version 120 + void main() { + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + } + """; + + String result1 = CompatShaderTransformer.transform(src, false); + String result2 = CompatShaderTransformer.transform(src, false); + assertSame(result1, result2, "Second call should return cached instance (same reference)"); + } + + @Test + void testAlphaTestDiscardInjected() { + String src = """ + #version 120 + void main() { + gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5); + } + """; + + String result = CompatShaderTransformer.transform(src, true); + assertTrue(result.contains("uniform float angelica_currentAlphaTest"), "Alpha test uniform should be injected"); + assertTrue(result.contains("angelica_FragData0 . a <= angelica_currentAlphaTest") || result.contains("angelica_FragData0.a <= angelica_currentAlphaTest"), + "Alpha test discard should be appended to main()"); + } + + @Test + void testTexelFetch3DTriggersTransformation() { + String src = """ + #version 120 + uniform sampler3D vol; + void main() { + vec4 v = texelFetch3D(vol, ivec3(0), 0); + gl_FragColor = v; + } + """; + + String result = CompatShaderTransformer.transform(src, true); + // texelFetch3D should be renamed to texelFetch + assertFalse(result.contains("texelFetch3D"), "texelFetch3D should be renamed"); + assertTrue(result.contains("texelFetch"), "texelFetch3D should become texelFetch"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java new file mode 100644 index 000000000..58cf5c867 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/CompatUniformManagerTest.java @@ -0,0 +1,219 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.AngelicaExtension; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.opengl.GL20; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(AngelicaExtension.class) +class CompatUniformManagerTest { + + private int program = 0; + + @AfterEach + void cleanup() { + if (program != 0) { + GL20.glUseProgram(0); + GL20.glDeleteProgram(program); + program = 0; + } + } + + @Test + void testProgramWithCompatUniforms() { + // Create a shader program that uses angelica_* uniforms + String vertSrc = """ + #version 330 core + uniform mat4 angelica_ModelViewMatrix; + uniform mat4 angelica_ProjectionMatrix; + uniform mat3 angelica_NormalMatrix; + in vec3 position; + in vec3 normal; + out vec3 vNormal; + void main() { + vNormal = angelica_NormalMatrix * normal; + gl_Position = angelica_ProjectionMatrix * angelica_ModelViewMatrix * vec4(position, 1.0); + } + """; + + String fragSrc = """ + #version 330 core + in vec3 vNormal; + layout (location = 0) out vec4 fragColor; + void main() { + fragColor = vec4(vNormal, 1.0); + } + """; + + program = createAndLinkProgram(vertSrc, fragSrc); + + // onLinkProgram should discover the uniform locations + CompatUniformManager.onLinkProgram(program); + + assertTrue(CompatUniformManager.hasProgram(program)); + + int[] locs = CompatUniformManager.getLocations(program); + assertNotNull(locs); + // ModelView, Projection, NormalMatrix should have valid locations + assertNotEquals(-1, locs[CompatUniformManager.LOC_MODELVIEW], "angelica_ModelViewMatrix location"); + assertNotEquals(-1, locs[CompatUniformManager.LOC_PROJECTION], "angelica_ProjectionMatrix location"); + assertNotEquals(-1, locs[CompatUniformManager.LOC_NORMAL], "angelica_NormalMatrix location"); + + // Use program and upload — should not error + GL20.glUseProgram(program); + CompatUniformManager.onUseProgram(program); + + // Verify no GL errors + assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after uniform upload"); + } + + @Test + void testProgramWithoutCompatUniforms() { + String vertSrc = """ + #version 330 core + uniform mat4 mvp; + in vec3 position; + void main() { + gl_Position = mvp * vec4(position, 1.0); + } + """; + + String fragSrc = """ + #version 330 core + layout (location = 0) out vec4 fragColor; + void main() { + fragColor = vec4(1.0); + } + """; + + program = createAndLinkProgram(vertSrc, fragSrc); + + CompatUniformManager.onLinkProgram(program); + + // No angelica_* uniforms → not tracked + assertFalse(CompatUniformManager.hasProgram(program)); + } + + @Test + void testProgramWithFogUniforms() { + // All fog uniforms must be used in the shader to prevent the GLSL compiler from optimizing them away (which would make glGetUniformLocation return -1) + String vertSrc = """ + #version 330 core + uniform float angelica_FogDensity; + uniform float angelica_FogStart; + uniform float angelica_FogEnd; + uniform vec4 angelica_FogColor; + in vec3 position; + out vec4 vFogData; + void main() { + gl_Position = vec4(position, 1.0); + float dist = length(position); + float linearFog = clamp((angelica_FogEnd - dist) / (angelica_FogEnd - angelica_FogStart), 0.0, 1.0); + float expFog = exp(-angelica_FogDensity * dist); + vFogData = angelica_FogColor * linearFog * expFog; + } + """; + + String fragSrc = """ + #version 330 core + in vec4 vFogData; + layout (location = 0) out vec4 fragColor; + void main() { + fragColor = vFogData; + } + """; + + program = createAndLinkProgram(vertSrc, fragSrc); + + CompatUniformManager.onLinkProgram(program); + + assertTrue(CompatUniformManager.hasProgram(program)); + + int[] locs = CompatUniformManager.getLocations(program); + assertNotNull(locs); + // Fog uniforms should have valid locations (indices 6-9) + assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_DENSITY], "angelica_FogDensity location"); + assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_START], "angelica_FogStart location"); + assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_END], "angelica_FogEnd location"); + assertNotEquals(-1, locs[CompatUniformManager.LOC_FOG_COLOR], "angelica_FogColor location"); + + // Use program and upload — should not error + GL20.glUseProgram(program); + CompatUniformManager.onUseProgram(program); + + assertEquals(0, org.lwjgl.opengl.GL11.glGetError(), "GL error after fog uniform upload"); + } + + @Test + void testDeleteProgramCleansUp() { + String vertSrc = """ + #version 330 core + uniform mat4 angelica_ModelViewMatrix; + in vec3 position; + void main() { + gl_Position = angelica_ModelViewMatrix * vec4(position, 1.0); + } + """; + + String fragSrc = """ + #version 330 core + layout (location = 0) out vec4 fragColor; + void main() { + fragColor = vec4(1.0); + } + """; + + program = createAndLinkProgram(vertSrc, fragSrc); + + CompatUniformManager.onLinkProgram(program); + assertTrue(CompatUniformManager.hasProgram(program)); + + CompatUniformManager.onDeleteProgram(program); + assertFalse(CompatUniformManager.hasProgram(program)); + } + + private static int createAndLinkProgram(String vertSrc, String fragSrc) { + int vs = GL20.glCreateShader(GL20.GL_VERTEX_SHADER); + GL20.glShaderSource(vs, vertSrc); + GL20.glCompileShader(vs); + if (GL20.glGetShaderi(vs, GL20.GL_COMPILE_STATUS) == 0) { + String log = GL20.glGetShaderInfoLog(vs, 4096); + GL20.glDeleteShader(vs); + fail("Vertex shader compilation failed: " + log); + } + + int fs = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER); + GL20.glShaderSource(fs, fragSrc); + GL20.glCompileShader(fs); + if (GL20.glGetShaderi(fs, GL20.GL_COMPILE_STATUS) == 0) { + String log = GL20.glGetShaderInfoLog(fs, 4096); + GL20.glDeleteShader(vs); + GL20.glDeleteShader(fs); + fail("Fragment shader compilation failed: " + log); + } + + int prog = GL20.glCreateProgram(); + GL20.glAttachShader(prog, vs); + GL20.glAttachShader(prog, fs); + GL20.glLinkProgram(prog); + if (GL20.glGetProgrami(prog, GL20.GL_LINK_STATUS) == 0) { + String log = GL20.glGetProgramInfoLog(prog, 4096); + GL20.glDeleteProgram(prog); + GL20.glDeleteShader(vs); + GL20.glDeleteShader(fs); + fail("Program link failed: " + log); + } + + GL20.glDeleteShader(vs); + GL20.glDeleteShader(fs); + return prog; + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java index bb086e076..99b0bb6ed 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListCompilationGLSMTest.java @@ -10,7 +10,10 @@ import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** Tests GLSM display list behavior matches OpenGL spec. */ @ExtendWith(AngelicaExtension.class) @@ -85,14 +88,14 @@ class DisplayListCompilationGLSMTest { @Test void glsm_compile_transformNotApplied() { FloatBuffer before = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, before); testList = GL11.glGenLists(1); GLStateManager.glNewList(testList, GL11.GL_COMPILE); GLStateManager.glTranslatef(10, 20, 30); FloatBuffer during = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, during); assertMatrixEquals(before, during, "During GL_COMPILE: matrix unchanged"); GLStateManager.glEndList(); @@ -102,26 +105,26 @@ class DisplayListCompilationGLSMTest { void glsm_compileAndExecute_transformQueuedUntilFlush() { // Transforms queue until draw/glEndList (state commands don't flush) FloatBuffer identity = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, identity); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, identity); testList = GL11.glGenLists(1); GLStateManager.glNewList(testList, GL11.GL_COMPILE_AND_EXECUTE); GLStateManager.glTranslatef(10, 0, 0); // Queued FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); assertMatrixEquals(identity, beforeFlush, "Before flush: transform queued"); GLStateManager.enableBlend(); // State commands DON'T flush transforms anymore FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); assertMatrixEquals(identity, afterStateCmd, "After state cmd: transform still queued"); GLStateManager.glEndList(); // glEndList flushes pending transforms FloatBuffer afterEndList = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterEndList); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterEndList); assertEquals(10.0f, afterEndList.get(12), 0.001f, "After glEndList: transform applied"); } @@ -169,16 +172,16 @@ class DisplayListCompilationGLSMTest { FloatBuffer proj = BufferUtils.createFloatBuffer(16); FloatBuffer mv = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); assertEquals(0.0f, proj.get(12), 0.001f, "After GL_COMPILE: PROJECTION unchanged"); assertEquals(0.0f, mv.get(12), 0.001f, "After GL_COMPILE: MODELVIEW unchanged"); GLStateManager.glCallList(testList); proj.clear(); mv.clear(); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); + GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, mv); assertEquals(5.0f, proj.get(12), 0.001f, "After playback: PROJECTION has translate(5)"); assertEquals(10.0f, mv.get(12), 0.001f, "After playback: MODELVIEW has translate(10)"); } @@ -195,13 +198,13 @@ class DisplayListCompilationGLSMTest { GLStateManager.glEndList(); FloatBuffer afterCompile = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterCompile); assertEquals(100.0f, afterCompile.get(12), 0.001f, "After GL_COMPILE: matrix at base"); GLStateManager.glCallList(testList); FloatBuffer afterPlay = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPlay); assertEquals(100.0f, afterPlay.get(12), 0.001f, "After playback: matrix at base"); } @@ -218,17 +221,17 @@ class DisplayListCompilationGLSMTest { GLStateManager.glRotatef(45, 0, 1, 0); // Queued FloatBuffer beforeMode = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeMode); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeMode); assertEquals(0.0f, beforeMode.get(12), 0.001f, "Before MatrixMode: queued"); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); // Barrier - flushes FloatBuffer afterMode = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterMode); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterMode); assertNotEquals(0.0f, afterMode.get(12), "After MatrixMode: flushed to MODELVIEW"); FloatBuffer proj = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); + GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj); assertEquals(0.0f, proj.get(12), 0.001f, "PROJECTION still identity"); GLStateManager.glEndList(); @@ -247,19 +250,19 @@ class DisplayListCompilationGLSMTest { GLStateManager.glTranslatef(10, 0, 0); FloatBuffer beforeFlush = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, beforeFlush); assertEquals(0.0f, beforeFlush.get(12), 0.001f, "Before flush: queued"); GLStateManager.enableBlend(); // NOT a barrier in new model FloatBuffer afterStateCmd = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterStateCmd); assertEquals(0.0f, afterStateCmd.get(12), 0.001f, "After state cmd: still queued"); GLStateManager.glPopMatrix(); // Matrix barrier: flushes transform, then pops FloatBuffer afterPop = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, afterPop); assertEquals(0.0f, afterPop.get(12), 0.001f, "After pop: back to identity (pushed state)"); GLStateManager.glEndList(); diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java new file mode 100644 index 000000000..2e5a5aae9 --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/DisplayListIdAllocatorTest.java @@ -0,0 +1,239 @@ +package com.gtnewhorizons.angelica.glsm; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DisplayListIdAllocatorTest { + + @Test + void zeroNeverReturned() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(1); + // Allocate enough IDs to fill the first word (32 IDs). None should be 0. + for (int i = 0; i < 31; i++) { + int id = alloc.allocRange(1); + assertNotEquals(0, id, "ID 0 must never be returned"); + assertTrue(id > 0, "All returned IDs must be positive"); + } + } + + @Test + void singleAllocReturnsSequential() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // First alloc should be 1 (0 is reserved) + assertEquals(1, alloc.allocRange(1)); + assertEquals(2, alloc.allocRange(1)); + assertEquals(3, alloc.allocRange(1)); + } + + @Test + void isAllocatedTracksState() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + assertFalse(alloc.isAllocated(0), "ID 0 should not report as allocated via isAllocated"); + assertFalse(alloc.isAllocated(1)); + + int id = alloc.allocRange(1); + assertTrue(alloc.isAllocated(id)); + assertFalse(alloc.isAllocated(id + 1)); + } + + @Test + void freeAndReuse() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + int a = alloc.allocRange(1); // 1 + int b = alloc.allocRange(1); // 2 + int c = alloc.allocRange(1); // 3 + + alloc.free(b); // free 2 + assertFalse(alloc.isAllocated(b)); + + // Next alloc should reuse 2 (lowestFreeIdx reset) + int d = alloc.allocRange(1); + assertEquals(b, d, "Freed ID should be reused"); + } + + @Test + void freeRangeReleasesAll() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + int base = alloc.allocRange(1); + alloc.allocRange(1); + alloc.allocRange(1); + // IDs 1, 2, 3 allocated + assertTrue(alloc.isAllocated(1)); + assertTrue(alloc.isAllocated(2)); + assertTrue(alloc.isAllocated(3)); + + alloc.freeRange(1, 3); + assertFalse(alloc.isAllocated(1)); + assertFalse(alloc.isAllocated(2)); + assertFalse(alloc.isAllocated(3)); + } + + @Test + void rangeAllocReturnsConsecutiveIds() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // Range alloc of 64 should return 64 consecutive IDs starting at a word-aligned base + int base = alloc.allocRange(64); + assertTrue(base > 0, "Base must be positive"); + assertEquals(0, base % 32, "Range base should be word-aligned"); + + // All IDs in range must be allocated + for (int i = 0; i < 64; i++) { + assertTrue(alloc.isAllocated(base + i), "ID " + (base + i) + " should be allocated"); + } + // ID just past range should not be allocated + assertFalse(alloc.isAllocated(base + 64)); + } + + @Test + void rangeAllocPartialWord() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // Allocate 10 IDs — less than a full word, still word-aligned base + int base = alloc.allocRange(10); + assertTrue(base > 0); + for (int i = 0; i < 10; i++) { + assertTrue(alloc.isAllocated(base + i)); + } + // Bits past the 10 in that same word should be free + assertFalse(alloc.isAllocated(base + 10)); + } + + @Test + void autoGrowOnExhaustion() { + // Start very small — 1 word = 32 IDs (minus ID 0 = 31 usable) + DisplayListIDAllocator alloc = new DisplayListIDAllocator(1); + // Allocate all 31 usable IDs in the first word + for (int i = 0; i < 31; i++) { + int id = alloc.allocRange(1); + assertTrue(id > 0 && id < 32); + } + // Next alloc must trigger grow + int id = alloc.allocRange(1); + assertTrue(id >= 32, "After exhausting first word, should allocate from grown region"); + assertTrue(alloc.isAllocated(id)); + } + + @Test + void autoGrowForRange() { + // Start with 1 word. Request 64 consecutive IDs — must grow. + DisplayListIDAllocator alloc = new DisplayListIDAllocator(1); + int base = alloc.allocRange(64); + assertTrue(base > 0); + for (int i = 0; i < 64; i++) { + assertTrue(alloc.isAllocated(base + i)); + } + } + + @Test + void freeZeroIsNoOp() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // Should not throw + alloc.free(0); + alloc.free(-1); + } + + @Test + void isAllocatedOutOfBoundsReturnsFalse() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(1); + assertFalse(alloc.isAllocated(99999), "Out-of-bounds ID should return false"); + assertFalse(alloc.isAllocated(-1)); + } + + @Test + void invalidCountThrows() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + assertThrows(IllegalArgumentException.class, () -> alloc.allocRange(0)); + assertThrows(IllegalArgumentException.class, () -> alloc.allocRange(-1)); + } + + @Test + void stressAllocFreeRealloc() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + int[] ids = new int[1000]; + // Allocate 1000 IDs + for (int i = 0; i < 1000; i++) { + ids[i] = alloc.allocRange(1); + assertTrue(ids[i] > 0); + assertTrue(alloc.isAllocated(ids[i])); + } + // Free all odd-indexed IDs + for (int i = 1; i < 1000; i += 2) { + alloc.free(ids[i]); + assertFalse(alloc.isAllocated(ids[i])); + } + // Even-indexed IDs should still be allocated + for (int i = 0; i < 1000; i += 2) { + assertTrue(alloc.isAllocated(ids[i])); + } + // Reallocate 500 IDs — should reuse freed slots + for (int i = 0; i < 500; i++) { + int id = alloc.allocRange(1); + assertTrue(id > 0); + assertTrue(alloc.isAllocated(id)); + } + } + + @Test + void noDoubleAllocation() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // Allocate many IDs and verify uniqueness + java.util.Set seen = new java.util.HashSet<>(); + for (int i = 0; i < 500; i++) { + int id = alloc.allocRange(1); + assertTrue(seen.add(id), "Duplicate ID returned: " + id); + } + } + + @Test + void rangeAfterSingleAllocs() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + // Fragment the bitmap with single allocs + for (int i = 0; i < 10; i++) { + alloc.allocRange(1); + } + // Now request a range — should skip past the occupied word(s) + int base = alloc.allocRange(32); + assertTrue(base > 0); + // The range must not overlap with any previously allocated ID + for (int i = 0; i < 32; i++) { + assertTrue(alloc.isAllocated(base + i)); + } + // The first 10 IDs (1-10) should still be allocated + for (int i = 1; i <= 10; i++) { + assertTrue(alloc.isAllocated(i)); + } + } + + @Test + void multipleRanges() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + int base1 = alloc.allocRange(32); + int base2 = alloc.allocRange(32); + // Ranges must not overlap + assertTrue(base2 >= base1 + 32 || base1 >= base2 + 32, + "Ranges must not overlap: base1=" + base1 + " base2=" + base2); + // All IDs in both ranges must be allocated + for (int i = 0; i < 32; i++) { + assertTrue(alloc.isAllocated(base1 + i)); + assertTrue(alloc.isAllocated(base2 + i)); + } + } + + @Test + void freeRangeThenReallocRange() { + DisplayListIDAllocator alloc = new DisplayListIDAllocator(); + int base1 = alloc.allocRange(64); + alloc.freeRange(base1, 64); + // All should be free + for (int i = 0; i < 64; i++) { + assertFalse(alloc.isAllocated(base1 + i)); + } + // Reallocate — should reuse the freed region + int base2 = alloc.allocRange(64); + assertEquals(base1, base2, "Freed range should be reused"); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Nesting_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Nesting_Test.java index add6971cf..a0307418a 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Nesting_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Nesting_Test.java @@ -10,7 +10,7 @@ import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for nested display list execution. @@ -64,7 +64,7 @@ class GLSM_DisplayList_Nesting_Test { // Check final matrix state - should have parent's translate applied FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: translate(10, 0, 0) Matrix4f expected = new Matrix4f().translate(10.0f, 0.0f, 0.0f); @@ -108,7 +108,7 @@ class GLSM_DisplayList_Nesting_Test { // Check final matrix state - should be translate(10,0,0) * translate(1,0,0) = translate(11,0,0) FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: translate(11, 0, 0) = parent(10) + child(1) Matrix4f expected = new Matrix4f().translate(11.0f, 0.0f, 0.0f); @@ -154,7 +154,7 @@ class GLSM_DisplayList_Nesting_Test { // Check final matrix state - should still be translate(10,0,0) because child did push/pop FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: translate(10, 0, 0) only (child's transform was popped) Matrix4f expected = new Matrix4f().translate(10.0f, 0.0f, 0.0f); @@ -203,7 +203,7 @@ class GLSM_DisplayList_Nesting_Test { // Check final matrix state - should be 100 + 10 + 1 = 111 FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: translate(111, 0, 0) Matrix4f expected = new Matrix4f().translate(111.0f, 0.0f, 0.0f); @@ -228,7 +228,7 @@ class GLSM_DisplayList_Nesting_Test { // This is a uncommon but technically valid per the spec. // Get initial stack depth - int initialDepth = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); + int initialDepth = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); // Create a display list that only pushes the matrix int matrixPushList = GL11.glGenLists(1); @@ -243,11 +243,11 @@ class GLSM_DisplayList_Nesting_Test { GLStateManager.glEndList(); // Verify initial stack depth hasn't changed after compilation - assertEquals(initialDepth, GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH), "Stack depth should be unchanged after compiling display lists"); + assertEquals(initialDepth, GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH), "Stack depth should be unchanged after compiling display lists"); // Call the push list - should increase stack depth GLStateManager.glCallList(matrixPushList); - int depthAfterPush = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); + int depthAfterPush = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); assertEquals(initialDepth + 1, depthAfterPush, "Stack depth should increase by 1 after calling push list"); // Optionally do some operations here that would benefit from the pushed matrix @@ -255,7 +255,7 @@ class GLSM_DisplayList_Nesting_Test { // Call the pop list - should restore stack depth GLStateManager.glCallList(matrixPopList); - int depthAfterPop = GL11.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); + int depthAfterPop = GLStateManager.glGetInteger(GL11.GL_MODELVIEW_STACK_DEPTH); assertEquals(initialDepth, depthAfterPop, "Stack depth should return to initial after calling pop list"); // Cleanup diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Stress_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Stress_Test.java index 6cde4e27f..9850be095 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Stress_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_Stress_Test.java @@ -12,7 +12,9 @@ import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Stress tests for display list system. @@ -97,7 +99,7 @@ class GLSM_DisplayList_Stress_Test { GLStateManager.glCallList(list); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // All push/pop pairs cancel out, only final translate remains assertEquals(42.0f, actualBuf.get(12), 0.0001f, @@ -155,7 +157,7 @@ class GLSM_DisplayList_Stress_Test { // Final matrix should have translation = chainLength (each list adds 1) FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); Matrix4f expected = new Matrix4f().translate(chainLength, 0.0f, 0.0f); FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16); @@ -198,7 +200,7 @@ class GLSM_DisplayList_Stress_Test { GLStateManager.glCallList(list); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // All pushes and pops cancel out, only final 99 translate remains assertEquals(99.0f, actualBuf.get(12), 0.0001f, @@ -230,7 +232,7 @@ class GLSM_DisplayList_Stress_Test { // Verify correct transform was applied FloatBuffer buf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf); assertEquals(i + 1, buf.get(12), 0.0001f, "List " + i + " should translate by " + (i + 1)); @@ -255,7 +257,7 @@ class GLSM_DisplayList_Stress_Test { GLStateManager.glCallList(list); FloatBuffer buf1 = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf1); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf1); assertEquals(5.0f, buf1.get(12), 0.0001f, "First compilation should translate by 5"); GLStateManager.glPopMatrix(); @@ -271,7 +273,7 @@ class GLSM_DisplayList_Stress_Test { GLStateManager.glCallList(list); FloatBuffer buf2 = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf2); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, buf2); assertEquals(10.0f, buf2.get(12), 0.0001f, "Recompilation should translate by 10"); GLStateManager.glPopMatrix(); @@ -297,7 +299,7 @@ class GLSM_DisplayList_Stress_Test { GLStateManager.glCallList(list); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Build expected with JOML Matrix4f expected = new Matrix4f() diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java index 9e1be587d..79f12b488 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_DisplayList_TransformCollapsing_Test.java @@ -14,7 +14,9 @@ import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** Tests for transform collapsing optimization in display lists. */ @ExtendWith(AngelicaExtension.class) @@ -74,7 +76,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); Matrix4f expected = new Matrix4f() .translate(1.0f, 2.0f, 3.0f) @@ -125,7 +127,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: translate(10,0,0) then translate(0,3,0) = translate(10,3,0) // The inner push/pop isolates the (5,0,0) translate and rotation @@ -168,7 +170,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Final state: translate(1,0,0) + translate(5,0,0) = translate(6,0,0) // Level 1 and 2 transforms are isolated by push/pop @@ -223,7 +225,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Build expected: translate(10,0,0) * rotate(90,Y) * translate(100,0,0) * translate(1,0,0) // After 90-degree Y rotation, X axis points into -Z, so nested translate goes along -Z @@ -293,7 +295,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Total translation should be 3.0 (1+2) assertEquals(3.0f, actualBuf.get(12), 0.0001f, @@ -320,7 +322,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); assertEquals(1.0f, actualBuf.get(12), 0.0001f, "X should be 1.0 (LoadIdentity reset)"); assertEquals(2.0f, actualBuf.get(13), 0.0001f, "Y should be 2.0 (LoadIdentity reset)"); @@ -363,7 +365,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); Matrix4f expected = new Matrix4f() .translate(1.0f, 0.0f, 0.0f) @@ -439,7 +441,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); assertEquals(3.0f, actualBuf.get(12), 0.0001f, "X translation should be 3.0 (1+2, inner transform isolated by push/pop)"); @@ -513,7 +515,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16); loadedMatrix.get(expectedBuf); @@ -551,7 +553,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Expected: loadedMatrix * translate(10,0,0) Matrix4f expected = new Matrix4f(loadedMatrix).translate(10.0f, 0.0f, 0.0f); @@ -595,7 +597,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); assertEquals(1.0f, actualBuf.get(12), 0.0001f, "X should be 1.0"); assertEquals(2.0f, actualBuf.get(13), 0.0001f, "Y should be 2.0"); @@ -632,7 +634,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); assertEquals(0.0f, actualBuf.get(12), 0.0001f, "X should be 0.0 (from second LoadMatrix)"); assertEquals(20.0f, actualBuf.get(13), 0.0001f, "Y should be 20.0 (from second LoadMatrix)"); @@ -706,7 +708,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X"); assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y"); @@ -722,28 +724,28 @@ class GLSM_DisplayList_TransformCollapsing_Test { @Test void testTransformsAcrossMatrixModeSwitch() { // Transforms must not leak across matrix mode boundaries + // Compute expected results via GLSM (same path as display list playback) GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); GLStateManager.glLoadIdentity(); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); GLStateManager.glLoadIdentity(); - // Execute directly via GL to get expected results GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glTranslatef(1.0f, 0.0f, 0.0f); - GL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f); + GLStateManager.glTranslatef(1.0f, 0.0f, 0.0f); + GLStateManager.glRotatef(45.0f, 0.0f, 1.0f, 0.0f); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GL11.glScalef(2.0f, 2.0f, 2.0f); + GLStateManager.glScalef(2.0f, 2.0f, 2.0f); GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glTranslatef(3.0f, 0.0f, 0.0f); + GLStateManager.glTranslatef(3.0f, 0.0f, 0.0f); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GL11.glTranslatef(5.0f, 0.0f, 0.0f); + GLStateManager.glTranslatef(5.0f, 0.0f, 0.0f); GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); FloatBuffer expectedMV = BufferUtils.createFloatBuffer(16); FloatBuffer expectedProj = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedMV); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedMV); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, expectedProj); + GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, expectedProj); // Reset and test via display list GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); @@ -770,9 +772,9 @@ class GLSM_DisplayList_TransformCollapsing_Test { FloatBuffer actualMV = BufferUtils.createFloatBuffer(16); FloatBuffer actualProj = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualMV); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualMV); GLStateManager.glMatrixMode(GL11.GL_PROJECTION); - GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, actualProj); + GLStateManager.glGetFloat(GL11.GL_PROJECTION_MATRIX, actualProj); for (int i = 0; i < 16; i++) { assertEquals(expectedMV.get(i), actualMV.get(i), 0.0001f, "MODELVIEW[" + i + "]"); @@ -831,7 +833,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); assertEquals(0.5f, matrixBuf.get(0), 0.0001f, "Scale X for mode " + mode); assertEquals(0.5f, matrixBuf.get(5), 0.0001f, "Scale Y for mode " + mode); @@ -894,7 +896,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrixBuf); assertEquals(2.0f, matrixBuf.get(0), 0.0001f, "Scale X after pop"); assertEquals(2.0f, matrixBuf.get(5), 0.0001f, "Scale Y after pop"); @@ -918,17 +920,17 @@ class GLSM_DisplayList_TransformCollapsing_Test { final float angle2 = 30.0f; final float tx2 = -1.0f, ty2 = 4.0f, tz2 = 0.5f; - // Execute directly via GL + // Execute directly via GLSM GLStateManager.glMatrixMode(GL11.GL_MODELVIEW); GLStateManager.glLoadIdentity(); - GL11.glTranslatef(tx1, ty1, tz1); - GL11.glRotatef(angle1, 0.0f, 1.0f, 0.0f); // Y-axis rotation - GL11.glScalef(sx, sy, sz); - GL11.glRotatef(angle2, 1.0f, 0.0f, 0.0f); // X-axis rotation - GL11.glTranslatef(tx2, ty2, tz2); + GLStateManager.glTranslatef(tx1, ty1, tz1); + GLStateManager.glRotatef(angle1, 0.0f, 1.0f, 0.0f); // Y-axis rotation + GLStateManager.glScalef(sx, sy, sz); + GLStateManager.glRotatef(angle2, 1.0f, 0.0f, 0.0f); // X-axis rotation + GLStateManager.glTranslatef(tx2, ty2, tz2); FloatBuffer expectedBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, expectedBuf); // Reset and execute via display list GLStateManager.glLoadIdentity(); @@ -945,7 +947,7 @@ class GLSM_DisplayList_TransformCollapsing_Test { GLStateManager.glCallList(testList); FloatBuffer actualBuf = BufferUtils.createFloatBuffer(16); - GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); + GLStateManager.glGetFloat(GL11.GL_MODELVIEW_MATRIX, actualBuf); // Verify equivalence for (int i = 0; i < 16; i++) { diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java index b5aa60488..7ed3ba8f1 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_MatrixStack_UnitTest.java @@ -11,7 +11,6 @@ import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; -import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(AngelicaExtension.class) @@ -40,12 +39,8 @@ public class GLSM_MatrixStack_UnitTest { assertTrue(matrixEquals(expected, actual), message); } void validateMatrix(Matrix4f expected, int matrix, String message) { - // Be careful of precision here - assertAll(message, - () -> assertMatrixEquals(expected, getMatrix(matrix, false), "GL State Mismatch"), - () -> assertMatrixEquals(expected, getMatrix(matrix, true), "GLSM State Mismatch") - ); - + // Matrix ops are FFP-only in core profile — verify GLSM cache only + assertMatrixEquals(expected, getMatrix(matrix, true), message + " - GLSM State Mismatch"); } enum MatrixMode { diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java index 4d1844add..1f3d38baf 100644 --- a/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/GLSM_PushPop_UnitTest.java @@ -12,18 +12,15 @@ import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL32; import java.nio.FloatBuffer; import java.util.ArrayList; -import static org.junit.jupiter.api.Assertions.assertTrue; - import static com.gtnewhorizons.angelica.util.GLSMUtil.resetGLState; import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyIsEnabled; import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyLightState; -import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyNotDefaultState; import static com.gtnewhorizons.angelica.util.GLSMUtil.verifyState; +import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(AngelicaExtension.class) class GLSM_PushPop_UnitTest { @@ -133,50 +130,23 @@ class GLSM_PushPop_UnitTest { @Test void testPushPopCurrentBit() { verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "Initial Color State"); // Verify no state leakage from other tests - verifyState(GL11.GL_CURRENT_INDEX, 1, "Initial Index State"); verifyState(GL11.GL_CURRENT_TEXTURE_COORDS, FLOAT_ARRAY_4_0001, "Initial Texture Coordinates"); - verifyState(GL11.GL_CURRENT_RASTER_POSITION, FLOAT_ARRAY_4_0001, "Initial Raster Position"); - verifyState(GL11.GL_CURRENT_RASTER_POSITION_VALID, true, "Initial Raster Position Valid"); - verifyState(GL11.GL_CURRENT_RASTER_COLOR, FLOAT_ARRAY_4_1, "Initial Raster Color"); - verifyState(GL11.GL_CURRENT_RASTER_INDEX, 1, "Initial Raster Index"); - verifyState(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS, FLOAT_ARRAY_4_0001, "Initial Raster Texture Coordinates"); GLStateManager.glPushAttrib(GL11.GL_CURRENT_BIT); GLStateManager.glColor4f(0.5f, 0.5f, 0.5f, 0.5f); - // Apparently glIndex is not implemented in lwjgl2? GLStateManager.glNormal3f(0.5f, 0.5f, 0.5f); - GLStateManager.glTexCoord4f(0.5f, 0.5f, 0.5f, 0.5f); // Current texture coordinates - GLStateManager.glRasterPos4f(0.5f, 0.5f, 0.5f, 0.5f); // Current raster position - // GL_CURRENT_RASTER_POSITION_VALID flag - // RGBA color associated with current raster position - // Color index associated with current raster position - // Texture coordinates associated with current raster position - GLStateManager.glEdgeFlag(false); // GL_EDGE_FLAG flag + GLStateManager.glTexCoord4f(0.5f, 0.5f, 0.5f, 0.5f); verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_POINT_5, "Current Color"); - verifyState(GL11.GL_CURRENT_INDEX, 1f, "Current Index"); verifyState(GL11.GL_CURRENT_NORMAL, FLOAT_ARRAY_3_POINT_5, "Current Normal"); verifyState(GL11.GL_CURRENT_TEXTURE_COORDS, FLOAT_ARRAY_4_POINT_5, "Texture coordinates"); - verifyNotDefaultState(GL11.GL_CURRENT_RASTER_POSITION, FLOAT_ARRAY_4_0001, "Raster Position"); - verifyState(GL11.GL_CURRENT_RASTER_POSITION_VALID, true, "Raster Position Valid"); - verifyState(GL11.GL_CURRENT_RASTER_COLOR, FLOAT_ARRAY_4_POINT_5, "Raster Color"); - verifyState(GL11.GL_CURRENT_RASTER_INDEX, 1, "Raster Index"); - verifyState(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS, FLOAT_ARRAY_4_POINT_5, "Raster Texture Coordinates"); - verifyState(GL11.GL_EDGE_FLAG, false, "Edge Flag"); GLStateManager.glPopAttrib(); verifyState(GL11.GL_CURRENT_COLOR, FLOAT_ARRAY_4_1, "Current Color - reset"); - verifyState(GL11.GL_CURRENT_INDEX, 1, "Current Index - reset"); verifyState(GL11.GL_CURRENT_NORMAL, FLOAT_ARRAY_3_001, "Current normal - reset"); verifyState(GL11.GL_CURRENT_TEXTURE_COORDS, FLOAT_ARRAY_4_0001, "Texture coordinates - reset"); - verifyState(GL11.GL_CURRENT_RASTER_POSITION, FLOAT_ARRAY_4_0001, "Raster Position - reset"); - verifyState(GL11.GL_CURRENT_RASTER_POSITION_VALID, true, "Raster Position Valid - reset"); - verifyState(GL11.GL_CURRENT_RASTER_COLOR, FLOAT_ARRAY_4_1, "Raster Color - reset"); - verifyState(GL11.GL_CURRENT_RASTER_INDEX, 1, "Raster Index - reset"); - verifyState(GL11.GL_CURRENT_RASTER_TEXTURE_COORDS, FLOAT_ARRAY_4_0001, "Raster Texture Coordinates - reset"); - verifyState(GL11.GL_EDGE_FLAG, true, "Edge Flag - reset"); } @Test @@ -300,7 +270,7 @@ class GLSM_PushPop_UnitTest { GLStateManager.glFogf(GL11.GL_FOG_END, 0.5f); GLStateManager.glFogf(GL11.GL_FOG_START, 0.5f); GLStateManager.glFogf(GL11.GL_FOG_MODE, GL11.GL_LINEAR); - if (!GLStateManager.vendorIsNVIDIA()) GLStateManager.glFogf(GL11.GL_FOG_INDEX, 1f); + // Fog index not tracked by GLSM (MC 1.7.10 never uses it) verifyIsEnabled(GL11.GL_FOG, true, "Fog Enable"); verifyState(GL11.GL_FOG_COLOR, FLOAT_ARRAY_4_POINT_5, "Fog Color"); @@ -308,7 +278,6 @@ class GLSM_PushPop_UnitTest { verifyState(GL11.GL_FOG_END, 0.5f, "Fog End"); verifyState(GL11.GL_FOG_START, 0.5f, "Fog Start"); verifyState(GL11.GL_FOG_MODE, GL11.GL_LINEAR, "Fog Mode"); - if (!GLStateManager.vendorIsNVIDIA()) verifyState(GL11.GL_FOG_INDEX, 1f, "Fog Index"); GLStateManager.glPopAttrib(); verifyIsEnabled(GL11.GL_FOG, false, "Fog Enable - Reset"); @@ -317,7 +286,6 @@ class GLSM_PushPop_UnitTest { verifyState(GL11.GL_FOG_END, 1f, "Fog End - Reset"); verifyState(GL11.GL_FOG_START, 0f, "Fog Start - Reset"); verifyState(GL11.GL_FOG_MODE, GL11.GL_EXP, "Fog Mode - Reset"); - if (!GLStateManager.vendorIsNVIDIA()) verifyState(GL11.GL_FOG_INDEX, 0f, "Fog Index - Reset"); } @Test @@ -526,35 +494,22 @@ class GLSM_PushPop_UnitTest { @Test void testPushPopLineBit() { - /* - * GL_LINE_BIT - * GL_LINE_SMOOTH enable bit - * GL_LINE_STIPPLE enable bit - * Line stipple pattern and repeat counter - * Line width - */ + // glLineStipple is guarded as unsupported in core profile — only test line width and smooth verifyState(GL11.GL_LINE_WIDTH, 1.0f, "Line Width - Initial"); - verifyState(GL11.GL_LINE_STIPPLE_PATTERN, (short) 0xFFFF, "Line Stipple Pattern - Initial"); - verifyState(GL11.GL_LINE_STIPPLE_REPEAT, 1, "Line Stipple Repeat - Initial"); verifyIsEnabled(GL11.GL_LINE_SMOOTH, false, "Line Smooth - Initial"); verifyIsEnabled(GL11.GL_LINE_STIPPLE, false, "Line Stipple - Initial"); GLStateManager.glPushAttrib(GL11.GL_LINE_BIT); GLStateManager.glLineWidth(2.5f); - GLStateManager.glLineStipple(3, (short) 0xAAAA); GLStateManager.glEnable(GL11.GL_LINE_SMOOTH); GLStateManager.glEnable(GL11.GL_LINE_STIPPLE); verifyState(GL11.GL_LINE_WIDTH, 2.5f, "Line Width"); - verifyState(GL11.GL_LINE_STIPPLE_PATTERN, (short) 0xAAAA, "Line Stipple Pattern"); - verifyState(GL11.GL_LINE_STIPPLE_REPEAT, 3, "Line Stipple Repeat"); verifyIsEnabled(GL11.GL_LINE_SMOOTH, true, "Line Smooth"); verifyIsEnabled(GL11.GL_LINE_STIPPLE, true, "Line Stipple"); GLStateManager.glPopAttrib(); verifyState(GL11.GL_LINE_WIDTH, 1.0f, "Line Width - Reset"); - verifyState(GL11.GL_LINE_STIPPLE_PATTERN, (short) 0xFFFF, "Line Stipple Pattern - Reset"); - verifyState(GL11.GL_LINE_STIPPLE_REPEAT, 1, "Line Stipple Repeat - Reset"); verifyIsEnabled(GL11.GL_LINE_SMOOTH, false, "Line Smooth - Reset"); verifyIsEnabled(GL11.GL_LINE_STIPPLE, false, "Line Stipple - Reset"); } diff --git a/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java b/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java new file mode 100644 index 000000000..1f1958b6c --- /dev/null +++ b/src/test/java/com/gtnewhorizons/angelica/glsm/VertexAttribDefaultBridgeTest.java @@ -0,0 +1,110 @@ +package com.gtnewhorizons.angelica.glsm; + +import com.gtnewhorizons.angelica.AngelicaExtension; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.lwjgl.BufferUtils; +import org.lwjgl.opengl.GL13; +import org.lwjgl.opengl.GL20; + +import java.nio.FloatBuffer; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ExtendWith(AngelicaExtension.class) +class VertexAttribDefaultBridgeTest { + + private static final int COLOR_ATTRIB = 1; // VertexFormatElement.Usage.COLOR + private static final int PRIMARY_UV_ATTRIB = 2; // VertexFormatElement.Usage.PRIMARY_UV + private static final int SECONDARY_UV_ATTRIB = 3; // VertexFormatElement.Usage.SECONDARY_UV + private static final int NORMAL_ATTRIB = 4; // VertexFormatElement.Usage.NORMAL + private static final float EPSILON = 1e-5f; + + private float[] getVertexAttrib4f(int index) { + FloatBuffer buf = BufferUtils.createFloatBuffer(4); + GL20.glGetVertexAttrib(index, GL20.GL_CURRENT_VERTEX_ATTRIB, buf); + return new float[] { buf.get(0), buf.get(1), buf.get(2), buf.get(3) }; + } + + @Test + void testGlColor4fSetsVertexAttrib() { + GLStateManager.glColor4f(0.5f, 0.25f, 0.75f, 0.8f); + GLStateManager.flushDeferredVertexAttribs(); + + float[] color = getVertexAttrib4f(COLOR_ATTRIB); + assertEquals(0.5f, color[0], EPSILON, "color.r"); + assertEquals(0.25f, color[1], EPSILON, "color.g"); + assertEquals(0.75f, color[2], EPSILON, "color.b"); + assertEquals(0.8f, color[3], EPSILON, "color.a"); + } + + @Test + void testGlNormal3fSetsVertexAttrib() { + GLStateManager.glNormal3f(0.0f, 1.0f, 0.0f); + GLStateManager.flushDeferredVertexAttribs(); + + float[] normal = getVertexAttrib4f(NORMAL_ATTRIB); + assertEquals(0.0f, normal[0], EPSILON, "normal.x"); + assertEquals(1.0f, normal[1], EPSILON, "normal.y"); + assertEquals(0.0f, normal[2], EPSILON, "normal.z"); + } + + @Test + void testSetLightmapTextureCoordsOnUnit1SetsVertexAttrib() { + GLStateManager.setLightmapTextureCoords(GL13.GL_TEXTURE1, 240.0f, 128.0f); + GLStateManager.flushDeferredVertexAttribs(); + + float[] lm = getVertexAttrib4f(SECONDARY_UV_ATTRIB); + assertEquals(240.0f, lm[0], EPSILON, "lightmap.s"); + assertEquals(128.0f, lm[1], EPSILON, "lightmap.t"); + assertEquals(0.0f, lm[2], EPSILON, "lightmap.r"); + assertEquals(1.0f, lm[3], EPSILON, "lightmap.q"); + } + + @Test + void testGlTexCoord2fSetsVertexAttrib() { + // glTexCoord2f outside recording → sets default vertex attrib 2 (PRIMARY_UV) + GLStateManager.glTexCoord2f(0.5f, 0.75f); + GLStateManager.flushDeferredVertexAttribs(); + + float[] uv = getVertexAttrib4f(PRIMARY_UV_ATTRIB); + assertEquals(0.5f, uv[0], EPSILON, "texcoord.s"); + assertEquals(0.75f, uv[1], EPSILON, "texcoord.t"); + } + + @Test + void testCacheDedup_SameColorTwice_AttribStillCorrect() { + GLStateManager.glColor4f(0.3f, 0.6f, 0.9f, 1.0f); + // Second call is a cache hit — changeColor not called. + // Vertex attrib should still hold the correct value from the first call. + GLStateManager.glColor4f(0.3f, 0.6f, 0.9f, 1.0f); + GLStateManager.flushDeferredVertexAttribs(); + + float[] color = getVertexAttrib4f(COLOR_ATTRIB); + assertEquals(0.3f, color[0], EPSILON, "color.r after dedup"); + assertEquals(0.6f, color[1], EPSILON, "color.g after dedup"); + assertEquals(0.9f, color[2], EPSILON, "color.b after dedup"); + assertEquals(1.0f, color[3], EPSILON, "color.a after dedup"); + } + + @Test + void testCompileMode_DoesNotSetVertexAttrib() { + GLStateManager.glColor4f(0.1f, 0.2f, 0.3f, 1.0f); + GLStateManager.flushDeferredVertexAttribs(); + + int listId = GLStateManager.glGenLists(1); + GLStateManager.glNewList(listId, org.lwjgl.opengl.GL11.GL_COMPILE); + + // Color during COMPILE should NOT reach changeColor (early return) + GLStateManager.glColor4f(0.9f, 0.8f, 0.7f, 0.6f); + + float[] color = getVertexAttrib4f(COLOR_ATTRIB); + assertEquals(0.1f, color[0], EPSILON, "color.r unchanged during COMPILE"); + assertEquals(0.2f, color[1], EPSILON, "color.g unchanged during COMPILE"); + assertEquals(0.3f, color[2], EPSILON, "color.b unchanged during COMPILE"); + assertEquals(1.0f, color[3], EPSILON, "color.a unchanged during COMPILE"); + + GLStateManager.glEndList(); + GLStateManager.glDeleteLists(listId, 1); + } +} diff --git a/src/test/java/com/gtnewhorizons/angelica/util/GLSMUtil.java b/src/test/java/com/gtnewhorizons/angelica/util/GLSMUtil.java index f995789e1..617899346 100644 --- a/src/test/java/com/gtnewhorizons/angelica/util/GLSMUtil.java +++ b/src/test/java/com/gtnewhorizons/angelica/util/GLSMUtil.java @@ -9,6 +9,7 @@ import org.lwjgl.opengl.GL13; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; +import java.util.Set; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertAll; @@ -38,15 +39,55 @@ public class GLSMUtil { GL11.GL_MAP2_VERTEX_3, GL11.GL_MAP2_VERTEX_4 }; + private static final Set FFP_ONLY_CAPS = Set.of( + // Enable/disable caps (BooleanState ffpStateOnly=true) + GL11.GL_FOG, GL11.GL_ALPHA_TEST, GL11.GL_LIGHTING, + GL12.GL_RESCALE_NORMAL, GL11.GL_NORMALIZE, GL11.GL_COLOR_MATERIAL, + GL11.GL_LIGHT0, GL11.GL_LIGHT1, GL11.GL_LIGHT2, GL11.GL_LIGHT3, + GL11.GL_LIGHT4, GL11.GL_LIGHT5, GL11.GL_LIGHT6, GL11.GL_LIGHT7, + // Texture enable/disable (TextureUnitBooleanStateStack ffpStateOnly=true) + GL11.GL_TEXTURE_1D, GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_3D, + GL11.GL_TEXTURE_GEN_S, GL11.GL_TEXTURE_GEN_T, + GL11.GL_TEXTURE_GEN_R, GL11.GL_TEXTURE_GEN_Q, + // Matrix state + GL11.GL_MATRIX_MODE, GL11.GL_MODELVIEW_MATRIX, + GL11.GL_PROJECTION_MATRIX, GL11.GL_TEXTURE_MATRIX, + // Current vertex state + GL11.GL_CURRENT_COLOR, GL11.GL_CURRENT_NORMAL, GL11.GL_CURRENT_TEXTURE_COORDS, + // Alpha test params + GL11.GL_ALPHA_TEST_FUNC, GL11.GL_ALPHA_TEST_REF, + // Shade model + GL11.GL_SHADE_MODEL, + // Color material params + GL11.GL_COLOR_MATERIAL_FACE, GL11.GL_COLOR_MATERIAL_PARAMETER, + // Light model params + GL11.GL_LIGHT_MODEL_AMBIENT, GL11.GL_LIGHT_MODEL_LOCAL_VIEWER, + GL11.GL_LIGHT_MODEL_TWO_SIDE, GL12.GL_LIGHT_MODEL_COLOR_CONTROL, + // Line stipple params (removed from core profile) + GL11.GL_LINE_STIPPLE, GL11.GL_LINE_STIPPLE_PATTERN, GL11.GL_LINE_STIPPLE_REPEAT, + // Fog params + GL11.GL_FOG_COLOR, GL11.GL_FOG_DENSITY, + GL11.GL_FOG_START, GL11.GL_FOG_END, + GL11.GL_FOG_MODE, GL11.GL_FOG_INDEX + ); + + private static boolean isFFPOnly(int glCap) { + return FFP_ONLY_CAPS.contains(glCap); + } + public static void verifyIsEnabled(int glCap, boolean expected) { verifyIsEnabled(glCap, expected, "Is Enabled Mismatch"); } public static void verifyIsEnabled(int glCap, boolean expected, String message) { - assertAll( message, - () -> assertEquals(expected, GL11.glIsEnabled(glCap), "GL State Mismatch"), - () -> assertEquals(expected, GLStateManager.glIsEnabled(glCap), "GLSM State Mismatch") - ); + if (isFFPOnly(glCap)) { + assertEquals(expected, GLStateManager.glIsEnabled(glCap), message + " - GLSM State Mismatch"); + } else { + assertAll(message, + () -> assertEquals(expected, GL11.glIsEnabled(glCap), "GL State Mismatch"), + () -> assertEquals(expected, GLStateManager.glIsEnabled(glCap), "GLSM State Mismatch") + ); + } } public static void verifyState(int glCap, boolean expected) { @@ -54,38 +95,53 @@ public class GLSMUtil { } public static void verifyState(int glCap, boolean expected, String message) { - assertAll( message, - () -> assertEquals(expected, GL11.glGetBoolean(glCap), "GL State Mismatch"), - () -> assertEquals(expected, GLStateManager.glGetBoolean(glCap), "GLSM State Mismatch") - ); + if (isFFPOnly(glCap)) { + assertEquals(expected, GLStateManager.glGetBoolean(glCap), message + " - GLSM State Mismatch"); + } else { + assertAll(message, + () -> assertEquals(expected, GL11.glGetBoolean(glCap), "GL State Mismatch"), + () -> assertEquals(expected, GLStateManager.glGetBoolean(glCap), "GLSM State Mismatch") + ); + } } public static void verifyState(int glCap, int expected) { verifyState(glCap, expected, "Int State Mismatch"); } public static void verifyState(int glCap, int expected, String message) { - assertAll(message, - () -> assertEquals(expected, GL11.glGetInteger(glCap), "GL State Mismatch"), - () -> assertEquals(expected, GLStateManager.glGetInteger(glCap), "GLSM State Mismatch") - ); + if (isFFPOnly(glCap)) { + assertEquals(expected, GLStateManager.glGetInteger(glCap), message + " - GLSM State Mismatch"); + } else { + assertAll(message, + () -> assertEquals(expected, GL11.glGetInteger(glCap), "GL State Mismatch"), + () -> assertEquals(expected, GLStateManager.glGetInteger(glCap), "GLSM State Mismatch") + ); + } } public static void verifyState(int glCap, short expected, String message) { - // For short state (e.g., line stipple pattern), GL returns it as int, we compare as short - assertAll(message, - () -> assertEquals(expected, (short) GL11.glGetInteger(glCap), "GL State Mismatch"), - () -> assertEquals(expected, (short) GLStateManager.glGetInteger(glCap), "GLSM State Mismatch") - ); + if (isFFPOnly(glCap)) { + assertEquals(expected, (short) GLStateManager.glGetInteger(glCap), message + " - GLSM State Mismatch"); + } else { + assertAll(message, + () -> assertEquals(expected, (short) GL11.glGetInteger(glCap), "GL State Mismatch"), + () -> assertEquals(expected, (short) GLStateManager.glGetInteger(glCap), "GLSM State Mismatch") + ); + } } public static void verifyState(int glCap, float expected) { verifyState(glCap, expected, "Float State Mismatch"); } public static void verifyState(int glCap, float expected, String message) { - assertAll(message, - () -> assertEquals(expected, GL11.glGetFloat(glCap), 0.0001f, "GL State Mismatch"), - () -> assertEquals(expected, GLStateManager.glGetFloat(glCap), 0.0001f, "GLSM State Mismatch") - ); + if (isFFPOnly(glCap)) { + assertEquals(expected, GLStateManager.glGetFloat(glCap), 0.0001f, message + " - GLSM State Mismatch"); + } else { + assertAll(message, + () -> assertEquals(expected, GL11.glGetFloat(glCap), 0.0001f, "GL State Mismatch"), + () -> assertEquals(expected, GLStateManager.glGetFloat(glCap), 0.0001f, "GLSM State Mismatch") + ); + } } public static void verifyState(int glCap, int[] expected) { verifyState(glCap, expected, "Int State Mismatch"); @@ -95,12 +151,19 @@ public class GLSMUtil { static final IntBuffer glsmIntBuffer = BufferUtils.createIntBuffer(16); public static void verifyState(int glCap, int[] expected, String message) { - GL11.glGetInteger(glCap, (IntBuffer) glIntBuffer.clear()); - GLStateManager.glGetInteger(glCap, (IntBuffer) glsmIntBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertEquals(expected[i], glIntBuffer.get(i), "GL State Mismatch: " + i), - () -> assertEquals(expected[i], glsmIntBuffer.get(i), "GLSM State Mismatch: " + i) - )); + if (isFFPOnly(glCap)) { + GLStateManager.glGetInteger(glCap, (IntBuffer) glsmIntBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> + assertEquals(expected[i], glsmIntBuffer.get(i), message + " - GLSM State Mismatch: " + i) + ); + } else { + GL11.glGetInteger(glCap, (IntBuffer) glIntBuffer.clear()); + GLStateManager.glGetInteger(glCap, (IntBuffer) glsmIntBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> assertAll(message, + () -> assertEquals(expected[i], glIntBuffer.get(i), "GL State Mismatch: " + i), + () -> assertEquals(expected[i], glsmIntBuffer.get(i), "GLSM State Mismatch: " + i) + )); + } } @@ -112,21 +175,35 @@ public class GLSMUtil { static final FloatBuffer glsmFloatBuffer = BufferUtils.createFloatBuffer(16); public static void verifyState(int glCap, float[] expected, String message) { - GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear()); - GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), - () -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) - )); + if (isFFPOnly(glCap)) { + GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> + assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i) + ); + } else { + GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear()); + GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> assertAll(message, + () -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), + () -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) + )); + } } public static void verifyNotDefaultState(int glCap, float[] expected, String message) { - GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear()); - GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertNotEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), - () -> assertNotEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) - )); + if (isFFPOnly(glCap)) { + GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> + assertNotEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i) + ); + } else { + GL11.glGetFloat(glCap, (FloatBuffer) glFloatBuffer.clear()); + GLStateManager.glGetFloat(glCap, (FloatBuffer) glsmFloatBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> assertAll(message, + () -> assertNotEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), + () -> assertNotEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) + )); + } } public static void verifyState(int glCap, boolean[] expected) { @@ -137,32 +214,36 @@ public class GLSMUtil { static final ByteBuffer glsmByteBuffer = BufferUtils.createByteBuffer(16); public static void verifyState(int glCap, boolean[] expected, String message) { - - GL11.glGetBoolean(glCap, (ByteBuffer) glByteBuffer.clear()); - GLStateManager.glGetBoolean(glCap, (ByteBuffer) glsmByteBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glByteBuffer.get(i), "GL State Mismatch: " + i), - () -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glsmByteBuffer.get(i), "GLSM State Mismatch: " + i) - )); + if (isFFPOnly(glCap)) { + GLStateManager.glGetBoolean(glCap, (ByteBuffer) glsmByteBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> + assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glsmByteBuffer.get(i), message + " - GLSM State Mismatch: " + i) + ); + } else { + GL11.glGetBoolean(glCap, (ByteBuffer) glByteBuffer.clear()); + GLStateManager.glGetBoolean(glCap, (ByteBuffer) glsmByteBuffer.clear()); + IntStream.range(0, expected.length).forEach(i -> assertAll(message, + () -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glByteBuffer.get(i), "GL State Mismatch: " + i), + () -> assertEquals(expected[i] ? GL11.GL_TRUE : GL11.GL_FALSE, glsmByteBuffer.get(i), "GLSM State Mismatch: " + i) + )); + } } + /** Light params are FFP-only — verify GLSM cache only. */ public static void verifyLightState(int glLight, int pname, float[] expected, String message) { - GL11.glGetLight(glLight, pname, (FloatBuffer) glFloatBuffer.clear()); GLStateManager.glGetLight(glLight, pname, (FloatBuffer) glsmFloatBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), - () -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) - )); + IntStream.range (0, expected.length).forEach(i -> + assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i) + ); } + /** Material params are FFP-only — verify GLSM cache only. */ public static void verifyMaterialState(int face, int pname, float[] expected, String message) { - GL11.glGetMaterial(face, pname, (FloatBuffer) glFloatBuffer.clear()); GLStateManager.glGetMaterial(face, pname, (FloatBuffer) glsmFloatBuffer.clear()); - IntStream.range (0, expected.length).forEach(i -> assertAll(message, - () -> assertEquals(expected[i], glFloatBuffer.get(i), 0.0001f, "GL State Mismatch: " + i), - () -> assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, "GLSM State Mismatch: " + i) - )); + IntStream.range (0, expected.length).forEach(i -> + assertEquals(expected[i], glsmFloatBuffer.get(i), 0.0001f, message + " - GLSM State Mismatch: " + i) + ); } /** @@ -264,7 +345,6 @@ public class GLSMUtil { // Reset line state GLStateManager.glLineWidth(1.0f); - GLStateManager.glLineStipple(1, (short) 0xFFFF); // Reset point state GLStateManager.glPointSize(1.0f);