diff --git a/.github/ISSUE_TEMPLATE/000-report-bug.yml b/.github/ISSUE_TEMPLATE/000-report-bug.yml index f8aeb308f..d5ff8930a 100644 --- a/.github/ISSUE_TEMPLATE/000-report-bug.yml +++ b/.github/ISSUE_TEMPLATE/000-report-bug.yml @@ -52,11 +52,10 @@ body: id: shaders attributes: label: Shaders - description: Do you have Iris/Shaders enabled? + description: Do you have a shaderpack enabled? options: - - "No: Go ahead and create an issue" - - "Yes: I will not create an issue" - - "Yes: I don't read and shouldn't be creating an issue" + - "No" + - "Yes: Please put relevant information about shaderpack in the report(what shaderpack, any special settings of note, etc)" validations: required: true - type: dropdown @@ -98,6 +97,6 @@ body: required: true - label: "I am running an officially released version. (Or, if I've compiled it myself I plan to fix the issue)" required: true - - label: "This issue is not related to a feature that is disabed by default - Shaders, MCPF, etc. [They'll be enabled when they're ready for testing]" + - label: "This issue is not related to a feature that is disabed by default - MCPF, etc. [They'll be enabled when they're ready for testing]" required: true - + diff --git a/.github/ISSUE_TEMPLATE/001-request-feature.yml b/.github/ISSUE_TEMPLATE/001-request-feature.yml index 56a807be7..fd24e46a8 100644 --- a/.github/ISSUE_TEMPLATE/001-request-feature.yml +++ b/.github/ISSUE_TEMPLATE/001-request-feature.yml @@ -29,5 +29,5 @@ body: required: true - label: "I have read the known incompatibilities and this is not related to one of those." required: true - - label: "This issue is not related to a feature that is disabed by default - Shaders, MCPF, etc. [They'll be enabled when they're ready for testing]" - required: true \ No newline at end of file + - label: "This issue is not related to a feature that is disabed by default - MCPF, etc. [They'll be enabled when they're ready for testing]" + required: true diff --git a/README.MD b/README.MD index 5f82e9e26..7a095dd03 100644 --- a/README.MD +++ b/README.MD @@ -75,4 +75,6 @@ license, see LICENSE in `com.gtnewhorizons.angelica.models` * Dynamic Lights * LambdAurora for [LambDynamicLights](https://github.com/LambdAurora/LambDynamicLights) under the MIT license, and the Forge port anthxnymc for [DynamicLightsReforged](https://github.com/anthxnymc/DynamicLightsReforged), also under the MIT license - +* Embeddedt and Ferri_Arnus for [glsl-transformation-lib](https://github.com/TauMC/glsl-transformation-lib) + * Also for work on [Monocle](https://github.com/ferriarnus/Monocle) which was used as a reference for implementing glsl-transformation-lib + * Code from both glsl-transformation-lib and Monocle taken under their respective LGPL 3.0 licenses diff --git a/dependencies.gradle b/dependencies.gradle index b3a894f63..20d40ddf4 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -63,10 +63,10 @@ dependencies { compileOnly('org.jetbrains:annotations:24.0.1') api("com.github.GTNewHorizons:GTNHLib:0.5.12:dev") shadowImplementation("org.anarres:jcpp:1.4.14") // Apache 2.0 - implementation("io.github.douira:glsl-transformer:1.0.0") - shadowImplementation("io.github.douira:glsl-transformer:1.0.0") { // glsl-transformer Noncommercial License 1.0.0 + shadowImplementation("org.taumc:glsl-transformation-lib:0.2.0-4.g6b42bca") { exclude module: "antlr4" // we only want to shadow the runtime module } + shadowImplementation("org.antlr:antlr4-runtime:4.13.2") compileOnly "org.apache.ant:ant:1.8.2" // Because who doesn't want NEI @@ -112,7 +112,6 @@ dependencies { // Better Crashes compileOnly("com.github.GTNewHorizons:BetterCrashes:1.4.0-GTNH:dev") - // Tests testImplementation(platform('org.junit:junit-bom:5.9.2')) testImplementation('org.junit.jupiter:junit-jupiter') diff --git a/repositories.gradle b/repositories.gradle index e268ed154..81d6086cd 100644 --- a/repositories.gradle +++ b/repositories.gradle @@ -25,5 +25,12 @@ repositories { includeGroup('CoreTweaks') } } + maven { + name = 'taumc' + url = 'https://maven.taumc.org/releases' + content { + includeGroup 'org.taumc' + } + } mavenLocal() } diff --git a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java index 47a7bb213..d4a661116 100644 --- a/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java +++ b/src/main/java/com/gtnewhorizons/angelica/config/AngelicaConfig.java @@ -33,7 +33,7 @@ public class AngelicaConfig { public static boolean enableTestBlocks; @Config.Comment("Enable Iris Shaders [Requires Sodium]") - @Config.DefaultBoolean(false) + @Config.DefaultBoolean(true) @Config.RequiresMcRestart public static boolean enableIris; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeParameters.java deleted file mode 100644 index 11d85b53f..000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeParameters.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.coderbot.iris.pipeline.transform; - -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; - -class AttributeParameters extends Parameters { - public final boolean hasGeometry; - public final InputAvailability inputs; - - public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) { - super(patch); - this.hasGeometry = hasGeometry; - this.inputs = inputs; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (hasGeometry ? 1231 : 1237); - result = prime * result + ((inputs == null) ? 0 : inputs.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - AttributeParameters other = (AttributeParameters) obj; - if (hasGeometry != other.hasGeometry) - return false; - if (inputs == null) { - if (other.inputs != null) - return false; - } else if (!inputs.equals(other.inputs)) - return false; - return true; - } -} 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 805951b70..428a8b5ec 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/AttributeTransformer.java @@ -1,30 +1,17 @@ package net.coderbot.iris.pipeline.transform; -import io.github.douira.glsl_transformer.ast.node.Identifier; -import io.github.douira.glsl_transformer.ast.node.Profile; -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.basic.ASTNode; -import io.github.douira.glsl_transformer.ast.node.external_declaration.ExternalDeclaration; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.query.match.AutoHintedMatcher; -import io.github.douira.glsl_transformer.ast.query.match.Matcher; -import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; import net.coderbot.iris.gl.shader.ShaderType; - -import java.util.stream.Stream; +import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.Util; /** * Implements AttributeShaderTransformer using glsl-transformer AST * transformation methods. */ class AttributeTransformer { - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - AttributeParameters parameters) { - boolean isCore = (tree.getVersionStatement().profile == Profile.CORE || (tree.getVersionStatement().profile == null && tree.getVersionStatement().version.number > 140)); + public static void transform(GLSLParser.Translation_unitContext translationUnit, AttributeParameters parameters, String profile, int version) { + boolean isCore = (profile.equals("core") || version > 140); if (isCore) { if (parameters.type == PatchShaderType.VERTEX) { throw new IllegalStateException("Vertex shaders must be in the compatibility profile to run properly!"); @@ -36,32 +23,22 @@ class AttributeTransformer { // lightmap texture coordinate. // See https://github.com/IrisShaders/Iris/issues/1149 if (parameters.inputs.lightmap) { - root.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); + Util.rename(translationUnit, "gl_MultiTexCoord2", "gl_MultiTexCoord1"); } - Stream stream = Stream.empty(); - boolean hasItems = false; - if (!parameters.inputs.lightmap) { - stream = Stream.concat(stream, - root.identifierIndex.getStream("gl_MultiTexCoord1")); - stream = Stream.concat(stream, - root.identifierIndex.getStream("gl_MultiTexCoord2")); - hasItems = true; - } - if (!parameters.inputs.texture) { - stream = Stream.concat(stream, - root.identifierIndex.getStream("gl_MultiTexCoord0")); - hasItems = true; - } - if (hasItems) { - root.replaceReferenceExpressions(t, stream, "vec4(240.0, 240.0, 0.0, 1.0)"); - } + if (!parameters.inputs.lightmap) { + Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "vec4(240.0, 240.0, 0.0, 1.0)"); + Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "vec4(240.0, 240.0, 0.0, 1.0)"); + } + if (!parameters.inputs.texture) { + Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(240.0, 240.0, 0.0, 1.0)"); + } - patchTextureMatrices(t, tree, root, parameters.inputs.lightmap); + patchTextureMatrices(translationUnit, parameters.inputs.lightmap); if (parameters.type.glShaderType == ShaderType.VERTEX - && root.identifierIndex.has("gl_MultiTexCoord3") - && !root.identifierIndex.has("mc_midTexCoord")) { + && Util.hasVariable(translationUnit, "gl_MultiTexCoord3") + && !Util.hasVariable(translationUnit, "mc_midTexCoord")) { // TODO: proper type conversion // gl_MultiTexCoord3 is a super legacy alias of mc_midTexCoord. We don't do this // replacement if we think mc_midTexCoord could be defined just we can't handle @@ -69,43 +46,44 @@ class AttributeTransformer { // to define mc_midTexCoord only if it's not defined, and if it is defined, // figure out its type, then replace all occurrences of gl_MultiTexCoord3 with // the correct conversion from mc_midTexCoord's declared type to vec4. - root.rename("gl_MultiTexCoord3", "mc_midTexCoord"); - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "attribute vec4 mc_midTexCoord;"); + Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord"); + Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;"); } } - private static void patchTextureMatrices( - ASTParser t, - TranslationUnit tree, - Root root, - boolean hasLightmap) { - root.rename("gl_TextureMatrix", "iris_TextureMatrix"); + private static void patchTextureMatrices(GLSLParser.Translation_unitContext translationUnit, boolean hasLightmap) { + Util.rename(translationUnit, "gl_TextureMatrix", "iris_TextureMatrix"); - tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "const float iris_ONE_OVER_256 = 0.00390625;", - "const float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;"); - if (hasLightmap) { - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];"); - } else { - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_FUNCTIONS, "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);"); - } + // TODO: These were originally marked const, but that breaks things + // If these are marked const, then using them below in the iris_LightmapTextureMatrix creation + // breaks with them being undefined. I suppose the const variables cause them to get defined later than otherwise? + // Similarly, if you make them a const, then iris_ONE_OVER_32 breaks because it references iris_ONE_OVER_256. + // Not sure if it really matters if these are marked const or not. Alternatively they can be marked const + // and the values hardcoded within the places that use them here, that seems to work fine, but this probably + // stayed closer to the original way it worked. + Util.injectVariable(translationUnit, "float iris_ONE_OVER_256 = 0.00390625;"); + Util.injectVariable(translationUnit, "float iris_ONE_OVER_32 = iris_ONE_OVER_256 * 8;"); - // column major - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_FUNCTIONS, "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)" + - ");"); + if (hasLightmap) { + Util.injectVariable(translationUnit, "mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[1];"); + } else { + Util.injectVariable(translationUnit, "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);"); + } + + // column major + Util.injectVariable(translationUnit, "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/CompatibilityTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java index cb31757e1..0a431b536 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompatibilityTransformer.java @@ -1,310 +1,55 @@ package net.coderbot.iris.pipeline.transform; -import io.github.douira.glsl_transformer.ast.node.Identifier; -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.basic.ASTNode; -import io.github.douira.glsl_transformer.ast.node.declaration.DeclarationMember; -import io.github.douira.glsl_transformer.ast.node.declaration.FunctionParameter; -import io.github.douira.glsl_transformer.ast.node.declaration.TypeAndInitDeclaration; -import io.github.douira.glsl_transformer.ast.node.expression.Expression; -import io.github.douira.glsl_transformer.ast.node.expression.LiteralExpression; -import io.github.douira.glsl_transformer.ast.node.expression.ReferenceExpression; -import io.github.douira.glsl_transformer.ast.node.expression.unary.FunctionCallExpression; -import io.github.douira.glsl_transformer.ast.node.external_declaration.DeclarationExternalDeclaration; -import io.github.douira.glsl_transformer.ast.node.external_declaration.EmptyDeclaration; -import io.github.douira.glsl_transformer.ast.node.external_declaration.ExternalDeclaration; -import io.github.douira.glsl_transformer.ast.node.external_declaration.FunctionDefinition; -import io.github.douira.glsl_transformer.ast.node.statement.Statement; -import io.github.douira.glsl_transformer.ast.node.type.qualifier.StorageQualifier; -import io.github.douira.glsl_transformer.ast.node.type.qualifier.StorageQualifier.StorageType; -import io.github.douira.glsl_transformer.ast.node.type.qualifier.TypeQualifier; -import io.github.douira.glsl_transformer.ast.node.type.qualifier.TypeQualifierPart; -import io.github.douira.glsl_transformer.ast.node.type.specifier.BuiltinNumericTypeSpecifier; -import io.github.douira.glsl_transformer.ast.node.type.specifier.FunctionPrototype; -import io.github.douira.glsl_transformer.ast.node.type.specifier.TypeSpecifier; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.query.match.AutoHintedMatcher; -import io.github.douira.glsl_transformer.ast.query.match.Matcher; -import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; -import io.github.douira.glsl_transformer.ast.transform.Template; -import io.github.douira.glsl_transformer.util.Type; -import net.coderbot.iris.Iris; import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.PatchedShaderPrinter; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import org.antlr.v4.runtime.tree.ParseTree; +import org.taumc.glsl.Util; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.stream.Stream; public class CompatibilityTransformer { - static Logger LOGGER = LogManager.getLogger(CompatibilityTransformer.class); - private static final AutoHintedMatcher sildursWaterFract = new AutoHintedMatcher<>( - "fract(worldpos.y + 0.001)", Matcher.expressionPattern); + private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.GEOMETRY, ShaderType.FRAGMENT}; - private static StorageQualifier getConstQualifier(TypeQualifier qualifier) { - if (qualifier == null) { - return null; - } - for (TypeQualifierPart constQualifier : qualifier.getChildren()) { - if (constQualifier instanceof StorageQualifier) { - StorageQualifier storageQualifier = (StorageQualifier) constQualifier; - if (storageQualifier.storageType == StorageQualifier.StorageType.CONST) { - return storageQualifier; - } - } - } - return null; - } - public static void transformEach(ASTParser t, TranslationUnit tree, Root root, Parameters parameters) { - if (parameters.type == PatchShaderType.VERTEX) { - if (root.replaceExpressionMatches(t, sildursWaterFract, "fract(worldpos.y + 0.01)")) { - Iris.logger.warn("Patched fract(worldpos.y + 0.001) to fract(worldpos.y + 0.01) to fix " + - "waving water disconnecting from other water blocks; See https://github.com/IrisShaders/Iris/issues/509"); - } - } + public static void transformEach(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + if (parameters.type == PatchShaderType.VERTEX) { + ; + // TODO: sildur's jankness + // This is a hacky patch for sildur's shaders that changes the way it does it's waving water to make it work better? + // Why is this the GLSL transformation code in Iris, tell sildur to fix it and remove this? + // it's still there in current, modern Iris + // See https://github.com/IrisShaders/Iris/issues/509 + Util.replaceExpression(translationUnit, "fract(worldpos.y + 0.001)", "fract(worldpos.y + 0.01)"); + } - /** - * Removes const storage qualifier from declarations in functions if they are - * initialized with const parameters. Const parameters are immutable parameters - * and can't be used to initialize const declarations because they expect - * constant, not just immutable, expressions. This varies between drivers and - * versions. Also removes the const qualifier from declarations that use the - * identifiers from which the declaration was removed previously. - * See https://wiki.shaderlabs.org/wiki/Compiler_Behavior_Notes - */ - Map> constFunctions = new HashMap<>(); - Set processingSet = new HashSet<>(); - List unusedFunctions = new LinkedList<>(); - for (FunctionDefinition definition : root.nodeIndex.get(FunctionDefinition.class)) { - // check if this function is ever used - FunctionPrototype prototype = definition.getFunctionPrototype(); - String functionName = prototype.getName().getName(); - if (!functionName.equals("main") && root.identifierIndex.getStream(functionName).count() <= 1) { - // remove unused functions - // unused function removal can be helpful since some drivers don't do some - // checks on unused functions. Additionally, sometimes bugs in unused code can - // be avoided this way. - // TODO: integrate into debug mode (allow user to disable this behavior for - // debugging purposes) - unusedFunctions.add(definition); - if (PatchedShaderPrinter.prettyPrintShaders) { - LOGGER.warn("Removing unused function " + functionName); - } else if (unusedFunctions.size() == 1) { - LOGGER.warn( - "Removing unused function " + functionName - + " and omitting further such messages outside of debug mode. See debugging.md for more information."); - } - continue; - } + /** + * Removes const storage qualifier from declarations in functions if they are + * initialized with const parameters. Const parameters are immutable parameters + * and can't be used to initialize const declarations because they expect + * constant, not just immutable, expressions. This varies between drivers and + * versions. Also removes the const qualifier from declarations that use the + * identifiers from which the declaration was removed previously. + * See https://wiki.shaderlabs.org/wiki/Compiler_Behavior_Notes + */ + Util.removeUnusedFunctions(translationUnit); + Util.removeConstAssignment(translationUnit); - // stop on functions without parameters - if (prototype.getChildren().isEmpty()) { - continue; - } - - // find the const parameters - Set names = new HashSet<>(prototype.getChildren().size()); - for (FunctionParameter parameter : prototype.getChildren()) { - if (getConstQualifier(parameter.getType().getTypeQualifier()) != null) { - String name = parameter.getName().getName(); - names.add(name); - processingSet.add(name); - } - } - if (!names.isEmpty()) { - constFunctions.put(definition, names); - } - } - - // remove collected unused functions - for (FunctionDefinition definition : unusedFunctions) { - definition.detachAndDelete(); - } - - // find the reference expressions for the const parameters - // and check that they are in the right function and are of the right type - boolean constDeclarationHit = false; - Deque processingQueue = new ArrayDeque<>(processingSet); - while (!processingQueue.isEmpty()) { - String name = processingQueue.poll(); - processingSet.remove(name); - for (Identifier id : root.identifierIndex.get(name)) { - // since this searches for reference expressions, this won't accidentally find - // the name as the name of a declaration member - ReferenceExpression reference = id.getAncestor(ReferenceExpression.class); - if (reference == null) { - continue; - } - TypeAndInitDeclaration taid = reference.getAncestor(TypeAndInitDeclaration.class); - if (taid == null) { - continue; - } - FunctionDefinition inDefinition = taid.getAncestor(FunctionDefinition.class); - if (inDefinition == null) { - continue; - } - Set constIdsInFunction = constFunctions.get(inDefinition); - if (constIdsInFunction == null) { - continue; - } - if (constIdsInFunction.contains(name)) { - // remove the const qualifier from the reference expression - TypeQualifier qualifier = taid.getType().getTypeQualifier(); - StorageQualifier constQualifier = getConstQualifier(qualifier); - if (constQualifier == null) { - continue; - } - constQualifier.detachAndDelete(); - if (qualifier.getChildren().isEmpty()) { - qualifier.detachAndDelete(); - } - constDeclarationHit = true; - - // add all members of the declaration to the list of const parameters to process - for (DeclarationMember member : taid.getMembers()) { - String memberName = member.getName().getName(); - - // the name may not be the same as the parameter name - if (constIdsInFunction.contains(memberName)) { - throw new IllegalStateException("Illegal redefinition of const parameter " + name); - } - - constIdsInFunction.add(memberName); - - // don't add to the queue twice if it's already been added by a different scope - if (!processingSet.contains(memberName)) { - processingQueue.add(memberName); - processingSet.add(memberName); - } - } - } - } - } - - if (constDeclarationHit) { - LOGGER.warn( - "Removed the const keyword from declarations that use const parameters. See debugging.md for more information."); - } - - // remove empty external declarations - boolean emptyDeclarationHit = root.process( - root.nodeIndex.getStream(EmptyDeclaration.class), - ASTNode::detachAndDelete); - if (emptyDeclarationHit) { - LOGGER.warn( - "Removed empty external declarations (\";\")."); - } - } - - private static class DeclarationMatcher extends AutoHintedMatcher { - private final StorageType storageType; - - public DeclarationMatcher(StorageType storageType) { - super("out float name;", Matcher.externalDeclarationPattern); - this.storageType = storageType; - markClassWildcard("qualifier", pattern.getRoot().nodeIndex.getOne(TypeQualifier.class)); - markClassWildcard("type", pattern.getRoot().nodeIndex.getOne(BuiltinNumericTypeSpecifier.class)); - markClassWildcard("name*", pattern.getRoot().identifierIndex.getOne("name").getAncestor(DeclarationMember.class)); - } - - public boolean matchesSpecialized(ExternalDeclaration tree, ShaderType shaderType) { - boolean result = super.matchesExtract(tree); - if (!result) { - return false; - } - TypeQualifier qualifier = getNodeMatch("qualifier", TypeQualifier.class); - for (TypeQualifierPart part : qualifier.getParts()) { - if (part instanceof StorageQualifier) { - StorageQualifier storageQualifier = (StorageQualifier) part; - StorageType qualifierStorageType = storageQualifier.storageType; - // TODO: investigate the specified behavior of varying in geometry shaders and - // the combination of varying with in or out qualifiers - if (qualifierStorageType == storageType || - qualifierStorageType == StorageType.VARYING && - (shaderType == ShaderType.VERTEX && storageType == StorageType.OUT || - shaderType == ShaderType.GEOMETRY && storageType == StorageType.OUT || - shaderType == ShaderType.FRAGMENT && storageType == StorageType.IN)) { - return true; - } - } - } - return false; - } - } - - private static final ShaderType[] pipeline = { ShaderType.VERTEX, ShaderType.GEOMETRY, ShaderType.FRAGMENT }; - private static final DeclarationMatcher outDeclarationMatcher = new DeclarationMatcher(StorageType.OUT); - private static final DeclarationMatcher inDeclarationMatcher = new DeclarationMatcher(StorageType.IN); - - private static final String tagPrefix = "iris_template_"; - private static final Template declarationTemplate = Template - .withExternalDeclaration("out __type __name;"); - private static final Template initTemplate = Template.withStatement("__decl = __value;"); - private static final Template variableTemplate = Template - .withExternalDeclaration("__type __internalDecl;"); - private static final Template statementTemplate = Template - .withStatement("__oldDecl = vec3(__internalDecl);"); - private static final Template statementTemplateVector = Template - .withStatement("__oldDecl = vec3(__internalDecl, vec4(0));"); - - static { - declarationTemplate.markLocalReplacement(declarationTemplate.getSourceRoot().nodeIndex.getOne(TypeQualifier.class)); - declarationTemplate.markLocalReplacement("__type", TypeSpecifier.class); - declarationTemplate.markIdentifierReplacement("__name"); - initTemplate.markIdentifierReplacement("__decl"); - initTemplate.markLocalReplacement("__value", ReferenceExpression.class); - variableTemplate.markLocalReplacement("__type", TypeSpecifier.class); - variableTemplate.markIdentifierReplacement("__internalDecl"); - statementTemplate.markIdentifierReplacement("__oldDecl"); - statementTemplate.markIdentifierReplacement("__internalDecl"); - statementTemplate.markLocalReplacement( - statementTemplate.getSourceRoot().nodeIndex.getStream(BuiltinNumericTypeSpecifier.class) - .filter(specifier -> specifier.type == Type.F32VEC3).findAny().get()); - statementTemplateVector.markIdentifierReplacement("__oldDecl"); - statementTemplateVector.markIdentifierReplacement("__internalDecl"); - statementTemplateVector.markLocalReplacement( - statementTemplateVector.getSourceRoot().nodeIndex.getStream(BuiltinNumericTypeSpecifier.class) - .filter(specifier -> specifier.type == Type.F32VEC3).findAny().get()); - } - - private static Statement getInitializer(Root root, String name, Type type) { - return initTemplate.getInstanceFor(root, - new Identifier(name), - type.isScalar() - ? LiteralExpression.getDefaultValue(type) - : Root.indexNodes(root, () -> new FunctionCallExpression( - new Identifier(type.getMostCompactName()), - Stream.of(LiteralExpression.getDefaultValue(type))))); - } - - private static TypeQualifier makeQualifierOut(TypeQualifier typeQualifier) { - for (TypeQualifierPart qualifierPart : typeQualifier.getParts()) { - if (qualifierPart instanceof StorageQualifier) { - StorageQualifier storageQualifier = (StorageQualifier) qualifierPart; - if (((StorageQualifier) qualifierPart).storageType == StorageType.IN) { - storageQualifier.storageType = StorageType.OUT; - } - } - } - return typeQualifier; - } + // TODO: glsl-transformation-lib doesn't have a way to identify empty declarations + // this transformation is not done in current versions of Iris, so not sure it's necessary +// boolean emptyDeclarationHit = root.process( +// root.nodeIndex.getStream(EmptyDeclaration.class), +// ASTNode::detachAndDelete); +// if (emptyDeclarationHit) { +// LOGGER.warn( +// "Removed empty external declarations (\";\")."); +// } + } // does transformations that require cross-shader type data - public static void transformGrouped( - ASTParser t, - Map trees, - Parameters parameters) { + public static void transformGrouped(Map trees, Parameters parameters) { /** * find attributes that are declared as "in" in geometry or fragment but not * declared as "out" in the previous stage. The missing "out" declarations for @@ -320,225 +65,73 @@ public class CompatibilityTransformer { * iris_FogFragCoord if there are geometry shaders present * - improved geometry shader support? They use funky declarations */ - ShaderType prevType = null; - for (int i = 0; i < pipeline.length; i++) { - ShaderType type = pipeline[i]; - PatchShaderType[] patchTypes = PatchShaderType.fromGlShaderType(type); + ShaderType prevType = null; + for (ShaderType type : pipeline) { + PatchShaderType[] patchTypes = PatchShaderType.fromGlShaderType(type); - // check if the patch types have sources and continue if not - boolean hasAny = false; - for (PatchShaderType currentType : patchTypes) { - if (trees.get(currentType) != null) { - hasAny = true; - } - } - if (!hasAny) { - continue; - } + // check if the patch types have sources and continue if not + boolean hasAny = false; + for (PatchShaderType currentType : patchTypes) { + if (trees.get(currentType) != null) { + hasAny = true; + } + } + if (!hasAny) { + continue; + } - // if the current type has sources but the previous one doesn't, set the - // previous one and continue - if (prevType == null) { - prevType = type; - continue; - } + // if the current type has sources but the previous one doesn't, set the + // previous one and continue + if (prevType == null) { + prevType = type; + continue; + } - PatchShaderType prevPatchTypes = PatchShaderType.fromGlShaderType(prevType)[0]; - TranslationUnit prevTree = trees.get(prevPatchTypes); - Root prevRoot = prevTree.getRoot(); + PatchShaderType prevPatchTypes = PatchShaderType.fromGlShaderType(prevType)[0]; + GLSLParser.Translation_unitContext prevTree = trees.get(prevPatchTypes); - // test if the prefix tag is used for some reason - if (prevRoot.identifierIndex.prefixQueryFlat(tagPrefix).findAny().isPresent()) { - LOGGER.warn("The prefix tag " + tagPrefix + " is used in the shader, bailing compatibility transformation."); - return; - } + // find out declarations + Map outDec = Util.findQualifiers(prevTree, GLSLLexer.OUT); + for (PatchShaderType currentType : patchTypes) { + GLSLParser.Translation_unitContext currentTree = trees.get(currentType); - // find out declarations - Map outDeclarations = new HashMap<>(); - for (DeclarationExternalDeclaration declaration : prevRoot.nodeIndex.get(DeclarationExternalDeclaration.class)) { - if (outDeclarationMatcher.matchesSpecialized(declaration, prevType)) { - BuiltinNumericTypeSpecifier extractedType = outDeclarationMatcher.getNodeMatch("type", - BuiltinNumericTypeSpecifier.class); - for (DeclarationMember member : outDeclarationMatcher - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class) - .getMembers()) { - String name = member.getName().getName(); - if (!name.startsWith("gl_")) { - outDeclarations.put(name, extractedType); - } - } - } - } + if (currentTree == null) { + continue; + } - // add out declarations that are missing for in declarations - for (PatchShaderType currentType : patchTypes) { - TranslationUnit currentTree = trees.get(currentType); - if (currentTree == null) { - continue; - } - Root currentRoot = currentTree.getRoot(); + Map inDec = Util.findQualifiers(currentTree, GLSLLexer.IN); + for (String in : inDec.keySet()) { + if (in.startsWith("gl_")) { + continue; + } - for (ExternalDeclaration declaration : currentRoot.nodeIndex.get(DeclarationExternalDeclaration.class)) { - if (!inDeclarationMatcher.matchesSpecialized(declaration, currentType.glShaderType)) { - continue; - } + if (!outDec.containsKey(in)) { + if (!Util.containsCall(currentTree, in)) { + continue; + } - BuiltinNumericTypeSpecifier inTypeSpecifier = inDeclarationMatcher.getNodeMatch("type", - BuiltinNumericTypeSpecifier.class); - for (DeclarationMember inDeclarationMember : inDeclarationMatcher - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class) - .getMembers()) { - String name = inDeclarationMember.getName().getName(); - if (name.startsWith("gl_")) { - continue; - } + Util.makeOutDeclaration(prevTree, inDec.get(in), in); - // patch missing declarations with an initialization - if (!outDeclarations.containsKey(name)) { - // make sure the declared in is actually used - if (!currentRoot.identifierIndex.getAncestors(name, ReferenceExpression.class).findAny().isPresent()) { - continue; - } + if (!Util.hasAssigment(prevTree, in)) { + Util.initialize(prevTree, inDec.get(in), in); + } + } else { + ParseTree outType = outDec.get(in).fully_specified_type().type_specifier().type_specifier_nonarray().children.get(0); + ParseTree inType = inDec.get(in).fully_specified_type().type_specifier().type_specifier_nonarray().children.get(0); - if (inTypeSpecifier == null) { - LOGGER.warn( - "The in declaration '" + name + "' in the " + currentType.glShaderType.name() - + " shader that has a missing corresponding out declaration in the previous stage " - + prevType.name() + " has a non-numeric type and could not be compatibility-patched. See debugging.md for more information."); - continue; - } - Type inType = inTypeSpecifier.type; + if (outDec.get(in).fully_specified_type().type_specifier().array_specifier() != null) { + continue; + } - // insert the new out declaration but copy over the type qualifiers, except for - // the in/out qualifier - TypeQualifier outQualifier = (TypeQualifier) inDeclarationMatcher - .getNodeMatch("qualifier").cloneInto(prevRoot); - makeQualifierOut(outQualifier); - prevTree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, declarationTemplate.getInstanceFor(prevRoot, - outQualifier, - inTypeSpecifier.cloneInto(prevRoot), - new Identifier(name))); - - // add the initializer to the main function - prevTree.prependMain(getInitializer(prevRoot, name, inType)); - - // update out declarations to prevent duplicates - outDeclarations.put(name, null); - - LOGGER.warn( - "The in declaration '" + name + "' in the " + currentType.glShaderType.name() - + " shader is missing a corresponding out declaration in the previous stage " - + prevType.name() + " and has been compatibility-patched. See debugging.md for more information."); - } - - // patch mismatching declaration with a local variable and a cast - else { - // there is an out declaration for this in declaration, check if the types match - BuiltinNumericTypeSpecifier outTypeSpecifier = outDeclarations.get(name); - - // skip newly inserted out declarations - if (outTypeSpecifier == null) { - continue; - } - - Type inType = inTypeSpecifier.type; - Type outType = outTypeSpecifier.type; - - // skip if the type matches, nothing has to be done - if (inType == outType) { - // if the types match but it's never assigned a value, - // an initialization is added - if (prevRoot.identifierIndex.get(name).size() > 1) { - continue; - } - - // add an initialization statement for this declaration - prevTree.prependMain(getInitializer(prevRoot, name, inType)); - outDeclarations.put(name, null); - continue; - } - - // bail and warn on mismatching dimensionality - if (outType.getDimension() != inType.getDimension()) { - LOGGER.warn( - "The in declaration '" + name + "' in the " + currentType.glShaderType.name() - + " shader has a mismatching dimensionality (scalar/vector/matrix) with the out declaration in the previous stage " - + prevType.name() + " and could not be compatibility-patched. See debugging.md for more information."); - continue; - } - - boolean isVector = outType.isVector(); - - // rename all references of this out declaration to a new name (iris_) - String newName = tagPrefix + name; - prevRoot.identifierIndex.rename(name, newName); - - // rename the original out declaration back to the original name - TypeAndInitDeclaration outDeclaration = outTypeSpecifier.getAncestor(TypeAndInitDeclaration.class); - if (outDeclaration == null) { - continue; - } - - List outMembers = outDeclaration.getMembers(); - DeclarationMember outMember = null; - for (DeclarationMember member : outMembers) { - if (member.getName().getName().equals(newName)) { - outMember = member; - } - } - if (outMember == null) { - throw new IllegalStateException("The targeted out declaration member is missing!"); - } - outMember.getName().replaceByAndDelete(new Identifier(name)); - - // move the declaration member out of the declaration in case there is more than - // one member to avoid changing the other member's type as well. - if (outMembers.size() > 1) { - outMember.detach(); - outTypeSpecifier = outTypeSpecifier.cloneInto(prevRoot); - DeclarationExternalDeclaration singleOutDeclaration = (DeclarationExternalDeclaration) declarationTemplate - .getInstanceFor(prevRoot, - makeQualifierOut(outDeclaration.getType().getTypeQualifier().cloneInto(prevRoot)), - outTypeSpecifier, - new Identifier(name)); - ((TypeAndInitDeclaration) singleOutDeclaration.getDeclaration()).getMembers().set(0, outMember); - prevTree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, singleOutDeclaration); - } - - // add a global variable with the new name and the old type - prevTree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, variableTemplate.getInstanceFor(prevRoot, - outTypeSpecifier.cloneInto(prevRoot), - new Identifier(newName))); - - // insert a statement at the end of the main function that sets the value of the - // out declaration to the value of the global variable and does a type cast - prevTree.appendMain( - (isVector && outType.getDimensions()[0] < inType.getDimensions()[0] ? statementTemplateVector - : statementTemplate).getInstanceFor(prevRoot, - new Identifier(name), - new Identifier(newName), - inTypeSpecifier.cloneInto(prevRoot))); - - // make the out declaration use the same type as the fragment shader - outTypeSpecifier.replaceByAndDelete(inTypeSpecifier.cloneInto(prevRoot)); - - // don't do the patch twice - outDeclarations.put(name, null); - - LOGGER.warn( - "The out declaration '" + name + "' in the " + prevType.name() - + " shader has a different type " + outType.getMostCompactName() - + " than the corresponding in declaration of type " + inType.getMostCompactName() - + " in the following stage " + currentType.glShaderType.name() - + " and has been compatibility-patched. See debugging.md for more information."); - } - } - } - } - - prevType = type; - } - } + if (inType.getText().equals(outType.getText())) { + if (!Util.hasAssigment(prevTree, in)) { + Util.initialize(prevTree, inDec.get(in), in); + } + } + } + } + } + prevType = type; + } + } } 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 105a6ba35..e524bff0c 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeDepthTransformer.java @@ -1,30 +1,16 @@ package net.coderbot.iris.pipeline.transform; -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.basic.ASTNode; -import io.github.douira.glsl_transformer.ast.node.external_declaration.ExternalDeclaration; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.query.match.AutoHintedMatcher; -import io.github.douira.glsl_transformer.ast.query.match.Matcher; -import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; +import org.taumc.glsl.Util; +import org.taumc.glsl.grammar.GLSLParser; class CompositeDepthTransformer { - private static final AutoHintedMatcher uniformFloatCenterDepthSmooth = new AutoHintedMatcher<>( - "uniform float centerDepthSmooth;", Matcher.externalDeclarationPattern); - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root) { + public static void transform(GLSLParser.Translation_unitContext translationUnit) { // replace original declaration - if (root.processMatches(t, uniformFloatCenterDepthSmooth, ASTNode::detachAndDelete)) { - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform sampler2D iris_centerDepthSmooth;"); - - // if centerDepthSmooth is not declared as a uniform, we don't make it available - root.replaceReferenceExpressions(t, "centerDepthSmooth", - "texture2D(iris_centerDepthSmooth, vec2(0.5)).r"); - } + int type = Util.findType(translationUnit, "centerDepthSmooth"); + if (type != 0) { + Util.injectVariable(translationUnit, "uniform sampler2D iris_centerDepthSmooth;"); + Util.replaceExpression(translationUnit, "centerDepthSmooth", "texture2D(iris_centerDepthSmooth, vec2(0.5)).r"); + } } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeTransformer.java index e058d6c3a..09dcfe737 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/CompositeTransformer.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/CompositeTransformer.java @@ -1,30 +1,26 @@ package net.coderbot.iris.pipeline.transform; -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.expression.unary.FunctionCallExpression; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; - -import java.util.stream.Stream; +import org.taumc.glsl.grammar.GLSLParser; class CompositeTransformer { - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root) { - CompositeDepthTransformer.transform(t, tree, root); + public static void transform(GLSLParser.Translation_unitContext translationUnit, int version) { + CompositeDepthTransformer.transform(translationUnit); + + // TODO: how to do this using glsl-transformation-lib? + // Need to specifically find that these functions are called, not 100% sure how to do that + // Also, is it possible to inject something before declarations? + // Modern Iris doesn't seem to have this patch, so maybe it's just not even needed + // More likely it's just an OpenGL core thing that ensures it's present // if using a lod texture sampler and on version 120, patch in the extension // #extension GL_ARB_shader_texture_lod : require - if (tree.getVersionStatement().version.number <= 120 - && Stream.concat( - root.identifierIndex.getStream("texture2DLod"), - root.identifierIndex.getStream("texture3DLod")) - .filter(id -> id.getParent() instanceof FunctionCallExpression) - .findAny().isPresent()) { - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "#extension GL_ARB_shader_texture_lod : require\n"); - } +// if (version <= 120 +// && Stream.concat( +// root.identifierIndex.getStream("texture2DLod"), +// root.identifierIndex.getStream("texture3DLod")) +// .filter(id -> id.getParent() instanceof FunctionCallExpression) +// .findAny().isPresent()) { +// tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, +// "#extension GL_ARB_shader_texture_lod : require\n") } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/Parameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/Parameters.java deleted file mode 100644 index 47d5b2521..000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/Parameters.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.coderbot.iris.pipeline.transform; - -import io.github.douira.glsl_transformer.job_parameter.JobParameters; - -class Parameters extends JobParameters { - public final Patch patch; - public PatchShaderType type; - - public Parameters(Patch patch) { - this.patch = patch; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((patch == null) ? 0 : patch.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Parameters other = (Parameters) obj; - if (patch != other.patch) - return false; - if (type != other.type) - return false; - return true; - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java b/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java index 83332bba5..285345aa3 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java @@ -1,6 +1,6 @@ package net.coderbot.iris.pipeline.transform; -enum Patch { +public enum Patch { ATTRIBUTES, SODIUM_TERRAIN, COMPOSITE diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java new file mode 100644 index 000000000..7e7f0f988 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/ShaderTransformer.java @@ -0,0 +1,271 @@ +package net.coderbot.iris.pipeline.transform; + +import com.google.common.base.Stopwatch; +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.BufferedTokenStream; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.taumc.glsl.Util; +import org.taumc.glsl.grammar.GLSLLexer; +import org.taumc.glsl.grammar.GLSLParser; +import org.taumc.glsl.grammar.GLSLPreParser; + +import java.util.AbstractMap; +import java.util.EnumMap; +import java.util.Map; +import java.util.Objects; + +public class ShaderTransformer { + static String tab = ""; + + private static final int CACHE_SIZE = 100; + private static final Object2ObjectLinkedOpenHashMap> shaderTransformationCache = new Object2ObjectLinkedOpenHashMap<>(); + private static final boolean useCache = true; + + private static final class TransformKey

{ + private final Patch patchType; + private final EnumMap inputs; + private final P params; + + private TransformKey(Patch patchType, EnumMap inputs, P params) { + this.patchType = patchType; + this.inputs = inputs; + this.params = params; + } + + public Patch patchType() { + return patchType; + } + + public EnumMap inputs() { + return inputs; + } + + public P params() { + return params; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (TransformKey) obj; + return Objects.equals(this.patchType, that.patchType) && + Objects.equals(this.inputs, that.inputs) && + Objects.equals(this.params, that.params); + } + + @Override + public int hashCode() { + return Objects.hash(patchType, inputs, params); + } + + @Override + public String toString() { + return "TransformKey[" + + "patchType=" + patchType + ", " + + "inputs=" + inputs + ", " + + "params=" + params + ']'; + } + } + + public static

Map transform(String vertex, String geometry, String fragment, P parameters) { + if (vertex == null && geometry == null && fragment == null) { + return null; + } else { + Map result; + + var patchType = parameters.patch; + + EnumMap inputs = new EnumMap<>(PatchShaderType.class); + inputs.put(PatchShaderType.VERTEX, vertex); + inputs.put(PatchShaderType.GEOMETRY, geometry); + inputs.put(PatchShaderType.FRAGMENT, fragment); + + var key = new TransformKey(patchType, inputs, parameters); + + result = shaderTransformationCache.getAndMoveToFirst(key); + if(result == null || !useCache) { + result = transformInternal(inputs, patchType, parameters); + // Clear this, we don't want whatever random type was last transformed being considered for the key + parameters.type = null; + if(shaderTransformationCache.size() >= CACHE_SIZE) { + shaderTransformationCache.removeLast(); + } + shaderTransformationCache.putAndMoveToLast(key, result); + } + + return result; + } + } + + private static

Map transformInternal(EnumMap inputs, Patch patchType, P parameters) { + EnumMap result = new EnumMap<>(PatchShaderType.class); + EnumMap types = new EnumMap<>(PatchShaderType.class); + EnumMap prepatched = new EnumMap<>(PatchShaderType.class); + + Stopwatch watch = Stopwatch.createStarted(); + + for (PatchShaderType type : PatchShaderType.values()) { + parameters.type = type; + if (inputs.get(type) == null) { + continue; + } + GLSLLexer lexer = new GLSLLexer(CharStreams.fromString(inputs.get(type))); + GLSLPreParser preParser = new GLSLPreParser(new BufferedTokenStream(lexer)); + GLSLParser parser = new GLSLParser(new CommonTokenStream(lexer)); + parser.setBuildParseTree(true); + var pre = preParser.translation_unit(); + var translationUnit = parser.translation_unit(); + var preparsed = pre.compiler_directive(); + String profile = ""; + String versionString = "0"; + GLSLPreParser.Compiler_directiveContext version = null; + for (var entry: preparsed) { + if (entry.version_directive() != null) { + version = entry; + if (entry.version_directive().number() != null) { + versionString = entry.version_directive().number().getText(); + } + if (entry.version_directive().profile() != null) { + profile = entry.version_directive().profile().getText(); + } + } + } + pre.children.remove(version); + if (versionString == null) { + continue; + } + + String profileString = "#version " + versionString + " " + profile; + int versionInt = Integer.parseInt(versionString); + + switch(patchType) { + case SODIUM_TERRAIN: + SodiumTransformer.transform(translationUnit, parameters); + break; + case COMPOSITE: + CompositeTransformer.transform(translationUnit, versionInt); + break; + case ATTRIBUTES: + AttributeTransformer.transform(translationUnit, (AttributeParameters) parameters, profile, versionInt); + break; + default: + throw new IllegalStateException("Unknown patch type: " + patchType.name()); + } + CompatibilityTransformer.transformEach(translationUnit, parameters); + types.put(type, translationUnit); + prepatched.put(type, getFormattedShader((ParseTree) pre, profileString)); + } + CompatibilityTransformer.transformGrouped(types, parameters); + for (var entry : types.entrySet()) { + result.put(entry.getKey(), getFormattedShader(entry.getValue(), prepatched.get(entry.getKey()))); + } + watch.stop(); + Iris.logger.info("Transformed shader for {} in {}", patchType.name(), watch); + return result; + } + + public static void applyIntelHd4000Workaround(GLSLParser.Translation_unitContext translationUnit) { + Util.renameFunctionCall(translationUnit, "ftransform", "iris_ftransform"); + } + + + public static void replaceGlMultiTexCoordBounded(GLSLParser.Translation_unitContext translationUnit, int min, int max) { + for (int i = min; i <= max; i++) { + Util.replaceExpression(translationUnit, "gl_MultiTexCoord" + i, "vec4(0.0, 0.0, 0.0, 1.0)"); + } + } + + public static void patchMultiTexCoord3(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + if (parameters.type.glShaderType == ShaderType.VERTEX && Util.hasVariable(translationUnit, "gl_MultiTexCoord3") && !Util.hasVariable(translationUnit, "mc_midTexCoord")) { + Util.rename(translationUnit, "gl_MultiTexCoord3", "mc_midTexCoord"); + Util.injectVariable(translationUnit, "attribute vec4 mc_midTexCoord;"); + } + } + + public static void replaceMidTexCoord(GLSLParser.Translation_unitContext translationUnit, float textureScale) { + int type = Util.findType(translationUnit, "mc_midTexCoord"); + if (type != 0) { + Util.removeVariable(translationUnit, "mc_midTexCoord"); + } + Util.replaceExpression(translationUnit, "mc_midTexCoord", "iris_MidTex"); + switch (type) { + case 0: + return; + case GLSLLexer.BOOL: + return; + case GLSLLexer.FLOAT: + Util.injectFunction(translationUnit, "float iris_MidTex = (mc_midTexCoord.x * " + textureScale + ").x;"); //TODO go back to variable if order is fixed + break; + case GLSLLexer.VEC2: + Util.injectFunction(translationUnit, "vec2 iris_MidTex = (mc_midTexCoord.xy * " + textureScale + ").xy;"); + break; + case GLSLLexer.VEC3: + Util.injectFunction(translationUnit, "vec3 iris_MidTex = vec3(mc_midTexCoord.xy * " + textureScale + ", 0.0);"); + break; + case GLSLLexer.VEC4: + Util.injectFunction(translationUnit, "vec4 iris_MidTex = vec4(mc_midTexCoord.xy * " + textureScale + ", 0.0, 1.0);"); + break; + default: + + } + + Util.injectVariable(translationUnit, "in vec2 mc_midTexCoord;"); //TODO why is this inserted oddly? + + } + + public static void addIfNotExists(GLSLParser.Translation_unitContext translationUnit, String name, String code) { + if (!Util.hasVariable(translationUnit, name)) { + Util.injectVariable(translationUnit, code); + } + } + + public static void addIfNotExistsType(GLSLParser.Translation_unitContext translationUnit, String name, String type) { + if (!Util.hasVariable(translationUnit, name)) { + Util.injectVariable(translationUnit, type + " " + name + ";"); + } + } + + public static String getFormattedShader(ParseTree tree, String string) { + StringBuilder sb = new StringBuilder(string + "\n"); + getFormattedShader(tree, sb); + return sb.toString(); + } + + private static void getFormattedShader(ParseTree tree, StringBuilder stringBuilder) { + if (tree instanceof TerminalNode) { + 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"); + tab = "\t"; + } + + if (text.equals("}")) { + stringBuilder.deleteCharAt(stringBuilder.length() - 2); + tab = ""; + } + stringBuilder.append(text.equals(";") ? " \n" + tab : " "); + } else { + for(int i = 0; i < tree.getChildCount(); ++i) { + getFormattedShader(tree.getChild(i), stringBuilder); + } + } + + } + +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTerrainTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTerrainTransformer.java deleted file mode 100644 index 81473b844..000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTerrainTransformer.java +++ /dev/null @@ -1,112 +0,0 @@ -package net.coderbot.iris.pipeline.transform; - -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.expression.Expression; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.query.match.AutoHintedMatcher; -import io.github.douira.glsl_transformer.ast.query.match.Matcher; -import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; - -/** - * Does the sodium terrain transformations using glsl-transformer AST. - */ -class SodiumTerrainTransformer { - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { - switch (parameters.type) { - // For Sodium patching, treat fragment and geometry the same - case FRAGMENT: - case GEOMETRY: - transformFragment(t, tree, root, parameters); - break; - case VERTEX: - transformVertex(t, tree, root, parameters); - break; - default: - throw new IllegalStateException("Unexpected Sodium terrain patching shader type: " + parameters.type); - } - } - - private static final AutoHintedMatcher glTextureMatrix0 = new AutoHintedMatcher<>( - "gl_TextureMatrix[0]", Matcher.expressionPattern); - - /** - * Transforms vertex shaders. - */ - public static void transformVertex( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { - tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "attribute vec3 iris_Pos;", - "attribute vec4 iris_Color;", - "attribute vec2 iris_TexCoord;", - "attribute vec2 iris_LightCoord;", - "attribute vec3 iris_Normal;", // some are shared - "uniform vec3 u_ModelScale;", - "uniform vec2 u_TextureScale;", - "attribute vec4 iris_ModelOffset;", - "vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);", - "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); - - transformShared(t, tree, root, parameters); - - root.replaceReferenceExpressions(t, "gl_Vertex", - "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)"); - root.replaceReferenceExpressions(t, "gl_MultiTexCoord0", - "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)"); - root.replaceReferenceExpressions(t, "gl_MultiTexCoord1", - "iris_LightTexCoord"); - root.replaceReferenceExpressions(t, "gl_MultiTexCoord2", - "iris_LightTexCoord"); - root.rename("gl_Color", "iris_Color"); - root.rename("gl_Normal", "iris_Normal"); - root.rename("ftransform", "iris_ftransform"); - } - - /** - * Transforms fragment shaders. The fragment shader does only the shared things - * from the vertex shader. - */ - public static void transformFragment( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { - // interestingly there is nothing that isn't shared - transformShared(t, tree, root, parameters); - } - - /** - * Does the things that transformVertex and transformFragment have in common. - */ - private static void transformShared( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { - tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform mat4 iris_ModelViewMatrix;", - "uniform mat4 u_ModelViewProjectionMatrix;", - "uniform mat4 iris_NormalMatrix;", - "uniform mat4 iris_LightmapTextureMatrix;"); - root.rename("gl_ModelViewMatrix", "iris_ModelViewMatrix"); - root.rename("gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix"); - root.replaceReferenceExpressions(t, - "gl_NormalMatrix", "mat3(iris_NormalMatrix)"); - - root.replaceExpressionMatches( - t, - glTextureMatrix0, - "mat4(1.0)"); - root.replaceExpressionMatches(t, glTextureMatrix1, "iris_LightmapTextureMatrix"); - } - private static final String lightmapCoordsExpression = "iris_LightCoord"; - private static final AutoHintedMatcher glTextureMatrix1 = new AutoHintedMatcher<>( - "gl_TextureMatrix[1]", Matcher.expressionPattern); -} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java new file mode 100644 index 000000000..2fbaa6f5d --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/SodiumTransformer.java @@ -0,0 +1,75 @@ +package net.coderbot.iris.pipeline.transform; + +import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import org.taumc.glsl.Util; +import org.taumc.glsl.grammar.GLSLParser; + +class SodiumTransformer { + public static void transform(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + switch (parameters.type) { + // For Sodium patching, treat fragment and geometry the same + case FRAGMENT: + case GEOMETRY: + transformFragment(translationUnit, parameters); + break; + case VERTEX: + transformVertex(translationUnit, parameters); + break; + default: + throw new IllegalStateException("Unexpected Sodium terrain patching shader type: " + parameters.type); + } + } + + /** + * Transforms vertex shaders. + */ + public static void transformVertex(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + + Util.injectVariable(translationUnit, "attribute vec3 iris_Pos;"); + Util.injectVariable(translationUnit, "attribute vec4 iris_Color;"); + Util.injectVariable(translationUnit, "attribute vec2 iris_TexCoord;"); + Util.injectVariable(translationUnit, "attribute vec2 iris_LightCoord;"); + Util.injectVariable(translationUnit, "attribute vec3 iris_Normal;"); + Util.injectVariable(translationUnit, "uniform vec3 u_ModelScale;"); + Util.injectVariable(translationUnit, "uniform vec2 u_TextureScale;"); + Util.injectVariable(translationUnit, "attribute vec4 iris_ModelOffset;"); + Util.injectFunction(translationUnit, "vec4 iris_LightTexCoord = vec4(iris_LightCoord, 0, 1);"); + Util.injectFunction(translationUnit, "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); + + transformShared(translationUnit, parameters); + + Util.replaceExpression(translationUnit, "gl_Vertex", "vec4((iris_Pos * u_ModelScale) + iris_ModelOffset.xyz, 1.0)"); + Util.replaceExpression(translationUnit, "gl_MultiTexCoord0", "vec4(iris_TexCoord * u_TextureScale, 0.0, 1.0)"); + Util.replaceExpression(translationUnit, "gl_MultiTexCoord1", "iris_LightTexCoord"); + Util.replaceExpression(translationUnit, "gl_MultiTexCoord2", "iris_LightTexCoord"); + Util.rename(translationUnit, "gl_Color", "iris_Color"); + Util.rename(translationUnit, "gl_Normal", "iris_Normal"); + Util.rename(translationUnit, "ftransform", "iris_ftransform"); + } + + /** + * Transforms fragment shaders. The fragment shader does only the shared things + * from the vertex shader. + */ + public static void transformFragment(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + // interestingly there is nothing that isn't shared + transformShared(translationUnit, parameters); + } + + /** + * Does the things that transformVertex and transformFragment have in common. + */ + private static void transformShared(GLSLParser.Translation_unitContext translationUnit, Parameters parameters) { + Util.injectVariable(translationUnit, "uniform mat4 iris_ModelViewMatrix;"); + Util.injectVariable(translationUnit, "uniform mat4 u_ModelViewProjectionMatrix;"); + Util.injectVariable(translationUnit, "uniform mat4 iris_NormalMatrix;"); + Util.injectVariable(translationUnit, "uniform mat4 iris_LightmapTextureMatrix;"); + + Util.rename(translationUnit, "gl_ModelViewMatrix", "iris_ModelViewMatrix"); + Util.rename(translationUnit, "gl_ModelViewProjectionMatrix", "u_ModelViewProjectionMatrix"); + Util.replaceExpression(translationUnit, "gl_NormalMatrix", "mat3(iris_NormalMatrix)"); + + Util.replaceExpression(translationUnit, "gl_TextureMatrix[0]", "mat4(1.0)"); + Util.replaceExpression(translationUnit, "gl_TextureMatrix[1]", "iris_LightmapTextureMatrix"); + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java index d9371668d..21ffacc30 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -1,226 +1,115 @@ package net.coderbot.iris.pipeline.transform; -import io.github.douira.glsl_transformer.ast.node.Identifier; -import io.github.douira.glsl_transformer.ast.node.TranslationUnit; -import io.github.douira.glsl_transformer.ast.node.Version; -import io.github.douira.glsl_transformer.ast.print.PrintType; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.transform.EnumASTTransformer; -import io.github.douira.glsl_transformer.cst.core.SemanticException; -import io.github.douira.glsl_transformer.cst.token_filter.ChannelFilter; -import io.github.douira.glsl_transformer.cst.token_filter.TokenChannel; -import io.github.douira.glsl_transformer.cst.token_filter.TokenFilter; -import io.github.douira.glsl_transformer.util.LRUCache; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.pipeline.PatchedShaderPrinter; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Token; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; +import net.coderbot.iris.pipeline.transform.parameter.Parameters; -import java.util.EnumMap; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Optional; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -/** - * The transform patcher (triforce 2) uses glsl-transformer's ASTTransformer to - * do shader transformation. - * - * The TransformPatcher does caching on the source string and associated - * parameters. For this to work, all objects contained in a parameter must have - * an equals method and they must never be changed after having been used for - * patching. Since the cache also contains the source string, it doesn't need to - * be disabled when developing shaderpacks. However, when changes are made to - * the patcher, the cache should be disabled with {@link #useCache}. - * - * NOTE: This patcher expects (and ensures) that the string doesn't contain any - * (!) preprocessor directives. The only allowed ones are #extension and #pragma - * as they are considered "parsed" directives. If any other directive appears in - * the string, it will throw. - */ public class TransformPatcher { - static Logger LOGGER = LogManager.getLogger(TransformPatcher.class); - private static EnumASTTransformer transformer; - private static final boolean useCache = true; - private static final Map> cache = new LRUCache<>(400); - private static class CacheKey { - final Parameters parameters; - final String vertex; - final String geometry; - final String fragment; + private static final int MAX_CACHE_ENTRIES = 400; + private static final Map> cache = new LinkedHashMap<>(MAX_CACHE_ENTRIES + 1, .75F, true) { + public boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_CACHE_ENTRIES; + } + }; - public CacheKey(Parameters parameters, String vertex, String geometry, String fragment) { - this.parameters = parameters; - this.vertex = vertex; - this.geometry = geometry; - this.fragment = fragment; - } + private static final boolean useCache = true; - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fragment == null) ? 0 : fragment.hashCode()); - result = prime * result + ((geometry == null) ? 0 : geometry.hashCode()); - result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); - result = prime * result + ((vertex == null) ? 0 : vertex.hashCode()); - return result; - } + private static class CacheKey { + final Parameters parameters; + final String vertex; + final String geometry; + final String fragment; - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CacheKey other = (CacheKey) obj; - if (fragment == null) { - if (other.fragment != null) - return false; - } else if (!fragment.equals(other.fragment)) - return false; - if (geometry == null) { - if (other.geometry != null) - return false; - } else if (!geometry.equals(other.geometry)) - return false; - if (parameters == null) { - if (other.parameters != null) - return false; - } else if (!parameters.equals(other.parameters)) - return false; - if (vertex == null) { - if (other.vertex != null) - return false; - } else if (!vertex.equals(other.vertex)) - return false; - return true; - } - } + public CacheKey(Parameters parameters, String vertex, String geometry, String fragment) { + this.parameters = parameters; + this.vertex = vertex; + this.geometry = geometry; + this.fragment = fragment; + } - // TODO: Only do the NewLines patches if the source code isn't from - // gbuffers_lines (what does this mean?) + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fragment == null) ? 0 : fragment.hashCode()); + result = prime * result + ((geometry == null) ? 0 : geometry.hashCode()); + result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); + result = prime * result + ((vertex == null) ? 0 : vertex.hashCode()); + return result; + } - static TokenFilter parseTokenFilter = new ChannelFilter(TokenChannel.PREPROCESSOR) { - @Override - public boolean isTokenAllowed(Token token) { - if (!super.isTokenAllowed(token)) { - throw new SemanticException("Unparsed preprocessor directives such as '" + token.getText() - + "' may not be present at this stage of shader processing!"); - } - return true; - } - }; + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TransformPatcher.CacheKey other = (TransformPatcher.CacheKey) obj; + if (fragment == null) { + if (other.fragment != null) + return false; + } else if (!fragment.equals(other.fragment)) + return false; + if (geometry == null) { + if (other.geometry != null) + return false; + } else if (!geometry.equals(other.geometry)) + return false; + if (parameters == null) { + if (other.parameters != null) + return false; + } else if (!parameters.equals(other.parameters)) + return false; + if (vertex == null) { + if (other.vertex != null) + return false; + } else if (!vertex.equals(other.vertex)) + return false; + return true; + } + } - static { - transformer = new EnumASTTransformer(PatchShaderType.class) { - @Override - public TranslationUnit parseTranslationUnit(String input) throws RecognitionException { - // parse #version directive using an efficient regex before parsing so that the - // parser can be set to the correct version - Matcher matcher = versionPattern.matcher(input); - if (!matcher.find()) { - throw new IllegalArgumentException("No #version directive found in source code! See debugging.md for more information."); - } - Version version = Version.fromNumber(Integer.parseInt(matcher.group(1))); - transformer.getLexer().version = version; + private static Map transform(String vertex, String geometry, String fragment, Parameters parameters) { + if (vertex == null && geometry == null && fragment == null) { + return null; + } - return super.parseTranslationUnit(input); - } - }; - transformer.setTransformation((trees, parameters) -> { - for (PatchShaderType type : PatchShaderType.values()) { - TranslationUnit tree = trees.get(type); - if (tree == null) { - continue; - } - // @Asek3 I have old GLSL-Transformer on JRE8, so I will off this - //tree.outputOptions.enablePrintInfo(); + // check if this has been cached + TransformPatcher.CacheKey key; + Map result = null; + if (useCache) { + key = new TransformPatcher.CacheKey(parameters, vertex, geometry, fragment); + if (cache.containsKey(key)) { + result = cache.get(key); + } + } - parameters.type = type; - Root root = tree.getRoot(); + // if there is no cache result, transform the shaders + if (result == null) { + result = ShaderTransformer.transform(vertex, geometry, fragment, parameters); + if (useCache) { + cache.put(key, result); + } + } - // check for illegal references to internal Iris shader interfaces - Optional violation = root.identifierIndex.prefixQueryFlat("iris_").findAny(); - if (!violation.isPresent()) { - violation = root.identifierIndex.prefixQueryFlat("irisMain").findAny(); - } - violation.ifPresent(id -> { - throw new SemanticException( - "Detected a potential reference to unstable and internal Iris shader interfaces (iris_ and irisMain). This isn't currently supported. Violation: " - + id.getName() + ". See debugging.md for more information."); - }); + return result; + } - Root.indexBuildSession(tree, () -> { - switch (parameters.patch) { - case ATTRIBUTES: - AttributeTransformer.transform(transformer, tree, root, (AttributeParameters) parameters); - break; - case SODIUM_TERRAIN: - SodiumTerrainTransformer.transform(transformer, tree, root, parameters); - break; - case COMPOSITE: - CompositeTransformer.transform(transformer, tree, root); - break; - } - CompatibilityTransformer.transformEach(transformer, tree, root, parameters); - }); - } + public static Map patchAttributes(String vertex, String geometry, String fragment, InputAvailability inputs) { + return transform(vertex, geometry, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs)); + } - // the compatibility transformer does a grouped transformation - CompatibilityTransformer.transformGrouped(transformer, trees, parameters); - }); - transformer.setParseTokenFilter(parseTokenFilter); - } + public static Map patchSodiumTerrain(String vertex, String geometry, String fragment) { + return transform(vertex, geometry, fragment, new Parameters(Patch.SODIUM_TERRAIN)); + } - private static final Pattern versionPattern = Pattern.compile("^.*#version\\s+(\\d+)", Pattern.DOTALL); - - private static Map transform(String vertex, String geometry, String fragment, Parameters parameters) { - // stop if all are null - if (vertex == null && geometry == null && fragment == null) { - return null; - } - - // check if this has been cached - CacheKey key; - Map result = null; - if (useCache) { - key = new CacheKey(parameters, vertex, geometry, fragment); - if (cache.containsKey(key)) { - result = cache.get(key); - } - } - - // if there is no cache result, transform the shaders - if (result == null) { - transformer.setPrintType(PatchedShaderPrinter.prettyPrintShaders ? PrintType.INDENTED : PrintType.SIMPLE); - EnumMap inputs = new EnumMap<>(PatchShaderType.class); - inputs.put(PatchShaderType.VERTEX, vertex); - inputs.put(PatchShaderType.GEOMETRY, geometry); - inputs.put(PatchShaderType.FRAGMENT, fragment); - result = transformer.transform(inputs, parameters); - if (useCache) { - cache.put(key, result); - } - } - - return result; - } - - public static Map patchAttributes(String vertex, String geometry, String fragment, InputAvailability inputs) { - return transform(vertex, geometry, fragment, new AttributeParameters(Patch.ATTRIBUTES, geometry != null, inputs)); - } - - public static Map patchSodiumTerrain(String vertex, String geometry, String fragment) { - return transform(vertex, geometry, fragment, new Parameters(Patch.SODIUM_TERRAIN)); - } - - public static Map patchComposite(String vertex, String geometry, String fragment) { - return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE)); - } + public static Map patchComposite(String vertex, String geometry, String fragment) { + return transform(vertex, geometry, fragment, new Parameters(Patch.COMPOSITE)); + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java new file mode 100644 index 000000000..ff4f6a5f4 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java @@ -0,0 +1,43 @@ +package net.coderbot.iris.pipeline.transform.parameter; + +import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; +import net.coderbot.iris.pipeline.transform.Patch; + +public class AttributeParameters extends Parameters { + public final boolean hasGeometry; + public final InputAvailability inputs; + + public AttributeParameters(Patch patch, boolean hasGeometry, InputAvailability inputs) { + super(patch); + this.hasGeometry = hasGeometry; + this.inputs = inputs; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (hasGeometry ? 1231 : 1237); + result = prime * result + ((inputs == null) ? 0 : inputs.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + AttributeParameters other = (AttributeParameters) obj; + if (hasGeometry != other.hasGeometry) + return false; + if (inputs == null) { + if (other.inputs != null) + return false; + } else if (!inputs.equals(other.inputs)) + return false; + return true; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/JobParameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/JobParameters.java new file mode 100644 index 000000000..1aeb5c670 --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/JobParameters.java @@ -0,0 +1,20 @@ +package net.coderbot.iris.pipeline.transform.parameter; + +public interface JobParameters { + + JobParameters EMPTY = new JobParameters() { + @Override + public boolean equals(Object other) { + return other == this; + } + + @Override + public int hashCode() { + return 0; + } + }; + + boolean equals(Object other); + + int hashCode(); +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java new file mode 100644 index 000000000..cc5e2507c --- /dev/null +++ b/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java @@ -0,0 +1,37 @@ +package net.coderbot.iris.pipeline.transform.parameter; + +import net.coderbot.iris.pipeline.transform.Patch; +import net.coderbot.iris.pipeline.transform.PatchShaderType; + +public class Parameters implements JobParameters { + public final Patch patch; + public PatchShaderType type; // may only be set by TransformPatcher + // WARNING: adding new fields requires updating hashCode and equals methods! + + // name of the shader, this should not be part of hash/equals + public String name; // set by TransformPatcher + + public Parameters(Patch patch) { + this.patch = patch; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((patch == null) ? 0 : patch.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Parameters other = (Parameters) obj; + return patch == other.patch; + } +}