diff --git a/DHApi.jar b/DHApi.jar new file mode 100644 index 0000000000..56752d5b31 Binary files /dev/null and b/DHApi.jar differ diff --git a/docs/changelogs/1.7.0/full.md b/docs/changelogs/1.7.0/full.md new file mode 100644 index 0000000000..161882190a --- /dev/null +++ b/docs/changelogs/1.7.0/full.md @@ -0,0 +1,31 @@ +# Iris 1.7.0 Changelog + +## New Features + +- Added Tessellation shaders. These new shader types allow you to subdivide and add more detail to geometry. + - These take the form of `.tcs` and `.tes` shaders respectively for control and evaluation. See the Khronos wiki for + details. +- Added an attribute that allows you to see the emission value of a block. It is stored in `at_midBlock.w` and ranges + from 0-15. +- Added `cameraPositionInt` and `cameraPositionFract` for better precision, along with their respective previous + uniforms. *These values are unshifted, unlike the normal ones.* +- Added `occlusion.culling` option. +- Added support for Distant Horizons 2.0.3. This version is not officially released yet. +- Added debug groups. This groups together information in RenderDoc for easy viewing. +- Added support for Indirect Compute shaders. This allows you to dispatch a compute shader with the work group amount + specified from a SSBO. + - To use this, you must use `indirect.pass = bufferObjectNumber offsetInBuffer` in shaders.properties, and the + object at offset in the + SSBO must be an `uvec3`. + - ***If you do not do this, your PC will most likely crash trying to dispatch 2147483647^3 work groups. Don't do + that.*** +- Added a keybind to see a wireframe view of the world. This is only usable in singleplayer. +- Added some uniforms, mostly `isRightHanded`. + +## Technical Changes + +- Relocated Iris from `net.coderbot` to `net.irisshaders` + - This will break any mods depending on Iris 1.6.17 and below. +- Added whitespace detection code to property files. + - This fixes SEUS PTGI GFME. +- Redesigned the pipeline layout. diff --git a/docs/usage/debugging.md b/docs/usage/debugging.md new file mode 100644 index 0000000000..5bf13f4912 --- /dev/null +++ b/docs/usage/debugging.md @@ -0,0 +1,72 @@ +# Debugging Shader Packs With Iris + +Iris has some built-in functionality that can assist you in developing a shader pack for Iris. This page will give some context and explain how to use these features. + +## Shader Code Transformation + +Iris uses [glsl-transformer](https://github.com/IrisShaders/glsl-transformer) to apply various patches to the GLSL code of a shader pack before sending it to the driver for compilation. There are generally two types of patches being applied; those necessary for compatibility with Iris, and compatibility patches that are done to make sure the shader pack works on as many systems as possible. For reference, the compatibility patches can be found in [`CompatibilityTransformer`](/src/main/java/net/irisshaders/iris/pipeline/transform/CompatibilityTransformer.java) while the other patches are grouped into the other files. + +Some terms: + +- **Translation Unit**: The GLSL code in a single file +- **External Declaration**: Anything at the top level of a translation unit, like a declaration or a function definition +- **Statement**: A single line of code in a function +- **Declaration** (Statement): The declaration of something in a function scope +- **Expression**: Code that evaluates to a value + +### Effects of Shader Code Transformation + +Roughly, glsl-transformer parses the GLSL code into an internal representation called an AST, applies the patches, and then prints the code back into a string. For better performance, the result of the patches is cached on multiple levels throughout the system. This results in faster loading times for shader packs that have already been loaded before or that have only been changed slightly. + +Since the internal representation omits formatting, comments, whitespace and preprocessor directives (not including extensions and the version marker of course), none of these are preserved when printing the code back into a string. Because of this, the code that is printed back out is not necessarily the same as the code that was originally provided. This can make debugging shader packs a bit more difficult, since the line numbers in the error messages will not match up with the line numbers in the source code. A feature called line annotation is being worked on in glsl-transformer that aims to fix this issue by inserting `#line` directives into the code. In the interim, enabling the printing of the patched code provides a workaround for this issue (See [Pretty Printing](#pretty-printing)). Additionally, non-essential whitespace is omitted from the output for better performance, this can also be enabled by the user if required. + +- The version statement is required. See [Version Statement](#version-statement) for more information. +- It is forbidden to use Iris internals, namely variables and functions prefixed with `iris_`, `irisMain` or `moj_import`. An exception will be thrown if these are encountered in the source code. + +### Compatibility Patches + +Since Iris aims to be compatible with many shader packs, hardware configurations and software environments, it is necessary to apply some compatibility patches to the shader packs to ensure wide compatibility. All known graphics drivers have some bugs or quirks that can cause issues with shader packs, and Iris aims to work around these issues where it is feasible. + +The goal is to present a maximally uniform interface to the shader pack by smoothing out the differences between the drivers. Since many existing shader packs have been developed for Nvidia drivers and hardware, they sometimes rely on Nvidia-specific quirks. Furthermore, in some situations drivers may be more stringent by either adhering to the GLSL specification more closely or through their own limitations. Of course there are also bugs in the drivers that may need to be worked around. Some of these issues can be fixed by adding or removing specific pieces of code if necessary. + +Naturally, shader packs that are currently in development could simply be fixed by their maintainers, but not all shader packs are still actively developed even if they have a significant following. Some shader packs don't test on certain systems which can also create incompatibilities that are often fixable through patching. **The compatibility patches are only applied if problematic pieces of code are detected, and they always print a warning message to the log prefixed with `(CompatibilityTransformer)` each time they do something**. + +The following is a list of the compatibility patches that are applied to shader packs. Additional information on the specifics of each patch can be found in the [source code](/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompatibilityTransformer.java). + +- Empty external declarations, which are just a single semicolon at the global level `;`, are removed. This is a workaround for a bug where they are not recognized as legal external declarations by some drivers. A semicolon following a function definition like `void main() {};` is in fact not part of the function definition but its own external declaration, namely an empty one. +- The `const` keyword is removed from declaration (statements) that refer to `const` parameters in their initializer expression, the part that comes after the `=`. Parameters with the `const` qualifier are not constant but rather immutable, meaning they may not be assigned to. Declarations with `const` are, depending on the driver and GLSL version, treated as constant meaning they only accept expressions that can be evaluated at compile time. Immutable parameters don't fulfill this requirement and thus cause a compilation error when they are used in the initializer of a constant. This is done to ensure better compatibility drivers' varying behavior at different versions. See Section 4.3.2 on Constant Qualifiers and Section 4.3.3 on Constant Expressions in the GLSL 4.1 and 4.2 specifications for more information. Additionally, see https://wiki.shaderlabs.org/wiki/Compiler_Behavior_Notes for the varying behavior of drivers. +- When an input variable, declared with `in`, is declared and used in a geometry or fragment shader, but there is no corresponding output variable in the shader of the previous stage, some drivers will error. To mitigate this, the missing declaration is inserted and initialized with a default value at the top of the `main` function. +- If the out declaration does exist but is never assigned to, an initialization is created. If the out declaration has an array type, compatibility patching is skipped for it and a warning is produced. +- When the types of declared and used input and output variables don't match, some drivers will error. To mitigate this, the type of the declaration is changed to match the type in the later stage (the fragment shader). An internal variable with the original type is added so that the code can assign a value to it. At the end of the `main` function this value is either truncated or padded to patch the expected type. +- Unused functions are removed. Some drivers don't do certain semantic checks on unused functions which may result in errors when the code is then compiled with stricter drivers that do perform these checks before unused code removal. This heuristic is not perfect and may fail to remove unreachable functions that are used in another unreachable function. +- In struct bodies (of the form `{ }`) unsized array specifiers are moved from the type to the identifier of the member. A member `int[] foo` is transformed into `int foo[]`. This is done because the specification only requires support for the latter form while the former is unsupported by some drivers. + +### Version Statement + +The version statement `#version ` where the number is required, but the profile is optionally one of `core` or `compatibility` is patched on versions starting with 1.17. For reference, the relevant code can be found in [`TransformPatcher`](/src/main/java/net/irisshaders/iris/pipeline/transform/TransformPatcher.java) in the section afer `Root.indexBuildSession`. If the core profile is used or the profile is missing, and the version is at least 150, then only compatibility patches are applied, as long as the shader is not a vertex shader. On vertex shaders an exception is thrown in this case. They are required to either use a version lower than 330, which is then changed to be exactly 330, or declare the compatibility profile, which is then changed to the core profile. + +The profile of compute shaders is always set to core. + +## Debug Mode + +The debug mode can be activated by pressing CTRL + D or Command + D on macOS on the shader selection screen or by setting the option `enableDebugOptions=true` in Iris' settings file. With this mode enabled a number of debug features are activated. + +- Pretty printing: The patched shader pack code is saved to the `patched_shaders` folder that is created game instance folder. Any previous files in this folder will be deleted. The files are named based on the input files they originate from and are numbered based on their order of processing. In debug mode, the code is printed with indentation whitespace. Otherwise, you'll notice that the code has been effectively minified. Also note that enabling this mode will slow down patching somewhat since more work is being done and files are written to disk. +- Printing of errored programs: When the transformer fails to parse a shader pack or an exception occurs during transformation, the exception is printed in the console but with debug mode enabled the program the error originated from is printed as `errored_program` in `patched_shaders`. +- Unused functions aren't removed in debug mode + +## List of GLSL Language Specifications + +- [GLSL 1.10](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.10.pdf) +- [GLSL 1.20](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.20.pdf) +- [GLSL 1.30](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.30.pdf) +- [GLSL 1.40](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.40.pdf) +- [GLSL 1.50](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.50.pdf) +- [GLSL 3.30](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.3.30.pdf) +- [GLSL 4.00](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.00.pdf) +- [GLSL 4.10](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.10.pdf) +- [GLSL 4.20](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.20.pdf) +- [GLSL 4.30](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.30.pdf) +- [GLSL 4.40](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.40.pdf) +- [GLSL 4.50](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.50.pdf) +- [GLSL 4.60](https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.4.60.pdf) diff --git a/src/desktop/java/net/irisshaders/iris/LaunchWarn.java b/src/desktop/java/net/irisshaders/iris/LaunchWarn.java new file mode 100644 index 0000000000..45dc00ed4a --- /dev/null +++ b/src/desktop/java/net/irisshaders/iris/LaunchWarn.java @@ -0,0 +1,45 @@ +package net.irisshaders.iris; + +import javax.swing.*; +import java.awt.*; +import java.io.IOException; +import java.net.URI; + +public class LaunchWarn { + public static void main(String[] args) { + // TODO: make this translatable + String message = DesktopBuildConfig.IS_SHARED_BETA + ? "If you're seeing this, you didn't read instructions.\n (Hint: This isn't a installer or a Forge mod. It's a Fabric mod.)" + : "This file is the Fabric version of Iris, meant to be installed as a mod. Would you like to get the Iris Installer instead?"; + String fallback = DesktopBuildConfig.IS_SHARED_BETA + ? "If you're seeing this, you didn't read instructions.\n (Hint: This isn't a installer or a Forge mod. It's a Fabric mod.)" + : "This file is the Fabric version of Iris, meant to be installed as a mod. Please download the Iris Installer from https://irisshaders.dev."; + if (GraphicsEnvironment.isHeadless()) { + System.err.println(fallback); + } else { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ReflectiveOperationException | UnsupportedLookAndFeelException ignored) { + // Ignored + } + + if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + int option = JOptionPane.showOptionDialog(null, message, "Iris Installer", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); + + if (option == JOptionPane.YES_OPTION) { + try { + Desktop.getDesktop().browse(URI.create("https://irisshaders.dev")); + } catch (IOException e) { + System.out.println("Welp; we're screwed."); + e.printStackTrace(); + } + } + } else { + // Fallback for Linux, etc users with no "default" browser + JOptionPane.showMessageDialog(null, fallback); + } + } + + System.exit(0); + } +} diff --git a/src/disabledTest/java/kroppeb/stareval/parser/IrisParserOptions.java b/src/disabledTest/java/kroppeb/stareval/parser/IrisParserOptions.java new file mode 100644 index 0000000000..844c1adb90 --- /dev/null +++ b/src/disabledTest/java/kroppeb/stareval/parser/IrisParserOptions.java @@ -0,0 +1,45 @@ +package kroppeb.stareval.parser; + +public class IrisParserOptions { + public static final ParserOptions options; + static final BinaryOp Multiply = new BinaryOp("multiply", 0); + static final BinaryOp Divide = new BinaryOp("divide", 0); + static final BinaryOp Remainder = new BinaryOp("remainder", 0); + static final BinaryOp Add = new BinaryOp("add", 1); + static final BinaryOp Subtract = new BinaryOp("subtract", 1); + static final BinaryOp Equals = new BinaryOp("equals", 2); + static final BinaryOp NotEquals = new BinaryOp("notEquals", 2); + static final BinaryOp LessThan = new BinaryOp("lessThan", 2); + static final BinaryOp MoreThan = new BinaryOp("moreThan", 2); + static final BinaryOp LessThanOrEquals = new BinaryOp("lessThanOrEquals", 2); + static final BinaryOp MoreThanOrEquals = new BinaryOp("moreThanOrEquals", 2); + static final BinaryOp And = new BinaryOp("or", 3); + static final BinaryOp Or = new BinaryOp("and", 3); + static final UnaryOp Not = new UnaryOp("not"); + static final UnaryOp Negate = new UnaryOp("negate"); + + static { + final ParserOptions.Builder builder = new ParserOptions.Builder(); + builder.addBinaryOp("*", Multiply); + builder.addBinaryOp("/", Divide); + builder.addBinaryOp("%", Remainder); + + builder.addBinaryOp("+", Add); + builder.addBinaryOp("-", Subtract); + + builder.addBinaryOp("==", Equals); + builder.addBinaryOp("!=", NotEquals); + builder.addBinaryOp("<", LessThan); + builder.addBinaryOp(">", MoreThan); + builder.addBinaryOp("<=", LessThanOrEquals); + builder.addBinaryOp(">=", MoreThanOrEquals); + + builder.addBinaryOp("&&", And); + builder.addBinaryOp("||", Or); + + builder.addUnaryOp("!", Not); + builder.addUnaryOp("-", Negate); + + options = builder.build(); + } +} diff --git a/src/disabledTest/java/kroppeb/stareval/parser/ParserTest.java b/src/disabledTest/java/kroppeb/stareval/parser/ParserTest.java new file mode 100644 index 0000000000..f7e1b3d8ff --- /dev/null +++ b/src/disabledTest/java/kroppeb/stareval/parser/ParserTest.java @@ -0,0 +1,45 @@ +package kroppeb.stareval.parser; + +import kroppeb.stareval.element.Element; +import kroppeb.stareval.exception.ParseException; +import kroppeb.stareval.element.ExpressionElement; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvFileSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +class ParserTest { + private static ExpressionElement parse(String string) throws ParseException { + return Parser.parse(string, IrisParserOptions.options); + } + + @ParameterizedTest + @CsvFileSource(resources = "/shouldBeAbleToBeParsed.csv", delimiter = ';') + void checkIfValidExpressionsParse(String input) throws ParseException { + parse(input); + } + + @ParameterizedTest + @CsvFileSource(resources = "/shouldNotBeAbleToBeParsed.csv", delimiter = ';') + void checkIfInvalidExpressionsDontParse(String input) { + try { + parse(input); + } catch (ParseException parseException) { + parseException.printStackTrace(); + return; + } catch (RuntimeException runtimeException) { + fail("Unexpected exception has been thrown", runtimeException); + return; + } + fail("No exception has been thrown"); + } + + @ParameterizedTest + @CsvFileSource(resources = "/fullyEquivalent.csv", delimiter = ';') + void checkOrderOfOperationsParse(String input1, String input2) throws ParseException { + Element exp1 = parse(input1); + Element exp2 = parse(input2); + assertEquals(exp1.toString(), exp2.toString()); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/IrisTests.java b/src/disabledTest/java/net/irisshaders/iris/test/IrisTests.java new file mode 100644 index 0000000000..5dcf9466ae --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/IrisTests.java @@ -0,0 +1,48 @@ +package net.irisshaders.iris.test; + +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.shaderpack.ShaderPack; +import org.junit.jupiter.api.Assertions; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class IrisTests { + public static ImmutableList TEST_ENVIRONMENT_DEFINES = ImmutableList.of( + new StringPair("MC_OS_WINDOWS", ""), + new StringPair("MC_VERSION", "11605"), + new StringPair("MC_GL_VERSION", "460"), + new StringPair("MC_GLSL_VERSION", "460"), + new StringPair("MC_GL_RENDERER_GEFORCE", ""), + new StringPair("MC_GL_VENDOR_NVIDIA", ""), + new StringPair("MC_RENDER_QUALITY", "1.0"), + new StringPair("MC_SHADOW_QUALITY", "1.0"), + new StringPair("MC_NORMAL_MAP", ""), + new StringPair("MC_SPECULAR_MAP", ""), + new StringPair("MC_HAND_DEPTH", "0.125") + ); + + static { + Iris.testing = true; + } + + public static ShaderPack loadPackOrFail(String name) { + try { + return new ShaderPack(IrisTests.getTestShaderPackPath(name), TEST_ENVIRONMENT_DEFINES); + } catch (Exception e) { + Assertions.fail("Couldn't load test shader pack " + name, e); + throw new AssertionError(); + } + } + + public static Path getTestShaderPackPath(String name) { + try { + return Paths.get(IrisTests.class.getResource("/shaderpacks/" + name + "/shaders/").toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/custom_uniforms/IrisFunctionsTest.java b/src/disabledTest/java/net/irisshaders/iris/test/custom_uniforms/IrisFunctionsTest.java new file mode 100644 index 0000000000..32d407c488 --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/custom_uniforms/IrisFunctionsTest.java @@ -0,0 +1,99 @@ +package net.irisshaders.iris.test.custom_uniforms; + +import kroppeb.stareval.element.ExpressionElement; +import kroppeb.stareval.exception.ParseException; +import kroppeb.stareval.expression.ConstantExpression; +import kroppeb.stareval.expression.Expression; +import kroppeb.stareval.function.FunctionContext; +import kroppeb.stareval.function.FunctionReturn; +import kroppeb.stareval.function.Type; +import kroppeb.stareval.parser.Parser; +import kroppeb.stareval.resolver.ExpressionResolver; +import net.irisshaders.iris.parsing.IrisFunctions; +import net.irisshaders.iris.parsing.IrisOptions; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.function.Consumer; + +public class IrisFunctionsTest { + private static void trivialTest(Type outputType, String expressionStr, Consumer verifier) throws ParseException { + ExpressionElement element = Parser.parse(expressionStr, IrisOptions.options); + ExpressionResolver resolver = new ExpressionResolver(IrisFunctions.functions, x -> { + if (x.equals("true") || x.equals("false")) { + return Type.Boolean; + } else { + return null; + } + }, true); + + FunctionReturn functionReturn = new FunctionReturn(); + FunctionContext context = new FunctionContext() { + @Override + public Expression getVariable(String name) { + if (name.equals("true")) { + return new ConstantExpression(Type.Boolean) { + @Override + public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { + functionReturn.booleanReturn = true; + } + }; + } else if (name.equals("false")) { + return new ConstantExpression(Type.Boolean) { + @Override + public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { + functionReturn.booleanReturn = false; + } + }; + } + + return null; + } + + @Override + public boolean hasVariable(String name) { + return name.equals("false") || name.equals("true"); + } + }; + + Expression expression = resolver.resolveExpression(outputType, element); + expression.evaluateTo(context, functionReturn); + + verifier.accept(functionReturn); + } + + @Test + void testIf() throws ParseException { + trivialTest(Type.Boolean, "if(1, 1, 0)", result -> { + Assertions.assertTrue(result.booleanReturn); + }); + } + + @Test + void testIfTF() throws ParseException { + trivialTest(Type.Boolean, "if(true, true, false)", result -> { + Assertions.assertTrue(result.booleanReturn); + }); + } + + @Test + void testAdd() throws ParseException { + trivialTest(Type.Int, "1 + 1", result -> { + Assertions.assertEquals(result.intReturn, 2); + }); + } + + @Test + void testAnd() throws ParseException { + trivialTest(Type.Boolean, "1 && 0", result -> { + Assertions.assertFalse(result.booleanReturn); + }); + } + + @Test + void testAndTF() throws ParseException { + trivialTest(Type.Boolean, "true && false", result -> { + Assertions.assertFalse(result.booleanReturn); + }); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/AmbientOcclusionBoundsTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/AmbientOcclusionBoundsTest.java new file mode 100644 index 0000000000..89b3361afc --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/AmbientOcclusionBoundsTest.java @@ -0,0 +1,17 @@ +package net.irisshaders.iris.test.shaderpack; + +import net.irisshaders.iris.shaderpack.DimensionId; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class AmbientOcclusionBoundsTest { + @Test + void testAmbientOcclusionBounds() { + ShaderPack shaderPack = IrisTests.loadPackOrFail("ambient_occlusion_out_of_bounds"); + + Assertions.assertEquals(1.0f, + shaderPack.getProgramSet(DimensionId.OVERWORLD).getPackDirectives().getAmbientOcclusionLevel()); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/IdMapTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/IdMapTest.java new file mode 100644 index 0000000000..e1ab1be130 --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/IdMapTest.java @@ -0,0 +1,62 @@ +package net.irisshaders.iris.test.shaderpack; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.materialmap.BlockEntry; +import net.irisshaders.iris.shaderpack.materialmap.BlockRenderType; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class IdMapTest { + private static final Map EXPECTED_LAYERS; + private static final Int2ObjectMap> EXPECTED_BLOCKS; + + static { + EXPECTED_LAYERS = new HashMap<>(); + + /* + layer.translucent=glass_pane fence minecraft:wooden_door + layer.solid=minecraft:oak_leaves + layer.cutout=terrestria:hemlock_leaves + layer.cutout_mipped=grass + */ + EXPECTED_LAYERS.put(new NamespacedId("minecraft", "glass_pane"), BlockRenderType.TRANSLUCENT); + EXPECTED_LAYERS.put(new NamespacedId("minecraft", "fence"), BlockRenderType.TRANSLUCENT); + EXPECTED_LAYERS.put(new NamespacedId("minecraft", "wooden_door"), BlockRenderType.TRANSLUCENT); + EXPECTED_LAYERS.put(new NamespacedId("minecraft", "oak_leaves"), BlockRenderType.SOLID); + EXPECTED_LAYERS.put(new NamespacedId("terrestria", "hemlock_leaves"), BlockRenderType.CUTOUT); + EXPECTED_LAYERS.put(new NamespacedId("minecraft", "grass"), BlockRenderType.CUTOUT_MIPPED); + + EXPECTED_BLOCKS = new Int2ObjectOpenHashMap<>(); + EXPECTED_BLOCKS.put(37, Arrays.asList( + new BlockEntry(new NamespacedId("minecraft", "red_stained_glass"), new HashMap<>()), + new BlockEntry(new NamespacedId("minecraft", "blue_stained_glass"), new HashMap<>()), + new BlockEntry(new NamespacedId("minecraft", "white_stained_glass"), new HashMap<>()))); + } + + @Test + void testLoadIdMaps() { + ShaderPack shaderPack; + + // ensure that we can actually load the shader pack + try { + shaderPack = new ShaderPack(IrisTests.getTestShaderPackPath("id_maps"), IrisTests.TEST_ENVIRONMENT_DEFINES); + } catch (Exception e) { + Assertions.fail("Couldn't load test shader pack id_maps", e); + return; + } + + Map overrides = shaderPack.getIdMap().getBlockRenderTypeMap(); + Int2ObjectMap> blocks = shaderPack.getIdMap().getBlockProperties(); + Assertions.assertEquals(EXPECTED_LAYERS, overrides); + Assertions.assertEquals(EXPECTED_BLOCKS, blocks); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LanguageMapTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LanguageMapTest.java new file mode 100644 index 0000000000..c91a55a336 --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LanguageMapTest.java @@ -0,0 +1,47 @@ +package net.irisshaders.iris.test.shaderpack; + +import net.irisshaders.iris.shaderpack.LanguageMap; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +public class LanguageMapTest { + @Test + void testLoadLanguages() { + ShaderPack shaderPack; + + // ensure that we can actually load the shader pack + try { + shaderPack = new ShaderPack(IrisTests.getTestShaderPackPath("language_maps"), IrisTests.TEST_ENVIRONMENT_DEFINES); + } catch (Exception e) { + Assertions.fail("Couldn't load test shader pack language_maps", e); + return; + } + + // ensure that we only loaded two language files + LanguageMap languageMap = shaderPack.getLanguageMap(); + Assertions.assertEquals(2, languageMap.getLanguages().size(), "number of languages loaded"); + + // test that en_US.lang was loaded properly + { + Map english = languageMap.getTranslations("en_us"); + Assertions.assertNotNull(english, "en_us translations"); + + Assertions.assertEquals(2, english.size(), "number of translations in en_US.lang"); + Assertions.assertEquals("Test screen", english.get("screen.TEST")); + Assertions.assertEquals("Test option", english.get("option.TEST_OPTION")); + } + + // test that fr_FR.lang was loaded properly + { + Map french = languageMap.getTranslations("fr_fr"); + Assertions.assertNotNull(french, "fr_fr translations"); + + Assertions.assertEquals(1, french.size(), "number of translations in fr_FR.lang"); + Assertions.assertEquals("Écran de test", french.get("screen.TEST")); + } + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LightmapCustomTextureTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LightmapCustomTextureTest.java new file mode 100644 index 0000000000..32dfc2868f --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/LightmapCustomTextureTest.java @@ -0,0 +1,18 @@ +package net.irisshaders.iris.test.shaderpack; + +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.texture.CustomTextureData; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +public class LightmapCustomTextureTest { + @Test + void testLightmapCustomTexture() { + ShaderPack shaderPack = IrisTests.loadPackOrFail("lightmap_custom_texture"); + + Assertions.assertEquals(Optional.of(new CustomTextureData.LightmapMarker()), shaderPack.getCustomNoiseTexture()); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionApplyTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionApplyTest.java new file mode 100644 index 0000000000..ba3031cf5f --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionApplyTest.java @@ -0,0 +1,109 @@ +package net.irisshaders.iris.test.shaderpack; + +import com.google.common.collect.ImmutableMap; +import net.irisshaders.iris.shaderpack.DimensionId; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.option.OptionAnnotatedSource; +import net.irisshaders.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +public class OptionApplyTest { + @Test + void testOptions() { + ShaderPack shaderPack; + + // ensure that we can actually load the shader pack + try { + shaderPack = new ShaderPack(IrisTests.getTestShaderPackPath("options"), IrisTests.TEST_ENVIRONMENT_DEFINES); + } catch (Exception e) { + Assertions.fail("Couldn't load test shader pack options", e); + return; + } + + ProgramSource basic = shaderPack + .getProgramSet(DimensionId.OVERWORLD) + .getGbuffersBasic() + .orElseThrow(RuntimeException::new); + + String basicVsh = basic.getVertexSource().orElseThrow(RuntimeException::new); + String basicFsh = basic.getFragmentSource().orElseThrow(RuntimeException::new); + + OptionAnnotatedSource basicVshAnnotated = new OptionAnnotatedSource(basicVsh); + OptionAnnotatedSource basicFshAnnotated = new OptionAnnotatedSource(basicFsh); + + // TODO: Separate includes will need more complex boolean define reference behavior + OptionSet basicVshSet = basicVshAnnotated.getOptionSet( + AbsolutePackPath.fromAbsolutePath("/basic.vsh"), + basicVshAnnotated.getBooleanDefineReferences().keySet()); + OptionSet basicFshSet = basicFshAnnotated.getOptionSet( + AbsolutePackPath.fromAbsolutePath("/basic.fsh"), + basicFshAnnotated.getBooleanDefineReferences().keySet()); + + OptionSet.Builder setBuilder = OptionSet.builder(); + + setBuilder.addAll(basicVshSet); + setBuilder.addAll(basicFshSet); + + OptionSet options = setBuilder.build(); + + Map changes = ImmutableMap.of( + "SHADOWS", "false", + "ambientOcclusionLevel", "0.0", + "shadowDistance", "64", + "ANNOYING_STUFF", "true", + "GODRAYS", "16" + ); + + OptionValues values = new MutableOptionValues(options, changes); + + System.out.println(basicVshAnnotated.apply(values)); + System.out.println(basicFshAnnotated.apply(values)); + + System.out.println(options); + } + + @Test + void testWeirdDefine() { + testTrivial( + "#define NAME fine // [fine notfine]", + ImmutableMap.of("NAME", "notfine"), + "#define NAME notfine // OptionAnnotatedSource: Changed option\n" + ); + } + + @Test + void testWeirdDefine2() { + testTrivial( + "#define MODE_DEFAULT MODE_D // [MODE_A MODE_D]", + ImmutableMap.of("MODE_DEFAULT", "MODE_A"), + "#define MODE_DEFAULT MODE_A // OptionAnnotatedSource: Changed option\n" + ); + } + + @Test + void testNormalDefine() { + testTrivial( + " #define OPTION A // [A B C]", + ImmutableMap.of("OPTION", "C"), + "#define OPTION C // OptionAnnotatedSource: Changed option\n" + ); + } + + private void testTrivial(String base, ImmutableMap changes, String expected) { + OptionAnnotatedSource source = new OptionAnnotatedSource(base); + OptionSet options = source.getOptionSet( + AbsolutePackPath.fromAbsolutePath("/"), + source.getBooleanDefineReferences().keySet()); + OptionValues values = new MutableOptionValues(options, changes); + + Assertions.assertEquals(expected, source.apply(values)); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionDiscoverTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionDiscoverTest.java new file mode 100644 index 0000000000..c75fdd095b --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/OptionDiscoverTest.java @@ -0,0 +1,79 @@ +package net.irisshaders.iris.test.shaderpack; + +import com.google.common.collect.ImmutableList; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.option.OptionAnnotatedSource; +import net.irisshaders.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.shaderpack.option.StringOption; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class OptionDiscoverTest { + @Test + void testSingleValueDefine() { + testTrivialString( + "#define SECRET 0 //[0]", + "SECRET", "0", ImmutableList.of("0") + ); + } + + @Test + void testAstraLexDefine() { + // AstraLex omits the space + testTrivialString( + "#define SECRET 0//[0]", + "SECRET", "0", ImmutableList.of("0") + ); + } + + @Test + void testInferredDefaultDefine() { + testTrivialString( + "#define OPT 1 //[0]", + "OPT", "1", ImmutableList.of("0", "1") + ); + } + + @Test + void testNonConfigurableConstant() { + // TODO: What about "const bool" options??? + testNoDiscovery("#define PI 3.14 // It's PI."); + testNoDiscovery("#define PI 3.14"); + testNoDiscovery("const int noiseTextureResolution = 512;"); + testNoDiscovery("const int noiseTextureResolution = 512; // Default noise texture size ["); + } + + private void testTrivialString(String base, String expectedOptionName, String expectedDefault, + ImmutableList expectedAllowed) { + OptionAnnotatedSource source = new OptionAnnotatedSource(base); + OptionSet options = source.getOptionSet( + AbsolutePackPath.fromAbsolutePath("/"), + source.getBooleanDefineReferences().keySet()); + + Assertions.assertEquals(options.getBooleanOptions().size(), 0, + "Unexpectedly discovered a boolean option"); + + if (options.getStringOptions().size() == 0) { + Assertions.fail("No string options were discovered, diagnostics: " + source.getDiagnostics()); + } + + StringOption option = options.getStringOptions().values().iterator().next().getOption(); + + Assertions.assertEquals(option.getName(), expectedOptionName); + Assertions.assertEquals(option.getDefaultValue(), expectedDefault); + Assertions.assertEquals(option.getAllowedValues(), expectedAllowed); + } + + private void testNoDiscovery(String base) { + OptionAnnotatedSource source = new OptionAnnotatedSource(base); + OptionSet options = source.getOptionSet( + AbsolutePackPath.fromAbsolutePath("/"), + source.getBooleanDefineReferences().keySet()); + + Assertions.assertEquals(options.getBooleanOptions().size(), 0, + "Unexpectedly discovered a boolean option"); + + Assertions.assertEquals(options.getStringOptions().size(), 0, + "Unexpectedly discovered a string option"); + } +} diff --git a/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/PreprocessorTest.java b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/PreprocessorTest.java new file mode 100644 index 0000000000..3a848c2272 --- /dev/null +++ b/src/disabledTest/java/net/irisshaders/iris/test/shaderpack/PreprocessorTest.java @@ -0,0 +1,64 @@ +package net.irisshaders.iris.test.shaderpack; + +import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor; +import net.irisshaders.iris.test.IrisTests; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class PreprocessorTest { + @Test + void testWeirdPropertiesLineContinuation() { + // This weirdness shows up in Voyager Shaders. + Assertions.assertEquals("Test\n", PropertiesPreprocessor.preprocessSource("\\\t\t \nTest", + IrisTests.TEST_ENVIRONMENT_DEFINES)); + } + + @Test + void testNormalPropertiesLineContinuation() { + // This weirdness shows up in Voyager Shaders. + Assertions.assertEquals("Test Test\n", PropertiesPreprocessor.preprocessSource("Test \\\nTest", + IrisTests.TEST_ENVIRONMENT_DEFINES)); + } + + @Test + void testWeirdHashComment() { + String line = "test= #[Comment]"; + + // This needs to be handled properly for Oceano shaders to work right + Assertions.assertEquals(line + "\n", PropertiesPreprocessor.preprocessSource(line, + IrisTests.TEST_ENVIRONMENT_DEFINES)); + } + + @Test + void testHashComment() { + // Note: Verify that this does not spam the log by inspecting manually. + String line = + "# Test\n" + + "#test comment\n" + + "#1xxx\n"; + + Assertions.assertEquals("", PropertiesPreprocessor.preprocessSource(line, + IrisTests.TEST_ENVIRONMENT_DEFINES).trim()); + } + + @Test + void testPreprocessorDirectives() { + String line = + "#if MC_VERSION >= 11300\n" + + "block.1=minecraft:grass_block\n" + + "#else\n" + + "block.1=minecraft:grass\n" + + "#endif\n"; + + Assertions.assertEquals("block.1=minecraft:grass_block", PropertiesPreprocessor.preprocessSource(line, + IrisTests.TEST_ENVIRONMENT_DEFINES).trim()); + } + + @Test + void testWeirdDefineDoesNotCrash() { + String line = "# define TEST"; + + Assertions.assertEquals("", PropertiesPreprocessor.preprocessSource(line, + IrisTests.TEST_ENVIRONMENT_DEFINES).trim()); + } +} diff --git a/src/disabledTest/resources/fullyEquivalent.csv b/src/disabledTest/resources/fullyEquivalent.csv new file mode 100644 index 0000000000..88d9a5e3ba --- /dev/null +++ b/src/disabledTest/resources/fullyEquivalent.csv @@ -0,0 +1,8 @@ +a;(a) +a - b - c;((a - b) - c) +a * b - c;((a * b) - c) +a - b * c;(a - (b * c)) +a * b / c % d; (((a * b) / c) % d) +a + b - c; ((a + b) - c) +a == b && b != c || c < d || d >= e || e <= f && f > h;((((((a == b) && (b != c)) || (c < d)) || (d >= e)) || (e <= f)) && (f > h)) +a + b * c - d % r * f * f / f - u + u;((((a + (b * c)) - ((((d % r) * f) * f) / f)) - u) + u) diff --git a/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.fsh b/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.fsh new file mode 100644 index 0000000000..523bf8fd65 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.fsh @@ -0,0 +1,7 @@ +#version 120 + +const float ambientOcclusionLevel = 2.0f; + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.vsh b/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.vsh new file mode 100644 index 0000000000..557e0da92f --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/ambient_occlusion_out_of_bounds/shaders/gbuffers_basic.vsh @@ -0,0 +1,5 @@ +#version 120 + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.fsh b/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.fsh new file mode 100644 index 0000000000..523bf8fd65 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.fsh @@ -0,0 +1,7 @@ +#version 120 + +const float ambientOcclusionLevel = 2.0f; + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.vsh b/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.vsh new file mode 100644 index 0000000000..557e0da92f --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/directives/shaders/gbuffers_basic.vsh @@ -0,0 +1,5 @@ +#version 120 + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shaderpacks/id_maps/shaders/block.properties b/src/disabledTest/resources/shaderpacks/id_maps/shaders/block.properties new file mode 100644 index 0000000000..d67d4b0c64 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/id_maps/shaders/block.properties @@ -0,0 +1,14 @@ +#if MC_VERSION >= 11300 || MC_VERSION < 11300 +layer.translucent=glass_pane fence minecraft:wooden_door +layer.solid=minecraft:oak_leaves +layer.cutout=terrestria:hemlock_leaves +layer.cutout_mipped=grass +# Test backslash behavior with the preprocessor +block.37=red_stained_glass \ + blue_stained_glass \ + white_stained_glass +#else +# Make sure preprocessing worked +block.37=minecraft:barrier +#endif + diff --git a/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/README b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/README new file mode 100644 index 0000000000..96ff296452 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/README @@ -0,0 +1,3 @@ +Language files + +This file doesn't have an extension diff --git a/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/en_US.lang b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/en_US.lang new file mode 100644 index 0000000000..875c7bc9d2 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/en_US.lang @@ -0,0 +1,3 @@ +#This is a valid language file +screen.TEST=Test screen +option.TEST_OPTION=Test option diff --git a/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/fr_FR.lang b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/fr_FR.lang new file mode 100644 index 0000000000..2259146b4d --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/fr_FR.lang @@ -0,0 +1,2 @@ +#This is a valid language file +screen.TEST=Écran de test diff --git a/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/test.txt b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/test.txt new file mode 100644 index 0000000000..2aa63dadd2 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/language_maps/shaders/lang/test.txt @@ -0,0 +1 @@ +This is a text file but it shouldn't be parsed as a language file diff --git a/src/disabledTest/resources/shaderpacks/lightmap_custom_texture/shaders/shaders.properties b/src/disabledTest/resources/shaderpacks/lightmap_custom_texture/shaders/shaders.properties new file mode 100644 index 0000000000..1eb5c7b267 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/lightmap_custom_texture/shaders/shaders.properties @@ -0,0 +1 @@ +texture.noise=minecraft:dynamic/lightmap_1 diff --git a/src/disabledTest/resources/shaderpacks/options/shaders/block.properties b/src/disabledTest/resources/shaderpacks/options/shaders/block.properties new file mode 100644 index 0000000000..3f55031ea6 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/options/shaders/block.properties @@ -0,0 +1 @@ +# empty, prevents LegacyIdMap from loading since currently that blows up our test suite :/ diff --git a/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.fsh b/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.fsh new file mode 100644 index 0000000000..7bd725fc81 --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.fsh @@ -0,0 +1,19 @@ +#version 120 + +// these shouldn't be recognized as options, conflicts with vsh values +// #define VSH +#define FSH + +#ifdef FSH +#endif + +#ifdef VSH +#endif + +const int shadowDistance = 128; // How far away should shadows be rendered in blocks [16 32 48 64 128 256 512] +const int shadowDistanceRenderMul = 1; // [-1 0 1] Controls shadow culling modes +const float ambientOcclusionLevel = 1.0; // [0.0] Allows disabling vanilla ambient occlusion + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.vsh b/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.vsh new file mode 100644 index 0000000000..f639083f0b --- /dev/null +++ b/src/disabledTest/resources/shaderpacks/options/shaders/gbuffers_basic.vsh @@ -0,0 +1,46 @@ +#version 120 + +#define GODRAYS 32 // [16 32 64 128] Number of godrays + #define SHADOWS + +#define GRASS_SHADOWS // whether tallgrass casts shadows +//#define // not really a valid define +//#define GALAXIES + +const int shadowDistance = 128; // How far away should shadows be rendered in blocks [16 32 48 64 128 256 512] +const int shadowDistanceRenderMul = 1; // [-1 0 1] Controls shadow culling modes +const float ambientOcclusionLevel = 1.0; // [0.0] Allows disabling vanilla ambient occlusion + +// #define volumetricLighting +//#define ANNOYING_STUFF +#define UNCONFIRMED_OR_UNUSED + +// these shouldn't be recognized as options, conflicts with fsh values +#define VSH +// #define FSH + +#ifdef SHADOWS +uniform sampler2D shadowtex0; +#endif + +#ifdef GRASS_SHADOWS +#endif + +#ifdef GALAXIES +#endif + +#ifdef volumetricLighting +#endif + +#ifdef ANNOYING_STUFF +#endif + +#ifdef VSH +#endif + +#ifdef FSH +#endif + +void main() { + // we're not really doing anything in particular +} diff --git a/src/disabledTest/resources/shouldBeAbleToBeParsed.csv b/src/disabledTest/resources/shouldBeAbleToBeParsed.csv new file mode 100644 index 0000000000..efcb971136 --- /dev/null +++ b/src/disabledTest/resources/shouldBeAbleToBeParsed.csv @@ -0,0 +1,38 @@ +5 +-5 +thunk +-thunk +!thunk +- ! thunk +- - thunk +a - a +a - - a +a + ! a +a * ! a +- a - a +- a - - a +- a + ! a +- a * ! a +a - - - - - - - - - - - - - - - a +- - - - - - - - - - - - - - - - - - a - - - - - - - - - - - - - - - a +17 / 30 % 6 +12.0 + stone +ohno() +!uwu() +smooth(3, 17, 15) +!smooth(3, 17, 15) +smooth(3, 17, 15,) +(3) +(5 + 3) +(ohno(oh, no)) +(!ohno()) +(!ohno(oh, no)) +a * b / c % d +a + b - c +a == b && b != c || c < d || d >= e || e <= f && f > h +a + b * c - d % r * f * f / f - u + u +test.field +test. field +test .field +test . field +function(tabs, are, valid) diff --git a/src/disabledTest/resources/shouldNotBeAbleToBeParsed.csv b/src/disabledTest/resources/shouldNotBeAbleToBeParsed.csv new file mode 100644 index 0000000000..31501c0116 --- /dev/null +++ b/src/disabledTest/resources/shouldNotBeAbleToBeParsed.csv @@ -0,0 +1,34 @@ +5 - +-5 - +5 * +-5 + +* 5 +/ 9 +( +) +, +(3 +3) +(3,) +3, +(3,,) +(,) +(,5) +(3,5) +(3,5,) +(5, * 3) +(5, 3 *) +ohno( +ohno(, +(ohno(oh, no),) +(ohno(oh, no),5) +ohno(,5) +ohno(,) +ohno(,,) +stone, +,stone +, +,5 +5, +5+, +spaces in identifiers are not valid diff --git a/src/main/java/com/seibel/distanthorizons/api/interfaces/override/IDhApiOverrideable.java b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/IDhApiOverrideable.java new file mode 100644 index 0000000000..b69170a941 --- /dev/null +++ b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/IDhApiOverrideable.java @@ -0,0 +1,43 @@ +/* + * This file is part of the Distant Horizons mod + * licensed under the GNU LGPL v3 License. + * + * Copyright (C) 2020-2023 James Seibel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.seibel.distanthorizons.api.interfaces.override; + +import com.seibel.distanthorizons.coreapi.interfaces.dependencyInjection.IBindable; +import com.seibel.distanthorizons.coreapi.interfaces.dependencyInjection.IOverrideInjector; + +/** + * Implemented by all DhApi objects that can be overridden. + * + * @author James Seibel + * @version 2022-9-5 + * @since API 1.0.0 + */ +public interface IDhApiOverrideable extends IBindable { + /** + * Higher (larger numerical) priorities override lower (smaller numerical) priorities.
+ * For most developers this can be left at the default. + * + * @return The priority of this interface, the lowest legal value is {@link IOverrideInjector#MIN_NON_CORE_OVERRIDE_PRIORITY}. + */ + default int getPriority() { + return IOverrideInjector.DEFAULT_NON_CORE_OVERRIDE_PRIORITY; + } + +} diff --git a/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiCullingFrustum.java b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiCullingFrustum.java new file mode 100644 index 0000000000..85217a86af --- /dev/null +++ b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiCullingFrustum.java @@ -0,0 +1,56 @@ +/* + * This file is part of the Distant Horizons mod + * licensed under the GNU LGPL v3 License. + * + * Copyright (C) 2020-2023 James Seibel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.seibel.distanthorizons.api.interfaces.override.rendering; + +import com.seibel.distanthorizons.api.enums.EDhApiDetailLevel; +import com.seibel.distanthorizons.api.interfaces.override.IDhApiOverrideable; +import com.seibel.distanthorizons.coreapi.util.math.Mat4f; + +/** + * Used to determine if a LOD should be rendered or is outside the + * user's field of view. + * + * @author James Seibel + * @version 2024-2-6 + * @since API 1.1.0 + */ +public interface IDhApiCullingFrustum extends IDhApiOverrideable { + + /** + * Called before a render pass is done. + * + * @param worldMinBlockY the lowest block position this level allows. + * @param worldMaxBlockY the highest block position this level allows. + * @param worldViewProjection the projection matrix used in this render pass. + */ + void update(int worldMinBlockY, int worldMaxBlockY, Mat4f worldViewProjection); + + /** + * returns true if the LOD bounds intersect this frustum + * + * @param lodBlockPosMinX this LOD's starting block X position closest to negative infinity + * @param lodBlockPosMinZ this LOD's starting block Z position closest to negative infinity + * @param lodBlockWidth this LOD's width in blocks + * @param lodDetailLevel this LOD's detail level + * @see EDhApiDetailLevel + */ + boolean intersects(int lodBlockPosMinX, int lodBlockPosMinZ, int lodBlockWidth, int lodDetailLevel); + +} diff --git a/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiShadowCullingFrustum.java b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiShadowCullingFrustum.java new file mode 100644 index 0000000000..a526cb2ed7 --- /dev/null +++ b/src/main/java/com/seibel/distanthorizons/api/interfaces/override/rendering/IDhApiShadowCullingFrustum.java @@ -0,0 +1,34 @@ +/* + * This file is part of the Distant Horizons mod + * licensed under the GNU LGPL v3 License. + * + * Copyright (C) 2020-2023 James Seibel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.seibel.distanthorizons.api.interfaces.override.rendering; + +/** + * The culling frustum used during Distant Horizons' shadow pass + * if another mod has enabled Distant Horizons' shadow + * pass via the API. + * + * @author James Seibel + * @version 2024-2-10 + * @see IDhApiCullingFrustum + * @since API 1.1.0 + */ +public interface IDhApiShadowCullingFrustum extends IDhApiCullingFrustum { + // should be identical to the parent culling frustum +} diff --git a/src/main/java/com/seibel/distanthorizons/coreapi/interfaces/dependencyInjection/IBindable.java b/src/main/java/com/seibel/distanthorizons/coreapi/interfaces/dependencyInjection/IBindable.java new file mode 100644 index 0000000000..bd32a2cf62 --- /dev/null +++ b/src/main/java/com/seibel/distanthorizons/coreapi/interfaces/dependencyInjection/IBindable.java @@ -0,0 +1,52 @@ +/* + * This file is part of the Distant Horizons mod + * licensed under the GNU LGPL v3 License. + * + * Copyright (C) 2020-2023 James Seibel + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.seibel.distanthorizons.coreapi.interfaces.dependencyInjection; + +/** + * Necessary for all singletons that can be dependency injected. + * + * @author James Seibel + * @version 2022-7-16 + */ +public interface IBindable { + /** + * Finish initializing this object.

+ *

+ * Generally this should just be used for getting other objects through + * dependency injection and is specifically designed to allow + * for circular references.

+ *

+ * If no circular dependencies are required this method + * doesn't have to be implemented. + */ + default void finishDelayedSetup() { + } + + /** + * Returns if this dependency has been setup yet.

+ *

+ * If this object doesn't require a delayed setup, this + * method doesn't have to be implemented and should always return true. + */ + default boolean getDelayedSetupComplete() { + return true; + } + +} diff --git a/src/main/java/kroppeb/stareval/Util.java b/src/main/java/kroppeb/stareval/Util.java index b102e74f42..a8368be1b5 100644 --- a/src/main/java/kroppeb/stareval/Util.java +++ b/src/main/java/kroppeb/stareval/Util.java @@ -7,7 +7,7 @@ public static T make(T item, Consumer init) { init.accept(item); return item; } - + } diff --git a/src/main/java/kroppeb/stareval/exception/ParseException.java b/src/main/java/kroppeb/stareval/exception/ParseException.java index 3a4f56106d..5dd9d6b14e 100644 --- a/src/main/java/kroppeb/stareval/exception/ParseException.java +++ b/src/main/java/kroppeb/stareval/exception/ParseException.java @@ -1,6 +1,6 @@ package kroppeb.stareval.exception; -public abstract class ParseException extends Exception{ +public abstract class ParseException extends Exception { public ParseException() { } diff --git a/src/main/java/kroppeb/stareval/expression/BasicVariableExpression.java b/src/main/java/kroppeb/stareval/expression/BasicVariableExpression.java index feb41f442e..c050565347 100644 --- a/src/main/java/kroppeb/stareval/expression/BasicVariableExpression.java +++ b/src/main/java/kroppeb/stareval/expression/BasicVariableExpression.java @@ -7,25 +7,25 @@ public class BasicVariableExpression implements VariableExpression { final private String name; final private Type type; - + public BasicVariableExpression(String name, Type type) { this.name = name; this.type = type; } - + @Override public void evaluateTo(FunctionContext c, FunctionReturn r) { c.getVariable(name).evaluateTo(c, r); } - + @Override public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) { - if(context.hasVariable(this.name)){ + if (context.hasVariable(this.name)) { context.getVariable(this.name).evaluateTo(context, functionReturn); return type.createConstant(functionReturn); - }else{ + } else { return this; } } - + } diff --git a/src/main/java/kroppeb/stareval/expression/CallExpression.java b/src/main/java/kroppeb/stareval/expression/CallExpression.java index 08dc109cc4..311653a5dd 100644 --- a/src/main/java/kroppeb/stareval/expression/CallExpression.java +++ b/src/main/java/kroppeb/stareval/expression/CallExpression.java @@ -9,17 +9,18 @@ public class CallExpression implements Expression { private final TypedFunction function; private final Expression[] arguments; - + public CallExpression(TypedFunction function, Expression[] arguments) { this.function = function; this.arguments = arguments; } - + @Override public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { this.function.evaluateTo(this.arguments, context, functionReturn); } -@Override + + @Override public void listVariables(Collection variables) { for (Expression argument : this.arguments) { argument.listVariables(variables); @@ -61,7 +62,7 @@ public Expression partialEval(FunctionContext context, FunctionReturn functionRe noneSimplified = false; } else { allFullySimplified = false; - if(simplified != this.arguments[i]){ + if (simplified != this.arguments[i]) { noneSimplified = false; } } diff --git a/src/main/java/kroppeb/stareval/expression/ConstantExpression.java b/src/main/java/kroppeb/stareval/expression/ConstantExpression.java index 337e7e45c6..100d745882 100644 --- a/src/main/java/kroppeb/stareval/expression/ConstantExpression.java +++ b/src/main/java/kroppeb/stareval/expression/ConstantExpression.java @@ -6,15 +6,15 @@ public abstract class ConstantExpression implements Expression { private final Type type; - + protected ConstantExpression(Type type) { this.type = type; } - + public Type getType() { return this.type; } - + @Override public void listVariables(Collection variables) { } diff --git a/src/main/java/kroppeb/stareval/expression/Expression.java b/src/main/java/kroppeb/stareval/expression/Expression.java index a77b6b054f..66c2a2e41b 100644 --- a/src/main/java/kroppeb/stareval/expression/Expression.java +++ b/src/main/java/kroppeb/stareval/expression/Expression.java @@ -7,10 +7,10 @@ public interface Expression { void evaluateTo(FunctionContext context, FunctionReturn functionReturn); - - default Expression partialEval(FunctionContext context, FunctionReturn functionReturn){ + + default Expression partialEval(FunctionContext context, FunctionReturn functionReturn) { return this; } - + void listVariables(Collection variables); } diff --git a/src/main/java/kroppeb/stareval/function/BasicFunctionContext.java b/src/main/java/kroppeb/stareval/function/BasicFunctionContext.java index 27d82cb2aa..1e9d7f5b84 100644 --- a/src/main/java/kroppeb/stareval/function/BasicFunctionContext.java +++ b/src/main/java/kroppeb/stareval/function/BasicFunctionContext.java @@ -8,27 +8,27 @@ public class BasicFunctionContext implements FunctionContext { final private Map variables = new Object2ObjectOpenHashMap<>(); - - public void setVariable(String name, Expression value){ + + public void setVariable(String name, Expression value) { variables.put(name, value); } - - public void setIntVariable(String name, int value){ + + public void setIntVariable(String name, int value) { setVariable(name, (VariableExpression) (c, r) -> r.intReturn = value); } - - public void setFloatVariable(String name, float value){ - setVariable(name, (VariableExpression) (c,r) -> r.floatReturn = value); + + public void setFloatVariable(String name, float value) { + setVariable(name, (VariableExpression) (c, r) -> r.floatReturn = value); } - + @Override public Expression getVariable(String name) { Expression expression = variables.get(name); - if(expression == null) + if (expression == null) throw new RuntimeException("Variable hasn't been set: " + name); return expression; } - + @Override public boolean hasVariable(String name) { return variables.containsKey(name); diff --git a/src/main/java/kroppeb/stareval/function/FunctionContext.java b/src/main/java/kroppeb/stareval/function/FunctionContext.java index 94bd14f4ab..ae924554ba 100644 --- a/src/main/java/kroppeb/stareval/function/FunctionContext.java +++ b/src/main/java/kroppeb/stareval/function/FunctionContext.java @@ -4,5 +4,6 @@ public interface FunctionContext { Expression getVariable(String name); + boolean hasVariable(String name); } diff --git a/src/main/java/kroppeb/stareval/function/FunctionResolver.java b/src/main/java/kroppeb/stareval/function/FunctionResolver.java index 6de747852c..c6b4769eda 100644 --- a/src/main/java/kroppeb/stareval/function/FunctionResolver.java +++ b/src/main/java/kroppeb/stareval/function/FunctionResolver.java @@ -3,7 +3,12 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -13,8 +18,8 @@ public class FunctionResolver { private final Map>>> dynamicFunctions; public FunctionResolver( - Map>> functions, - Map>>> dynamicFunctions) { + Map>> functions, + Map>>> dynamicFunctions) { this.functions = functions; this.dynamicFunctions = dynamicFunctions; } @@ -49,6 +54,42 @@ public List resolve(String name, Type returnType) { return u; } + public void logAllFunctions() { + final Set names = new LinkedHashSet<>(); + names.addAll(this.functions.keySet()); + names.addAll(this.dynamicFunctions.keySet()); + for (final String name : names) { + final Map> overloads = new Object2ObjectLinkedOpenHashMap<>(); + Map> normal = this.functions.get(name); + if (normal != null) + overloads.putAll(normal); + + Map>> dynamic = this.dynamicFunctions.get(name); + if (dynamic != null) + overloads.putAll( + dynamic + .entrySet() + .stream() + .collect(Collectors.toMap( + Map.Entry::getKey, + entry -> entry.getValue() + .stream() + .map(Supplier::get) + .collect(Collectors.toList()) + ) + ) + ); + + for (Map.Entry> returnTypeOverloads : overloads.entrySet()) { + for (TypedFunction typedFunction : returnTypeOverloads.getValue()) { + System.out.println(TypedFunction.format(typedFunction, name)); + } + System.out.println(); + } + System.out.println(); + } + } + public static class Builder { private final Map> functions = new Object2ObjectLinkedOpenHashMap<>(); private final Map>>> dynamicFunctions = new Object2ObjectLinkedOpenHashMap<>(); @@ -63,9 +104,9 @@ public void addDynamic(String name, Type returnType, S public void addDynamicFunction(String name, Type returnType, Supplier function) { this.dynamicFunctions - .computeIfAbsent(name, (n) -> new Object2ObjectLinkedOpenHashMap<>()) - .computeIfAbsent(returnType, (n) -> new ObjectArrayList<>()) - .add(function); + .computeIfAbsent(name, (n) -> new Object2ObjectLinkedOpenHashMap<>()) + .computeIfAbsent(returnType, (n) -> new ObjectArrayList<>()) + .add(function); } public void addFunction(String name, TypedFunction function) { @@ -78,7 +119,7 @@ public FunctionResolver build() { Map> typeMap = new Object2ObjectLinkedOpenHashMap<>(); for (TypedFunction function : entry.getValue()) { typeMap.computeIfAbsent(function.getReturnType(), i -> new ObjectArrayList<>()) - .add(function); + .add(function); } functions.put(entry.getKey(), typeMap); } @@ -87,40 +128,4 @@ public FunctionResolver build() { } } - public void logAllFunctions() { - final Set names = new LinkedHashSet<>(); - names.addAll(this.functions.keySet()); - names.addAll(this.dynamicFunctions.keySet()); - for (final String name : names) { - final Map> overloads = new Object2ObjectLinkedOpenHashMap<>(); - Map> normal = this.functions.get(name); - if (normal != null) - overloads.putAll(normal); - - Map>> dynamic = this.dynamicFunctions.get(name); - if (dynamic != null) - overloads.putAll( - dynamic - .entrySet() - .stream() - .collect(Collectors.toMap( - Map.Entry::getKey, - entry -> entry.getValue() - .stream() - .map(Supplier::get) - .collect(Collectors.toList()) - ) - ) - ); - - for (Map.Entry> returnTypeOverloads : overloads.entrySet()) { - for (TypedFunction typedFunction : returnTypeOverloads.getValue()) { - System.out.println(TypedFunction.format(typedFunction, name)); - } - System.out.println(); - } - System.out.println(); - } - } - } diff --git a/src/main/java/kroppeb/stareval/function/Type.java b/src/main/java/kroppeb/stareval/function/Type.java index fd7cff31bf..437d8bb674 100644 --- a/src/main/java/kroppeb/stareval/function/Type.java +++ b/src/main/java/kroppeb/stareval/function/Type.java @@ -2,13 +2,42 @@ import kroppeb.stareval.expression.ConstantExpression; import kroppeb.stareval.function.TypedFunction.Parameter; -import net.coderbot.iris.gl.uniform.UniformType; -import net.coderbot.iris.parsing.MatrixType; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformType; +import net.irisshaders.iris.parsing.MatrixType; +import net.irisshaders.iris.parsing.VectorType; public abstract class Type { + public static Boolean Boolean = new Boolean(); + public static Int Int = new Int(); + public static Float Float = new Float(); + public static Parameter BooleanParameter = new Parameter(Boolean); + public static Parameter IntParameter = new Parameter(Int); + public static Parameter FloatParameter = new Parameter(Float); + public static Primitive[] AllPrimitives = {Type.Boolean, Type.Int, Type.Float}; + + @Deprecated + public static UniformType convert(Type type) { + if (type == Type.Int || type == Type.Boolean) return UniformType.INT; + else if (type == Type.Float) return UniformType.FLOAT; + else if (type == VectorType.VEC2) return UniformType.VEC2; + else if (type == VectorType.VEC3) return UniformType.VEC3; + else if (type == VectorType.VEC4) return UniformType.VEC4; + else if (type == VectorType.I_VEC2) return UniformType.VEC2I; + else if (type == VectorType.I_VEC3) return UniformType.VEC3I; + else if (type == MatrixType.MAT4) return UniformType.MAT4; + else throw new IllegalArgumentException("Unsupported custom uniform type: " + type); + } + public abstract ConstantExpression createConstant(FunctionReturn functionReturn); + public abstract Object createArray(int length); + + public abstract void setValueFromReturn(Object array, int index, FunctionReturn value); + + public abstract void getValueFromArray(Object array, int index, FunctionReturn value); + + public abstract String toString(); + public abstract static class Primitive extends Type { } @@ -151,35 +180,4 @@ public String toString() { return "float"; } } - - public static Boolean Boolean = new Boolean(); - public static Int Int = new Int(); - public static Float Float = new Float(); - - public static Parameter BooleanParameter = new Parameter(Boolean); - public static Parameter IntParameter = new Parameter(Int); - public static Parameter FloatParameter = new Parameter(Float); - - public static Primitive[] AllPrimitives = {Type.Boolean, Type.Int, Type.Float}; - - public abstract Object createArray(int length); - - public abstract void setValueFromReturn(Object array, int index, FunctionReturn value); - - public abstract void getValueFromArray(Object array, int index, FunctionReturn value); - - public abstract String toString(); - - @Deprecated - public static UniformType convert(Type type) { - if (type == Type.Int || type == Type.Boolean) return UniformType.INT; - else if (type == Type.Float) return UniformType.FLOAT; - else if (type == VectorType.VEC2) return UniformType.VEC2; - else if (type == VectorType.VEC3) return UniformType.VEC3; - else if (type == VectorType.VEC4) return UniformType.VEC4; - else if (type == VectorType.I_VEC2) return UniformType.VEC2I; - else if (type == VectorType.I_VEC3) return UniformType.VEC3I; - else if (type == MatrixType.MAT4) return UniformType.MAT4; - else throw new IllegalArgumentException("Unsupported custom uniform type: " + type); - } } diff --git a/src/main/java/kroppeb/stareval/function/TypedFunction.java b/src/main/java/kroppeb/stareval/function/TypedFunction.java index 3a0fb165a2..b9f2837c29 100644 --- a/src/main/java/kroppeb/stareval/function/TypedFunction.java +++ b/src/main/java/kroppeb/stareval/function/TypedFunction.java @@ -7,9 +7,22 @@ public interface TypedFunction { + static String format(TypedFunction function, String name) { + return String.format("%s %s(%s) (priority: %d, pure:%s)", + function.getReturnType().toString(), + name, + Arrays.stream(function.getParameters()) + .map(param -> param.constant() ? "const " + param.type() : param.type().toString()) + .collect(Collectors.joining(", ")), + function.priority(), + function.isPure() ? "yes" : "no" + ); + } + Type getReturnType(); Parameter[] getParameters(); + void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn); default boolean isPure() { @@ -41,17 +54,5 @@ public boolean constant() { return this.isConstant; } } - - static String format(TypedFunction function, String name) { - return String.format("%s %s(%s) (priority: %d, pure:%s)", - function.getReturnType().toString(), - name, - Arrays.stream(function.getParameters()) - .map(param -> param.constant() ? "const " + param.type() : param.type().toString()) - .collect(Collectors.joining(", ")), - function.priority(), - function.isPure() ? "yes" : "no" - ); - } } diff --git a/src/main/java/kroppeb/stareval/parser/OpResolver.java b/src/main/java/kroppeb/stareval/parser/OpResolver.java index 80307e712e..bd23378627 100644 --- a/src/main/java/kroppeb/stareval/parser/OpResolver.java +++ b/src/main/java/kroppeb/stareval/parser/OpResolver.java @@ -7,6 +7,7 @@ /** * OpResolver maps the trailing characters identifying an operator to an actual operator. + * * @param */ abstract class OpResolver { @@ -27,7 +28,7 @@ public void singleChar(T op) { * Adds a new multi-character operator. Calling this with an empty string is equivalent to calling singleChar. * * @param trailing every character after the first character of the operator. - * @param op the operator + * @param op the operator */ public void multiChar(String trailing, T op) { T previous = map.put(trailing, op); @@ -40,7 +41,7 @@ public void multiChar(String trailing, T op) { public OpResolver build() { if (map.size() > 2) { throw new RuntimeException("unimplemented: Cannot currently build an optimized operator resolver " + - "tree when more than two operators start with the same character"); + "tree when more than two operators start with the same character"); } T singleChar = map.get(""); @@ -57,33 +58,33 @@ public OpResolver build() { if (subEntry.getKey().length() != 1) { throw new RuntimeException("unimplemented: Optimized operator resolver trees can " + - "currently only be built of operators that contain one or two characters."); + "currently only be built of operators that contain one or two characters."); } // We can assume that this is the only other entry in the map due to the size check above return new OpResolver.SingleDualChar<>( - singleChar, - subEntry.getValue(), - subEntry.getKey().charAt(0) + singleChar, + subEntry.getValue(), + subEntry.getKey().charAt(0) ); } } } else { if (map.size() > 1) { throw new RuntimeException("unimplemented: Optimized operator resolver trees can currently only " + - "handle two operators starting with the same character if one operator is a single character"); + "handle two operators starting with the same character if one operator is a single character"); } for (Map.Entry subEntry : map.entrySet()) { if (subEntry.getKey().length() != 1) { throw new RuntimeException("unimplemented: Optimized operator resolver trees can " + - "currently only be built of operators that contain one or two characters."); + "currently only be built of operators that contain one or two characters."); } // We can assume that this is the only entry in the map due to the size check above. return new OpResolver.DualChar<>( - subEntry.getValue(), - subEntry.getKey().charAt(0) + subEntry.getValue(), + subEntry.getKey().charAt(0) ); } } diff --git a/src/main/java/kroppeb/stareval/parser/Parser.java b/src/main/java/kroppeb/stareval/parser/Parser.java index 4824c6f48b..ffde57fc7f 100644 --- a/src/main/java/kroppeb/stareval/parser/Parser.java +++ b/src/main/java/kroppeb/stareval/parser/Parser.java @@ -60,6 +60,10 @@ public class Parser { Parser() { } + public static ExpressionElement parse(String input, ParserOptions options) throws ParseException { + return Tokenizer.parse(input, options); + } + private Element peek() { if (!this.stack.isEmpty()) { return this.stack.get(this.stack.size() - 1); @@ -115,6 +119,8 @@ private ExpressionElement expressionReducePop(int priority) { return token; } + // visitor methods + /** * Executes following reduce step: *

    @@ -134,8 +140,8 @@ private void commaReduce(int index) throws ParseException { if (args == null) { throw new MissingTokenException( - "Expected an opening bracket '(' before seeing a comma ',' or closing bracket ')'", - index + "Expected an opening bracket '(' before seeing a comma ',' or closing bracket ')'", + index ); } @@ -143,13 +149,11 @@ private void commaReduce(int index) throws ParseException { ((UnfinishedArgsExpression) args).tokens.add(expr); } else { throw new UnexpectedTokenException( - "Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " + - "closing bracket ')' or a comma ','", index); + "Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " + + "closing bracket ')' or a comma ','", index); } } - // visitor methods - void visitId(String id) { this.push(new IdToken(id)); } @@ -213,8 +217,8 @@ void visitClosingParenthesis(int index) throws ParseException { if (!(pop instanceof UnfinishedArgsExpression)) { throw new UnexpectedTokenException( - "Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " + - "closing bracket ')' or a comma ','", index); + "Expected to see an opening bracket '(' or a comma ',' right before an expression followed by a " + + "closing bracket ')' or a comma ','", index); } args = (UnfinishedArgsExpression) pop; } @@ -287,8 +291,8 @@ ExpressionElement getFinal(int endIndex) throws ParseException { throw new MissingTokenException("Expected a closing bracket", endIndex); } else { throw new UnexpectedTokenException( - "The stack of tokens isn't empty at the end of the expression: " + this.stack + - " top: " + result, endIndex); + "The stack of tokens isn't empty at the end of the expression: " + this.stack + + " top: " + result, endIndex); } } else { Element top = this.peek(); @@ -296,20 +300,16 @@ ExpressionElement getFinal(int endIndex) throws ParseException { throw new MissingTokenException("Expected a closing bracket", endIndex); } else if (top instanceof PriorityOperatorElement) { throw new MissingTokenException( - "Expected a identifier, constant or subexpression on the right side of the operator", - endIndex); + "Expected a identifier, constant or subexpression on the right side of the operator", + endIndex); } else { throw new UnexpectedTokenException( - "The stack of tokens contains an unexpected token at the top: " + this.stack, - endIndex); + "The stack of tokens contains an unexpected token at the top: " + this.stack, + endIndex); } } } else { throw new MissingTokenException("The input seems to be empty", endIndex); } } - - public static ExpressionElement parse(String input, ParserOptions options) throws ParseException { - return Tokenizer.parse(input, options); - } } diff --git a/src/main/java/kroppeb/stareval/parser/ParserOptions.java b/src/main/java/kroppeb/stareval/parser/ParserOptions.java index 2c3ee04eda..b21fc20ec8 100644 --- a/src/main/java/kroppeb/stareval/parser/ParserOptions.java +++ b/src/main/java/kroppeb/stareval/parser/ParserOptions.java @@ -9,9 +9,9 @@ public final class ParserOptions { private final TokenRules tokenRules; private ParserOptions( - Char2ObjectMap> unaryOpResolvers, - Char2ObjectMap> binaryOpResolvers, - TokenRules tokenRules) { + Char2ObjectMap> unaryOpResolvers, + Char2ObjectMap> binaryOpResolvers, + TokenRules tokenRules) { this.unaryOpResolvers = unaryOpResolvers; this.binaryOpResolvers = binaryOpResolvers; this.tokenRules = tokenRules; @@ -29,52 +29,12 @@ OpResolver getBinaryOpResolver(char c) { return this.binaryOpResolvers.get(c); } - public static class Builder { - private final Char2ObjectMap> unaryOpResolvers = new Char2ObjectOpenHashMap<>(); - private final Char2ObjectMap> binaryOpResolvers = new Char2ObjectOpenHashMap<>(); - private TokenRules tokenRules = TokenRules.DEFAULT; - - public void addUnaryOp(String s, UnaryOp op) { - char first = s.charAt(0); - String trailing = s.substring(1); - - this.unaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op); - } - - public void addBinaryOp(String s, BinaryOp op) { - char first = s.charAt(0); - String trailing = s.substring(1); - - this.binaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op); - } - - public void setTokenRules(TokenRules tokenRules) { - this.tokenRules = tokenRules; - } - - private static Char2ObjectMap> buildOpResolvers( - Char2ObjectMap> ops) { - Char2ObjectMap> result = new Char2ObjectOpenHashMap<>(); - - ops.char2ObjectEntrySet().forEach( - entry -> result.put(entry.getCharKey(), entry.getValue().build())); - - return result; - } - - public ParserOptions build() { - return new ParserOptions( - buildOpResolvers(this.unaryOpResolvers), - buildOpResolvers(this.binaryOpResolvers), - this.tokenRules); - } - } - /** * Defines a set of rules that allows the tokenizer to identify tokens within a string. */ public interface TokenRules { - TokenRules DEFAULT = new TokenRules() {}; + TokenRules DEFAULT = new TokenRules() { + }; static boolean isNumber(final char c) { return c >= '0' && c <= '9'; @@ -116,4 +76,45 @@ default boolean isAccessPart(final char c) { return this.isAccessStart(c); } } + + public static class Builder { + private final Char2ObjectMap> unaryOpResolvers = new Char2ObjectOpenHashMap<>(); + private final Char2ObjectMap> binaryOpResolvers = new Char2ObjectOpenHashMap<>(); + private TokenRules tokenRules = TokenRules.DEFAULT; + + private static Char2ObjectMap> buildOpResolvers( + Char2ObjectMap> ops) { + Char2ObjectMap> result = new Char2ObjectOpenHashMap<>(); + + ops.char2ObjectEntrySet().forEach( + entry -> result.put(entry.getCharKey(), entry.getValue().build())); + + return result; + } + + public void addUnaryOp(String s, UnaryOp op) { + char first = s.charAt(0); + String trailing = s.substring(1); + + this.unaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op); + } + + public void addBinaryOp(String s, BinaryOp op) { + char first = s.charAt(0); + String trailing = s.substring(1); + + this.binaryOpResolvers.computeIfAbsent(first, (c) -> new OpResolver.Builder<>()).multiChar(trailing, op); + } + + public void setTokenRules(TokenRules tokenRules) { + this.tokenRules = tokenRules; + } + + public ParserOptions build() { + return new ParserOptions( + buildOpResolvers(this.unaryOpResolvers), + buildOpResolvers(this.binaryOpResolvers), + this.tokenRules); + } + } } diff --git a/src/main/java/kroppeb/stareval/resolver/ExpressionResolver.java b/src/main/java/kroppeb/stareval/resolver/ExpressionResolver.java index 22103db8f9..ca4ea3e0ef 100644 --- a/src/main/java/kroppeb/stareval/resolver/ExpressionResolver.java +++ b/src/main/java/kroppeb/stareval/resolver/ExpressionResolver.java @@ -12,10 +12,18 @@ import kroppeb.stareval.expression.ConstantExpression; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.expression.VariableExpression; -import kroppeb.stareval.function.*; +import kroppeb.stareval.function.FunctionContext; +import kroppeb.stareval.function.FunctionResolver; +import kroppeb.stareval.function.FunctionReturn; +import kroppeb.stareval.function.Type; +import kroppeb.stareval.function.TypedFunction; import kroppeb.stareval.function.TypedFunction.Parameter; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; @@ -23,20 +31,20 @@ public class ExpressionResolver { private final FunctionResolver functionResolver; private final Function variableTypeMap; private final boolean enableDebugging; - + private final Map numbers = new Object2ObjectOpenHashMap<>(); private List logs; public ExpressionResolver(FunctionResolver functionResolver, Function variableTypeMap) { this(functionResolver, variableTypeMap, false); } + public ExpressionResolver(FunctionResolver functionResolver, Function variableTypeMap, boolean enableDebugging) { this.functionResolver = functionResolver; this.variableTypeMap = variableTypeMap; this.enableDebugging = enableDebugging; } - public Expression resolveExpression(Type targetType, ExpressionElement expression) { this.clearLogs(); Expression result = this.resolveExpressionInternal(targetType, expression, true, true); @@ -47,10 +55,10 @@ public Expression resolveExpression(Type targetType, ExpressionElement expressio } Expression resolveCallExpressionInternal( - Type targetType, - String name, - List inner, - boolean implicit + Type targetType, + String name, + List inner, + boolean implicit ) { int innerLength = inner.size(); Expression result = null; @@ -71,7 +79,7 @@ Expression resolveCallExpressionInternal( } Expression expression = this.resolveExpressionInternal(param.type(), paramExpression, - !implicit || innerLength > 1, implicit); + !implicit || innerLength > 1, implicit); if (expression == null) continue functions; params[i] = expression; @@ -87,16 +95,15 @@ Expression resolveCallExpressionInternal( return result; } - private Expression resolveCallExpression( - Type targetType, - String name, - List inner, - boolean allowNonImplicit, - boolean allowImplicit) { + Type targetType, + String name, + List inner, + boolean allowNonImplicit, + boolean allowImplicit) { this.log("[DEBUG] resolving function %s with args %s to type %s", - name, inner, targetType); + name, inner, targetType); Expression result = null; @@ -106,11 +113,11 @@ private Expression resolveCallExpression( if (result != null) { this.log("[DEBUG] resolved function %s with args %s to type %s directly", - name, inner, targetType); + name, inner, targetType); return result; } else if (!allowImplicit) { this.log("[DEBUG] Failed to resolve function %s with args %s to type %s directly", - name, inner, targetType); + name, inner, targetType); return null; } @@ -126,17 +133,17 @@ private Expression resolveCallExpression( } if (result != null) { this.log("[DEBUG] resolved function %s with args %s to type %s using only final cast", - name, inner, targetType); + name, inner, targetType); return result; } result = this.resolveCallExpressionInternal(targetType, name, inner, true); if (result != null) { this.log("[DEBUG] resolved function %s with args %s to type %s using implicit inner casts", - name, inner, targetType); + name, inner, targetType); } else { this.log("[DEBUG] failed to resolve function %s with args %s to type %s", - name, inner, targetType); + name, inner, targetType); } return result; } @@ -167,35 +174,30 @@ private void log(Supplier str) { } private Expression resolveExpressionInternal( - Type targetType, - ExpressionElement expression, - boolean allowNonImplicit, - boolean allowImplicit) { + Type targetType, + ExpressionElement expression, + boolean allowNonImplicit, + boolean allowImplicit) { Expression castable; Type innerType; this.log("[DEBUG] resolving %s to type %s (%d%d)", - expression, targetType, allowNonImplicit ? 1 : 0, allowImplicit ? 1 : 0); - if (expression instanceof UnaryExpressionElement) { + expression, targetType, allowNonImplicit ? 1 : 0, allowImplicit ? 1 : 0); + if (expression instanceof UnaryExpressionElement token) { // I want my pattern matching =( - UnaryExpressionElement token = (UnaryExpressionElement) expression; return this.resolveCallExpression(targetType, token.getOp().getName(), Collections.singletonList(token.getInner()), - allowNonImplicit, allowImplicit); - } else if (expression instanceof BinaryExpressionElement) { - BinaryExpressionElement token = (BinaryExpressionElement) expression; + allowNonImplicit, allowImplicit); + } else if (expression instanceof BinaryExpressionElement token) { return this.resolveCallExpression(targetType, token.getOp().getName(), Arrays.asList(token.getLeft(), token.getRight()), - allowNonImplicit, allowImplicit); - } else if (expression instanceof FunctionCall) { - FunctionCall token = (FunctionCall) expression; + allowNonImplicit, allowImplicit); + } else if (expression instanceof FunctionCall token) { return this.resolveCallExpression(targetType, token.getId(), token.getArgs(), - allowNonImplicit, allowImplicit); - } else if (expression instanceof AccessExpressionElement) { - AccessExpressionElement token = (AccessExpressionElement) expression; + allowNonImplicit, allowImplicit); + } else if (expression instanceof AccessExpressionElement token) { return this.resolveCallExpression(targetType, "", - Collections.singletonList(token.getBase()), - allowNonImplicit, allowImplicit); - } else if (expression instanceof NumberToken) { - NumberToken token = (NumberToken) expression; + Collections.singletonList(token.getBase()), + allowNonImplicit, allowImplicit); + } else if (expression instanceof NumberToken token) { ConstantExpression exp = this.resolveNumber(token.getNumber()); if (exp.getType().equals(targetType)) { this.log("[DEBUG] resolved constant %s to type %s", token.getNumber(), targetType); @@ -204,15 +206,14 @@ private Expression resolveExpressionInternal( // TODO: implicit casting is split up too much if (!allowImplicit) { this.log("[DEBUG] failed to resolve constant %s (of type %s) to type %s without implicit casts", - token.getNumber(), exp.getType(), targetType); + token.getNumber(), exp.getType(), targetType); return null; } this.log("[DEBUG] trying implicit casts to resolve constant %s (of type %s) to type %s", - token.getNumber(), exp.getType(), targetType); + token.getNumber(), exp.getType(), targetType); castable = exp; innerType = exp.getType(); - } else if (expression instanceof IdToken) { - IdToken token = (IdToken) expression; + } else if (expression instanceof IdToken token) { final String name = token.getId(); Type type = this.variableTypeMap.apply(name); if (type == null) @@ -229,13 +230,13 @@ public void evaluateTo(FunctionContext c, FunctionReturn r) { @Override public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) { - return context.hasVariable(name)?context.getVariable(name):this; + return context.hasVariable(name) ? context.getVariable(name) : this; } }; } if (!allowImplicit) { log("[DEBUG] failed to resolve variable %s (of type %s) to type %s without implicit casts", - name, type, targetType); + name, type, targetType); return null; } // TODO duplicate of above @@ -247,7 +248,7 @@ public void evaluateTo(FunctionContext c, FunctionReturn r) { @Override public Expression partialEval(FunctionContext context, FunctionReturn functionReturn) { - return context.hasVariable(name)?context.getVariable(name):this; + return context.hasVariable(name) ? context.getVariable(name) : this; } }; innerType = type; @@ -260,7 +261,7 @@ public Expression partialEval(FunctionContext context, FunctionReturn functionRe for (TypedFunction f : casts) { if (f.getParameters()[0].type().equals(innerType)) { this.log("[DEBUG] resolved %s to type %s using implicit casts", - expression, targetType); + expression, targetType); return new CallExpression(f, new Expression[]{castable}); } } @@ -268,8 +269,6 @@ public Expression partialEval(FunctionContext context, FunctionReturn functionRe return null; } - private final Map numbers = new Object2ObjectOpenHashMap<>(); - private ConstantExpression resolveNumber(String s) { return this.numbers.computeIfAbsent(s, str -> { NumberFormatException p; diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BlendingStateHolder.java b/src/main/java/net/coderbot/batchedentityrendering/impl/BlendingStateHolder.java deleted file mode 100644 index 723902f2ec..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BlendingStateHolder.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -public interface BlendingStateHolder { - TransparencyType getTransparencyType(); - - void setTransparencyType(TransparencyType transparencyType); -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferBuilderExt.java b/src/main/java/net/coderbot/batchedentityrendering/impl/BufferBuilderExt.java deleted file mode 100644 index 720e03949c..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferBuilderExt.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -import com.mojang.blaze3d.vertex.BufferBuilder; - -import java.nio.ByteBuffer; - -public interface BufferBuilderExt { - void splitStrip(); -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegmentRenderer.java b/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegmentRenderer.java deleted file mode 100644 index f67be19b52..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegmentRenderer.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -import com.mojang.blaze3d.vertex.BufferUploader; - -public class BufferSegmentRenderer { - public BufferSegmentRenderer() { - } - - /** - * Sets up the render type, draws the buffer, and then tears down the render type. - */ - public void draw(BufferSegment segment) { - if (segment.renderedBuffer() != null) { - segment.type().setupRenderState(); - drawInner(segment); - segment.type().clearRenderState(); - } - } - - /** - * Like draw(), but it doesn't setup / tear down the render type. - */ - public void drawInner(BufferSegment segment) { - BufferUploader.drawWithShader(segment.renderedBuffer()); - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/Groupable.java b/src/main/java/net/coderbot/batchedentityrendering/impl/Groupable.java deleted file mode 100644 index 343d094d77..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/Groupable.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -public interface Groupable { - void startGroup(); - boolean maybeStartGroup(); - void endGroup(); -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java b/src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java deleted file mode 100644 index 7414dce9e6..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -public interface MemoryTrackingRenderBuffers { - int getEntityBufferAllocatedSize(); - int getMiscBufferAllocatedSize(); - int getMaxBegins(); - void freeAndDeleteBuffers(); -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/RenderTypeUtil.java b/src/main/java/net/coderbot/batchedentityrendering/impl/RenderTypeUtil.java deleted file mode 100644 index 9d3e3d1566..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/RenderTypeUtil.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderType; - -public class RenderTypeUtil { - public static boolean isTriangleStripDrawMode(RenderType renderType) { - return renderType.mode() == VertexFormat.Mode.TRIANGLE_STRIP; - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java b/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java deleted file mode 100644 index 17065ce465..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/SegmentedBufferBuilder.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.coderbot.batchedentityrendering.impl; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.coderbot.batchedentityrendering.mixin.RenderTypeAccessor; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public class SegmentedBufferBuilder implements MultiBufferSource, MemoryTrackingBuffer { - private final BufferBuilder buffer; - private RenderType currentType; - private final List buffers; - - public SegmentedBufferBuilder() { - // 2 MB initial allocation - this.buffer = new BufferBuilder(512 * 1024); - this.buffers = new ArrayList<>(); - this.currentType = null; - } - - @Override - public VertexConsumer getBuffer(RenderType renderType) { - if (!Objects.equals(currentType, renderType)) { - if (currentType != null) { - if (shouldSortOnUpload(currentType)) { - buffer.setQuadSorting(RenderSystem.getVertexSorting()); - } - - buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); - } - - buffer.begin(renderType.mode(), renderType.format()); - - currentType = renderType; - } - - // Use duplicate vertices to break up triangle strips - // https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/Art/degenerate_triangle_strip_2x.png - // This works by generating zero-area triangles that don't end up getting rendered. - // TODO: How do we handle DEBUG_LINE_STRIP? - if (RenderTypeUtil.isTriangleStripDrawMode(currentType)) { - ((BufferBuilderExt) buffer).splitStrip(); - } - - return buffer; - } - - public List getSegments() { - if (currentType == null) { - return Collections.emptyList(); - } - - if (shouldSortOnUpload(currentType)) { - buffer.setQuadSorting(RenderSystem.getVertexSorting()); - } - - buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); - - currentType = null; - - List finalSegments = new ArrayList<>(buffers); - - buffers.clear(); - - return finalSegments; - } - - public List getSegmentsForType(TransparencyType transparencyType) { - if (currentType == null) { - return Collections.emptyList(); - } - - if (((BlendingStateHolder) currentType).getTransparencyType() == transparencyType) { - if (shouldSortOnUpload(currentType)) { - buffer.setQuadSorting(RenderSystem.getVertexSorting()); - } - - buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); - - currentType = null; - } - - List finalSegments = buffers.stream().filter(segment -> ((BlendingStateHolder) segment.type()).getTransparencyType() == transparencyType).toList(); - - buffers.removeAll(finalSegments); - - return finalSegments; - } - - private static boolean shouldSortOnUpload(RenderType type) { - return ((RenderTypeAccessor) type).shouldSortOnUpload(); - } - - @Override - public int getAllocatedSize() { - return ((MemoryTrackingBuffer) buffer).getAllocatedSize(); - } - - @Override - public int getUsedSize() { - return ((MemoryTrackingBuffer) buffer).getUsedSize(); - } - - @Override - public void freeAndDeleteBuffer() { - ((MemoryTrackingBuffer) buffer).freeAndDeleteBuffer(); - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java deleted file mode 100644 index 6eae98ee0c..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java +++ /dev/null @@ -1,146 +0,0 @@ -package net.coderbot.batchedentityrendering.impl.ordering; - -import de.odysseus.ithaka.digraph.Digraph; -import de.odysseus.ithaka.digraph.Digraphs; -import de.odysseus.ithaka.digraph.MapDigraph; -import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSet; -import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetPolicy; -import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetProvider; -import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import net.minecraft.client.renderer.RenderType; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; - -public class GraphTranslucencyRenderOrderManager implements RenderOrderManager { - private final FeedbackArcSetProvider feedbackArcSetProvider; - private final EnumMap> types; - - private boolean inGroup = false; - private final EnumMap currentTypes; - - public GraphTranslucencyRenderOrderManager() { - feedbackArcSetProvider = new SimpleFeedbackArcSetProvider(); - types = new EnumMap<>(TransparencyType.class); - currentTypes = new EnumMap<>(TransparencyType.class); - - for (TransparencyType type : TransparencyType.values()) { - types.put(type, new MapDigraph<>()); - } - } - - private static TransparencyType getTransparencyType(RenderType type) { - while (type instanceof WrappableRenderType) { - type = ((WrappableRenderType) type).unwrap(); - } - - if (type instanceof BlendingStateHolder) { - return ((BlendingStateHolder) type).getTransparencyType(); - } - - // Default to "generally transparent" if we can't figure it out. - return TransparencyType.GENERAL_TRANSPARENT; - } - - public void begin(RenderType renderType) { - TransparencyType transparencyType = getTransparencyType(renderType); - Digraph graph = types.get(transparencyType); - graph.add(renderType); - - if (inGroup) { - RenderType previous = currentTypes.put(transparencyType, renderType); - - if (previous == null) { - return; - } - - int weight = graph.get(previous, renderType).orElse(0); - weight += 1; - graph.put(previous, renderType, weight); - } - } - - public void startGroup() { - if (inGroup) { - throw new IllegalStateException("Already in a group"); - } - - currentTypes.clear(); - inGroup = true; - } - - public boolean maybeStartGroup() { - if (inGroup) { - return false; - } - - currentTypes.clear(); - inGroup = true; - return true; - } - - public void endGroup() { - if (!inGroup) { - throw new IllegalStateException("Not in a group"); - } - - currentTypes.clear(); - inGroup = false; - } - - @Override - public void reset() { - // TODO: Is reallocation efficient? - types.clear(); - - for (TransparencyType type : TransparencyType.values()) { - types.put(type, new MapDigraph<>()); - } - } - - @Override - public void resetType(TransparencyType type) { - // TODO: Is reallocation efficient? - types.put(type, new MapDigraph<>()); - } - - public List getRenderOrder() { - int layerCount = 0; - - for (Digraph graph : types.values()) { - layerCount += graph.getVertexCount(); - } - - List allLayers = new ArrayList<>(layerCount); - - for (Digraph graph : types.values()) { - // TODO: Make sure that FAS can't become a bottleneck! - // Running NP-hard algorithms in a real time rendering loop might not be an amazing idea. - // This shouldn't be necessary in sane scenes, though, and if there aren't cycles, - // then this *should* be relatively inexpensive, since it'll bail out and return an empty set. - FeedbackArcSet arcSet = - feedbackArcSetProvider.getFeedbackArcSet(graph, graph, FeedbackArcSetPolicy.MIN_WEIGHT); - - if (arcSet.getEdgeCount() > 0) { - // This means that our dependency graph had cycles!!! - // This is very weird and isn't expected - but we try to handle it gracefully anyways. - - // Our feedback arc set algorithm finds some dependency links that can be removed hopefully - // without disrupting the overall order too much. Hopefully it isn't too slow! - for (RenderType source : arcSet.vertices()) { - for (RenderType target : arcSet.targets(source)) { - graph.remove(source, target); - } - } - } - - allLayers.addAll(Digraphs.toposort(graph, false)); - } - - return allLayers; - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java deleted file mode 100644 index 6756fe048b..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/RenderOrderManager.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.coderbot.batchedentityrendering.impl.ordering; - -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.minecraft.client.renderer.RenderType; - -import java.util.List; - -public interface RenderOrderManager { - void begin(RenderType type); - void startGroup(); - boolean maybeStartGroup(); - void endGroup(); - void reset(); - - void resetType(TransparencyType type); - - List getRenderOrder(); -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java deleted file mode 100644 index 8396f2fd97..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.coderbot.batchedentityrendering.impl.ordering; - -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.minecraft.client.renderer.RenderType; - -import java.util.LinkedHashSet; -import java.util.List; - -public class SimpleRenderOrderManager implements RenderOrderManager { - private final LinkedHashSet renderTypes; - - public SimpleRenderOrderManager() { - renderTypes = new LinkedHashSet<>(); - } - - public void begin(RenderType type) { - renderTypes.add(type); - } - - public void startGroup() { - // no-op - } - - public boolean maybeStartGroup() { - // no-op - return false; - } - - public void endGroup() { - // no-op - } - - @Override - public void reset() { - renderTypes.clear(); - } - - @Override - public void resetType(TransparencyType type) { - - } - - public List getRenderOrder() { - return List.copyOf(renderTypes); - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java b/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java deleted file mode 100644 index 2b459e262f..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.coderbot.batchedentityrendering.impl.ordering; - -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import net.minecraft.client.renderer.RenderType; - -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.LinkedHashSet; -import java.util.List; - -public class TranslucencyRenderOrderManager implements RenderOrderManager { - private final EnumMap> renderTypes; - - public TranslucencyRenderOrderManager() { - renderTypes = new EnumMap<>(TransparencyType.class); - - for (TransparencyType type : TransparencyType.values()) { - renderTypes.put(type, new LinkedHashSet<>()); - } - } - - private static TransparencyType getTransparencyType(RenderType type) { - while (type instanceof WrappableRenderType) { - type = ((WrappableRenderType) type).unwrap(); - } - - if (type instanceof BlendingStateHolder) { - return ((BlendingStateHolder) type).getTransparencyType(); - } - - // Default to "generally transparent" if we can't figure it out. - return TransparencyType.GENERAL_TRANSPARENT; - } - - public void begin(RenderType type) { - renderTypes.get(getTransparencyType(type)).add(type); - } - - public void startGroup() { - // no-op - } - - public boolean maybeStartGroup() { - // no-op - return false; - } - - public void endGroup() { - // no-op - } - - @Override - public void reset() { - renderTypes.forEach((type, set) -> { - set.clear(); - }); - } - - @Override - public void resetType(TransparencyType type) { - renderTypes.get(type).clear(); - } - - public List getRenderOrder() { - int layerCount = 0; - - for (LinkedHashSet set : renderTypes.values()) { - layerCount += set.size(); - } - - List allRenderTypes = new ArrayList<>(layerCount); - - for (LinkedHashSet set : renderTypes.values()) { - allRenderTypes.addAll(set); - } - - return allRenderTypes; - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java b/src/main/java/net/coderbot/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java deleted file mode 100644 index f9c96d1a95..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java +++ /dev/null @@ -1,68 +0,0 @@ -package net.coderbot.batchedentityrendering.impl.wrappers; - -import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import net.coderbot.batchedentityrendering.mixin.RenderTypeAccessor; -import net.minecraft.client.renderer.RenderType; -import org.jetbrains.annotations.Nullable; - -import java.util.Objects; -import java.util.Optional; - -public class TaggingRenderTypeWrapper extends RenderType implements WrappableRenderType { - private final int tag; - private final RenderType wrapped; - - public TaggingRenderTypeWrapper(String name, RenderType wrapped, int tag) { - super(name, wrapped.format(), wrapped.mode(), wrapped.bufferSize(), - wrapped.affectsCrumbling(), shouldSortOnUpload(wrapped), wrapped::setupRenderState, wrapped::clearRenderState); - - this.tag = tag; - this.wrapped = wrapped; - } - - @Override - public RenderType unwrap() { - return this.wrapped; - } - - @Override - public Optional outline() { - return this.wrapped.outline(); - } - - @Override - public boolean isOutline() { - return this.wrapped.isOutline(); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object == null) { - return false; - } - - if (object.getClass() != this.getClass()) { - return false; - } - - TaggingRenderTypeWrapper other = (TaggingRenderTypeWrapper) object; - - return this.tag == other.tag && Objects.equals(this.wrapped, other.wrapped); - } - - @Override - public int hashCode() { - // Add one so that we don't have the exact same hash as the wrapped object. - // This means that we won't have a guaranteed collision if we're inserted to a map alongside the unwrapped object. - return this.wrapped.hashCode() + 1; - } - - @Override - public String toString() { - return "tagged(" +tag+ "):" + this.wrapped.toString(); - } - - private static boolean shouldSortOnUpload(RenderType type) { - return ((RenderTypeAccessor) type).shouldSortOnUpload(); - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java b/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java deleted file mode 100644 index 3d40f43829..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java +++ /dev/null @@ -1,65 +0,0 @@ -package net.coderbot.batchedentityrendering.mixin; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.datafixers.util.Pair; -import net.coderbot.batchedentityrendering.impl.Groupable; -import net.coderbot.batchedentityrendering.impl.wrappers.TaggingRenderTypeWrapper; -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.blockentity.BannerRenderer; -import net.minecraft.client.resources.model.Material; -import net.minecraft.world.item.DyeColor; -import net.minecraft.world.level.block.entity.BannerPattern; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; - -/** - * This Mixin groups banner patterns separately, to not batch the wrong patterns. - * It has been disabled for now, as the behavior seems to not be required. (IMS, September 2, 2022) - */ -@Mixin(BannerRenderer.class) -public class MixinBannerRenderer_Disabled { - private static final String RENDER_PATTERNS = - "Lnet/minecraft/client/renderer/blockentity/BannerRenderer;renderPatterns(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/model/geom/ModelPart;Lnet/minecraft/client/resources/model/Material;ZLjava/util/List;Z)V"; - - /** - * Holds a Groupable instance, if we successfully started a group. - * This is because we need to make sure to end the group that we started. - */ - @Unique - private static Groupable groupableToEnd; - private static int index; - - @ModifyVariable(method = RENDER_PATTERNS, at = @At("HEAD"), argsOnly = true) - private static MultiBufferSource iris$wrapBufferSource(MultiBufferSource multiBufferSource) { - if (multiBufferSource instanceof Groupable) { - Groupable groupable = (Groupable) multiBufferSource; - boolean started = groupable.maybeStartGroup(); - - if (started) { - groupableToEnd = groupable; - } - - index = 0; - // NB: Groupable not needed for this implementation of MultiBufferSource. - return type -> multiBufferSource.getBuffer(new TaggingRenderTypeWrapper(type.toString(), type, index++)); - } - - return multiBufferSource; - } - - @Inject(method = RENDER_PATTERNS, at = @At("RETURN")) - private static void iris$endRenderingCanvas(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j, ModelPart modelPart, Material material, boolean bl, List> list, boolean bl2, CallbackInfo ci) { - if (groupableToEnd != null) { - groupableToEnd.endGroup(); - groupableToEnd = null; - index = 0; - } - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java b/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java deleted file mode 100644 index 6a0937324d..0000000000 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java +++ /dev/null @@ -1,74 +0,0 @@ -package net.coderbot.batchedentityrendering.mixin; - -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.batchedentityrendering.impl.BufferBuilderExt; -import net.minecraft.util.Mth; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexFormat; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.nio.ByteBuffer; -import java.util.List; - -@Mixin(BufferBuilder.class) -public class MixinBufferBuilder_SegmentRendering implements BufferBuilderExt { - @Shadow - private ByteBuffer buffer; - - @Shadow - private VertexFormat format; - - @Shadow - private int vertices; - - @Shadow - protected void ensureVertexCapacity() { - throw new AssertionError("not shadowed"); - } - - @Shadow - private int nextElementByte; - - @Override - public void splitStrip() { - if (vertices == 0) { - // no strip to split, not building. - return; - } - - duplicateLastVertex(); - dupeNextVertex = true; - } - - @Unique - private boolean dupeNextVertex; - - private void duplicateLastVertex() { - int i = this.format.getVertexSize(); - this.buffer.put(this.nextElementByte, this.buffer, this.nextElementByte - i, i); - this.nextElementByte += i; - ++this.vertices; - this.ensureVertexCapacity(); - } - - @Inject(method = "end", at = @At("RETURN")) - private void batchedentityrendering$onEnd(CallbackInfoReturnable cir) { - dupeNextVertex = false; - } - - @Inject(method = "endVertex", at = @At("RETURN")) - private void batchedentityrendering$onNext(CallbackInfo ci) { - if (dupeNextVertex) { - dupeNextVertex = false; - duplicateLastVertex(); - } - } -} diff --git a/src/main/java/net/coderbot/iris/LaunchWarn.java b/src/main/java/net/coderbot/iris/LaunchWarn.java deleted file mode 100644 index 30ee3c91e9..0000000000 --- a/src/main/java/net/coderbot/iris/LaunchWarn.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.coderbot.iris; - -import javax.swing.JOptionPane; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import java.awt.Desktop; -import java.awt.GraphicsEnvironment; -import java.io.IOException; -import java.net.URI; - -public class LaunchWarn { - public static void main(String[] args) { - // TODO: make this translatable - String message = "This file is the Forge version of Oculus, meant to be installed as a mod. Would you like to get the Forge Installer instead?"; - String fallback = "This file is the Forge version of Oculus, meant to be installed as a mod. Please download the Forge Installer from https://neoforged.net/"; - if (GraphicsEnvironment.isHeadless()) { - System.err.println(fallback); - } else { - try { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (ReflectiveOperationException | UnsupportedLookAndFeelException ignored) { - // Ignored - } - - if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { - int option = JOptionPane.showOptionDialog(null, message, "Oculus Installer", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); - - if (option == JOptionPane.YES_OPTION) { - try { - Desktop.getDesktop().browse(URI.create("https://neoforged.net")); - } catch (IOException e) { - e.printStackTrace(); - } - } - } else { - // Fallback for Linux, etc users with no "default" browser - JOptionPane.showMessageDialog(null, fallback); - } - } - - System.exit(0); - } -} diff --git a/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java b/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java deleted file mode 100644 index e30dfec871..0000000000 --- a/src/main/java/net/coderbot/iris/compat/dh/DHCompat.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.coderbot.iris.compat.dh; - -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; - -public class DHCompat { - private GlFramebuffer fb; - - public int getFramebuffer() { - return fb.getId(); - } - - public void setFramebuffer(GlFramebuffer fb) { - this.fb = fb; - } -} diff --git a/src/main/java/net/coderbot/iris/compat/dh/mixin/IrisDHCompatMixinPlugin.java b/src/main/java/net/coderbot/iris/compat/dh/mixin/IrisDHCompatMixinPlugin.java deleted file mode 100644 index d7e39b6728..0000000000 --- a/src/main/java/net/coderbot/iris/compat/dh/mixin/IrisDHCompatMixinPlugin.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.coderbot.iris.compat.dh.mixin; - -import net.minecraftforge.fml.loading.FMLLoader; -import org.objectweb.asm.tree.ClassNode; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; - -import java.util.List; -import java.util.Set; - -/** - * Non-critical mixin config plugin, just disables mixins if Distant Horizons isn't present, - * since otherwise the log gets spammed with warnings. - */ -public class IrisDHCompatMixinPlugin implements IMixinConfigPlugin { - @Override - public void onLoad(String mixinPackage) { - - } - - @Override - public String getRefMapperConfig() { - return null; - } - - @Override - public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { - return FMLLoader.getLoadingModList().getModFileById("distanthorizons") != null; - } - - @Override - public void acceptTargets(Set myTargets, Set otherTargets) { - - } - - @Override - public List getMixins() { - return null; - } - - @Override - public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } - - @Override - public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } -} diff --git a/src/main/java/net/coderbot/iris/compat/dh/mixin/MixinDHApplyShader.java b/src/main/java/net/coderbot/iris/compat/dh/mixin/MixinDHApplyShader.java deleted file mode 100644 index 9880c13d52..0000000000 --- a/src/main/java/net/coderbot/iris/compat/dh/mixin/MixinDHApplyShader.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.coderbot.iris.compat.dh.mixin; - -import com.seibel.distanthorizons.core.render.renderer.shaders.DhApplyShader; -import com.seibel.distanthorizons.core.wrapperInterfaces.minecraft.IMinecraftRenderWrapper; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.dh.DHCompat; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.NewWorldRenderingPipeline; -import net.irisshaders.iris.api.v0.IrisApi; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(value = DhApplyShader.class, remap = false) -public class MixinDHApplyShader { - @Redirect(method = "onRender", at = @At(value = "INVOKE", target = "Lcom/seibel/distanthorizons/core/wrapperInterfaces/minecraft/IMinecraftRenderWrapper;getTargetFrameBuffer()I")) - private int changeFB(IMinecraftRenderWrapper instance) { - if (Iris.getPipelineManager().getPipelineNullable() instanceof NewWorldRenderingPipeline pipeline) { - return pipeline.getDHCompat().getFramebuffer(); - } else { - return instance.getTargetFrameBuffer(); - } - } -} diff --git a/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/MixinNormalizedFace.java b/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/MixinNormalizedFace.java deleted file mode 100644 index 214530d4fd..0000000000 --- a/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/MixinNormalizedFace.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.coderbot.iris.compat.pixelmon.mixin; - -import com.mojang.blaze3d.vertex.BufferBuilder; -import org.objectweb.asm.Opcodes; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Pseudo; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Coerce; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Pseudo -@Mixin(targets = {"com/pixelmonmod/pixelmon/client/models/smd/NormalizedFace"}) -public class MixinNormalizedFace { - /** - * @author embeddedt (original idea by NanoLive) - * @reason Pixelmon manipulates the buffer of a {@link BufferBuilder} directly which causes problems. - * We bypass that code path. - */ - @Redirect(method = "addFaceForRender", at = @At(value = "FIELD", opcode = Opcodes.GETFIELD, target = "Lcom/pixelmonmod/pixelmon/client/models/smd/DeformVertex;id2:I")) - public int hideBufferBuilderId(@Coerce Object instance) { - return -1; // prevent using "optimized" code path - } -} diff --git a/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/OculusPixelmonCompatMixinPlugin.java b/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/OculusPixelmonCompatMixinPlugin.java deleted file mode 100644 index 9189816f7c..0000000000 --- a/src/main/java/net/coderbot/iris/compat/pixelmon/mixin/OculusPixelmonCompatMixinPlugin.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.coderbot.iris.compat.pixelmon.mixin; - -import net.minecraftforge.fml.loading.FMLLoader; -import org.objectweb.asm.tree.ClassNode; -import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; - -import java.util.List; -import java.util.Set; - -public class OculusPixelmonCompatMixinPlugin implements IMixinConfigPlugin { - @Override - public void onLoad(String mixinPackage) { - - } - - @Override - public String getRefMapperConfig() { - return null; - } - - @Override - public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { - return FMLLoader.getLoadingModList().getModFileById("pixelmon") != null; - } - - @Override - public void acceptTargets(Set myTargets, Set otherTargets) { - - } - - @Override - public List getMixins() { - return null; - } - - @Override - public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } - - @Override - public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { - - } -} \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java deleted file mode 100644 index da1c59a9a9..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/InputAvailability.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.matching; - -public class InputAvailability { - public static final int NUM_VALUES = 8; - - public final boolean texture; - public final boolean lightmap; - public final boolean overlay; - // WARNING: adding new fields requires updating hashCode and equals methods! - - public InputAvailability(boolean texture, boolean lightmap, boolean overlay) { - this.texture = texture; - this.lightmap = lightmap; - this.overlay = overlay; - } - - public InputAvailability withoutOverlay() { - return new InputAvailability(texture, lightmap, false); - } - - public static InputAvailability unpack(int packed) { - return new InputAvailability((packed & 1) == 1, (packed & 2) == 2, (packed & 4) == 4); - } - - public int pack() { - int packed = 0; - - if (overlay) { - packed |= 4; - } - - if (lightmap) { - packed |= 2; - } - - if (texture) { - packed |= 1; - } - - return packed; - } - - @Override - public String toString() { - return "InputAvailability{" + - "texture=" + texture + - ", lightmap=" + lightmap + - ", overlay=" + overlay + - '}'; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (texture ? 1231 : 1237); - result = prime * result + (lightmap ? 1231 : 1237); - result = prime * result + (overlay ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - InputAvailability other = (InputAvailability) obj; - if (texture != other.texture) - return false; - if (lightmap != other.lightmap) - return false; - if (overlay != other.overlay) - return false; - return true; - } -} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/ProgramTable.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/ProgramTable.java deleted file mode 100644 index e581a4830c..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/ProgramTable.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.matching; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Consumer; - -public class ProgramTable { - private final List table = new ArrayList<>(); - - public ProgramTable(BiFunction constructor) { - for (RenderCondition condition : RenderCondition.values()) { - for (int packedAvailability = 0; packedAvailability < InputAvailability.NUM_VALUES; packedAvailability++) { - InputAvailability availability = InputAvailability.unpack(packedAvailability); - - table.add(constructor.apply(condition, availability)); - } - } - } - - // TODO: Remove InputAvailability allocations? - public T match(RenderCondition condition, InputAvailability availability) { - int index = (condition.ordinal() * InputAvailability.NUM_VALUES) + availability.pack(); - - return table.get(index); - } - - public void forEach(Consumer consumer) { - table.forEach(consumer); - } -} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java deleted file mode 100644 index 2583362747..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/RenderCondition.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.matching; - -public enum RenderCondition { - DEFAULT, - SKY, - TERRAIN_OPAQUE, - TERRAIN_TRANSLUCENT, - CLOUDS, - DESTROY, - BLOCK_ENTITIES, - BEACON_BEAM, - ENTITIES, - ENTITIES_TRANSLUCENT, - GLINT, - ENTITY_EYES, - HAND_OPAQUE, - HAND_TRANSLUCENT, - RAIN_SNOW, - WORLD_BORDER, - // NB: Must be last due to implementation details of DeferredWorldRenderingPipeline - SHADOW -} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java deleted file mode 100644 index deeb20933c..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/matching/SpecialCondition.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.matching; - -public enum SpecialCondition { - ENTITY_EYES, - BEACON_BEAM, - GLINT -} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/RenderTargetStateListener.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/state/RenderTargetStateListener.java deleted file mode 100644 index a3a7a9212e..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/RenderTargetStateListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.state; - -public interface RenderTargetStateListener { - RenderTargetStateListener NOP = new RenderTargetStateListener() { - @Override - public void beginPostChain() { - - } - - @Override - public void endPostChain() { - - } - - @Override - public void setIsMainBound(boolean bound) { - - } - }; - - void beginPostChain(); - void endPostChain(); - - void setIsMainBound(boolean bound); -} diff --git a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java b/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java deleted file mode 100644 index bf6c6e982b..0000000000 --- a/src/main/java/net/coderbot/iris/gbuffer_overrides/state/StateTracker.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.coderbot.iris.gbuffer_overrides.state; - -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; - -public class StateTracker { - public static final StateTracker INSTANCE = new StateTracker(); - - // All textures are disabled by default - - // TextureStateShard / TextureUnit.TERRAIN - public boolean albedoSampler; - // LightmapStateShard / TextureUnit.LIGHTMAP - public boolean lightmapSampler; - // OverlayStateShard / TextureUnit.OVERLAY - public boolean overlaySampler; - - public InputAvailability getInputs() { - return new InputAvailability(albedoSampler, - lightmapSampler, - overlaySampler); - } -} diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestOverride.java b/src/main/java/net/coderbot/iris/gl/blending/AlphaTestOverride.java deleted file mode 100644 index 3df5d59072..0000000000 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestOverride.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.coderbot.iris.gl.blending; - -public class AlphaTestOverride { - public static final AlphaTestOverride OFF = new AlphaTestOverride(null); - - private final AlphaTest alphaTest; - - public AlphaTestOverride(AlphaTest alphaTest) { - this.alphaTest = alphaTest; - } - - public void apply() { - AlphaTestStorage.overrideAlphaTest(this.alphaTest); - } - - public static void restore() { - AlphaTestStorage.restoreAlphaTest(); - } -} diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java b/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java deleted file mode 100644 index ab3a259f11..0000000000 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestStorage.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.coderbot.iris.gl.blending; - -import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.mixin.statelisteners.BooleanStateAccessor; - -public class AlphaTestStorage { - private static boolean originalAlphaTestEnable; - private static AlphaTest originalAlphaTest; - private static boolean alphaTestLocked; - - public static boolean isAlphaTestLocked() { - return alphaTestLocked; - } - - public static void overrideAlphaTest(AlphaTest override) { - /*if (!alphaTestLocked) { - // Only save the previous state if the alpha test wasn't already locked - GlStateManager.AlphaState alphaState = GlStateManagerAccessor.getALPHA_TEST(); - - originalAlphaTestEnable = ((BooleanStateAccessor) alphaState.mode).isEnabled(); - originalAlphaTest = new AlphaTest(AlphaTestFunction.fromGlId(alphaState.func).get(), alphaState.reference); - } - - alphaTestLocked = false; - - if (override == null) { - GlStateManager._disableAlphaTest(); - } else { - GlStateManager._enableAlphaTest(); - GlStateManager._alphaFunc(override.getFunction().getGlId(), override.getReference()); - } - - alphaTestLocked = true;*/ - } - - public static void deferAlphaTestToggle(boolean enabled) { - originalAlphaTestEnable = enabled; - } - - public static void deferAlphaFunc(int function, float reference) { - originalAlphaTest = new AlphaTest(AlphaTestFunction.fromGlId(function).get(), reference); - } - - public static void restoreAlphaTest() { - /*if (!alphaTestLocked) { - return; - } - - alphaTestLocked = false; - - if (originalAlphaTestEnable) { - GlStateManager._enableAlphaTest(); - } else { - GlStateManager._disableAlphaTest(); - } - - GlStateManager._alphaFunc(originalAlphaTest.getFunction().getGlId(), originalAlphaTest.getReference());*/ - } -} diff --git a/src/main/java/net/coderbot/iris/gl/blending/BlendMode.java b/src/main/java/net/coderbot/iris/gl/blending/BlendMode.java deleted file mode 100644 index 659cec779a..0000000000 --- a/src/main/java/net/coderbot/iris/gl/blending/BlendMode.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.coderbot.iris.gl.blending; - -public class BlendMode { - private final int srcRgb; - private final int dstRgb; - private final int srcAlpha; - private final int dstAlpha; - - public BlendMode(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { - this.srcRgb = srcRgb; - this.dstRgb = dstRgb; - this.srcAlpha = srcAlpha; - this.dstAlpha = dstAlpha; - } - - public int getSrcRgb() { - return srcRgb; - } - - public int getDstRgb() { - return dstRgb; - } - - public int getSrcAlpha() { - return srcAlpha; - } - - public int getDstAlpha() { - return dstAlpha; - } -} diff --git a/src/main/java/net/coderbot/iris/gl/blending/BufferBlendInformation.java b/src/main/java/net/coderbot/iris/gl/blending/BufferBlendInformation.java deleted file mode 100644 index bbd688a277..0000000000 --- a/src/main/java/net/coderbot/iris/gl/blending/BufferBlendInformation.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.coderbot.iris.gl.blending; - -public class BufferBlendInformation { - private final int index; - private final BlendMode blendMode; - - public BufferBlendInformation(int index, BlendMode blendMode) { - this.index = index; - this.blendMode = blendMode; - } - - public BlendMode getBlendMode() { - return blendMode; - } - - public int getIndex() { - return index; - } -} diff --git a/src/main/java/net/coderbot/iris/gl/program/GlUniform1iCall.java b/src/main/java/net/coderbot/iris/gl/program/GlUniform1iCall.java deleted file mode 100644 index 004fc87b31..0000000000 --- a/src/main/java/net/coderbot/iris/gl/program/GlUniform1iCall.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.coderbot.iris.gl.program; - -public class GlUniform1iCall { - private final int location; - private final int value; - - public GlUniform1iCall(int location, int value) { - this.location = location; - this.value = value; - } - - public int getLocation() { - return location; - } - - public int getValue() { - return value; - } -} diff --git a/src/main/java/net/coderbot/iris/gl/shader/ShaderType.java b/src/main/java/net/coderbot/iris/gl/shader/ShaderType.java deleted file mode 100644 index 0bcc1c52f7..0000000000 --- a/src/main/java/net/coderbot/iris/gl/shader/ShaderType.java +++ /dev/null @@ -1,25 +0,0 @@ -// This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license. - -package net.coderbot.iris.gl.shader; - -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL32C; -import org.lwjgl.opengl.GL43C; - -/** - * An enumeration over the supported OpenGL shader types. - */ -public enum ShaderType { - VERTEX(GL20.GL_VERTEX_SHADER), - GEOMETRY(GL32C.GL_GEOMETRY_SHADER), - FRAGMENT(GL20.GL_FRAGMENT_SHADER), - COMPUTE(GL43C.GL_COMPUTE_SHADER), - TESSELATION_CONTROL(GL43C.GL_TESS_CONTROL_SHADER), - TESSELATION_EVAL(GL43C.GL_TESS_EVALUATION_SHADER); - - public final int id; - - ShaderType(int id) { - this.id = id; - } -} diff --git a/src/main/java/net/coderbot/iris/gl/state/ValueUpdateNotifier.java b/src/main/java/net/coderbot/iris/gl/state/ValueUpdateNotifier.java deleted file mode 100644 index 81774db5a7..0000000000 --- a/src/main/java/net/coderbot/iris/gl/state/ValueUpdateNotifier.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.coderbot.iris.gl.state; - -/** - * A - */ -public interface ValueUpdateNotifier { - /** - * Sets up a listener with this notifier. Whenever the underlying value of - * @param listener - */ - void setListener(Runnable listener); -} diff --git a/src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java b/src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java deleted file mode 100644 index c3e7db5c5b..0000000000 --- a/src/main/java/net/coderbot/iris/gl/texture/DepthBufferFormat.java +++ /dev/null @@ -1,97 +0,0 @@ -package net.coderbot.iris.gl.texture; - -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL30C; -import org.lwjgl.opengl.GL43C; - -public enum DepthBufferFormat { - DEPTH(false), - DEPTH16(false), - DEPTH24(false), - DEPTH32(false), - DEPTH32F(false), - DEPTH_STENCIL(true), - DEPTH24_STENCIL8(true), - DEPTH32F_STENCIL8(true); - - private final boolean combinedStencil; - - DepthBufferFormat(boolean combinedStencil) { - this.combinedStencil = combinedStencil; - } - - @Nullable - public static DepthBufferFormat fromGlEnum(int glenum) { - switch (glenum) { - case GL30C.GL_DEPTH_COMPONENT: return DepthBufferFormat.DEPTH; - case GL30C.GL_DEPTH_COMPONENT16: return DepthBufferFormat.DEPTH16; - case GL30C.GL_DEPTH_COMPONENT24: return DepthBufferFormat.DEPTH24; - case GL30C.GL_DEPTH_COMPONENT32: return DepthBufferFormat.DEPTH32; - case GL30C.GL_DEPTH_COMPONENT32F: return DepthBufferFormat.DEPTH32F; - case GL30C.GL_DEPTH_STENCIL: return DepthBufferFormat.DEPTH_STENCIL; - case GL30C.GL_DEPTH24_STENCIL8: return DepthBufferFormat.DEPTH24_STENCIL8; - case GL30C.GL_DEPTH32F_STENCIL8: return DepthBufferFormat.DEPTH32F_STENCIL8; - default: return null; - } - } - - public static DepthBufferFormat fromGlEnumOrDefault(int glenum) { - DepthBufferFormat format = fromGlEnum(glenum); - if (format == null) { - // yolo, just assume it's GL_DEPTH_COMPONENT - return DepthBufferFormat.DEPTH; - } - return format; - } - - public int getGlInternalFormat() { - switch (this) { - case DEPTH: - return GL30C.GL_DEPTH_COMPONENT; - case DEPTH16: - return GL30C.GL_DEPTH_COMPONENT16; - case DEPTH24: - return GL30C.GL_DEPTH_COMPONENT24; - case DEPTH32: - return GL30C.GL_DEPTH_COMPONENT32; - case DEPTH32F: - return GL30C.GL_DEPTH_COMPONENT32F; - case DEPTH_STENCIL: - return GL30C.GL_DEPTH_STENCIL; - case DEPTH24_STENCIL8: - return GL30C.GL_DEPTH24_STENCIL8; - case DEPTH32F_STENCIL8: - return GL30C.GL_DEPTH32F_STENCIL8; - } - - throw new AssertionError("unreachable"); - } - - public int getGlType() { - return isCombinedStencil() ? GL30C.GL_DEPTH_STENCIL : GL30C.GL_DEPTH_COMPONENT; - } - - public int getGlFormat() { - switch (this) { - case DEPTH: - case DEPTH16: - return GL43C.GL_UNSIGNED_SHORT; - case DEPTH24: - case DEPTH32: - return GL43C.GL_UNSIGNED_INT; - case DEPTH32F: - return GL30C.GL_FLOAT; - case DEPTH_STENCIL: - case DEPTH24_STENCIL8: - return GL30C.GL_UNSIGNED_INT_24_8; - case DEPTH32F_STENCIL8: - return GL30C.GL_FLOAT_32_UNSIGNED_INT_24_8_REV; - } - - throw new AssertionError("unreachable"); - } - - public boolean isCombinedStencil() { - return combinedStencil; - } -} diff --git a/src/main/java/net/coderbot/iris/gl/texture/TexturePair.java b/src/main/java/net/coderbot/iris/gl/texture/TexturePair.java deleted file mode 100644 index 9ecd1c0b46..0000000000 --- a/src/main/java/net/coderbot/iris/gl/texture/TexturePair.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.coderbot.iris.gl.texture; - -import java.util.function.IntSupplier; - -public class TexturePair { - private final TextureType type; - private final IntSupplier id; - - public TexturePair(TextureType type, IntSupplier id) { - this.type = type; - this.id = id; - } - - public TextureType getType() { - return type; - } - - public IntSupplier getId() { - return id; - } -} diff --git a/src/main/java/net/coderbot/iris/gui/element/screen/ElementWidgetScreenData.java b/src/main/java/net/coderbot/iris/gui/element/screen/ElementWidgetScreenData.java deleted file mode 100644 index 060d0d29ed..0000000000 --- a/src/main/java/net/coderbot/iris/gui/element/screen/ElementWidgetScreenData.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.coderbot.iris.gui.element.screen; - -import net.minecraft.network.chat.Component; - - -public class ElementWidgetScreenData { - public static final ElementWidgetScreenData EMPTY = new ElementWidgetScreenData(Component.empty(), true); - - public final Component heading; - public final boolean backButton; - - public ElementWidgetScreenData(Component heading, boolean backButton) { - this.heading = heading; - this.backButton = backButton; - } -} diff --git a/src/main/java/net/coderbot/iris/gui/option/ShadowDistanceSliderButton.java b/src/main/java/net/coderbot/iris/gui/option/ShadowDistanceSliderButton.java deleted file mode 100644 index 813db212ef..0000000000 --- a/src/main/java/net/coderbot/iris/gui/option/ShadowDistanceSliderButton.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.coderbot.iris.gui.option; - -import java.util.List; -import net.minecraft.util.FormattedCharSequence; - -public class ShadowDistanceSliderButton { //extends AbstractWidget { - /* - public ShadowDistanceSliderButton(Options gameOptions, int x, int y, int width, int height, ProgressOption option, Option.TooltipSupplier orderedTooltip) { - super(gameOptions, x, y, width, height, option, orderedTooltip); - } - - public boolean isMouseOver(double mouseX, double mouseY) { - boolean actuallyActive = this.active; - this.active = true; - - // Temporarily set active to true so that isMouseOver doesn't immediately bail out. - // We don't just copy the code here in case some other mod wants to change how it works. - boolean mouseOver = super.isMouseOver(mouseX, mouseY); - - this.active = actuallyActive; - return mouseOver; - }*/ -} diff --git a/src/main/java/net/coderbot/iris/helpers/Tri.java b/src/main/java/net/coderbot/iris/helpers/Tri.java deleted file mode 100644 index f09e56f462..0000000000 --- a/src/main/java/net/coderbot/iris/helpers/Tri.java +++ /dev/null @@ -1,48 +0,0 @@ -package net.coderbot.iris.helpers; - -public class Tri { - private final X first; - private final Y second; - private final Z third; - - public Tri(X first, Y second, Z third) { - this.first = first; - this.second = second; - this.third = third; - } - - public X getFirst() { - return first; - } - - public Y getSecond() { - return second; - } - - public Z getThird() { - return third; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (!(obj instanceof Tri)) return false; - Tri tri = (Tri) obj; - return tri.first == this.first && tri.second == this.second && tri.third == this.third; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - result = prime * result + ((third == null) ? 0 : third.hashCode()); - return result; - } - - @Override - public String toString() { - return "First: " + first.toString() + " Second: " + second.toString() + " Third: " + third.toString(); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinChunkRenderDispatcherRebuildTask.java b/src/main/java/net/coderbot/iris/mixin/MixinChunkRenderDispatcherRebuildTask.java deleted file mode 100644 index 64d0cdaaa8..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/MixinChunkRenderDispatcherRebuildTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.coderbot.iris.mixin; - -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Holder; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.registries.ForgeRegistries; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Map; - -@Mixin(ChunkRenderDispatcher.RenderChunk.RebuildTask.class) -public class MixinChunkRenderDispatcherRebuildTask { - @Redirect(method = "compile", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/resources/model/BakedModel;getRenderTypes(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;)Lnet/minecraftforge/client/ChunkRenderTypeSet;")) - private ChunkRenderTypeSet oculus$overrideRenderTypes(BakedModel instance, BlockState blockState, RandomSource randomSource, ModelData modelData) { - Map, ChunkRenderTypeSet> idMap = BlockRenderingSettings.INSTANCE.getBlockTypeIds(); - if (idMap != null) { - ChunkRenderTypeSet type = idMap.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(blockState.getBlock())); - if (type != null) { - return type; - } - } - - return instance.getRenderTypes(blockState, randomSource, modelData); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_AlphaTestOverride.java b/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_AlphaTestOverride.java deleted file mode 100644 index b7f60a1808..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_AlphaTestOverride.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.coderbot.iris.mixin; - -import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.blending.AlphaTestStorage; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(GlStateManager.class) -public class MixinGlStateManager_AlphaTestOverride { - //@Inject(method = "_disableAlphaTest", at = @At("HEAD"), cancellable = true) - private static void iris$alphaTestDisableLock(CallbackInfo ci) { - if (AlphaTestStorage.isAlphaTestLocked()) { - AlphaTestStorage.deferAlphaTestToggle(false); - ci.cancel(); - } - } - - //@Inject(method = "_enableAlphaTest", at = @At("HEAD"), cancellable = true) - private static void iris$alphaTestEnableLock(CallbackInfo ci) { - if (AlphaTestStorage.isAlphaTestLocked()) { - AlphaTestStorage.deferAlphaTestToggle(true); - ci.cancel(); - } - } - - //@Inject(method = "_alphaFunc", at = @At("HEAD"), cancellable = true) - private static void iris$alphaFuncLock(int function, float reference, CallbackInfo ci) { - if (AlphaTestStorage.isAlphaTestLocked()) { - AlphaTestStorage.deferAlphaFunc(function, reference); - ci.cancel(); - } - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinProgramType.java b/src/main/java/net/coderbot/iris/mixin/MixinProgramType.java deleted file mode 100644 index 44316a1ff2..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/MixinProgramType.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.coderbot.iris.mixin; - -import com.mojang.blaze3d.shaders.Program; -import net.coderbot.iris.pipeline.newshader.IrisProgramTypes; -import org.apache.commons.lang3.ArrayUtils; -import org.lwjgl.opengl.GL32C; -import org.lwjgl.opengl.GL42C; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(Program.Type.class) -public class MixinProgramType { - @SuppressWarnings("target") - @Shadow - @Final - @Mutable - private static Program.Type[] $VALUES; - - static { - int baseOrdinal = $VALUES.length; - - IrisProgramTypes.GEOMETRY - = ProgramTypeAccessor.createProgramType("GEOMETRY", baseOrdinal, "geometry", ".gsh", GL32C.GL_GEOMETRY_SHADER); - - IrisProgramTypes.TESS_CONTROL - = ProgramTypeAccessor.createProgramType("TESS_CONTROL", baseOrdinal + 1, "tess_control", ".tcs", GL42C.GL_TESS_CONTROL_SHADER); - - IrisProgramTypes.TESS_EVAL - = ProgramTypeAccessor.createProgramType("TESS_EVAL", baseOrdinal + 2, "tess_eval", ".tes", GL42C.GL_TESS_EVALUATION_SHADER); - - $VALUES = ArrayUtils.addAll($VALUES, IrisProgramTypes.GEOMETRY, IrisProgramTypes.TESS_CONTROL, IrisProgramTypes.TESS_EVAL); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinShaderInstance.java b/src/main/java/net/coderbot/iris/mixin/MixinShaderInstance.java deleted file mode 100644 index 110afef27a..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/MixinShaderInstance.java +++ /dev/null @@ -1,100 +0,0 @@ -package net.coderbot.iris.mixin; - -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonObject; -import com.mojang.blaze3d.shaders.Uniform; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.DepthColorStorage; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.CoreWorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.ExtendedShader; -import net.coderbot.iris.pipeline.newshader.ShaderInstanceInterface; -import net.coderbot.iris.pipeline.newshader.fallback.FallbackShader; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.minecraft.util.GsonHelper; -import org.lwjgl.opengl.ARBTextureSwizzle; -import org.lwjgl.opengl.GL20C; -import org.lwjgl.opengl.GL30C; -import org.slf4j.Logger; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -import java.io.Reader; -import java.util.Objects; - -@Mixin(ShaderInstance.class) -public abstract class MixinShaderInstance implements ShaderInstanceInterface { - @Shadow - public abstract int getId(); - - @Unique - private static final ImmutableSet ATTRIBUTE_LIST = ImmutableSet.of("Position", "Color", "Normal", "UV0", "UV1", "UV2"); - - @Redirect(method = "updateLocations", - at = @At(value = "INVOKE", target = "Lorg/slf4j/Logger;warn(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", remap = false)) - private void iris$redirectLogSpam(Logger logger, String message, Object arg1, Object arg2) { - if (((Object) this) instanceof ExtendedShader || ((Object) this) instanceof FallbackShader) { - return; - } - - logger.warn(message, arg1, arg2); - } - - @Redirect(method = "(Lnet/minecraft/server/packs/resources/ResourceProvider;Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/vertex/VertexFormat;)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/shaders/Uniform;glBindAttribLocation(IILjava/lang/CharSequence;)V")) - public void iris$redirectBindAttributeLocation(int i, int j, CharSequence charSequence) { - if (((Object) this) instanceof ExtendedShader && ATTRIBUTE_LIST.contains(charSequence)) { - Uniform.glBindAttribLocation(i, j, "iris_" + charSequence); - } else { - Uniform.glBindAttribLocation(i, j, charSequence); - } - } - - @Inject(method = "apply", at = @At("TAIL")) - private void iris$lockDepthColorState(CallbackInfo ci) { - if (((Object) this) instanceof ExtendedShader || ((Object) this) instanceof FallbackShader || !shouldOverrideShaders()) { - return; - } - - DepthColorStorage.disableDepthColor(); - } - - @Inject(method = "clear", at = @At("HEAD")) - private void iris$unlockDepthColorState(CallbackInfo ci) { - if (((Object) this) instanceof ExtendedShader || ((Object) this) instanceof FallbackShader || !shouldOverrideShaders()) { - return; - } - - DepthColorStorage.unlockDepthColor(); - } - - private static boolean shouldOverrideShaders() { - WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); - - if (pipeline instanceof CoreWorldRenderingPipeline) { - return ((CoreWorldRenderingPipeline) pipeline).shouldOverrideShaders(); - } else { - return false; - } - } - - @Redirect(method = "(Lnet/minecraft/server/packs/resources/ResourceProvider;Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/vertex/VertexFormat;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/GsonHelper;parse(Ljava/io/Reader;)Lcom/google/gson/JsonObject;")) - public JsonObject iris$setupGeometryShader(Reader reader, ResourceProvider resourceProvider, ResourceLocation name, VertexFormat vertexFormat) { - this.iris$createExtraShaders(resourceProvider, name); - return GsonHelper.parse(reader); - } - - @Override - public void iris$createExtraShaders(ResourceProvider provider, ResourceLocation name) { - //no-op, used for ExtendedShader to call before the super constructor - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/ProgramTypeAccessor.java b/src/main/java/net/coderbot/iris/mixin/ProgramTypeAccessor.java deleted file mode 100644 index 2b8598d85e..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/ProgramTypeAccessor.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.coderbot.iris.mixin; - -import com.mojang.blaze3d.shaders.Program; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - -@Mixin(Program.Type.class) -public interface ProgramTypeAccessor { - @Invoker(value = "") - static Program.Type createProgramType(String name, int ordinal, String typeName, String extension, int glId) { - throw new AssertionError(); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinCapeLayer.java b/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinCapeLayer.java deleted file mode 100644 index dfcf899165..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinCapeLayer.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.coderbot.iris.mixin.entity_render_context; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.minecraft.client.player.AbstractClientPlayer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.layers.CapeLayer; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -@Mixin(CapeLayer.class) -public class MixinCapeLayer { - private static final NamespacedId CAPE_LOCATION = new NamespacedId("minecraft", "player_cape"); - - @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;FFFFFF)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;pushPose()V")) - private void changeId(PoseStack pCapeLayer0, MultiBufferSource pMultiBufferSource1, int pInt2, AbstractClientPlayer pAbstractClientPlayer3, float pFloat4, float pFloat5, float pFloat6, float pFloat7, float pFloat8, float pFloat9, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; - - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(CAPE_LOCATION)); - } - - @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;FFFFFF)V", at = @At(value = "RETURN")) - private void changeId2(CallbackInfo ci) { - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinElytraLayer.java b/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinElytraLayer.java deleted file mode 100644 index 069668dece..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinElytraLayer.java +++ /dev/null @@ -1,59 +0,0 @@ -package net.coderbot.iris.mixin.entity_render_context; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.minecraft.client.model.EntityModel; -import net.minecraft.client.model.HumanoidModel; -import net.minecraft.client.player.AbstractClientPlayer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.RenderLayerParent; -import net.minecraft.client.renderer.entity.layers.ElytraLayer; -import net.minecraft.client.renderer.entity.layers.HumanoidArmorLayer; -import net.minecraft.client.renderer.entity.layers.RenderLayer; -import net.minecraft.core.Registry; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.PlayerModelPart; -import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -@Mixin(ElytraLayer.class) -public abstract class MixinElytraLayer> extends RenderLayer { - @Unique - private static final NamespacedId ELYTRA_CAPE_LOCATION = new NamespacedId("minecraft", "elytra_with_cape"); - - public MixinElytraLayer(RenderLayerParent pRenderLayer0) { - super(pRenderLayer0); - } - - @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/LivingEntity;FFFFFF)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;pushPose()V"), locals = LocalCapture.CAPTURE_FAILHARD) - private void changeId(PoseStack pElytraLayer0, MultiBufferSource pMultiBufferSource1, int pInt2, T pLivingEntity3, float pFloat4, float pFloat5, float pFloat6, float pFloat7, float pFloat8, float pFloat9, CallbackInfo ci, ItemStack lvItemStack11, ResourceLocation lvResourceLocation12) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; - - if (pLivingEntity3 instanceof AbstractClientPlayer player && player.getCloakTextureLocation() != null - && player.isModelPartShown(PlayerModelPart.CAPE)) { - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(ELYTRA_CAPE_LOCATION)); - return; - } - - ResourceLocation location = BuiltInRegistries.ITEM.getKey(Items.ELYTRA); - - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); - } - - @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/LivingEntity;FFFFFF)V", at = @At(value = "RETURN")) - private void changeId2(CallbackInfo ci) { - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/math/MixinMatrix4f.java b/src/main/java/net/coderbot/iris/mixin/math/MixinMatrix4f.java deleted file mode 100644 index 7081fcdbb8..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/math/MixinMatrix4f.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.coderbot.iris.mixin.math; - -import org.joml.Matrix4f; -import net.coderbot.iris.shadows.Matrix4fAccess; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -/** - * @author FoundationGames - */ -@Mixin(Matrix4f.class) -public class MixinMatrix4f implements Matrix4fAccess { - @Shadow protected float m00; - @Shadow protected float m01; - @Shadow protected float m02; - @Shadow protected float m03; - @Shadow protected float m10; - @Shadow protected float m11; - @Shadow protected float m12; - @Shadow protected float m13; - @Shadow protected float m20; - @Shadow protected float m21; - @Shadow protected float m22; - @Shadow protected float m23; - @Shadow protected float m30; - @Shadow protected float m31; - @Shadow protected float m32; - @Shadow protected float m33; - - @Override - public void copyFromArray(float[] m) { - if (m.length != 16) return; - this.m00 = m[0]; - this.m10 = m[1]; - this.m20 = m[2]; - this.m30 = m[3]; - this.m01 = m[4]; - this.m11 = m[5]; - this.m21 = m[6]; - this.m31 = m[7]; - this.m02 = m[8]; - this.m12 = m[9]; - this.m22 = m[10]; - this.m32 = m[11]; - this.m03 = m[12]; - this.m13 = m[13]; - this.m23 = m[14]; - this.m33 = m[15]; - } - - @Override - public float[] copyIntoArray() { - return new float[] { - m00, m10, m20, m30, - m01, m11, m21, m31, - m02, m12, m22, m32, - m03, m13, m23, m33 - }; - } - - @Override - public org.joml.Matrix4f convertToJOML() { - return new org.joml.Matrix4f( - m00, m10, m20, m30, - m01, m11, m21, m31, - m02, m12, m22, m32, - m03, m13, m23, m33 - ); - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderStateShard_Tagging.java b/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderStateShard_Tagging.java deleted file mode 100644 index dcbbb1861c..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderStateShard_Tagging.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.coderbot.iris.mixin.rendertype; - -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.layer.GbufferPrograms; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(RenderStateShard.class) -public class MixinRenderStateShard_Tagging { - @Shadow - @Final - protected String name; - - @Shadow - @Final - @Mutable - private Runnable setupState; - - @Shadow - @Final - @Mutable - private Runnable clearState; - - @Inject(method = "(Ljava/lang/String;Ljava/lang/Runnable;Ljava/lang/Runnable;)V", at = @At("RETURN")) - private void iris$onInit(String nameArg, Runnable clearStateArg, Runnable setupStateArg, CallbackInfo ci) { - // IntelliJ is wrong here, it doesn't understand how Mixin works - // We only want to apply this to RenderTypes. - if (!((Object) this instanceof RenderType)) { - return; - } - - Runnable previousSetupState = setupState; - Runnable previousClearState = clearState; - - // Change the Runnable instead of injecting into setup / clear state functions so that we don't add - // unnecessary overhead if we've determined that the render type doesn't match. - - if (name.equals("beacon_beam")) { - setupState = () -> { - GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.BEACON_BEAM); - previousSetupState.run(); - }; - - clearState = () -> { - GbufferPrograms.teardownSpecialRenderCondition(SpecialCondition.BEACON_BEAM); - previousClearState.run(); - }; - } else if (name.equals("eyes")) { - setupState = () -> { - GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.ENTITY_EYES); - previousSetupState.run(); - }; - - clearState = () -> { - GbufferPrograms.teardownSpecialRenderCondition(SpecialCondition.ENTITY_EYES); - previousClearState.run(); - }; - } else if (name.contains("glint")) { - // TODO: Use blend mode & depth state instead of matching on render types. - // That would potentially be more more robust... but more complex. - // So this works for now. - setupState = () -> { - GbufferPrograms.setupSpecialRenderCondition(SpecialCondition.GLINT); - previousSetupState.run(); - }; - - clearState = () -> { - GbufferPrograms.teardownSpecialRenderCondition(SpecialCondition.GLINT); - previousClearState.run(); - }; - } else if (name.contains("crumbling")) { - // TODO: Use blend mode & depth state instead of matching on render types. - // That would potentially be more robust... but more complex. - // So this works for now. - setupState = () -> { - GbufferPrograms.setOverridePhase(WorldRenderingPhase.DESTROY); - previousSetupState.run(); - }; - - clearState = () -> { - GbufferPrograms.setOverridePhase(null); - previousClearState.run(); - }; - } - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderType.java b/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderType.java deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderType_FixEyesTranslucency.java b/src/main/java/net/coderbot/iris/mixin/rendertype/MixinRenderType_FixEyesTranslucency.java deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/main/java/net/coderbot/iris/mixin/shadows/ChunkInfoAccessor.java b/src/main/java/net/coderbot/iris/mixin/shadows/ChunkInfoAccessor.java deleted file mode 100644 index ec3933cc77..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/shadows/ChunkInfoAccessor.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.coderbot.iris.mixin.shadows; - -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -@Mixin(LevelRenderer.RenderChunkInfo.class) -public interface ChunkInfoAccessor { - @Accessor("chunk") - ChunkRenderDispatcher.RenderChunk getChunk(); -} diff --git a/src/main/java/net/coderbot/iris/mixin/shadows/MixinLevelRenderer.java b/src/main/java/net/coderbot/iris/mixin/shadows/MixinLevelRenderer.java deleted file mode 100644 index 03e9529029..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/shadows/MixinLevelRenderer.java +++ /dev/null @@ -1,102 +0,0 @@ -package net.coderbot.iris.mixin.shadows; - -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import net.coderbot.iris.shadows.CullingDataCache; -import net.minecraft.client.renderer.LevelRenderer; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; - -@Mixin(LevelRenderer.class) -public class MixinLevelRenderer implements CullingDataCache { - @Shadow - @Final - @Mutable - private ObjectArrayList renderChunksInFrustum; - - @Unique - private ObjectArrayList savedRenderChunks = new ObjectArrayList(69696); - - @Shadow - private boolean needsFullRenderChunkUpdate; - - @Unique - private boolean savedNeedsTerrainUpdate; - - @Shadow - private double lastCameraX; - - @Shadow - private double lastCameraY; - - @Shadow - private double lastCameraZ; - - @Shadow - private double prevCamRotX; - - @Shadow - private double prevCamRotY; - - @Unique - private double savedLastCameraX; - - @Unique - private double savedLastCameraY; - - @Unique - private double savedLastCameraZ; - - @Unique - private double savedLastCameraPitch; - - @Unique - private double savedLastCameraYaw; - - @Override - public void saveState() { - swap(); - } - - @Override - public void restoreState() { - swap(); - } - - @Unique - private void swap() { - ObjectArrayList tmpList = renderChunksInFrustum; - renderChunksInFrustum = savedRenderChunks; - savedRenderChunks = tmpList; - - // TODO: If the normal chunks need a terrain update, these chunks probably do too... - // We probably should copy it over - boolean tmpBool = needsFullRenderChunkUpdate; - needsFullRenderChunkUpdate = savedNeedsTerrainUpdate; - savedNeedsTerrainUpdate = tmpBool; - - double tmp; - - tmp = lastCameraX; - lastCameraX = savedLastCameraX; - savedLastCameraX = tmp; - - tmp = lastCameraY; - lastCameraY = savedLastCameraY; - savedLastCameraY = tmp; - - tmp = lastCameraZ; - lastCameraZ = savedLastCameraZ; - savedLastCameraZ = tmp; - - tmp = prevCamRotX; - prevCamRotX = savedLastCameraPitch; - savedLastCameraPitch = tmp; - - tmp = prevCamRotY; - prevCamRotY = savedLastCameraYaw; - savedLastCameraYaw = tmp; - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java b/src/main/java/net/coderbot/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java deleted file mode 100644 index f5777e4481..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java +++ /dev/null @@ -1,65 +0,0 @@ -package net.coderbot.iris.mixin.shadows; - -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import it.unimi.dsi.fastutil.objects.ObjectList; -import net.coderbot.iris.pipeline.ShadowRenderer; -import net.minecraft.client.Camera; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.culling.Frustum; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Group; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * Prevent nearby chunks from being rebuilt on the main thread in the shadow pass. Aside from causing FPS to tank, - * this also causes weird chunk corruption! It's critical to make sure that it's disabled as a result. - * - * This patch is not relevant with Sodium installed since Sodium has a completely different build path for terrain - * setup. - * - * Uses a priority of 1010 to apply after Sodium's overwrite, to allow for the Group behavior to activate. Otherwise, - * if we apply with the same priority, then we'll just get a Mixin error due to the injects conflicting with the - * {@code @Overwrite}. Using {@code @Group} allows us to avoid a fragile Mixin plugin. - */ -@Mixin(value = LevelRenderer.class, priority = 1010) -public abstract class MixinPreventRebuildNearInShadowPass { - @Shadow - @Final - private ObjectArrayList renderChunksInFrustum; - - @Shadow - protected abstract void applyFrustum(Frustum frustum); - - @Group(name = "iris_MixinPreventRebuildNearInShadowPass", min = 1, max = 1) - @Inject(method = "setupRender", - at = @At(value = "INVOKE", - target = "Ljava/util/concurrent/atomic/AtomicReference;get()Ljava/lang/Object;"), - cancellable = true, - require = 0) - private void iris$preventRebuildNearInShadowPass(Camera camera, Frustum frustum, boolean bl, boolean bl2, CallbackInfo ci) { - if (ShadowRenderer.ACTIVE) { - for (LevelRenderer.RenderChunkInfo chunk : this.renderChunksInFrustum) { - ShadowRenderer.visibleBlockEntities.addAll(((ChunkInfoAccessor) chunk).getChunk().getCompiledChunk().getRenderableBlockEntities()); - } - Minecraft.getInstance().getProfiler().pop(); - this.applyFrustum(frustum); - ci.cancel(); - } - } - - @Group(name = "iris_MixinPreventRebuildNearInShadowPass", min = 1, max = 1) - @Inject(method = "setupRender", - at = @At(value = "INVOKE", - target = "me/jellysquid/mods/sodium/client/gl/device/RenderDevice.enterManagedCode ()V", - remap = false), - require = 0) - private void iris$cannotInject(Camera camera, Frustum frustum, boolean bl, boolean bl2, CallbackInfo ci) { - // Dummy injection just to assert that either Sodium is present, or the vanilla injection passed. - } -} diff --git a/src/main/java/net/coderbot/iris/mixin/state_tracking/MixinPostChain.java b/src/main/java/net/coderbot/iris/mixin/state_tracking/MixinPostChain.java deleted file mode 100644 index 1ca4d8f748..0000000000 --- a/src/main/java/net/coderbot/iris/mixin/state_tracking/MixinPostChain.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.coderbot.iris.mixin.state_tracking; - -import net.coderbot.iris.Iris; -import net.minecraft.client.renderer.PostChain; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(PostChain.class) -public class MixinPostChain { - @Inject(method = "process(F)V", at = @At("HEAD")) - private void iris$beforeProcess(float f, CallbackInfo ci) { - Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.getRenderTargetStateListener().beginPostChain()); - } - - @Inject(method = "process(F)V", at = @At("RETURN")) - private void iris$afterProcess(float f, CallbackInfo ci) { - Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.getRenderTargetStateListener().endPostChain()); - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java deleted file mode 100644 index 3607e3fdf5..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/DeferredWorldRenderingPipeline.java +++ /dev/null @@ -1,1380 +0,0 @@ -package net.coderbot.iris.pipeline; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.primitives.Ints; -import com.mojang.blaze3d.pipeline.RenderTarget; -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.datafixers.util.Pair; -import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.block_rendering.BlockMaterialMapping; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.dh.DHCompat; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gbuffer_overrides.matching.ProgramTable; -import net.coderbot.iris.gbuffer_overrides.matching.RenderCondition; -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.AlphaTestOverride; -import net.coderbot.iris.gl.blending.AlphaTestStorage; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.gl.blending.BufferBlendOverride; -import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -import net.coderbot.iris.gl.program.ProgramBuilder; -import net.coderbot.iris.gl.program.ProgramImages; -import net.coderbot.iris.gl.program.ProgramSamplers; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.layer.GbufferPrograms; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.mixin.LevelRendererAccessor; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.postprocess.BufferFlipper; -import net.coderbot.iris.postprocess.CenterDepthSampler; -import net.coderbot.iris.postprocess.CompositeRenderer; -import net.coderbot.iris.postprocess.FinalPassRenderer; -import net.coderbot.iris.rendertarget.Blaze3dRenderTargetExt; -import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.samplers.IrisImages; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.CloudSetting; -import net.coderbot.iris.shaderpack.IdMap; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shaderpack.ParticleRenderingSettings; -import net.coderbot.iris.shaderpack.ProgramDirectives; -import net.coderbot.iris.shaderpack.ProgramFallbackResolver; -import net.coderbot.iris.shaderpack.ProgramSet; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.loading.ProgramId; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.shadows.ShadowCompositeRenderer; -import net.coderbot.iris.shadows.ShadowRenderTargets; -import net.coderbot.iris.texture.TextureInfoCache; -import net.coderbot.iris.texture.format.TextureFormat; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.coderbot.iris.texture.pbr.PBRTextureHolder; -import net.coderbot.iris.texture.pbr.PBRTextureManager; -import net.coderbot.iris.texture.pbr.PBRType; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.custom.CustomUniforms; -import net.coderbot.iris.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import org.joml.Vector3d; -import org.joml.Vector4f; -import net.minecraft.client.Camera; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.DimensionSpecialEffects; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.texture.AbstractTexture; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL15C; -import org.lwjgl.opengl.GL20C; -import org.lwjgl.opengl.GL21C; -import org.lwjgl.opengl.GL30C; -import org.lwjgl.opengl.GL43C; - -import java.util.function.IntFunction; -import java.util.function.Supplier; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.OptionalInt; -import java.util.Set; - -/** - * Encapsulates the compiled shader program objects for the currently loaded shaderpack. - */ -public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener { - private final RenderTargets renderTargets; - private final ShadowCompositeRenderer shadowCompositeRenderer; - - @Nullable - private ShadowRenderTargets shadowRenderTargets; - @Nullable - private ComputeProgram[] shadowComputes; - private final Supplier shadowTargetsSupplier; - - private final ProgramTable table; - - private ImmutableList clearPassesFull; - private ImmutableList clearPasses; - private ImmutableList shadowClearPasses; - private ImmutableList shadowClearPassesFull; - - private final CompositeRenderer prepareRenderer; - - @Nullable - private final ShadowRenderer shadowRenderer; - - private final int shadowMapResolution; - private final CompositeRenderer deferredRenderer; - private final CompositeRenderer compositeRenderer; - private final FinalPassRenderer finalPassRenderer; - private final CustomTextureManager customTextureManager; - private final AbstractTexture whitePixel; - private final FrameUpdateNotifier updateNotifier; - private final CenterDepthSampler centerDepthSampler; - - private final ImmutableSet flippedBeforeShadow; - private final ImmutableSet flippedAfterPrepare; - private final ImmutableSet flippedAfterTranslucent; - - private final SodiumTerrainPipeline sodiumTerrainPipeline; - - private final HorizonRenderer horizonRenderer = new HorizonRenderer(); - - private final float sunPathRotation; - private final CloudSetting cloudSetting; - private final boolean shouldRenderUnderwaterOverlay; - private final boolean shouldRenderVignette; - private final boolean shouldRenderSun; - private final boolean shouldRenderMoon; - private final boolean shouldWriteRainAndSnowToDepthBuffer; - private final boolean shouldRenderParticlesBeforeDeferred; - private final boolean shouldRenderPrepareBeforeShadow; - private final boolean oldLighting; - private final boolean allowConcurrentCompute; - private final OptionalInt forcedShadowRenderDistanceChunks; - - private Pass current = null; - - private WorldRenderingPhase overridePhase = null; - private WorldRenderingPhase phase = WorldRenderingPhase.NONE; - private boolean isBeforeTranslucent; - private boolean isRenderingShadow = false; - private InputAvailability inputs = new InputAvailability(false, false, false); - private SpecialCondition special = null; - private ShaderStorageBufferHolder shaderStorageBufferHolder; - private boolean showSSBOError = false; - - private boolean shouldBindPBR; - private int currentNormalTexture; - private int currentSpecularTexture; - private PackDirectives packDirectives; - - private final CustomUniforms customUniforms; - private Object2ObjectMap, String> customTextureMap; - private ParticleRenderingSettings particleRenderingSettings; - - public DeferredWorldRenderingPipeline(ProgramSet programs) { - Objects.requireNonNull(programs); - - this.cloudSetting = programs.getPackDirectives().getCloudSetting(); - this.shouldRenderUnderwaterOverlay = programs.getPackDirectives().underwaterOverlay(); - this.shouldRenderVignette = programs.getPackDirectives().vignette(); - this.shouldRenderSun = programs.getPackDirectives().shouldRenderSun(); - this.shouldRenderMoon = programs.getPackDirectives().shouldRenderMoon(); - this.shouldWriteRainAndSnowToDepthBuffer = programs.getPackDirectives().rainDepth(); - this.shouldRenderParticlesBeforeDeferred = false; - this.allowConcurrentCompute = programs.getPackDirectives().getConcurrentCompute(); - this.shouldRenderPrepareBeforeShadow = programs.getPackDirectives().isPrepareBeforeShadow(); - this.oldLighting = programs.getPackDirectives().isOldLighting(); - this.updateNotifier = new FrameUpdateNotifier(); - this.customTextureMap = programs.getPackDirectives().getTextureMap(); - - this.packDirectives = programs.getPackDirectives(); - - this.particleRenderingSettings = programs.getPackDirectives().getParticleRenderingSettings().orElseGet(() -> { - if (programs.getDeferred().length > 0) { - return ParticleRenderingSettings.AFTER; - } else { - return ParticleRenderingSettings.MIXED; - } - }); - - if (!programs.getPackDirectives().getBufferObjects().isEmpty()) { - if (IrisRenderSystem.supportsSSBO()) { - //this.shaderStorageBufferHolder = new ShaderStorageBufferHolder(programs.getPackDirectives().getBufferObjects()); - - this.shaderStorageBufferHolder.setupBuffers(); - } else { - Iris.logger.fatal("Shader storage buffers/immutable buffer storage is not supported on this graphics card, however the shaderpack requested them? Let's hope it's not a problem."); - showSSBOError = true; - for (int i = 0; i < 16; i++) { - IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, i, i); - } - } - } else { - for (int i = 0; i < 16; i++) { - IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, i, i); - } - } - - RenderTarget mainTarget = Minecraft.getInstance().getMainRenderTarget(); - - int depthTextureId = mainTarget.getDepthTextureId(); - int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat(); - DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); - - this.renderTargets = new RenderTargets(mainTarget.width, mainTarget.height, depthTextureId, - ((Blaze3dRenderTargetExt) mainTarget).iris$getDepthBufferVersion(), - depthBufferFormat, programs.getPackDirectives().getRenderTargetDirectives().getRenderTargetSettings(), programs.getPackDirectives()); - - this.sunPathRotation = programs.getPackDirectives().getSunPathRotation(); - - PackShadowDirectives shadowDirectives = programs.getPackDirectives().getShadowDirectives(); - - if (shadowDirectives.isDistanceRenderMulExplicit()) { - if (shadowDirectives.getDistanceRenderMul() >= 0.0) { - // add 15 and then divide by 16 to ensure we're rounding up - forcedShadowRenderDistanceChunks = - OptionalInt.of(((int) (shadowDirectives.getDistance() * shadowDirectives.getDistanceRenderMul()) + 15) / 16); - } else { - forcedShadowRenderDistanceChunks = OptionalInt.of(-1); - } - } else { - forcedShadowRenderDistanceChunks = OptionalInt.empty(); - } - - BlockRenderingSettings.INSTANCE.setBlockStateIds( - BlockMaterialMapping.createBlockStateIdMap(programs.getPack().getIdMap().getBlockProperties())); - BlockRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programs.getPack().getIdMap().getBlockRenderTypeMap())); - - BlockRenderingSettings.INSTANCE.setEntityIds(programs.getPack().getIdMap().getEntityIdMap()); - BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programs.getPackDirectives().getAmbientOcclusionLevel()); - BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); - BlockRenderingSettings.INSTANCE.setUseSeparateAo(programs.getPackDirectives().shouldUseSeparateAo()); - BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(true); - - // Don't clobber anything in texture unit 0. It probably won't cause issues, but we're just being cautious here. - GlStateManager.glActiveTexture(GL20C.GL_TEXTURE2); - - customTextureManager = new CustomTextureManager(programs.getPackDirectives(), programs.getPack().getCustomTextureDataMap(), programs.getPack().getIrisCustomTextureDataMap(), programs.getPack().getCustomNoiseTexture()); - - whitePixel = new NativeImageBackedSingleColorTexture(255, 255, 255, 255); - - GlStateManager.glActiveTexture(GL20C.GL_TEXTURE0); - - this.flippedBeforeShadow = ImmutableSet.of(); - - this.customUniforms = programs.getPack().customUniforms.build( - holder -> CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), this.updateNotifier) - ); - - BufferFlipper flipper = new BufferFlipper(); - - this.centerDepthSampler = new CenterDepthSampler(() -> getRenderTargets().getDepthTexture(), programs.getPackDirectives().getCenterDepthHalfLife()); - - this.shadowMapResolution = programs.getPackDirectives().getShadowDirectives().getResolution(); - - this.shadowTargetsSupplier = () -> { - if (shadowRenderTargets == null) { - this.shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives); - } - - return shadowRenderTargets; - }; - - ShaderPrinter.resetPrintState(); - - this.prepareRenderer = new CompositeRenderer(this, programs.getPackDirectives(), programs.getPrepare(), programs.getPrepareCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - TextureStage.PREPARE, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), - customTextureManager.getIrisCustomTextures(), null, programs.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms); - - flippedAfterPrepare = flipper.snapshot(); - - this.deferredRenderer = new CompositeRenderer(this, programs.getPackDirectives(), programs.getDeferred(), programs.getDeferredCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - TextureStage.DEFERRED, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customTextureManager.getIrisCustomTextures(), null, - programs.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms); - - flippedAfterTranslucent = flipper.snapshot(); - - this.compositeRenderer = new CompositeRenderer(this, programs.getPackDirectives(), programs.getComposite(), programs.getCompositeCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, - TextureStage.COMPOSITE_AND_FINAL, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), - customTextureManager.getIrisCustomTextures(), null, programs.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms); - this.finalPassRenderer = new FinalPassRenderer(this, programs, renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, flipper.snapshot(), - centerDepthSampler, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customTextureManager.getIrisCustomTextures(), null, - this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms); - - // [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)] - ProgramId[] ids = new ProgramId[] { - ProgramId.Basic, ProgramId.Textured, ProgramId.TexturedLit, - ProgramId.SkyBasic, ProgramId.SkyTextured, ProgramId.SkyTextured, - null, null, ProgramId.Terrain, - null, null, ProgramId.Water, - null, ProgramId.Clouds, ProgramId.Clouds, - null, ProgramId.DamagedBlock, ProgramId.DamagedBlock, - ProgramId.Block, ProgramId.Block, ProgramId.Block, - ProgramId.BeaconBeam, ProgramId.BeaconBeam, ProgramId.BeaconBeam, - ProgramId.Entities, ProgramId.Entities, ProgramId.Entities, - ProgramId.EntitiesTrans, ProgramId.EntitiesTrans, ProgramId.EntitiesTrans, - null, ProgramId.ArmorGlint, ProgramId.ArmorGlint, - null, ProgramId.SpiderEyes, ProgramId.SpiderEyes, - ProgramId.Hand, ProgramId.Hand, ProgramId.Hand, - ProgramId.HandWater, ProgramId.HandWater, ProgramId.HandWater, - null, null, ProgramId.Weather, - // world border uses textured_lit even though it has no lightmap :/ - null, ProgramId.TexturedLit, ProgramId.TexturedLit, - ProgramId.Shadow, ProgramId.Shadow, ProgramId.Shadow - }; - - if (ids.length != RenderCondition.values().length * 3) { - throw new IllegalStateException("Program ID table length mismatch"); - } - - ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs); - - Map, Pass> cachedPasses = new HashMap<>(); - - this.shadowComputes = createShadowComputes(programs.getShadowCompute(), programs); - - this.table = new ProgramTable<>((condition, availability) -> { - int idx; - - if (availability.texture && availability.lightmap) { - idx = 2; - } else if (availability.texture) { - idx = 1; - } else { - idx = 0; - } - - ProgramId id = ids[condition.ordinal() * 3 + idx]; - - if (id == null) { - id = ids[idx]; - } - - ProgramId finalId = id; - - return cachedPasses.computeIfAbsent(new Pair<>(id, availability), p -> { - ProgramSource source = resolver.resolveNullable(p.getFirst()); - - if (condition == RenderCondition.SHADOW) { - if (!shadowDirectives.isShadowEnabled().orElse(shadowRenderTargets != null)) { - // shadow is not used - return null; - } else if (source == null) { - // still need the custom framebuffer, viewport, and blend mode behavior - GlFramebuffer shadowFb = - shadowTargetsSupplier.get().createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] {0}); - return new Pass(null, shadowFb, shadowFb, null, - BlendModeOverride.OFF, Collections.emptyList(), true); - } - } - - if (source == null) { - return createDefaultPass(); - } - - try { - return createPass(source, availability, condition == RenderCondition.SHADOW, finalId); - } catch (Exception e) { - throw new RuntimeException("Failed to create pass for " + source.getName() + " for rendering condition " - + condition + " specialized to input availability " + availability, e); - } - }); - }); - - if (shadowRenderTargets == null && shadowDirectives.isShadowEnabled() == OptionalBoolean.TRUE) { - shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives); - } - - if (shadowRenderTargets != null) { - this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives); - this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives); - - if (programs.getPackDirectives().getShadowDirectives().isShadowEnabled().orElse(true)) { - Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true, true)).getProgram(); - - this.shadowCompositeRenderer = new ShadowCompositeRenderer(this, programs.getPackDirectives(), programs.getShadowComposite(), programs.getShadowCompCompute(), this.shadowRenderTargets, customTextureManager.getNoiseTexture(), updateNotifier, - customTextureManager.getCustomTextureIdMap(TextureStage.SHADOWCOMP), null, programs.getPackDirectives().getExplicitFlips("shadowcomp_pre"), customTextureManager.getIrisCustomTextures(), customUniforms); - this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null), - programs.getPackDirectives(), shadowRenderTargets, shadowCompositeRenderer, customUniforms, false); - } else { - shadowCompositeRenderer = null; - shadowRenderer = null; - } - } else { - this.shadowClearPasses = ImmutableList.of(); - this.shadowClearPassesFull = ImmutableList.of(); - shadowCompositeRenderer = null; - this.shadowRenderer = null; - } - - this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, - programs.getPackDirectives().getRenderTargetDirectives()); - this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, - programs.getPackDirectives().getRenderTargetDirectives()); - - // SodiumTerrainPipeline setup follows. - - Supplier> flipped = - () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; - - IntFunction createTerrainSamplers = (programId) -> { - ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); - ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW)); - - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); - IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); - IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); - IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); - - if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, false); - } - - return builder.build(); - }; - - IntFunction createTerrainImages = (programId) -> { - ProgramImages.Builder builder = ProgramImages.builder(programId); - - IrisImages.addRenderTargetImages(builder, flipped, renderTargets); - - if (IrisImages.hasShadowImages(builder)) { - IrisImages.addShadowColorImages(builder, Objects.requireNonNull(shadowRenderTargets), null); - } - - return builder.build(); - }; - - IntFunction createShadowTerrainSamplers = (programId) -> { - ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); - ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(TextureStage.GBUFFERS_AND_SHADOW)); - - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flippedAfterPrepare, renderTargets, false); - IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); - IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); - - // Only initialize these samplers if the shadow map renderer exists. - // Otherwise, this program shouldn't be used at all? - if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets), null, false); - } - - return builder.build(); - }; - - IntFunction createShadowTerrainImages = (programId) -> { - ProgramImages.Builder builder = ProgramImages.builder(programId); - - IrisImages.addRenderTargetImages(builder, () -> flippedAfterPrepare, renderTargets); - - if (IrisImages.hasShadowImages(builder)) { - IrisImages.addShadowColorImages(builder, Objects.requireNonNull(shadowRenderTargets), null); - } - - return builder.build(); - }; - - this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers, - shadowRenderTargets == null ? null : createShadowTerrainSamplers, createTerrainImages, createShadowTerrainImages, renderTargets, flippedAfterPrepare, flippedAfterTranslucent, - shadowRenderTargets != null ? shadowRenderTargets.createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] { 0, 1 }) : null, customUniforms); - - // first optimization pass - this.customUniforms.optimise(); - } - - private RenderTargets getRenderTargets() { - return renderTargets; - } - - private void checkWorld() { - // If we're not in a world, then obviously we cannot possibly be rendering a world. - if (Minecraft.getInstance().level == null) { - isRenderingWorld = false; - current = null; - } - } - - @Override - public boolean shouldDisableVanillaEntityShadows() { - // OptiFine seems to disable vanilla shadows when the shaderpack uses shadow mapping? - return shadowRenderer != null; - } - - @Override - public boolean shouldDisableDirectionalShading() { - return !oldLighting; - } - - @Override - public boolean shouldDisableFrustumCulling() { - return false; - } - - @Override - public CloudSetting getCloudSetting() { - return cloudSetting; - } - - @Override - public boolean shouldRenderUnderwaterOverlay() { - return shouldRenderUnderwaterOverlay; - } - - @Override - public boolean shouldRenderVignette() { - return shouldRenderVignette; - } - - @Override - public boolean shouldRenderSun() { - return shouldRenderSun; - } - - @Override - public boolean shouldRenderMoon() { - return shouldRenderMoon; - } - - @Override - public boolean shouldWriteRainAndSnowToDepthBuffer() { - return shouldWriteRainAndSnowToDepthBuffer; - } - - @Override - public ParticleRenderingSettings getParticleRenderingSettings() { - return particleRenderingSettings; - } - - @Override - public boolean allowConcurrentCompute() { - return allowConcurrentCompute; - } - - @Override - public boolean hasFeature(FeatureFlags flags) { - return false; - } - - @Override - public float getSunPathRotation() { - return sunPathRotation; - } - - @Override - public DHCompat getDHCompat() { - return null; - } - - private RenderCondition getCondition(WorldRenderingPhase phase) { - if (isRenderingShadow) { - return RenderCondition.SHADOW; - } - - if (special != null) { - if (special == SpecialCondition.BEACON_BEAM) { - return RenderCondition.BEACON_BEAM; - } else if (special == SpecialCondition.ENTITY_EYES) { - return RenderCondition.ENTITY_EYES; - } else if (special == SpecialCondition.GLINT) { - return RenderCondition.GLINT; - } - } - - switch (phase) { - case NONE: - case OUTLINE: - case DEBUG: - case PARTICLES: - return RenderCondition.DEFAULT; - case SKY: - case SUNSET: - case CUSTOM_SKY: - case SUN: - case MOON: - case STARS: - case VOID: - return RenderCondition.SKY; - case TERRAIN_SOLID: - case TERRAIN_CUTOUT: - case TERRAIN_CUTOUT_MIPPED: - return RenderCondition.TERRAIN_OPAQUE; - case ENTITIES: - if (GlStateManagerAccessor.getBLEND().srcRgb == GlStateManager.SourceFactor.SRC_ALPHA.value && GlStateManagerAccessor.getBLEND().dstRgb == GlStateManager.SourceFactor.ONE_MINUS_SRC_ALPHA.value && GlStateManagerAccessor.getBLEND().srcAlpha == GlStateManager.SourceFactor.ONE.value && GlStateManagerAccessor.getBLEND().dstAlpha == GlStateManager.SourceFactor.ONE_MINUS_SRC_ALPHA.value) { - return RenderCondition.ENTITIES_TRANSLUCENT; - } else { - return RenderCondition.ENTITIES; - } - case BLOCK_ENTITIES: - return RenderCondition.BLOCK_ENTITIES; - case DESTROY: - return RenderCondition.DESTROY; - case HAND_SOLID: - return RenderCondition.HAND_OPAQUE; - case TERRAIN_TRANSLUCENT: - case TRIPWIRE: - return RenderCondition.TERRAIN_TRANSLUCENT; - case CLOUDS: - return RenderCondition.CLOUDS; - case RAIN_SNOW: - return RenderCondition.RAIN_SNOW; - case HAND_TRANSLUCENT: - return RenderCondition.HAND_TRANSLUCENT; - case WORLD_BORDER: - return RenderCondition.WORLD_BORDER; - default: - throw new IllegalStateException("Unknown render phase " + phase); - } - } - - private void matchPass() { - if (!isRenderingWorld || isRenderingFullScreenPass || isPostChain || !isMainBound) { - return; - } - - if (sodiumTerrainRendering) { - beginPass(table.match(getCondition(getPhase()), new InputAvailability(true, true, false))); - return; - } - - beginPass(table.match(getCondition(getPhase()), inputs)); - } - - public void beginPass(Pass pass) { - if (current == pass) { - return; - } - - if (current != null) { - current.stopUsing(); - } - - current = pass; - - if (pass != null) { - pass.use(); - } else { - Program.unbind(); - } - } - - private Pass createDefaultPass() { - GlFramebuffer framebufferBeforeTranslucents; - GlFramebuffer framebufferAfterTranslucents; - - framebufferBeforeTranslucents = - renderTargets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); - framebufferAfterTranslucents = - renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, new int[] {0}); - - return new Pass(null, framebufferBeforeTranslucents, framebufferAfterTranslucents, null, - null, Collections.emptyList(), false); - } - - private Pass createPass(ProgramSource source, InputAvailability availability, boolean shadow, ProgramId id) { - // TODO: Properly handle empty shaders? - - - return createPassInner(null, source.getParent().getPack().getIdMap(), source.getDirectives(), source.getParent().getPackDirectives(), availability, shadow, id); - } - - private Pass createPassInner(ProgramBuilder builder, IdMap map, ProgramDirectives programDirectives, - PackDirectives packDirectives, InputAvailability availability, boolean shadow, ProgramId id) { - - CommonUniforms.addDynamicUniforms(builder, FogMode.PER_VERTEX); - this.customUniforms.assignTo(builder); - - Supplier> flipped; - - if (shadow) { - flipped = () -> (shouldRenderPrepareBeforeShadow ? flippedAfterPrepare : flippedBeforeShadow); - } else { - flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; - } - - TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; - - ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = - ProgramSamplers.customTextureSamplerInterceptor(builder, - customTextureManager.getCustomTextureIdMap(textureStage)); - - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); - IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); - IrisImages.addRenderTargetImages(builder, flipped, renderTargets); - - if (!shouldBindPBR) { - shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor); - } - - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, availability); - - if (!shadow) { - IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); - } - - IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); - - if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - if (!shadow) { - shadowTargetsSupplier.get(); - } - - if (shadowRenderTargets != null) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, false); - IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); - } - } - - GlFramebuffer framebufferBeforeTranslucents; - GlFramebuffer framebufferAfterTranslucents; - - if (shadow) { - // Always add both draw buffers on the shadow pass. - framebufferBeforeTranslucents = - shadowTargetsSupplier.get().createShadowFramebuffer(shadowRenderTargets.snapshot(), new int[] { 0, 1 }); - framebufferAfterTranslucents = framebufferBeforeTranslucents; - } else { - framebufferBeforeTranslucents = - renderTargets.createGbufferFramebuffer(flippedAfterPrepare, programDirectives.getDrawBuffers()); - framebufferAfterTranslucents = - renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, programDirectives.getDrawBuffers()); - } - - builder.bindAttributeLocation(11, "mc_Entity"); - builder.bindAttributeLocation(12, "mc_midTexCoord"); - builder.bindAttributeLocation(13, "at_tangent"); - builder.bindAttributeLocation(14, "at_midBlock"); - - AlphaTest alphaTestOverride = programDirectives.getAlphaTestOverride().orElse(null); - - List bufferOverrides = new ArrayList<>(); - - programDirectives.getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(programDirectives.getDrawBuffers(), information.getIndex()); - if (index > -1) { - bufferOverrides.add(new BufferBlendOverride(index, information.getBlendMode())); - } - }); - - Pass pass = new Pass(builder.build(), framebufferBeforeTranslucents, framebufferAfterTranslucents, alphaTestOverride, - programDirectives.getBlendModeOverride().orElse(id.getBlendModeOverride()), bufferOverrides, shadow); - - // tell the customUniforms that those locations belong to this pass - this.customUniforms.mapholderToPass(builder, pass); - - return pass; - } - - private boolean isPostChain; - private boolean isMainBound = true; - - @Override - public void beginPostChain() { - isPostChain = true; - - beginPass(null); - } - - @Override - public void endPostChain() { - isPostChain = false; - } - - @Override - public void setIsMainBound(boolean bound) { - isMainBound = bound; - - if (!isRenderingWorld || isRenderingFullScreenPass || isPostChain) { - return; - } - - if (bound) { - // force refresh - current = null; - } else { - beginPass(null); - } - } - - @Override - public Object2ObjectMap, String> getTextureMap() { - return customTextureMap; - } - - private final class Pass { - @Nullable - private final Program program; - private final GlFramebuffer framebufferBeforeTranslucents; - private final GlFramebuffer framebufferAfterTranslucents; - @Nullable - private final AlphaTest alphaTestOverride; - @Nullable - private final BlendModeOverride blendModeOverride; - @Nullable - private final List bufferBlendOverrides; - private final boolean shadowViewport; - - private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents, - @Nullable AlphaTest alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List bufferBlendOverrides, boolean shadowViewport) { - this.program = program; - this.framebufferBeforeTranslucents = framebufferBeforeTranslucents; - this.framebufferAfterTranslucents = framebufferAfterTranslucents; - this.alphaTestOverride = alphaTestOverride; - this.blendModeOverride = blendModeOverride; - this.bufferBlendOverrides = bufferBlendOverrides; - this.shadowViewport = shadowViewport; - } - - public void use() { - if (isBeforeTranslucent) { - framebufferBeforeTranslucents.bind(); - } else { - framebufferAfterTranslucents.bind(); - } - - if (shadowViewport) { - RenderSystem.viewport(0, 0, shadowMapResolution, shadowMapResolution); - } else { - RenderTarget main = Minecraft.getInstance().getMainRenderTarget(); - RenderSystem.viewport(0, 0, main.width, main.height); - } - - if (program != null) { - program.use(); - } - - // push the custom uniforms - DeferredWorldRenderingPipeline.this.customUniforms.push(this); - if (alphaTestOverride != null) { - AlphaTestStorage.overrideAlphaTest(alphaTestOverride); - } else { - // Previous program on the stack might have applied an override - AlphaTestStorage.restoreAlphaTest(); - } - - if (blendModeOverride != null) { - blendModeOverride.apply(); - } else { - // Previous program on the stack might have applied an override - BlendModeOverride.restore(); - } - - if (bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty()) { - bufferBlendOverrides.forEach(BufferBlendOverride::apply); - } - } - - public void stopUsing() { - if (alphaTestOverride != null) { - AlphaTestStorage.restoreAlphaTest(); - } - - if (blendModeOverride != null || (bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty())) { - BlendModeOverride.restore(); - } - } - - @Nullable - public Program getProgram() { - return program; - } - - public void destroy() { - if (this.program != null) { - this.program.destroy(); - } - } - } - - @Override - public void destroy() { - BlendModeOverride.restore(); - AlphaTestOverride.restore(); - - destroyPasses(table); - - // Destroy the composite rendering pipeline - // - // This destroys all the loaded composite programs as well. - compositeRenderer.destroy(); - deferredRenderer.destroy(); - finalPassRenderer.destroy(); - centerDepthSampler.destroy(); - - horizonRenderer.destroy(); - - // Make sure that any custom framebuffers are not bound before destroying render targets - GlStateManager._glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, 0); - GlStateManager._glBindFramebuffer(GL30C.GL_DRAW_FRAMEBUFFER, 0); - GlStateManager._glBindFramebuffer(GL30C.GL_FRAMEBUFFER, 0); - - Minecraft.getInstance().getMainRenderTarget().bindWrite(false); - // Destroy our render targets - // - // While it's possible to just clear them instead and reuse them, we'd need to investigate whether or not this - // would help performance. - renderTargets.destroy(); - - // destroy the shadow render targets - if (shadowRenderTargets != null) { - shadowRenderTargets.destroy(); - } - - // Destroy custom textures and the static samplers (normals, specular, and noise) - customTextureManager.destroy(); - whitePixel.releaseId(); - - if (shaderStorageBufferHolder != null) { - // Destroy shader storage buffer objects - shaderStorageBufferHolder.destroyBuffers(); - } - } - - private static void destroyPasses(ProgramTable table) { - Set destroyed = new HashSet<>(); - - table.forEach(pass -> { - if (pass == null) { - return; - } - - if (destroyed.contains(pass)) { - return; - } - - pass.destroy(); - destroyed.add(pass); - }); - } - - private void prepareRenderTargets() { - // Make sure we're using texture unit 0 for this. - RenderSystem.activeTexture(GL15C.GL_TEXTURE0); - Vector4f emptyClearColor = new Vector4f(1.0F); - - if (shadowRenderTargets != null) { - if (packDirectives.getShadowDirectives().isShadowEnabled() == OptionalBoolean.FALSE) { - if (shadowRenderTargets.isFullClearRequired()) { - shadowRenderTargets.onFullClear(); - for (ClearPass clearPass : shadowClearPassesFull) { - clearPass.execute(emptyClearColor); - } - } - } else { - // Clear depth first, regardless of any color clearing. - shadowRenderTargets.getDepthSourceFb().bind(); - RenderSystem.clear(GL21C.GL_DEPTH_BUFFER_BIT, Minecraft.ON_OSX); - - ImmutableList passes; - - for (ComputeProgram computeProgram : shadowComputes) { - if (computeProgram != null) { - computeProgram.use(); - this.customUniforms.push(computeProgram); - computeProgram.dispatch(shadowMapResolution, shadowMapResolution); - } - } - - if (shadowRenderTargets.isFullClearRequired()) { - passes = shadowClearPassesFull; - shadowRenderTargets.onFullClear(); - } else { - passes = shadowClearPasses; - } - - for (ClearPass clearPass : passes) { - clearPass.execute(emptyClearColor); - } - } - } - - RenderTarget main = Minecraft.getInstance().getMainRenderTarget(); - Blaze3dRenderTargetExt mainExt = (Blaze3dRenderTargetExt) main; - - int depthTextureId = main.getDepthTextureId(); - int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat(); - DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); - - boolean changed = renderTargets.resizeIfNeeded(mainExt.iris$getDepthBufferVersion(), depthTextureId, main.width, - main.height, depthBufferFormat, packDirectives); - - if (changed) { - prepareRenderer.recalculateSizes(); - deferredRenderer.recalculateSizes(); - compositeRenderer.recalculateSizes(); - finalPassRenderer.recalculateSwapPassSize(); - - this.clearPassesFull.forEach(clearPass -> renderTargets.destroyFramebuffer(clearPass.getFramebuffer())); - this.clearPasses.forEach(clearPass -> renderTargets.destroyFramebuffer(clearPass.getFramebuffer())); - - this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, - packDirectives.getRenderTargetDirectives()); - this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, - packDirectives.getRenderTargetDirectives()); - } - - final ImmutableList passes; - - if (renderTargets.isFullClearRequired()) { - renderTargets.onFullClear(); - passes = clearPassesFull; - } else { - passes = clearPasses; - } - - Vector3d fogColor3 = CapturedRenderingState.INSTANCE.getFogColor(); - - // NB: The alpha value must be 1.0 here, or else you will get a bunch of bugs. Sildur's Vibrant Shaders - // will give you pink reflections and other weirdness if this is zero. - Vector4f fogColor = new Vector4f((float) fogColor3.x, (float) fogColor3.y, (float) fogColor3.z, 1.0F); - - for (ClearPass clearPass : passes) { - clearPass.execute(fogColor); - } - - // Reset framebuffer and viewport - Minecraft.getInstance().getMainRenderTarget().bindWrite(true); - } - - private ComputeProgram[] createShadowComputes(ComputeSource[] compute, ProgramSet programSet) { - ComputeProgram[] programs = new ComputeProgram[compute.length]; - for (int i = 0; i < programs.length; i++) { - ComputeSource source = compute[i]; - if (source == null || !source.getSource().isPresent()) { - continue; - } else { - ProgramBuilder builder; - - try { - builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); - } catch (ShaderCompileException e) { - throw e; - } catch (RuntimeException e) { - // TODO: Better error handling - throw new RuntimeException("Shader compilation failed!", e); - } - - CommonUniforms.addDynamicUniforms(builder, FogMode.OFF); - this.customUniforms.assignTo(builder); - - Supplier> flipped; - - flipped = () -> flippedBeforeShadow; - - TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; - - ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = - ProgramSamplers.customTextureSamplerInterceptor(builder, - customTextureManager.getCustomTextureIdMap(textureStage)); - - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); - IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); - IrisImages.addRenderTargetImages(builder, flipped, renderTargets); - - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); - - IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); - - if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { - if (shadowRenderTargets != null) { - IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets, null, false); - IrisImages.addShadowColorImages(builder, shadowRenderTargets, null); - } - } - - programs[i] = builder.buildCompute(); - - // tell the customUniforms that those locations belong to this pass - this.customUniforms.mapholderToPass(builder, programs[i]); - - programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups()); - } - } - - - return programs; - } - - @Override - public void beginHand() { - // We need to copy the current depth texture so that depthtex2 can contain the depth values for - // all non-translucent content without the hand, as required. - renderTargets.copyPreHandDepth(); - } - - @Override - public void beginTranslucents() { - isBeforeTranslucent = false; - - // We need to copy the current depth texture so that depthtex1 can contain the depth values for - // all non-translucent content, as required. - renderTargets.copyPreTranslucentDepth(); - - - // needed to remove blend mode overrides and similar - beginPass(null); - - isRenderingFullScreenPass = true; - - deferredRenderer.renderAll(); - - RenderSystem.enableBlend(); - - // note: we are careful not to touch the lightmap texture unit or overlay color texture unit here, - // so we don't need to do anything to restore them if needed. - // - // Previous versions of the code tried to "restore" things by enabling the lightmap & overlay color - // but that actually broke rendering of clouds and rain by making them appear red in the case of - // a pack not overriding those shader programs. - // - // Not good! - - isRenderingFullScreenPass = false; - } - - @Override - public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCamera) { - if (shouldRenderPrepareBeforeShadow) { - isRenderingFullScreenPass = true; - - prepareRenderer.renderAll(); - - isRenderingFullScreenPass = false; - } - - if (shadowRenderer != null) { - isRenderingShadow = true; - - shadowRenderer.renderShadows(levelRenderer, playerCamera); - - // needed to remove blend mode overrides and similar - beginPass(null); - isRenderingShadow = false; - } - - if (!shouldRenderPrepareBeforeShadow) { - isRenderingFullScreenPass = true; - - prepareRenderer.renderAll(); - - isRenderingFullScreenPass = false; - } - } - - @Override - public void addDebugText(List messages) { - messages.add(""); - - if (shadowRenderer != null) { - shadowRenderer.addDebugText(messages); - } else { - messages.add("[Iris] Shadow Maps: not used by shader pack"); - } - } - - @Override - public OptionalInt getForcedShadowRenderDistanceChunksForDisplay() { - return forcedShadowRenderDistanceChunks; - } - - // TODO: better way to avoid this global state? - private boolean isRenderingWorld = false; - private boolean isRenderingFullScreenPass = false; - - @Override - public void onShadowBufferChange() { - - } - - @Override - public void beginLevelRendering() { - isRenderingFullScreenPass = false; - isRenderingWorld = true; - isBeforeTranslucent = true; - isMainBound = true; - isPostChain = false; - phase = WorldRenderingPhase.NONE; - overridePhase = null; - HandRenderer.INSTANCE.getBufferSource().resetDrawCalls(); - - checkWorld(); - - if (!isRenderingWorld) { - Iris.logger.warn("beginWorldRender was called but we are not currently rendering a world?"); - return; - } - - if (current != null) { - throw new IllegalStateException("Called beginLevelRendering but level rendering appears to still be in progress?"); - } - - if (showSSBOError) { - showSSBOError = false; - if (Minecraft.getInstance().player != null) { - } - } - - updateNotifier.onNewFrame(); - // Get ready for world rendering - prepareRenderTargets(); - - // Update custom uniforms - DeferredWorldRenderingPipeline.this.customUniforms.update(); - - setPhase(WorldRenderingPhase.SKY); - - // Render our horizon box before actual sky rendering to avoid being broken by mods that do weird things - // while rendering the sky. - // - // A lot of dimension mods touch sky rendering, FabricSkyboxes injects at HEAD and cancels, etc. - DimensionSpecialEffects.SkyType skyType = Minecraft.getInstance().level.effects().skyType(); - - if (skyType == DimensionSpecialEffects.SkyType.NORMAL) { - RenderSystem.depthMask(false); - - Vector3d fogColor = CapturedRenderingState.INSTANCE.getFogColor(); - RenderSystem.setShaderColor((float) fogColor.x, (float) fogColor.y, (float) fogColor.z, 1.0f); - - horizonRenderer.renderHorizon(CapturedRenderingState.INSTANCE.getGbufferModelView(), CapturedRenderingState.INSTANCE.getGbufferProjection(), GameRenderer.getPositionShader()); - - RenderSystem.depthMask(true); - } - } - - @Override - public void finalizeLevelRendering() { - checkWorld(); - - if (!isRenderingWorld) { - Iris.logger.warn("finalizeWorldRendering was called but we are not currently rendering a world?"); - return; - } - - beginPass(null); - - isRenderingWorld = false; - phase = WorldRenderingPhase.NONE; - overridePhase = null; - - isRenderingFullScreenPass = true; - - centerDepthSampler.sampleCenterDepth(); - - compositeRenderer.renderAll(); - finalPassRenderer.renderFinalPass(); - - isRenderingFullScreenPass = false; - } - - @Override - public void finalizeGameRendering() { - - } - - @Override - public SodiumTerrainPipeline getSodiumTerrainPipeline() { - return sodiumTerrainPipeline; - } - - @Override - public FrameUpdateNotifier getFrameUpdateNotifier() { - return updateNotifier; - } - - @Override - public WorldRenderingPhase getPhase() { - if (overridePhase != null) { - return overridePhase; - } - - return phase; - } - - boolean sodiumTerrainRendering = false; - - //@Override - public void syncProgram() { - matchPass(); - } - - @Override - public void beginSodiumTerrainRendering() { - sodiumTerrainRendering = true; - syncProgram(); - - } - - @Override - public void endSodiumTerrainRendering() { - sodiumTerrainRendering = false; - current = null; - syncProgram(); - } - - @Override - public void setOverridePhase(WorldRenderingPhase phase) { - this.overridePhase = phase; - - GbufferPrograms.runPhaseChangeNotifier(); - } - - @Override - public void setPhase(WorldRenderingPhase phase) { - this.phase = phase; - - GbufferPrograms.runPhaseChangeNotifier(); - } - - //@Override - public void setInputs(InputAvailability availability) { - this.inputs = availability; - } - - @Override - public void setSpecialCondition(SpecialCondition special) { - this.special = special; - } - - @Override - public RenderTargetStateListener getRenderTargetStateListener() { - return this; - } - - @Override - public int getCurrentNormalTexture() { - return currentNormalTexture; - } - - @Override - public int getCurrentSpecularTexture() { - return currentSpecularTexture; - } - - @Override - public void onSetShaderTexture(int id) { - if (shouldBindPBR && isRenderingWorld) { - PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); - currentNormalTexture = pbrHolder.getNormalTexture().getId(); - currentSpecularTexture = pbrHolder.getSpecularTexture().getId(); - - TextureFormat textureFormat = TextureFormatLoader.getFormat(); - if (textureFormat != null) { - textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); - textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); - } - - PBRTextureManager.notifyPBRTexturesChanged(); - } - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/LightningHandler.java b/src/main/java/net/coderbot/iris/pipeline/LightningHandler.java deleted file mode 100644 index 82945958b9..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/LightningHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.coderbot.iris.pipeline; - -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.layer.InnerWrappedRenderType; -import net.coderbot.iris.layer.LightningRenderStateShard; -import net.coderbot.iris.layer.OuterWrappedRenderType; -import net.minecraft.client.renderer.RenderType; - -public class LightningHandler extends RenderType { - public static final RenderType IRIS_LIGHTNING = new InnerWrappedRenderType("iris_lightning2", RenderType.create( - "iris_lightning", - DefaultVertexFormat.POSITION_COLOR, - VertexFormat.Mode.QUADS, - 256, - false, - true, - RenderType.CompositeState.builder() - .setShaderState(RENDERTYPE_LIGHTNING_SHADER) - .setWriteMaskState(COLOR_DEPTH_WRITE) - .setTransparencyState(LIGHTNING_TRANSPARENCY) - .setOutputState(WEATHER_TARGET) - .createCompositeState(false) - ), new LightningRenderStateShard()); - - public LightningHandler(String pRenderType0, VertexFormat pVertexFormat1, VertexFormat.Mode pVertexFormat$Mode2, int pInt3, boolean pBoolean4, boolean pBoolean5, Runnable pRunnable6, Runnable pRunnable7) { - super(pRenderType0, pVertexFormat1, pVertexFormat$Mode2, pInt3, pBoolean4, pBoolean5, pRunnable6, pRunnable7); - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/CoreWorldRenderingPipeline.java b/src/main/java/net/coderbot/iris/pipeline/newshader/CoreWorldRenderingPipeline.java deleted file mode 100644 index 51e46c6802..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/CoreWorldRenderingPipeline.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.coderbot.iris.pipeline.newshader; - -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; - -public interface CoreWorldRenderingPipeline extends WorldRenderingPipeline { - ShaderMap getShaderMap(); - FrameUpdateNotifier getFrameUpdateNotifier(); - void destroy(); - - boolean shouldOverrideShaders(); -} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/NewShaderTests.java b/src/main/java/net/coderbot/iris/pipeline/newshader/NewShaderTests.java deleted file mode 100644 index 5df1309e16..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/NewShaderTests.java +++ /dev/null @@ -1,247 +0,0 @@ -package net.coderbot.iris.pipeline.newshader; - -import com.google.common.collect.ImmutableSet; -import com.google.common.primitives.Ints; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import net.coderbot.iris.gl.blending.AlphaTest; -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.ShaderPrinter; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.fallback.FallbackShader; -import net.coderbot.iris.pipeline.newshader.fallback.ShaderSynthesizer; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.loading.ProgramId; -import net.coderbot.iris.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.VanillaUniforms; -import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; -import net.coderbot.iris.uniforms.custom.CustomUniforms; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.PathPackResources; -import net.minecraft.server.packs.resources.IoSupplier; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraftforge.fml.loading.FMLPaths; -import org.apache.commons.io.IOUtils; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Supplier; - -public class NewShaderTests { - public static ExtendedShader create(WorldRenderingPipeline pipeline, String name, ProgramSource source, ProgramId programId, GlFramebuffer writingToBeforeTranslucent, - GlFramebuffer writingToAfterTranslucent, GlFramebuffer baseline, AlphaTest fallbackAlpha, - VertexFormat vertexFormat, ShaderAttributeInputs inputs, FrameUpdateNotifier updateNotifier, - NewWorldRenderingPipeline parent, Supplier> flipped, FogMode fogMode, boolean isIntensity, - boolean isFullbright, boolean isShadowPass, boolean isLines, CustomUniforms customUniforms) throws IOException { - AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha); - BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride()); - - Map transformed = TransformPatcher.patchVanilla( - name, - source.getVertexSource().orElseThrow(RuntimeException::new), - source.getGeometrySource().orElse(null), - source.getTessControlSource().orElse(null), - source.getTessEvalSource().orElse(null), - source.getFragmentSource().orElseThrow(RuntimeException::new), - alpha, isLines, true, inputs, pipeline.getTextureMap()); - String vertex = transformed.get(PatchShaderType.VERTEX); - String geometry = transformed.get(PatchShaderType.GEOMETRY); - String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); - String tessEval = transformed.get(PatchShaderType.TESS_EVAL); - String fragment = transformed.get(PatchShaderType.FRAGMENT); - - StringBuilder shaderJson = new StringBuilder("{\n" + - " \"blend\": {\n" + - " \"func\": \"add\",\n" + - " \"srcrgb\": \"srcalpha\",\n" + - " \"dstrgb\": \"1-srcalpha\"\n" + - " },\n" + - " \"vertex\": \"" + name + "\",\n" + - " \"fragment\": \"" + name + "\",\n" + - " \"attributes\": [\n" + - " \"Position\",\n" + - " \"Color\",\n" + - " \"UV0\",\n" + - " \"UV1\",\n" + - " \"UV2\",\n" + - " \"Normal\"\n" + - " ],\n" + - " \"uniforms\": [\n" + - " { \"name\": \"iris_TextureMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"iris_ModelViewMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"iris_ModelViewMatInverse\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"iris_ProjMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"iris_ProjMatInverse\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"iris_NormalMat\", \"type\": \"matrix3x3\", \"count\": 9, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 ] },\n" + - " { \"name\": \"iris_ChunkOffset\", \"type\": \"float\", \"count\": 3, \"values\": [ 0.0, 0.0, 0.0 ] },\n" + - " { \"name\": \"iris_ColorModulator\", \"type\": \"float\", \"count\": 4, \"values\": [ 1.0, 1.0, 1.0, 1.0 ] },\n" + - " { \"name\": \"iris_GlintAlpha\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"iris_FogStart\", \"type\": \"float\", \"count\": 1, \"values\": [ 0.0 ] },\n" + - " { \"name\": \"iris_FogEnd\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"iris_FogColor\", \"type\": \"float\", \"count\": 4, \"values\": [ 0.0, 0.0, 0.0, 0.0 ] }\n" + - " ]\n" + - "}"); - - String shaderJsonString = shaderJson.toString(); - - ShaderPrinter.printProgram(name).addSources(transformed).addJson(shaderJsonString).print(); - - ResourceProvider shaderResourceFactory = new IrisProgramResourceFactory(shaderJsonString, vertex, geometry, tessControl, tessEval, fragment); - - List overrides = new ArrayList<>(); - source.getDirectives().getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(source.getDirectives().getDrawBuffers(), information.getIndex()); - if (index > -1) { - overrides.add(new BufferBlendOverride(index, information.getBlendMode())); - } - }); - - return new ExtendedShader(shaderResourceFactory, name, vertexFormat, tessControl != null || tessEval != null, writingToBeforeTranslucent, writingToAfterTranslucent, baseline, blendModeOverride, alpha, uniforms -> { - CommonUniforms.addDynamicUniforms(uniforms, FogMode.PER_VERTEX); - customUniforms.assignTo(uniforms); - //SamplerUniforms.addWorldSamplerUniforms(uniforms); - //SamplerUniforms.addDepthSamplerUniforms(uniforms); - BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms); - VanillaUniforms.addVanillaUniforms(uniforms); - }, (samplerHolder, imageHolder) -> { - parent.addGbufferOrShadowSamplers(samplerHolder, imageHolder, flipped, isShadowPass, inputs.toAvailability()); - }, isIntensity, parent, inputs, overrides, customUniforms); - } - - public static FallbackShader createFallback(String name, GlFramebuffer writingToBeforeTranslucent, - GlFramebuffer writingToAfterTranslucent, AlphaTest alpha, - VertexFormat vertexFormat, BlendModeOverride blendModeOverride, - NewWorldRenderingPipeline parent, FogMode fogMode, boolean entityLighting, - boolean isGlint, boolean isText, boolean intensityTex, boolean isFullbright) throws IOException { - ShaderAttributeInputs inputs = new ShaderAttributeInputs(vertexFormat, isFullbright, false, isGlint, isText); - - // TODO: Is this check sound in newer versions? - boolean isLeash = vertexFormat == DefaultVertexFormat.POSITION_COLOR_LIGHTMAP; - String vertex = ShaderSynthesizer.vsh(true, inputs, fogMode, entityLighting, isLeash); - String fragment = ShaderSynthesizer.fsh(inputs, fogMode, alpha, intensityTex, isLeash); - - - String shaderJsonString = "{\n" + - " \"blend\": {\n" + - " \"func\": \"add\",\n" + - " \"srcrgb\": \"srcalpha\",\n" + - " \"dstrgb\": \"1-srcalpha\"\n" + - " },\n" + - " \"vertex\": \"" + name + "\",\n" + - " \"fragment\": \"" + name + "\",\n" + - " \"attributes\": [\n" + - " \"Position\",\n" + - " \"Color\",\n" + - (inputs.hasTex() ? " \"UV0\",\n" : "") + - (inputs.hasOverlay() ? " \"UV1\",\n" : "") + - (inputs.hasLight() ? " \"UV2\",\n" : "") + - " \"Normal\"\n" + - " ],\n" + - " \"uniforms\": [\n" + - " { \"name\": \"TextureMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"ModelViewMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"ProjMat\", \"type\": \"matrix4x4\", \"count\": 16, \"values\": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] },\n" + - " { \"name\": \"ChunkOffset\", \"type\": \"float\", \"count\": 3, \"values\": [ 0.0, 0.0, 0.0 ] },\n" + - " { \"name\": \"ColorModulator\", \"type\": \"float\", \"count\": 4, \"values\": [ 1.0, 1.0, 1.0, 1.0 ] },\n" + - " { \"name\": \"GlintAlpha\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"Light0_Direction\", \"type\": \"float\", \"count\": 3, \"values\": [0.0, 0.0, 0.0] },\n" + - " { \"name\": \"Light1_Direction\", \"type\": \"float\", \"count\": 3, \"values\": [0.0, 0.0, 0.0] },\n" + - " { \"name\": \"FogStart\", \"type\": \"float\", \"count\": 1, \"values\": [ 0.0 ] },\n" + - " { \"name\": \"FogEnd\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"FogDensity\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"FogIsExp2\", \"type\": \"int\", \"count\": 1, \"values\": [ 0 ] },\n" + - " { \"name\": \"AlphaTestValue\", \"type\": \"float\", \"count\": 1, \"values\": [ 0.0 ] },\n" + - " { \"name\": \"LineWidth\", \"type\": \"float\", \"count\": 1, \"values\": [ 1.0 ] },\n" + - " { \"name\": \"ScreenSize\", \"type\": \"float\", \"count\": 2, \"values\": [ 1.0, 1.0 ] },\n" + - " { \"name\": \"FogColor\", \"type\": \"float\", \"count\": 4, \"values\": [ 0.0, 0.0, 0.0, 0.0 ] }\n" + - " ]\n" + - "}"; - - ShaderPrinter.printProgram(name) - .addSource(PatchShaderType.VERTEX, vertex) - .addSource(PatchShaderType.FRAGMENT, fragment) - .addJson(shaderJsonString) - .print(); - - ResourceProvider shaderResourceFactory = new IrisProgramResourceFactory(shaderJsonString, vertex, null, null, null, fragment); - - return new FallbackShader(shaderResourceFactory, name, vertexFormat, writingToBeforeTranslucent, - writingToAfterTranslucent, blendModeOverride, alpha.getReference(), parent); - } - - private static class IrisProgramResourceFactory implements ResourceProvider { - private final String json; - private final String vertex; - private final String geometry; - private final String tessControl; - private final String tessEval; - private final String fragment; - - public IrisProgramResourceFactory(String json, String vertex, String geometry, String tessControl, String tessEval, String fragment) { - this.json = json; - this.vertex = vertex; - this.geometry = geometry; - this.tessControl = tessControl; - this.tessEval = tessEval; - this.fragment = fragment; - } - - @Override - public Optional getResource(ResourceLocation id) { - final String path = id.getPath(); - - if (path.endsWith("json")) { - return Optional.of(new StringResource(id, json)); - } else if (path.endsWith("vsh")) { - return Optional.of(new StringResource(id, vertex)); - } else if (path.endsWith("gsh")) { - if (geometry == null) { - return Optional.empty(); - } - return Optional.of(new StringResource(id, geometry)); - } else if (path.endsWith("tcs")) { - if (tessControl == null) { - return Optional.empty(); - } - return Optional.of(new StringResource(id, tessControl)); - } else if (path.endsWith("tes")) { - if (tessEval == null) { - return Optional.empty(); - } - return Optional.of(new StringResource(id, tessEval)); - } else if (path.endsWith("fsh")) { - return Optional.of(new StringResource(id, fragment)); - } - - return Optional.empty(); - } - } - - private static class StringResource extends Resource { - private final ResourceLocation id; - private final String content; - - private StringResource(ResourceLocation id, String content) { - super(new PathPackResources("", FMLPaths.CONFIGDIR.get(), true), (IoSupplier) () -> new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))); - this.id = id; - this.content = content; - } - - @Override - public InputStream open() throws IOException { - return IOUtils.toInputStream(content, StandardCharsets.UTF_8); - } - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderKey.java b/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderKey.java deleted file mode 100644 index 9044bdaac8..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderKey.java +++ /dev/null @@ -1,145 +0,0 @@ -package net.coderbot.iris.pipeline.newshader; - -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.shaderpack.loading.ProgramId; -import net.coderbot.iris.vertices.IrisVertexFormats; - -import java.util.Locale; - -public enum ShaderKey { - // if you auto-format this and destroy all the manual indentation, I'll steal your kneecaps - - BASIC (ProgramId.Basic, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - BASIC_COLOR (ProgramId.Basic, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - TEXTURED (ProgramId.Textured, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP ), - TEXTURED_COLOR (ProgramId.Textured, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - SKY_BASIC (ProgramId.SkyBasic, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - SKY_BASIC_COLOR (ProgramId.SkyBasic, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - SKY_TEXTURED (ProgramId.SkyTextured, AlphaTests.OFF, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP ), - SKY_TEXTURED_COLOR (ProgramId.SkyTextured, AlphaTests.OFF, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - CLOUDS (ProgramId.Clouds, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR_NORMAL, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - CLOUDS_SODIUM (ProgramId.Clouds, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.CLOUDS, FogMode.PER_FRAGMENT, LightingModel.LIGHTMAP ), - TERRAIN_SOLID (ProgramId.TerrainSolid,AlphaTests.OFF, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TERRAIN_CUTOUT (ProgramId.TerrainCutout,AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TERRAIN_TRANSLUCENT (ProgramId.Water, AlphaTests.OFF, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - MOVING_BLOCK (ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - ENTITIES_ALPHA (ProgramId.Entities, AlphaTests.VERTEX_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - ENTITIES_SOLID (ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - ENTITIES_SOLID_DIFFUSE (ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - ENTITIES_SOLID_BRIGHT (ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - ENTITIES_CUTOUT (ProgramId.Entities, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - ENTITIES_CUTOUT_DIFFUSE(ProgramId.Entities, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - ENTITIES_TRANSLUCENT (ProgramId.EntitiesTrans,AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - ENTITIES_EYES (ProgramId.SpiderEyes, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - ENTITIES_EYES_TRANS (ProgramId.SpiderEyes, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - HAND_CUTOUT (ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - HAND_CUTOUT_BRIGHT (ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - HAND_CUTOUT_DIFFUSE (ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - HAND_TEXT (ProgramId.Hand, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - HAND_TEXT_INTENSITY (ProgramId.Hand, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - HAND_TRANSLUCENT (ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - HAND_WATER_BRIGHT (ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - HAND_WATER_DIFFUSE (ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - LIGHTNING (ProgramId.Entities, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - LEASH (ProgramId.Basic, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TEXT_BG (ProgramId.EntitiesTrans,AlphaTests.ONE_TENTH_ALPHA,DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - PARTICLES (ProgramId.Particles, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - PARTICLES_TRANS (ProgramId.ParticlesTrans,AlphaTests.ONE_TENTH_ALPHA,DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - WEATHER (ProgramId.Weather, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - CRUMBLING (ProgramId.DamagedBlock,AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.OFF, LightingModel.LIGHTMAP ), - TEXT (ProgramId.EntitiesTrans,AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TEXT_INTENSITY (ProgramId.EntitiesTrans,AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TEXT_BE (ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - TEXT_INTENSITY_BE (ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA,IrisVertexFormats.GLYPH , FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - BLOCK_ENTITY (ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - BLOCK_ENTITY_BRIGHT (ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), - BLOCK_ENTITY_DIFFUSE (ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - BE_TRANSLUCENT (ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), - BEACON (ProgramId.BeaconBeam, AlphaTests.OFF, DefaultVertexFormat.BLOCK, FogMode.PER_FRAGMENT, LightingModel.FULLBRIGHT), - GLINT (ProgramId.ArmorGlint, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - LINES (ProgramId.Line, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_NORMAL, FogMode.PER_VERTEX, LightingModel.LIGHTMAP ), - - // Note: These must be at the very end (NewWorldRenderingPipeline implementation details) - SHADOW_TERRAIN_CUTOUT (ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_ENTITIES_CUTOUT (ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_BEACON_BEAM (ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.BLOCK, FogMode.OFF, LightingModel.FULLBRIGHT), - SHADOW_BASIC (ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_BASIC_COLOR (ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_TEX (ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_TEX_COLOR (ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_CLOUDS (ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR_NORMAL, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_LINES (ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_NORMAL, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_LEASH (ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_LIGHTNING (ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.FULLBRIGHT), - SHADOW_PARTICLES (ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_TEXT (ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH , FogMode.OFF, LightingModel.LIGHTMAP ), - SHADOW_TEXT_BG (ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.OFF , LightingModel.LIGHTMAP ), - SHADOW_TEXT_INTENSITY (ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH , FogMode.OFF, LightingModel.LIGHTMAP ); - - private final ProgramId program; - private final AlphaTest alphaTest; - private final VertexFormat vertexFormat; - private final FogMode fogMode; - private final LightingModel lightingModel; - - ShaderKey(ProgramId program, AlphaTest alphaTest, VertexFormat vertexFormat, FogMode fogMode, LightingModel lightingModel) { - this.program = program; - this.alphaTest = alphaTest; - this.vertexFormat = vertexFormat; - this.fogMode = fogMode; - this.lightingModel = lightingModel; - } - - public ProgramId getProgram() { - return program; - } - - public AlphaTest getAlphaTest() { - return alphaTest; - } - - public VertexFormat getVertexFormat() { - return vertexFormat; - } - - public FogMode getFogMode() { - return fogMode; - } - - public boolean isIntensity() { - return this == TEXT_INTENSITY || this == TEXT_INTENSITY_BE || this == SHADOW_TEXT_INTENSITY; - } - - public String getName() { - return toString().toLowerCase(Locale.ROOT); - } - - public boolean isShadow() { - return this.getProgram() == ProgramId.Shadow; - } - - public boolean hasDiffuseLighting() { - return lightingModel == LightingModel.DIFFUSE || lightingModel == LightingModel.DIFFUSE_LM; - } - - public boolean shouldIgnoreLightmap() { - return lightingModel == LightingModel.FULLBRIGHT || lightingModel == LightingModel.DIFFUSE; - } - - public boolean isGlint() { - return this == GLINT; - } - - public boolean isText() { - return this.name().contains("TEXT"); - } - - enum LightingModel { - FULLBRIGHT, - LIGHTMAP, - DIFFUSE, - DIFFUSE_LM - } -} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java b/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java deleted file mode 100644 index a3c8474b69..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/PatchShaderType.java +++ /dev/null @@ -1,39 +0,0 @@ -package net.coderbot.iris.pipeline.transform; - -import net.coderbot.iris.gl.shader.ShaderType; - -public enum PatchShaderType { - VERTEX(ShaderType.VERTEX, ".vsh"), - GEOMETRY(ShaderType.GEOMETRY, ".gsh"), - TESS_CONTROL(ShaderType.TESSELATION_CONTROL, ".tcs"), - TESS_EVAL(ShaderType.TESSELATION_EVAL, ".tes"), - FRAGMENT(ShaderType.FRAGMENT, ".fsh"), - COMPUTE(ShaderType.COMPUTE, ".csh"); - - public final ShaderType glShaderType; - public final String extension; - - private PatchShaderType(ShaderType glShaderType, String extension) { - this.glShaderType = glShaderType; - this.extension = extension; - } - - public static PatchShaderType[] fromGlShaderType(ShaderType glShaderType) { - switch (glShaderType) { - case VERTEX: - return new PatchShaderType[] { VERTEX }; - case GEOMETRY: - return new PatchShaderType[] { GEOMETRY }; - case TESSELATION_CONTROL: - return new PatchShaderType[] { TESS_CONTROL }; - case TESSELATION_EVAL: - return new PatchShaderType[] { TESS_EVAL }; - case COMPUTE: - return new PatchShaderType[] { COMPUTE }; - case FRAGMENT: - return new PatchShaderType[] { FRAGMENT }; - default: - throw new IllegalArgumentException("Unknown shader type: " + glShaderType); - } - } -} 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 deleted file mode 100644 index fd9a81ecfe..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/AttributeParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.coderbot.iris.pipeline.transform.parameter; - -import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.shaderpack.texture.TextureStage; - -public class AttributeParameters extends GeometryInfoParameters { - public final InputAvailability inputs; - // WARNING: adding new fields requires updating hashCode and equals methods! - - public AttributeParameters(Patch patch, - Object2ObjectMap, String> textureMap, - boolean hasGeometry, - InputAvailability inputs) { - super(patch, textureMap, hasGeometry, false); - this.inputs = inputs; - } - - @Override - public TextureStage getTextureStage() { - return TextureStage.GBUFFERS_AND_SHADOW; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - 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 (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/transformer/TextureTransformer.java b/src/main/java/net/coderbot/iris/pipeline/transform/transformer/TextureTransformer.java deleted file mode 100644 index 6934fdcdb1..0000000000 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/TextureTransformer.java +++ /dev/null @@ -1,72 +0,0 @@ -package net.coderbot.iris.pipeline.transform.transformer; - -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.declaration.TypeAndInitDeclaration; -import io.github.douira.glsl_transformer.ast.node.external_declaration.DeclarationExternalDeclaration; -import io.github.douira.glsl_transformer.ast.node.type.specifier.BuiltinFixedTypeSpecifier; -import io.github.douira.glsl_transformer.ast.query.Root; -import io.github.douira.glsl_transformer.ast.transform.ASTParser; -import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.shaderpack.texture.TextureStage; - -public class TextureTransformer { - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - TextureStage stage, Object2ObjectMap, String> textureMap) { - textureMap.forEach((stringTextureTypeTextureStageTri, s) -> { - if (stringTextureTypeTextureStageTri.getThird() == stage) { - String name = stringTextureTypeTextureStageTri.getFirst(); - - // check if the declaration has the right type and rename if one is found - // iterates all hits of the identifier and checks the ancestors - for (Identifier id : root.identifierIndex.get(name)) { - TypeAndInitDeclaration initDeclaration = (TypeAndInitDeclaration) id.getAncestor( - 2, 0, TypeAndInitDeclaration.class::isInstance); - if (initDeclaration == null) { - continue; - } - DeclarationExternalDeclaration declaration = (DeclarationExternalDeclaration) initDeclaration.getAncestor( - 1, 0, DeclarationExternalDeclaration.class::isInstance); - if (declaration == null) { - continue; - } - if (initDeclaration.getType().getTypeSpecifier() instanceof BuiltinFixedTypeSpecifier fixed - && isTypeValid(stringTextureTypeTextureStageTri.getSecond(), fixed.type)) { - root.rename(stringTextureTypeTextureStageTri.getFirst(), s); - break; - } - } - } - }); - } - - private static boolean isTypeValid(TextureType expectedType, BuiltinFixedTypeSpecifier.BuiltinType extractedType) { - switch (expectedType) { - case TEXTURE_1D: - return extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER1D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER1D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER1D; - case TEXTURE_RECTANGLE: - return extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER2DRECT || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER2DRECT || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER2DRECT; - case TEXTURE_2D: - return extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER2D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER2D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER2D; - case TEXTURE_3D: - return extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER3D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER3D || - extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER3D; - default: - // not TransformationException because this should never happen - throw new IllegalStateException("Unexpected enum! " + expectedType); - } - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/ImageInformation.java b/src/main/java/net/coderbot/iris/shaderpack/ImageInformation.java deleted file mode 100644 index eb5b3bd276..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/ImageInformation.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.coderbot.iris.shaderpack; - -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; -import net.coderbot.iris.gl.texture.TextureType; - -public record ImageInformation(String name, String samplerName, TextureType target, PixelFormat format, InternalTextureFormat internalTextureFormat, - PixelType type, int width, int height, int depth, boolean clear, boolean isRelative, float relativeWidth, float relativeHeight) { -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/OrderBackedProperties.java b/src/main/java/net/coderbot/iris/shaderpack/OrderBackedProperties.java deleted file mode 100644 index 5c391db42b..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/OrderBackedProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.coderbot.iris.shaderpack; - -import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; - -import java.util.Map; -import java.util.Properties; -import java.util.function.BiConsumer; - -/** - * Properties backed by a {@link java.util.LinkedHashMap}, in order to preserve iteration order - */ -public class OrderBackedProperties extends Properties { - private transient final Map backing = Object2ObjectMaps.synchronize(new Object2ObjectLinkedOpenHashMap<>()); - - @Override - public synchronized Object put(Object key, Object value) { - backing.put(key, value); - - return super.put(key, value); - } - - @Override - public synchronized void forEach(BiConsumer action) { - this.backing.forEach(action); - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/error/RusticError.java b/src/main/java/net/coderbot/iris/shaderpack/error/RusticError.java deleted file mode 100644 index 4e188d76f0..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/error/RusticError.java +++ /dev/null @@ -1,55 +0,0 @@ -package net.coderbot.iris.shaderpack.error; - -import org.apache.commons.lang3.StringUtils; - -public class RusticError { - private final String severity; - private final String message; - private final String detailMessage; - private final String file; - private final int lineNumber; - private final String badLine; - - public RusticError(String severity, String message, String detailMessage, String file, int lineNumber, String badLine) { - this.severity = severity; - this.message = message; - this.detailMessage = detailMessage; - this.file = file; - this.lineNumber = lineNumber; - this.badLine = badLine; - } - - public String getSeverity() { - return severity; - } - - public String getMessage() { - return message; - } - - public String getDetailMessage() { - return detailMessage; - } - - public String getFile() { - return file; - } - - public int getLineNumber() { - return lineNumber; - } - - public String getBadLine() { - return badLine; - } - - @Override - public String toString() { - return severity + ": " + message + "\n" - + " --> " + file + ":" + lineNumber + "\n" - + " |\n" - + " | " + badLine + "\n" - + " | " + StringUtils.repeat('^', badLine.length()) + " " + detailMessage + "\n" - + " |"; - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/SourceSet.java b/src/main/java/net/coderbot/iris/shaderpack/loading/SourceSet.java deleted file mode 100644 index fb728561ac..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/SourceSet.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.coderbot.iris.shaderpack.loading; - -import java.util.function.Function; - -// TODO: Actually implement this class. -public class SourceSet { - //private final EnumMap singlePrograms; - //private final EnumMap programArrays; - - public SourceSet(Function sourceProvider) { - - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/MergedBooleanOption.java b/src/main/java/net/coderbot/iris/shaderpack/option/MergedBooleanOption.java deleted file mode 100644 index d3ea6963ed..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/option/MergedBooleanOption.java +++ /dev/null @@ -1,50 +0,0 @@ -package net.coderbot.iris.shaderpack.option; - -import com.google.common.collect.ImmutableSet; -import org.jetbrains.annotations.Nullable; - -public class MergedBooleanOption { - private final BooleanOption option; - private final ImmutableSet locations; - - MergedBooleanOption(BooleanOption option, ImmutableSet locations) { - this.option = option; - this.locations = locations; - } - - public MergedBooleanOption(OptionLocation location, BooleanOption option) { - this.option = option; - this.locations = ImmutableSet.of(location); - } - - @Nullable - public MergedBooleanOption merge(MergedBooleanOption other) { - if (this.option.getDefaultValue() != other.option.getDefaultValue()) { - return null; - } - - BooleanOption option; - - // TODO: Collect all known comments - if (this.option.getComment().isPresent()) { - option = this.option; - } else { - option = other.option; - } - - ImmutableSet.Builder mergedLocations = ImmutableSet.builder(); - - mergedLocations.addAll(this.locations); - mergedLocations.addAll(other.locations); - - return new MergedBooleanOption(option, mergedLocations.build()); - } - - public BooleanOption getOption() { - return option; - } - - public ImmutableSet getLocations() { - return locations; - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/OptionLocation.java b/src/main/java/net/coderbot/iris/shaderpack/option/OptionLocation.java deleted file mode 100644 index 36a078dd50..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/option/OptionLocation.java +++ /dev/null @@ -1,29 +0,0 @@ -package net.coderbot.iris.shaderpack.option; - -import net.coderbot.iris.shaderpack.include.AbsolutePackPath; - -/** - * Encapsulates a single location of an option. - */ -public class OptionLocation { - private final AbsolutePackPath filePath; - private final int lineIndex; - - public OptionLocation(AbsolutePackPath filePath, int lineIndex) { - this.filePath = filePath; - this.lineIndex = lineIndex; - } - - public AbsolutePackPath getFilePath() { - return filePath; - } - - /** - * Gets the index of the line this option is on. - * Note that this is the index - so the first line is - * 0, the second is 1, etc. - */ - public int getLineIndex() { - return lineIndex; - } -} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/OptionType.java b/src/main/java/net/coderbot/iris/shaderpack/option/OptionType.java deleted file mode 100644 index 8ff93bf9a5..0000000000 --- a/src/main/java/net/coderbot/iris/shaderpack/option/OptionType.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.coderbot.iris.shaderpack.option; - -public enum OptionType { - DEFINE, CONST -} diff --git a/src/main/java/net/coderbot/iris/shadows/Matrix4fAccess.java b/src/main/java/net/coderbot/iris/shadows/Matrix4fAccess.java deleted file mode 100644 index dd005e05b3..0000000000 --- a/src/main/java/net/coderbot/iris/shadows/Matrix4fAccess.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.coderbot.iris.shadows; - -public interface Matrix4fAccess { - /** - * Sets the values of this matrix from an array. The values in the array must be specified in column-major order, - * just like with OpenGL. Keep this in mind, since the natural way of laying out a matrix in array form is row-major - * order! - */ - void copyFromArray(float[] m); - - /** - * Gets the values of this matrix into an array. The values in the array will be laid out in column-major order, - * just like with OpenGL. Keep this in mind, since the natural way of laying out a matrix in array form is row-major - * order! - */ - float[] copyIntoArray(); - - /** - * Converts the matrix into a JOML matrix. This matrix is inherently column-major, and compatible with OpenGL. - * @return JOML matrix - */ - org.joml.Matrix4f convertToJOML(); -} diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/CullEverythingFrustum.java b/src/main/java/net/coderbot/iris/shadows/frustum/CullEverythingFrustum.java deleted file mode 100644 index 607b2cc459..0000000000 --- a/src/main/java/net/coderbot/iris/shadows/frustum/CullEverythingFrustum.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.coderbot.iris.shadows.frustum; - -import org.joml.Matrix4f; -import net.minecraft.client.renderer.culling.Frustum; -import net.minecraft.world.phys.AABB; - -public class CullEverythingFrustum extends Frustum { - public CullEverythingFrustum() { - super(new Matrix4f(), new Matrix4f()); - } - - // For Immersive Portals - // We return false here since isVisible is going to return false anyways. - public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - return false; - } - - public boolean isVisible(AABB box) { - return false; - } -} diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/NeighboringPlaneSet.java b/src/main/java/net/coderbot/iris/shadows/frustum/advanced/NeighboringPlaneSet.java deleted file mode 100644 index d631f6bc66..0000000000 --- a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/NeighboringPlaneSet.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.coderbot.iris.shadows.frustum.advanced; - -public class NeighboringPlaneSet { - private static final NeighboringPlaneSet FOR_PLUS_X = new NeighboringPlaneSet(2, 3, 4, 5); - private static final NeighboringPlaneSet FOR_PLUS_Y = new NeighboringPlaneSet(0, 1, 4, 5); - private static final NeighboringPlaneSet FOR_PLUS_Z = new NeighboringPlaneSet(0, 1, 2, 3); - - private static final NeighboringPlaneSet[] TABLE = new NeighboringPlaneSet[] { - FOR_PLUS_X, - FOR_PLUS_Y, - FOR_PLUS_Z - }; - - private final int plane0; - private final int plane1; - private final int plane2; - private final int plane3; - - public NeighboringPlaneSet(int plane0, int plane1, int plane2, int plane3) { - this.plane0 = plane0; - this.plane1 = plane1; - this.plane2 = plane2; - this.plane3 = plane3; - } - - public static NeighboringPlaneSet forPlane(int planeIndex) { - return TABLE[planeIndex >>> 1]; - } - - public int getPlane0() { - return plane0; - } - - public int getPlane1() { - return plane1; - } - - public int getPlane2() { - return plane2; - } - - public int getPlane3() { - return plane3; - } -} diff --git a/src/main/java/net/coderbot/iris/texture/format/LabPBRTextureFormat.java b/src/main/java/net/coderbot/iris/texture/format/LabPBRTextureFormat.java deleted file mode 100644 index 568a71fe67..0000000000 --- a/src/main/java/net/coderbot/iris/texture/format/LabPBRTextureFormat.java +++ /dev/null @@ -1,71 +0,0 @@ -package net.coderbot.iris.texture.format; - -import net.coderbot.iris.texture.mipmap.ChannelMipmapGenerator; -import net.coderbot.iris.texture.mipmap.CustomMipmapGenerator; -import net.coderbot.iris.texture.mipmap.DiscreteBlendFunction; -import net.coderbot.iris.texture.mipmap.LinearBlendFunction; -import net.coderbot.iris.texture.pbr.PBRType; -import org.jetbrains.annotations.Nullable; - -import java.util.Objects; - -public class LabPBRTextureFormat implements TextureFormat { - public static final ChannelMipmapGenerator SPECULAR_MIPMAP_GENERATOR = new ChannelMipmapGenerator( - LinearBlendFunction.INSTANCE, - new DiscreteBlendFunction(v -> v < 230 ? 0 : v - 229), - new DiscreteBlendFunction(v -> v < 65 ? 0 : 1), - new DiscreteBlendFunction(v -> v < 255 ? 0 : 1) - ); - - private final String name; - @Nullable - private final String version; - - public LabPBRTextureFormat(String name, @Nullable String version) { - this.name = name; - this.version = version; - } - - @Override - public String getName() { - return name; - } - - @Override - public @Nullable String getVersion() { - return version; - } - - @Override - public boolean canInterpolateValues(PBRType pbrType) { - if (pbrType == PBRType.SPECULAR) { - return false; - } - return true; - } - - @Override - public @Nullable CustomMipmapGenerator getMipmapGenerator(PBRType pbrType) { - if (pbrType == PBRType.SPECULAR) { - return SPECULAR_MIPMAP_GENERATOR; - } - return null; - } - - @Override - public int hashCode() { - return Objects.hash(name, version); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LabPBRTextureFormat other = (LabPBRTextureFormat) obj; - return Objects.equals(name, other.name) && Objects.equals(version, other.version); - } -} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BatchingDebugMessageHelper.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/BatchingDebugMessageHelper.java similarity index 84% rename from src/main/java/net/coderbot/batchedentityrendering/impl/BatchingDebugMessageHelper.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/BatchingDebugMessageHelper.java index 4f13c5200a..f52c233238 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BatchingDebugMessageHelper.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/BatchingDebugMessageHelper.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public class BatchingDebugMessageHelper { public static String getDebugMessage(DrawCallTrackingRenderBuffers drawTracker) { @@ -10,7 +10,7 @@ public static String getDebugMessage(DrawCallTrackingRenderBuffers drawTracker) float effectiveness = effectivenessTimes10 / 10.0F; return drawCalls + " draw calls / " + renderTypes + " render types = " - + effectiveness + "% effective"; + + effectiveness + "% effective"; } else { return "(no draw calls)"; } diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/BlendingStateHolder.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/BlendingStateHolder.java new file mode 100644 index 0000000000..4b9597059f --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/BlendingStateHolder.java @@ -0,0 +1,7 @@ +package net.irisshaders.batchedentityrendering.impl; + +public interface BlendingStateHolder { + TransparencyType getTransparencyType(); + + void setTransparencyType(TransparencyType transparencyType); +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferBuilderExt.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferBuilderExt.java new file mode 100644 index 0000000000..cfa961b996 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferBuilderExt.java @@ -0,0 +1,5 @@ +package net.irisshaders.batchedentityrendering.impl; + +public interface BufferBuilderExt { + void splitStrip(); +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegment.java similarity index 79% rename from src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegment.java index 4e783f2c87..c0dcb9d6c2 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/BufferSegment.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegment.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; import com.mojang.blaze3d.vertex.BufferBuilder; import net.minecraft.client.renderer.RenderType; diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegmentRenderer.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegmentRenderer.java new file mode 100644 index 0000000000..db02e97041 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/BufferSegmentRenderer.java @@ -0,0 +1,26 @@ +package net.irisshaders.batchedentityrendering.impl; + +import com.mojang.blaze3d.vertex.BufferUploader; + +public class BufferSegmentRenderer { + public BufferSegmentRenderer() { + } + + /** + * Sets up the render type, draws the buffer, and then tears down the render type. + */ + public void draw(BufferSegment segment) { + if (segment.renderedBuffer() != null) { + segment.type().setupRenderState(); + drawInner(segment); + segment.type().clearRenderState(); + } + } + + /** + * Like draw(), but it doesn't setup / tear down the render type. + */ + public void drawInner(BufferSegment segment) { + BufferUploader.drawWithShader(segment.renderedBuffer()); + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java similarity index 68% rename from src/main/java/net/coderbot/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java index d527db5c88..9ea9133e4f 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/DrawCallTrackingRenderBuffers.java @@ -1,7 +1,9 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public interface DrawCallTrackingRenderBuffers { int getDrawCalls(); + int getRenderTypes(); + void resetDrawCounts(); } diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/FlushableMultiBufferSource.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/FlushableMultiBufferSource.java similarity index 68% rename from src/main/java/net/coderbot/batchedentityrendering/impl/FlushableMultiBufferSource.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/FlushableMultiBufferSource.java index 3d77c02e6b..afcd1cad52 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/FlushableMultiBufferSource.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/FlushableMultiBufferSource.java @@ -1,6 +1,7 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public interface FlushableMultiBufferSource { void flushNonTranslucentContent(); + void flushTranslucentContent(); } diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java similarity index 95% rename from src/main/java/net/coderbot/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java index 32c59cad25..d5b168e5e5 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/FullyBufferedMultiBufferSource.java @@ -1,10 +1,10 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexConsumer; -import net.coderbot.batchedentityrendering.impl.ordering.GraphTranslucencyRenderOrderManager; -import net.coderbot.batchedentityrendering.impl.ordering.RenderOrderManager; -import net.coderbot.iris.fantastic.WrappingMultiBufferSource; +import net.irisshaders.batchedentityrendering.impl.ordering.GraphTranslucencyRenderOrderManager; +import net.irisshaders.batchedentityrendering.impl.ordering.RenderOrderManager; +import net.irisshaders.iris.layer.WrappingMultiBufferSource; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; @@ -28,13 +28,15 @@ public class FullyBufferedMultiBufferSource extends MultiBufferSource.BufferSour * An LRU cache mapping RenderType objects to a relevant buffer. */ private final LinkedHashMap affinities; - private int drawCalls; - private int renderTypes; - private final BufferSegmentRenderer segmentRenderer; private final UnflushableWrapper unflushableWrapper; private final List> wrappingFunctionStack; + private final Map> typeToSegment = new HashMap<>(); + private int drawCalls; + private int renderTypes; private Function wrappingFunction = null; + private boolean isReady; + private List renderOrder = new ArrayList<>(); public FullyBufferedMultiBufferSource() { super(new BufferBuilder(0), Collections.emptyMap()); @@ -55,10 +57,6 @@ public FullyBufferedMultiBufferSource() { this.wrappingFunctionStack = new ArrayList<>(); } - private boolean isReady; - private Map> typeToSegment = new HashMap<>(); - private List renderOrder = new ArrayList<>(); - @Override public VertexConsumer getBuffer(RenderType renderType) { removeReady(); diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/Groupable.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/Groupable.java new file mode 100644 index 0000000000..e1a729c202 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/Groupable.java @@ -0,0 +1,9 @@ +package net.irisshaders.batchedentityrendering.impl; + +public interface Groupable { + void startGroup(); + + boolean maybeStartGroup(); + + void endGroup(); +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingBuffer.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingBuffer.java similarity index 68% rename from src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingBuffer.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingBuffer.java index a74fa3466b..b0ebcde5b6 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/MemoryTrackingBuffer.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingBuffer.java @@ -1,7 +1,9 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public interface MemoryTrackingBuffer { int getAllocatedSize(); + int getUsedSize(); + void freeAndDeleteBuffer(); } diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java new file mode 100644 index 0000000000..2915fa64ba --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/MemoryTrackingRenderBuffers.java @@ -0,0 +1,11 @@ +package net.irisshaders.batchedentityrendering.impl; + +public interface MemoryTrackingRenderBuffers { + int getEntityBufferAllocatedSize(); + + int getMiscBufferAllocatedSize(); + + int getMaxBegins(); + + void freeAndDeleteBuffers(); +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java similarity index 96% rename from src/main/java/net/coderbot/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java index 529271ba8a..becf14d130 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/OldFullyBufferedMultiBufferSource.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -21,10 +21,9 @@ public class OldFullyBufferedMultiBufferSource extends MultiBufferSource.BufferS private final Map bufferBuilders; private final Object2IntMap unused; private final Set activeBuffers; - private boolean flushed; - private final Set typesThisFrame; private final List typesInOrder; + private boolean flushed; public OldFullyBufferedMultiBufferSource() { super(new BufferBuilder(0), Collections.emptyMap()); @@ -98,7 +97,7 @@ public void endBatch() { if (activeBuffers.contains(buffer)) { throw new IllegalStateException( - "A buffer was simultaneously marked as inactive and as active, something is very wrong..."); + "A buffer was simultaneously marked as inactive and as active, something is very wrong..."); } }); diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/RenderBuffersExt.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/RenderBuffersExt.java similarity index 63% rename from src/main/java/net/coderbot/batchedentityrendering/impl/RenderBuffersExt.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/RenderBuffersExt.java index 0226be468d..219324283c 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/RenderBuffersExt.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/RenderBuffersExt.java @@ -1,6 +1,7 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public interface RenderBuffersExt { void beginLevelRendering(); + void endLevelRendering(); } diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/RenderTypeUtil.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/RenderTypeUtil.java new file mode 100644 index 0000000000..651b6db602 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/RenderTypeUtil.java @@ -0,0 +1,10 @@ +package net.irisshaders.batchedentityrendering.impl; + +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderType; + +public class RenderTypeUtil { + public static boolean isTriangleStripDrawMode(RenderType renderType) { + return renderType.mode() == VertexFormat.Mode.TRIANGLE_STRIP; + } +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/SegmentedBufferBuilder.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/SegmentedBufferBuilder.java new file mode 100644 index 0000000000..92cd98d144 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/SegmentedBufferBuilder.java @@ -0,0 +1,114 @@ +package net.irisshaders.batchedentityrendering.impl; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.irisshaders.batchedentityrendering.mixin.RenderTypeAccessor; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +public class SegmentedBufferBuilder implements MultiBufferSource, MemoryTrackingBuffer { + private final BufferBuilder buffer; + private final List buffers; + private RenderType currentType; + + public SegmentedBufferBuilder() { + // 2 MB initial allocation + this.buffer = new BufferBuilder(512 * 1024); + this.buffers = new ArrayList<>(); + this.currentType = null; + } + + private static boolean shouldSortOnUpload(RenderType type) { + return ((RenderTypeAccessor) type).shouldSortOnUpload(); + } + + @Override + public VertexConsumer getBuffer(RenderType renderType) { + if (!Objects.equals(currentType, renderType)) { + if (currentType != null) { + if (shouldSortOnUpload(currentType)) { + buffer.setQuadSorting(RenderSystem.getVertexSorting()); + } + + buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); + } + + buffer.begin(renderType.mode(), renderType.format()); + + currentType = renderType; + } + + // Use duplicate vertices to break up triangle strips + // https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/Art/degenerate_triangle_strip_2x.png + // This works by generating zero-area triangles that don't end up getting rendered. + // TODO: How do we handle DEBUG_LINE_STRIP? + if (RenderTypeUtil.isTriangleStripDrawMode(currentType)) { + ((BufferBuilderExt) buffer).splitStrip(); + } + + return buffer; + } + + public List getSegments() { + if (currentType == null) { + return Collections.emptyList(); + } + + if (shouldSortOnUpload(currentType)) { + buffer.setQuadSorting(RenderSystem.getVertexSorting()); + } + + buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); + + currentType = null; + + List finalSegments = new ArrayList<>(buffers); + + buffers.clear(); + + return finalSegments; + } + + public List getSegmentsForType(TransparencyType transparencyType) { + if (currentType == null) { + return Collections.emptyList(); + } + + if (((BlendingStateHolder) currentType).getTransparencyType() == transparencyType) { + if (shouldSortOnUpload(currentType)) { + buffer.setQuadSorting(RenderSystem.getVertexSorting()); + } + + buffers.add(new BufferSegment(Objects.requireNonNull(buffer.end()), currentType)); + + currentType = null; + } + + List finalSegments = buffers.stream().filter(segment -> ((BlendingStateHolder) segment.type()).getTransparencyType() == transparencyType).toList(); + + buffers.removeAll(finalSegments); + + return finalSegments; + } + + @Override + public int getAllocatedSize() { + return ((MemoryTrackingBuffer) buffer).getAllocatedSize(); + } + + @Override + public int getUsedSize() { + return ((MemoryTrackingBuffer) buffer).getUsedSize(); + } + + @Override + public void freeAndDeleteBuffer() { + ((MemoryTrackingBuffer) buffer).freeAndDeleteBuffer(); + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/TransparencyType.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/TransparencyType.java similarity index 93% rename from src/main/java/net/coderbot/batchedentityrendering/impl/TransparencyType.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/TransparencyType.java index 152228f827..ccf1bcc786 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/TransparencyType.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/TransparencyType.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; public enum TransparencyType { /** diff --git a/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/WrappableRenderType.java similarity index 81% rename from src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java rename to src/main/java/net/irisshaders/batchedentityrendering/impl/WrappableRenderType.java index 661df37afd..8b50066fd2 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/impl/WrappableRenderType.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/WrappableRenderType.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.impl; +package net.irisshaders.batchedentityrendering.impl; import net.minecraft.client.renderer.RenderType; diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java new file mode 100644 index 0000000000..dc1226cacc --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/GraphTranslucencyRenderOrderManager.java @@ -0,0 +1,145 @@ +package net.irisshaders.batchedentityrendering.impl.ordering; + +import de.odysseus.ithaka.digraph.Digraph; +import de.odysseus.ithaka.digraph.Digraphs; +import de.odysseus.ithaka.digraph.MapDigraph; +import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSet; +import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetPolicy; +import de.odysseus.ithaka.digraph.util.fas.FeedbackArcSetProvider; +import de.odysseus.ithaka.digraph.util.fas.SimpleFeedbackArcSetProvider; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.WrappableRenderType; +import net.minecraft.client.renderer.RenderType; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; + +public class GraphTranslucencyRenderOrderManager implements RenderOrderManager { + private final FeedbackArcSetProvider feedbackArcSetProvider; + private final EnumMap> types; + private final EnumMap currentTypes; + private boolean inGroup = false; + + public GraphTranslucencyRenderOrderManager() { + feedbackArcSetProvider = new SimpleFeedbackArcSetProvider(); + types = new EnumMap<>(TransparencyType.class); + currentTypes = new EnumMap<>(TransparencyType.class); + + for (TransparencyType type : TransparencyType.values()) { + types.put(type, new MapDigraph<>()); + } + } + + private static TransparencyType getTransparencyType(RenderType type) { + while (type instanceof WrappableRenderType) { + type = ((WrappableRenderType) type).unwrap(); + } + + if (type instanceof BlendingStateHolder) { + return ((BlendingStateHolder) type).getTransparencyType(); + } + + // Default to "generally transparent" if we can't figure it out. + return TransparencyType.GENERAL_TRANSPARENT; + } + + public void begin(RenderType renderType) { + TransparencyType transparencyType = getTransparencyType(renderType); + Digraph graph = types.get(transparencyType); + graph.add(renderType); + + if (inGroup) { + RenderType previous = currentTypes.put(transparencyType, renderType); + + if (previous == null) { + return; + } + + int weight = graph.get(previous, renderType).orElse(0); + weight += 1; + graph.put(previous, renderType, weight); + } + } + + public void startGroup() { + if (inGroup) { + throw new IllegalStateException("Already in a group"); + } + + currentTypes.clear(); + inGroup = true; + } + + public boolean maybeStartGroup() { + if (inGroup) { + return false; + } + + currentTypes.clear(); + inGroup = true; + return true; + } + + public void endGroup() { + if (!inGroup) { + throw new IllegalStateException("Not in a group"); + } + + currentTypes.clear(); + inGroup = false; + } + + @Override + public void reset() { + // TODO: Is reallocation efficient? + types.clear(); + + for (TransparencyType type : TransparencyType.values()) { + types.put(type, new MapDigraph<>()); + } + } + + @Override + public void resetType(TransparencyType type) { + // TODO: Is reallocation efficient? + types.put(type, new MapDigraph<>()); + } + + public List getRenderOrder() { + int layerCount = 0; + + for (Digraph graph : types.values()) { + layerCount += graph.getVertexCount(); + } + + List allLayers = new ArrayList<>(layerCount); + + for (Digraph graph : types.values()) { + // TODO: Make sure that FAS can't become a bottleneck! + // Running NP-hard algorithms in a real time rendering loop might not be an amazing idea. + // This shouldn't be necessary in sane scenes, though, and if there aren't cycles, + // then this *should* be relatively inexpensive, since it'll bail out and return an empty set. + FeedbackArcSet arcSet = + feedbackArcSetProvider.getFeedbackArcSet(graph, graph, FeedbackArcSetPolicy.MIN_WEIGHT); + + if (arcSet.getEdgeCount() > 0) { + // This means that our dependency graph had cycles!!! + // This is very weird and isn't expected - but we try to handle it gracefully anyways. + + // Our feedback arc set algorithm finds some dependency links that can be removed hopefully + // without disrupting the overall order too much. Hopefully it isn't too slow! + for (RenderType source : arcSet.vertices()) { + for (RenderType target : arcSet.targets(source)) { + graph.remove(source, target); + } + } + } + + allLayers.addAll(Digraphs.toposort(graph, false)); + } + + return allLayers; + } +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/RenderOrderManager.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/RenderOrderManager.java new file mode 100644 index 0000000000..db74f3aee2 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/RenderOrderManager.java @@ -0,0 +1,22 @@ +package net.irisshaders.batchedentityrendering.impl.ordering; + +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.minecraft.client.renderer.RenderType; + +import java.util.List; + +public interface RenderOrderManager { + void begin(RenderType type); + + void startGroup(); + + boolean maybeStartGroup(); + + void endGroup(); + + void reset(); + + void resetType(TransparencyType type); + + List getRenderOrder(); +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java new file mode 100644 index 0000000000..3069696354 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/SimpleRenderOrderManager.java @@ -0,0 +1,46 @@ +package net.irisshaders.batchedentityrendering.impl.ordering; + +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.minecraft.client.renderer.RenderType; + +import java.util.LinkedHashSet; +import java.util.List; + +public class SimpleRenderOrderManager implements RenderOrderManager { + private final LinkedHashSet renderTypes; + + public SimpleRenderOrderManager() { + renderTypes = new LinkedHashSet<>(); + } + + public void begin(RenderType type) { + renderTypes.add(type); + } + + public void startGroup() { + // no-op + } + + public boolean maybeStartGroup() { + // no-op + return false; + } + + public void endGroup() { + // no-op + } + + @Override + public void reset() { + renderTypes.clear(); + } + + @Override + public void resetType(TransparencyType type) { + + } + + public List getRenderOrder() { + return List.copyOf(renderTypes); + } +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java new file mode 100644 index 0000000000..05fb184110 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/ordering/TranslucencyRenderOrderManager.java @@ -0,0 +1,81 @@ +package net.irisshaders.batchedentityrendering.impl.ordering; + +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.WrappableRenderType; +import net.minecraft.client.renderer.RenderType; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; + +public class TranslucencyRenderOrderManager implements RenderOrderManager { + private final EnumMap> renderTypes; + + public TranslucencyRenderOrderManager() { + renderTypes = new EnumMap<>(TransparencyType.class); + + for (TransparencyType type : TransparencyType.values()) { + renderTypes.put(type, new LinkedHashSet<>()); + } + } + + private static TransparencyType getTransparencyType(RenderType type) { + while (type instanceof WrappableRenderType) { + type = ((WrappableRenderType) type).unwrap(); + } + + if (type instanceof BlendingStateHolder) { + return ((BlendingStateHolder) type).getTransparencyType(); + } + + // Default to "generally transparent" if we can't figure it out. + return TransparencyType.GENERAL_TRANSPARENT; + } + + public void begin(RenderType type) { + renderTypes.get(getTransparencyType(type)).add(type); + } + + public void startGroup() { + // no-op + } + + public boolean maybeStartGroup() { + // no-op + return false; + } + + public void endGroup() { + // no-op + } + + @Override + public void reset() { + renderTypes.forEach((type, set) -> { + set.clear(); + }); + } + + @Override + public void resetType(TransparencyType type) { + renderTypes.get(type).clear(); + } + + public List getRenderOrder() { + int layerCount = 0; + + for (LinkedHashSet set : renderTypes.values()) { + layerCount += set.size(); + } + + List allRenderTypes = new ArrayList<>(layerCount); + + for (LinkedHashSet set : renderTypes.values()) { + allRenderTypes.addAll(set); + } + + return allRenderTypes; + } +} diff --git a/src/main/java/net/irisshaders/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java b/src/main/java/net/irisshaders/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java new file mode 100644 index 0000000000..e2023683d0 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/impl/wrappers/TaggingRenderTypeWrapper.java @@ -0,0 +1,68 @@ +package net.irisshaders.batchedentityrendering.impl.wrappers; + +import net.irisshaders.batchedentityrendering.impl.WrappableRenderType; +import net.irisshaders.batchedentityrendering.mixin.RenderTypeAccessor; +import net.minecraft.client.renderer.RenderType; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; +import java.util.Optional; + +public class TaggingRenderTypeWrapper extends RenderType implements WrappableRenderType { + private final int tag; + private final RenderType wrapped; + + public TaggingRenderTypeWrapper(String name, RenderType wrapped, int tag) { + super(name, wrapped.format(), wrapped.mode(), wrapped.bufferSize(), + wrapped.affectsCrumbling(), shouldSortOnUpload(wrapped), wrapped::setupRenderState, wrapped::clearRenderState); + + this.tag = tag; + this.wrapped = wrapped; + } + + private static boolean shouldSortOnUpload(RenderType type) { + return ((RenderTypeAccessor) type).shouldSortOnUpload(); + } + + @Override + public RenderType unwrap() { + return this.wrapped; + } + + @Override + public Optional outline() { + return this.wrapped.outline(); + } + + @Override + public boolean isOutline() { + return this.wrapped.isOutline(); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object == null) { + return false; + } + + if (object.getClass() != this.getClass()) { + return false; + } + + TaggingRenderTypeWrapper other = (TaggingRenderTypeWrapper) object; + + return this.tag == other.tag && Objects.equals(this.wrapped, other.wrapped); + } + + @Override + public int hashCode() { + // Add one so that we don't have the exact same hash as the wrapped object. + // This means that we won't have a guaranteed collision if we're inserted to a map alongside the unwrapped object. + return this.wrapped.hashCode() + 1; + } + + @Override + public String toString() { + return "tagged(" + tag + "):" + this.wrapped.toString(); + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/BufferSourceAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/BufferSourceAccessor.java similarity index 88% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/BufferSourceAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/BufferSourceAccessor.java index 3596a0fba0..743b2d019a 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/BufferSourceAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/BufferSourceAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.BufferBuilder; import net.minecraft.client.renderer.MultiBufferSource; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/SectionBufferBuilderPackAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/ChunkBufferBuilderPackAccessor.java similarity index 78% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/SectionBufferBuilderPackAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/ChunkBufferBuilderPackAccessor.java index 132b01bb5e..ad65e95e26 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/SectionBufferBuilderPackAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/ChunkBufferBuilderPackAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.BufferBuilder; import net.minecraft.client.renderer.ChunkBufferBuilderPack; @@ -9,7 +9,7 @@ import java.util.Map; @Mixin(ChunkBufferBuilderPack.class) -public interface SectionBufferBuilderPackAccessor { +public interface ChunkBufferBuilderPackAccessor { @Accessor Map getBuilders(); } diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/CompositeStateAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/CompositeStateAccessor.java similarity index 87% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/CompositeStateAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/CompositeStateAccessor.java index b5479387e7..0b75ba5f03 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/CompositeStateAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/CompositeStateAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; diff --git a/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java new file mode 100644 index 0000000000..18cbee43f1 --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBannerRenderer_Disabled.java @@ -0,0 +1,64 @@ +package net.irisshaders.batchedentityrendering.mixin; + +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.datafixers.util.Pair; +import net.irisshaders.batchedentityrendering.impl.Groupable; +import net.irisshaders.batchedentityrendering.impl.wrappers.TaggingRenderTypeWrapper; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.blockentity.BannerRenderer; +import net.minecraft.client.resources.model.Material; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.level.block.entity.BannerPattern; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.ModifyVariable; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +/** + * This Mixin groups banner patterns separately, to not batch the wrong patterns. + * It has been disabled for now, as the behavior seems to not be required. (IMS, September 2, 2022) + */ +@Mixin(BannerRenderer.class) +public class MixinBannerRenderer_Disabled { + private static final String RENDER_PATTERNS = + "Lnet/minecraft/client/renderer/blockentity/BannerRenderer;renderPatterns(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/model/geom/ModelPart;Lnet/minecraft/client/resources/model/Material;ZLjava/util/List;Z)V"; + + /** + * Holds a Groupable instance, if we successfully started a group. + * This is because we need to make sure to end the group that we started. + */ + @Unique + private static Groupable groupableToEnd; + private static int index; + + @ModifyVariable(method = RENDER_PATTERNS, at = @At("HEAD"), argsOnly = true) + private static MultiBufferSource iris$wrapBufferSource(MultiBufferSource multiBufferSource) { + if (multiBufferSource instanceof Groupable groupable) { + boolean started = groupable.maybeStartGroup(); + + if (started) { + groupableToEnd = groupable; + } + + index = 0; + // NB: Groupable not needed for this implementation of MultiBufferSource. + return type -> multiBufferSource.getBuffer(new TaggingRenderTypeWrapper(type.toString(), type, index++)); + } + + return multiBufferSource; + } + + @Inject(method = RENDER_PATTERNS, at = @At("RETURN")) + private static void iris$endRenderingCanvas(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, int j, ModelPart modelPart, Material material, boolean bl, List> list, boolean bl2, CallbackInfo ci) { + if (groupableToEnd != null) { + groupableToEnd.endGroup(); + groupableToEnd = null; + index = 0; + } + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder.java similarity index 83% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder.java index cf04f98421..fabb553a3b 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferBuilder.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder.java @@ -1,7 +1,7 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.BufferBuilder; -import net.coderbot.batchedentityrendering.impl.MemoryTrackingBuffer; +import net.irisshaders.batchedentityrendering.impl.MemoryTrackingBuffer; import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java new file mode 100644 index 0000000000..c28cc8c07b --- /dev/null +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferBuilder_SegmentRendering.java @@ -0,0 +1,79 @@ +package net.irisshaders.batchedentityrendering.mixin; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.caffeinemc.mods.sodium.api.memory.MemoryIntrinsics; +import net.irisshaders.batchedentityrendering.impl.BufferBuilderExt; +import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.Dynamic; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.nio.ByteBuffer; + +@Mixin(value = BufferBuilder.class, priority = 1010) +public class MixinBufferBuilder_SegmentRendering implements BufferBuilderExt { + @Shadow + private ByteBuffer buffer; + + @Shadow + private VertexFormat format; + + @Shadow + private int vertices; + @Shadow + private int nextElementByte; + @Unique + private boolean dupeNextVertex; + + @Shadow + private void ensureVertexCapacity() { + throw new AssertionError("not shadowed"); + } + + @Override + public void splitStrip() { + if (vertices == 0) { + // no strip to split, not building. + return; + } + + duplicateLastVertex(); + dupeNextVertex = true; + } + + private void duplicateLastVertex() { + int i = this.format.getVertexSize(); + MemoryIntrinsics.copyMemory(MemoryUtil.memAddress(this.buffer, this.nextElementByte - i), MemoryUtil.memAddress(this.buffer, this.nextElementByte), i); + this.nextElementByte += i; + ++this.vertices; + this.ensureVertexCapacity(); + } + + @Inject(method = "end", at = @At("RETURN")) + private void batchedentityrendering$onEnd(CallbackInfoReturnable cir) { + dupeNextVertex = false; + } + + @Inject(method = "endVertex", at = @At("RETURN")) + private void batchedentityrendering$onNext(CallbackInfo ci) { + if (dupeNextVertex) { + dupeNextVertex = false; + duplicateLastVertex(); + } + } + + @Dynamic + @Inject(method = "sodium$moveToNextVertex", at = @At("RETURN"), require = 0) + private void batchedentityrendering$onNextSodium(CallbackInfo ci) { + if (dupeNextVertex) { + dupeNextVertex = false; + duplicateLastVertex(); + } + } +} diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferSource.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferSource.java similarity index 91% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferSource.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferSource.java index 953ccc1987..397fd920d2 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinBufferSource.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinBufferSource.java @@ -1,7 +1,7 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.BufferBuilder; -import net.coderbot.batchedentityrendering.impl.MemoryTrackingBuffer; +import net.irisshaders.batchedentityrendering.impl.MemoryTrackingBuffer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Final; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinCompositeRenderType.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinCompositeRenderType.java similarity index 79% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinCompositeRenderType.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinCompositeRenderType.java index 6fcc0ec35b..c6c24d8bef 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinCompositeRenderType.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinCompositeRenderType.java @@ -1,8 +1,8 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Mixin; @@ -11,10 +11,10 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -@Mixin(targets = "net/minecraft/client/renderer/RenderType$CompositeRenderType") +@Mixin(RenderType.CompositeRenderType.class) public abstract class MixinCompositeRenderType extends RenderType implements BlendingStateHolder { private static final String INIT = - "(Ljava/lang/String;Lcom/mojang/blaze3d/vertex/VertexFormat;Lcom/mojang/blaze3d/vertex/VertexFormat$Mode;IZZLnet/minecraft/client/renderer/RenderType$CompositeState;)V"; + "(Ljava/lang/String;Lcom/mojang/blaze3d/vertex/VertexFormat;Lcom/mojang/blaze3d/vertex/VertexFormat$Mode;IZZLnet/minecraft/client/renderer/RenderType$CompositeState;)V"; @Unique private TransparencyType transparencyType; @@ -34,7 +34,7 @@ private MixinCompositeRenderType(String name, VertexFormat vertexFormat, VertexF } else if (transparency == RenderStateShardAccessor.getNO_TRANSPARENCY()) { transparencyType = TransparencyType.OPAQUE; } else if (transparency == RenderStateShardAccessor.getGLINT_TRANSPARENCY() || - transparency == RenderStateShardAccessor.getCRUMBLING_TRANSPARENCY()) { + transparency == RenderStateShardAccessor.getCRUMBLING_TRANSPARENCY()) { transparencyType = TransparencyType.DECAL; } else { transparencyType = TransparencyType.GENERAL_TRANSPARENT; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinDebugScreenOverlay.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinDebugScreenOverlay.java similarity index 67% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinDebugScreenOverlay.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinDebugScreenOverlay.java index c33e02197e..b84103dc8c 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinDebugScreenOverlay.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinDebugScreenOverlay.java @@ -1,8 +1,8 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; -import net.coderbot.batchedentityrendering.impl.BatchingDebugMessageHelper; -import net.coderbot.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; -import net.coderbot.iris.Iris; +import net.irisshaders.batchedentityrendering.impl.BatchingDebugMessageHelper; +import net.irisshaders.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; +import net.irisshaders.iris.Iris; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.DebugScreenOverlay; import org.spongepowered.asm.mixin.Mixin; @@ -19,16 +19,16 @@ */ @Mixin(value = DebugScreenOverlay.class, priority = 1010) public abstract class MixinDebugScreenOverlay { - @Inject(method = "getGameInformation", at = @At("RETURN")) - private void batchedentityrendering$appendStats(CallbackInfoReturnable> cir) { - List messages = cir.getReturnValue(); + @Inject(method = "getGameInformation", at = @At("RETURN")) + private void batchedentityrendering$appendStats(CallbackInfoReturnable> cir) { + List messages = cir.getReturnValue(); DrawCallTrackingRenderBuffers drawTracker = (DrawCallTrackingRenderBuffers) Minecraft.getInstance().renderBuffers(); - // blank line separator + // blank line separator if (Iris.getIrisConfig().areDebugOptionsEnabled()) { messages.add(""); messages.add("[Entity Batching] " + BatchingDebugMessageHelper.getDebugMessage(drawTracker)); } - } + } } diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinFishingHookRenderer.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinFishingHookRenderer.java similarity index 91% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinFishingHookRenderer.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinFishingHookRenderer.java index 0d29564fa7..1f9aeb63e1 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinFishingHookRenderer.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinFishingHookRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -10,7 +10,6 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(FishingHookRenderer.class) public class MixinFishingHookRenderer { diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer.java similarity index 84% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer.java index ed8ca5d222..ad9bf73cc1 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer.java @@ -1,12 +1,12 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; -import net.coderbot.batchedentityrendering.impl.FullyBufferedMultiBufferSource; -import net.coderbot.batchedentityrendering.impl.Groupable; -import net.coderbot.batchedentityrendering.impl.RenderBuffersExt; -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; +import net.irisshaders.batchedentityrendering.impl.FullyBufferedMultiBufferSource; +import net.irisshaders.batchedentityrendering.impl.Groupable; +import net.irisshaders.batchedentityrendering.impl.RenderBuffersExt; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GameRenderer; @@ -31,7 +31,7 @@ @Mixin(value = LevelRenderer.class, priority = 999) public class MixinLevelRenderer { private static final String RENDER_ENTITY = - "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"; + "Lnet/minecraft/client/renderer/LevelRenderer;renderEntity(Lnet/minecraft/world/entity/Entity;DDDFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;)V"; @Shadow private RenderBuffers renderBuffers; @@ -73,7 +73,7 @@ public class MixinLevelRenderer { fullyBufferedMultiBufferSource.readyUp(); } - if (BlockRenderingSettings.INSTANCE.shouldSeparateEntityDraws()) { + if (WorldRenderingSettings.INSTANCE.shouldSeparateEntityDraws()) { Minecraft.getInstance().getProfiler().popPush("entity_draws_opaque"); if (renderBuffers.bufferSource() instanceof FullyBufferedMultiBufferSource source) { source.endBatchWithType(TransparencyType.OPAQUE); @@ -90,7 +90,7 @@ public class MixinLevelRenderer { @Inject(method = "renderLevel", at = @At(value = "CONSTANT", args = "stringValue=translucent", shift = At.Shift.AFTER), locals = LocalCapture.CAPTURE_FAILHARD) private void batchedentityrendering$endTranslucents(PoseStack poseStack, float f, long l, boolean bl, Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, Matrix4f projectionMatrix, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.shouldSeparateEntityDraws()) { + if (WorldRenderingSettings.INSTANCE.shouldSeparateEntityDraws()) { this.renderBuffers.bufferSource().endBatch(); } } diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java similarity index 59% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java index 60b98aaa4d..ad8c9a93ea 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinLevelRenderer_EntityListSorting.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.LevelRenderer; @@ -19,18 +19,18 @@ /** * Sorts the entity list to allow entities of the same type to be properly batched. Without sorting, entities are * essentially rendered in random order, which makes it harder for entity batching to work properly. - * + *

    * Sorting reduces the number of RenderTypes that need to be active at any given time for batching to be effective. * For example, instead of the batching system needing to be prepared to render a pig at any time, it can know that * every pig is being rendered all at once, then it can use unused space within the buffer previously used for pigs for * something else. - * + *

    * This is even more effective with vanilla's entity rendering, since it only has a single buffer for most purposes, * except for a configured set of batched render types. - * - * This injection point has been carefully chosen to avoid conflicts with other mixins such as one from Carpet: - * https://github.com/gnembon/fabric-carpet/blob/776f798aecb792a5881ccae8784888156207a047/src/main/java/carpet/mixins/WorldRenderer_pausedShakeMixin.java#L23 - * + *

    + * This injection point has been carefully chosen to avoid conflicts with other mixins such as + * one from Carpet: + *

    * By using ModifyVariable instead of Redirect, it is more likely to be compatible with other rendering mods. We also * use a priority of 999 to apply before most other mixins to this method, meaning that other mods adding entities to * the rendering list (like Twilight Forest) are more likely to have these added entities sorted. @@ -41,23 +41,23 @@ public class MixinLevelRenderer_EntityListSorting { private ClientLevel level; @ModifyVariable(method = "renderLevel", at = @At(value = "INVOKE_ASSIGN", target = "Ljava/lang/Iterable;iterator()Ljava/util/Iterator;"), - slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBuffers;bufferSource()Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;"), - to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;shouldRender(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/client/renderer/culling/Frustum;DDD)Z")), allow = 1) - private Iterator batchedentityrendering$sortEntityList(Iterator iterator) { - // Sort the entity list first in order to allow vanilla's entity batching code to work better. - this.level.getProfiler().push("sortEntityList"); + slice = @Slice(from = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/RenderBuffers;bufferSource()Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;"), + to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/entity/EntityRenderDispatcher;shouldRender(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/client/renderer/culling/Frustum;DDD)Z")), allow = 1) + private Iterator batchedentityrendering$sortEntityList(Iterator iterator) { + // Sort the entity list first in order to allow vanilla's entity batching code to work better. + this.level.getProfiler().push("sortEntityList"); - Map, List> sortedEntities = new HashMap<>(); + Map, List> sortedEntities = new HashMap<>(); - List entities = new ArrayList<>(); - iterator.forEachRemaining(entity -> { - sortedEntities.computeIfAbsent(entity.getType(), entityType -> new ArrayList<>(32)).add(entity); - }); + List entities = new ArrayList<>(); + iterator.forEachRemaining(entity -> { + sortedEntities.computeIfAbsent(entity.getType(), entityType -> new ArrayList<>(32)).add(entity); + }); - sortedEntities.values().forEach(entities::addAll); + sortedEntities.values().forEach(entities::addAll); - this.level.getProfiler().pop(); + this.level.getProfiler().pop(); - return entities.iterator(); - } + return entities.iterator(); + } } diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderBuffers.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderBuffers.java similarity index 85% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderBuffers.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderBuffers.java index 92e4b810ae..fab81ac42b 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderBuffers.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderBuffers.java @@ -1,16 +1,15 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import com.mojang.blaze3d.vertex.BufferBuilder; -import net.coderbot.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; -import net.coderbot.batchedentityrendering.impl.FullyBufferedMultiBufferSource; -import net.coderbot.batchedentityrendering.impl.MemoryTrackingBuffer; -import net.coderbot.batchedentityrendering.impl.MemoryTrackingRenderBuffers; -import net.coderbot.batchedentityrendering.impl.RenderBuffersExt; +import net.irisshaders.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; +import net.irisshaders.batchedentityrendering.impl.FullyBufferedMultiBufferSource; +import net.irisshaders.batchedentityrendering.impl.MemoryTrackingBuffer; +import net.irisshaders.batchedentityrendering.impl.MemoryTrackingRenderBuffers; +import net.irisshaders.batchedentityrendering.impl.RenderBuffersExt; import net.minecraft.client.renderer.ChunkBufferBuilderPack; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.OutlineBufferSource; import net.minecraft.client.renderer.RenderBuffers; -import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -19,22 +18,16 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import java.util.SortedMap; - @Mixin(RenderBuffers.class) public class MixinRenderBuffers implements RenderBuffersExt, MemoryTrackingRenderBuffers, DrawCallTrackingRenderBuffers { @Unique private final FullyBufferedMultiBufferSource buffered = new FullyBufferedMultiBufferSource(); - + @Unique + private final OutlineBufferSource outlineBufferSource = new OutlineBufferSource(buffered); @Unique private int begins = 0; - @Unique private int maxBegins = 0; - - @Unique - private final OutlineBufferSource outlineBufferSource = new OutlineBufferSource(buffered); - @Shadow @Final private MultiBufferSource.BufferSource bufferSource; @@ -121,7 +114,7 @@ public int getMaxBegins() { @Override public void freeAndDeleteBuffers() { buffered.freeAndDeleteBuffer(); - ((SectionBufferBuilderPackAccessor) this.fixedBufferPack).getBuilders().values().forEach(bufferBuilder -> ((MemoryTrackingBuffer) bufferBuilder).freeAndDeleteBuffer()); + ((ChunkBufferBuilderPackAccessor) this.fixedBufferPack).getBuilders().values().forEach(bufferBuilder -> ((MemoryTrackingBuffer) bufferBuilder).freeAndDeleteBuffer()); ((BufferSourceAccessor) bufferSource).getFixedBuffers().forEach((renderType, bufferBuilder) -> ((MemoryTrackingBuffer) bufferBuilder).freeAndDeleteBuffer()); ((BufferSourceAccessor) bufferSource).getFixedBuffers().clear(); ((MemoryTrackingBuffer) ((OutlineBufferSourceAccessor) outlineBufferSource).getOutlineBufferSource()).freeAndDeleteBuffer(); diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderType.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderType.java similarity index 73% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderType.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderType.java index 286cbfce8a..1071acf8eb 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinRenderType.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinRenderType.java @@ -1,7 +1,7 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinSheets.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinSheets.java similarity index 82% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/MixinSheets.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinSheets.java index adfa76be15..1ef3553c32 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/MixinSheets.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/MixinSheets.java @@ -1,7 +1,7 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.Sheets; import org.spongepowered.asm.mixin.Final; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java similarity index 86% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java index 3d84127ebd..08ddac3070 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/OutlineBufferSourceAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.OutlineBufferSource; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/RenderStateShardAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderStateShardAccessor.java similarity index 92% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/RenderStateShardAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderStateShardAccessor.java index db4f65c61f..b4a8c70b8a 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/RenderStateShardAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderStateShardAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import net.minecraft.client.renderer.RenderStateShard; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/batchedentityrendering/mixin/RenderTypeAccessor.java b/src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderTypeAccessor.java similarity index 83% rename from src/main/java/net/coderbot/batchedentityrendering/mixin/RenderTypeAccessor.java rename to src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderTypeAccessor.java index 60e13e2f0f..8b4cad2595 100644 --- a/src/main/java/net/coderbot/batchedentityrendering/mixin/RenderTypeAccessor.java +++ b/src/main/java/net/irisshaders/batchedentityrendering/mixin/RenderTypeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.batchedentityrendering.mixin; +package net.irisshaders.batchedentityrendering.mixin; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/Iris.java b/src/main/java/net/irisshaders/iris/Iris.java similarity index 90% rename from src/main/java/net/coderbot/iris/Iris.java rename to src/main/java/net/irisshaders/iris/Iris.java index 85b8d536db..324184b3d5 100644 --- a/src/main/java/net/coderbot/iris/Iris.java +++ b/src/main/java/net/irisshaders/iris/Iris.java @@ -1,38 +1,37 @@ -package net.coderbot.iris; +package net.irisshaders.iris; import com.google.common.base.Throwables; import com.mojang.blaze3d.platform.GlDebug; import com.mojang.blaze3d.platform.InputConstants; import com.sun.jna.platform.unix.LibC; -import net.coderbot.iris.config.IrisConfig; -import net.coderbot.iris.gl.GLDebug; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.gl.shader.StandardMacros; -import net.coderbot.iris.gui.debug.DebugLoadFailedGridScreen; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; -import net.coderbot.iris.pipeline.PipelineManager; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.NewWorldRenderingPipeline; -import net.coderbot.iris.shaderpack.DimensionId; -import net.coderbot.iris.shaderpack.IrisDefines; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.ProgramSet; -import net.coderbot.iris.shaderpack.ShaderPack; -import net.coderbot.iris.shaderpack.discovery.ShaderpackDirectoryManager; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.shaderpack.option.OptionSet; -import net.coderbot.iris.shaderpack.option.Profile; -import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; -import net.coderbot.iris.shaderpack.option.values.OptionValues; -import net.coderbot.iris.texture.pbr.PBRTextureManager; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.config.IrisConfig; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.shader.StandardMacros; +import net.irisshaders.iris.gui.debug.DebugLoadFailedGridScreen; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.pipeline.PipelineManager; +import net.irisshaders.iris.pipeline.VanillaRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.DimensionId; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.discovery.ShaderpackDirectoryManager; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.shaderpack.option.Profile; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.texture.pbr.PBRTextureManager; import net.minecraft.ChatFormatting; import net.minecraft.SharedConstants; import net.minecraft.Util; import net.minecraft.client.KeyMapping; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; - import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraftforge.client.ConfigScreenHandler; @@ -44,6 +43,7 @@ import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.FMLPaths; import net.minecraftforge.network.NetworkConstants; import org.jetbrains.annotations.NotNull; @@ -78,17 +78,18 @@ public class Iris { * separately in mixin plugin classes & the language files. */ public static final String MODNAME = "Oculus"; - public static final IrisLogging logger = new IrisLogging(MODNAME); - + private static final Map shaderPackOptionQueue = new HashMap<>(); + // Change this for snapshots! + private static final String backupVersionNumber = "1.20.3"; + public static NamespacedId lastDimension = null; + public static boolean testing = false; private static Path shaderpacksDirectory; private static ShaderpackDirectoryManager shaderpacksDirectoryManager; - private static ShaderPack currentPack; private static String currentPackName; private static Optional storedError = Optional.empty(); private static boolean initialized; - private static PipelineManager pipelineManager; private static IrisConfig irisConfig; private static FileSystem zipFileSystem; @@ -97,8 +98,6 @@ public class Iris { private static KeyMapping toggleShadersKeybind; private static KeyMapping shaderpackScreenKeybind; private static KeyMapping wireframeKeybind; - - private static final Map shaderPackOptionQueue = new HashMap<>(); // Flag variable used when reloading // Used in favor of queueDefaultShaderPackOptionValues() for resetting as the // behavior is more concrete and therefore is more likely to repair a user's issues @@ -107,9 +106,6 @@ public class Iris { private static String IRIS_VERSION; private static boolean fallback; - // Change this for snapshots! - private static String backupVersionNumber = "1.20.3"; - public Iris() { try { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onKeyRegister); @@ -123,42 +119,6 @@ public Iris() { } } - /** - * Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do - * some very basic setup, config loading, and environment checks. - * - *

    This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except - * it's entirely cross platform & we get to decide its exact semantics.

    - * - *

    This is called right before options are loaded, so we can add key bindings here.

    - */ - public static void onEarlyInitialize() { - reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds"); - toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds"); - shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds"); - wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds"); - - try { - if (!Files.exists(getShaderpacksDirectory())) { - Files.createDirectories(getShaderpacksDirectory()); - } - } catch (IOException e) { - logger.warn("Failed to create the shaderpacks directory!"); - logger.warn("", e); - } - - irisConfig = new IrisConfig(FMLPaths.CONFIGDIR.get().resolve(MODID + ".properties")); - - try { - irisConfig.initialize(); - } catch (IOException e) { - logger.error("Failed to initialize " + MODNAME + " configuration, default values will be used instead"); - logger.error("", e); - } - - initialized = true; - } - public void onKeyRegister(RegisterKeyMappingsEvent event) { event.register(reloadKeybind); event.register(toggleShadersKeybind); @@ -175,7 +135,7 @@ public void onKeyInput(InputEvent.Key event) { public static void onRenderSystemInit() { if (!initialized) { Iris.logger.warn("Iris::onRenderSystemInit was called, but Iris::onEarlyInitialize was not called." + - " Trying to avoid a crash but this is an odd state."); + " Trying to avoid a crash but this is an odd state."); return; } @@ -261,7 +221,7 @@ public static void loadShaderpack() { if (irisConfig == null) { if (!initialized) { throw new IllegalStateException("Iris::loadShaderpack was called, but Iris::onInitializeClient wasn't" + - " called yet. How did this happen?"); + " called yet. How did this happen?"); } else { throw new NullPointerException("Iris.irisConfig was null unexpectedly"); } @@ -293,6 +253,7 @@ public static void loadShaderpack() { } } + @SuppressWarnings("unchecked") private static boolean loadExternalShaderpack(String name) { Path shaderPackRoot; Path shaderPackConfigTxt; @@ -355,8 +316,8 @@ private static boolean loadExternalShaderpack(String name) { } Map changedConfigs = tryReadConfigProperties(shaderPackConfigTxt) - .map(properties -> (Map) (Map) properties) - .orElse(new HashMap<>()); + .map(properties -> (Map) (Object) properties) + .orElse(new HashMap<>()); changedConfigs.putAll(shaderPackOptionQueue); clearShaderPackOptionQueue(); @@ -413,9 +374,9 @@ private static Optional loadExternalZipShaderpack(Path shaderpackPath) thr // This makes it hard to determine what is the actual shaders dir try (Stream stream = Files.walk(root)) { return stream - .filter(Files::isDirectory) - .filter(path -> path.endsWith("shaders")) - .findFirst(); + .filter(Files::isDirectory) + .filter(path -> path.endsWith("shaders")) + .findFirst(); } } @@ -428,10 +389,18 @@ private static void setShadersDisabled() { } public static void setDebug(boolean enable) { + try { + irisConfig.setDebugEnabled(enable); + irisConfig.save(); + } catch (IOException e) { + Iris.logger.fatal("Failed to save config!", e); + } + int success; if (enable) { success = GLDebug.setupDebugMessageCallback(); } else { + GLDebug.reloadDebugState(); GlDebug.enableDebugCallback(Minecraft.getInstance().options.glDebugVerbosity, false); success = 1; } @@ -443,13 +412,6 @@ public static void setDebug(boolean enable) { Minecraft.getInstance().player.displayClientMessage(Component.translatable("iris.shaders.debug.restart"), false); } } - - try { - irisConfig.setDebugEnabled(enable); - irisConfig.save(); - } catch (IOException e) { - e.printStackTrace(); - } } private static Optional tryReadConfigProperties(Path path) { @@ -503,11 +465,11 @@ public static boolean isValidShaderpack(Path pack) { } try (Stream stream = Files.walk(pack)) { return stream - .filter(Files::isDirectory) - // Prevent a pack simply named "shaders" from being - // identified as a valid pack - .filter(path -> !path.equals(pack)) - .anyMatch(path -> path.endsWith("shaders")); + .filter(Files::isDirectory) + // Prevent a pack simply named "shaders" from being + // identified as a valid pack + .filter(path -> !path.equals(pack)) + .anyMatch(path -> path.endsWith("shaders")); } catch (IOException ignored) { // ignored, not a valid shader pack. return false; @@ -519,8 +481,8 @@ public static boolean isValidShaderpack(Path pack) { Path root = zipSystem.getRootDirectories().iterator().next(); try (Stream stream = Files.walk(root)) { return stream - .filter(Files::isDirectory) - .anyMatch(path -> path.endsWith("shaders")); + .filter(Files::isDirectory) + .anyMatch(path -> path.endsWith("shaders")); } } catch (ZipError zipError) { // Java 8 seems to throw a ZipError instead of a subclass of IOException @@ -545,7 +507,7 @@ public static void queueShaderPackOptionsFromProperties(Properties properties) { queueDefaultShaderPackOptionValues(); properties.stringPropertyNames().forEach(key -> - getShaderPackOptionQueue().put(key, properties.getProperty(key))); + getShaderPackOptionQueue().put(key, properties.getProperty(key))); } // Used in favor of resetShaderPackOptions as the aforementioned requires the pack to be reloaded @@ -598,7 +560,6 @@ public static void reload() throws IOException { } } - /** * Destroys and deallocates all created OpenGL resources. Useful as part of a reload. */ @@ -621,8 +582,6 @@ private static void destroyEverything() { } } - public static NamespacedId lastDimension = null; - public static NamespacedId getCurrentDimension() { ClientLevel level = Minecraft.getInstance().level; @@ -639,14 +598,14 @@ public static NamespacedId getCurrentDimension() { private static WorldRenderingPipeline createPipeline(NamespacedId dimensionId) { if (currentPack == null) { // Completely disables shader-based rendering - return new FixedFunctionWorldRenderingPipeline(); + return new VanillaRenderingPipeline(); } ProgramSet programs = currentPack.getProgramSet(dimensionId); // We use DeferredWorldRenderingPipeline on 1.16, and NewWorldRendering pipeline on 1.17 when rendering shaders. try { - return new NewWorldRenderingPipeline(programs); + return new IrisRenderingPipeline(programs); } catch (Exception e) { if (irisConfig.areDebugOptionsEnabled()) { Minecraft.getInstance().setScreen(new DebugLoadFailedGridScreen(Minecraft.getInstance().screen, Component.literal(e instanceof ShaderCompileException ? "Failed to compile shaders" : "Exception"), e)); @@ -661,7 +620,7 @@ private static WorldRenderingPipeline createPipeline(NamespacedId dimensionId) { // TODO: This should be reverted if a dimension change causes shaders to compile again fallback = true; - return new FixedFunctionWorldRenderingPipeline(); + return new VanillaRenderingPipeline(); } } @@ -709,9 +668,9 @@ public static String getFormattedVersion() { ChatFormatting color; String version = getVersion(); - if (version.endsWith("-development-environment")) { + if (!FMLEnvironment.production) { color = ChatFormatting.GOLD; - version = version.replace("-development-environment", " (Development Environment)"); + version = version + " (Development Environment)"; } else if (version.endsWith("-dirty") || version.contains("unknown") || version.endsWith("-nogit")) { color = ChatFormatting.RED; } else if (version.contains("+rev.")) { @@ -725,10 +684,12 @@ public static String getFormattedVersion() { /** * Gets the current release target. Since 1.19.3, Mojang no longer stores this information, so we must manually provide it for snapshots. + * * @return Release target */ public static String getReleaseTarget() { // If this is a snapshot, you must change backupVersionNumber! + SharedConstants.tryDetectVersion(); return SharedConstants.getCurrentVersion().isStable() ? SharedConstants.getCurrentVersion().getName() : backupVersionNumber; } @@ -751,4 +712,46 @@ public static ShaderpackDirectoryManager getShaderpacksDirectoryManager() { return shaderpacksDirectoryManager; } + + public static boolean loadedIncompatiblePack() { + return DHCompat.lastPackIncompatible(); + } + + /** + * Called very early on in Minecraft initialization. At this point we *cannot* safely access OpenGL, but we can do + * some very basic setup, config loading, and environment checks. + * + *

    This is roughly equivalent to Fabric Loader's ClientModInitializer#onInitializeClient entrypoint, except + * it's entirely cross platform & we get to decide its exact semantics.

    + * + *

    This is called right before options are loaded, so we can add key bindings here.

    + */ + public static void onEarlyInitialize() { + reloadKeybind = new KeyMapping("iris.keybind.reload", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_R, "iris.keybinds"); + toggleShadersKeybind = new KeyMapping("iris.keybind.toggleShaders", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_K, "iris.keybinds"); + shaderpackScreenKeybind = new KeyMapping("iris.keybind.shaderPackSelection", InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_O, "iris.keybinds"); + wireframeKeybind = new KeyMapping("iris.keybind.wireframe", InputConstants.Type.KEYSYM, InputConstants.UNKNOWN.getValue(), "iris.keybinds"); + + DHCompat.run(); + + try { + if (!Files.exists(getShaderpacksDirectory())) { + Files.createDirectories(getShaderpacksDirectory()); + } + } catch (IOException e) { + logger.warn("Failed to create the shaderpacks directory!"); + logger.warn("", e); + } + + irisConfig = new IrisConfig(FMLPaths.CONFIGDIR.get().resolve(MODID + ".properties")); + + try { + irisConfig.initialize(); + } catch (IOException e) { + logger.error("Failed to initialize Iris configuration, default values will be used instead"); + logger.error("", e); + } + + initialized = true; + } } diff --git a/src/main/java/net/coderbot/iris/IrisLogging.java b/src/main/java/net/irisshaders/iris/IrisLogging.java similarity index 90% rename from src/main/java/net/coderbot/iris/IrisLogging.java rename to src/main/java/net/irisshaders/iris/IrisLogging.java index d80d059ca6..71571a111a 100644 --- a/src/main/java/net/coderbot/iris/IrisLogging.java +++ b/src/main/java/net/irisshaders/iris/IrisLogging.java @@ -1,4 +1,4 @@ -package net.coderbot.iris; +package net.irisshaders.iris; import com.mojang.logging.LogUtils; import org.slf4j.Logger; @@ -17,6 +17,10 @@ public void fatal(String fatal) { this.logger.error(LogUtils.FATAL_MARKER, fatal); } + public void fatal(String fatal, Throwable t) { + this.logger.error(LogUtils.FATAL_MARKER, fatal, t); + } + public void error(String error) { this.logger.error(error); } diff --git a/src/main/java/net/irisshaders/iris/api/v0/IrisApi.java b/src/main/java/net/irisshaders/iris/api/v0/IrisApi.java index 4d294265b7..15e4476579 100644 --- a/src/main/java/net/irisshaders/iris/api/v0/IrisApi.java +++ b/src/main/java/net/irisshaders/iris/api/v0/IrisApi.java @@ -1,6 +1,6 @@ package net.irisshaders.iris.api.v0; -import net.coderbot.iris.apiimpl.IrisApiV0Impl; +import net.irisshaders.iris.apiimpl.IrisApiV0Impl; import java.nio.ByteBuffer; import java.util.function.IntFunction; @@ -8,7 +8,7 @@ /** * The entry point to the Iris API, major version 0. This is currently the latest * version of the API. - * + *

    * To access the API, use {@link #getInstance()}. */ public interface IrisApi { @@ -68,7 +68,7 @@ static IrisApi getInstance() { * Opens the main Iris GUI screen. It's up to Iris to decide * what this screen is, but generally this is the shader selection * screen. - * + *

    * This method takes and returns Objects instead of any concrete * Minecraft screen class to avoid referencing Minecraft classes. * Nevertheless, the passed parent must either be null, or an @@ -87,20 +87,22 @@ static IrisApi getInstance() { * is "options.iris.shaderPackSelection". * * @return the language key, for use with {@code TranslatableText} - * / {@code TranslatableComponent} + * / {@code TranslatableComponent} * @since API v0.0 */ String getMainScreenLanguageKey(); /** * Gets a config object that can edit the Iris configuration. + * * @since API v0.0 */ IrisApiConfig getConfig(); /** * Gets a text vertex sink to render into. - * @param maxQuadCount Maximum amount of quads that will be rendered with this sink + * + * @param maxQuadCount Maximum amount of quads that will be rendered with this sink * @param bufferProvider An IntFunction that can provide a {@code ByteBuffer} with at minimum the bytes provided by the input parameter * @since API 0.1 */ diff --git a/src/main/java/net/irisshaders/iris/api/v0/IrisApiConfig.java b/src/main/java/net/irisshaders/iris/api/v0/IrisApiConfig.java index 66285a3d62..34af4febe3 100644 --- a/src/main/java/net/irisshaders/iris/api/v0/IrisApiConfig.java +++ b/src/main/java/net/irisshaders/iris/api/v0/IrisApiConfig.java @@ -16,6 +16,7 @@ public interface IrisApiConfig { /** * Sets whether shaders are enabled or not, and then applies the change. + * * @since API v0.0 */ void setShadersEnabledAndApply(boolean enabled); diff --git a/src/main/java/net/irisshaders/iris/api/v0/IrisTextVertexSink.java b/src/main/java/net/irisshaders/iris/api/v0/IrisTextVertexSink.java index 08503f0884..33c113edb1 100644 --- a/src/main/java/net/irisshaders/iris/api/v0/IrisTextVertexSink.java +++ b/src/main/java/net/irisshaders/iris/api/v0/IrisTextVertexSink.java @@ -7,27 +7,31 @@ public interface IrisTextVertexSink { /** * Gets the underlying vertex format used for rendering text. + * * @return a valid {@code VertexFormat} instance */ VertexFormat getUnderlyingVertexFormat(); + /** * Gets the underlying buffer used for rendering text in the current sink. + * * @return a valid {@code ByteBuffer} */ ByteBuffer getUnderlyingByteBuffer(); /** * Writes a singular quad with all vertex attributes needed by the current format into the current {@code ByteBuffer}. - * @param x1 Left-most x coordinate of the quad - * @param y1 Top Y coordinate of the quad - * @param x2 Right-most x coordinate of the quad - * @param y2 Bottom Y coordinate of the quad - * @param z Z coordinate of the quad + * + * @param x1 Left-most x coordinate of the quad + * @param y1 Top Y coordinate of the quad + * @param x2 Right-most x coordinate of the quad + * @param y2 Bottom Y coordinate of the quad + * @param z Z coordinate of the quad * @param color Integer-packed ABGR value, with the equation {@code int color = ((int) (a * 255.0F) & 0xFF) << 24 | ((int) (b * 255.0F) & 0xFF) << 16 | ((int) (g * 255.0F) & 0xFF) << 8 | ((int) (r * 255.0F) & 0xFF)} - * @param u1 Top-left U coordinate of the quad texture - * @param v1 Top-left V coordinate of the quad texture - * @param u2 Bottom-right U coordinate of the quad texture - * @param v2 Bottom right V coordinate of the quad texture + * @param u1 Top-left U coordinate of the quad texture + * @param v1 Top-left V coordinate of the quad texture + * @param u2 Bottom-right U coordinate of the quad texture + * @param v2 Bottom right V coordinate of the quad texture * @param light Integer packed light coordinate */ void quad(float x1, float y1, float x2, float y2, float z, int color, float u1, float v1, float u2, float v2, int light); diff --git a/src/main/java/net/irisshaders/iris/api/v0/item/IrisItemLightProvider.java b/src/main/java/net/irisshaders/iris/api/v0/item/IrisItemLightProvider.java index 44bcceeb6b..c9fe1416eb 100644 --- a/src/main/java/net/irisshaders/iris/api/v0/item/IrisItemLightProvider.java +++ b/src/main/java/net/irisshaders/iris/api/v0/item/IrisItemLightProvider.java @@ -10,8 +10,7 @@ public interface IrisItemLightProvider { Vector3f DEFAULT_LIGHT_COLOR = new Vector3f(1, 1, 1); default int getLightEmission(Player player, ItemStack stack) { - if (stack.getItem() instanceof BlockItem) { - BlockItem item = (BlockItem)stack.getItem(); + if (stack.getItem() instanceof BlockItem item) { return item.getBlock().defaultBlockState().getLightEmission(); } diff --git a/src/main/java/net/coderbot/iris/apiimpl/IrisApiV0ConfigImpl.java b/src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0ConfigImpl.java similarity index 84% rename from src/main/java/net/coderbot/iris/apiimpl/IrisApiV0ConfigImpl.java rename to src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0ConfigImpl.java index 952bc51835..7fe837ca84 100644 --- a/src/main/java/net/coderbot/iris/apiimpl/IrisApiV0ConfigImpl.java +++ b/src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0ConfigImpl.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.apiimpl; +package net.irisshaders.iris.apiimpl; -import net.coderbot.iris.Iris; -import net.coderbot.iris.config.IrisConfig; +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApiConfig; +import net.irisshaders.iris.config.IrisConfig; import java.io.IOException; diff --git a/src/main/java/net/coderbot/iris/apiimpl/IrisApiV0Impl.java b/src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0Impl.java similarity index 78% rename from src/main/java/net/coderbot/iris/apiimpl/IrisApiV0Impl.java rename to src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0Impl.java index f814d6bb80..2c07e06857 100644 --- a/src/main/java/net/coderbot/iris/apiimpl/IrisApiV0Impl.java +++ b/src/main/java/net/irisshaders/iris/apiimpl/IrisApiV0Impl.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.apiimpl; +package net.irisshaders.iris.apiimpl; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.pipeline.FixedFunctionWorldRenderingPipeline; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.coderbot.iris.vertices.IrisTextVertexSinkImpl; +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApi; import net.irisshaders.iris.api.v0.IrisApiConfig; import net.irisshaders.iris.api.v0.IrisTextVertexSink; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.pipeline.VanillaRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.irisshaders.iris.vertices.IrisTextVertexSinkImpl; import net.minecraft.client.gui.screens.Screen; import java.nio.ByteBuffer; @@ -31,7 +31,7 @@ public boolean isShaderPackInUse() { return false; } - return !(pipeline instanceof FixedFunctionWorldRenderingPipeline); + return !(pipeline instanceof VanillaRenderingPipeline); } @Override diff --git a/src/main/java/net/irisshaders/iris/compat/dh/DHCompat.java b/src/main/java/net/irisshaders/iris/compat/dh/DHCompat.java new file mode 100644 index 0000000000..042a2e3d63 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/compat/dh/DHCompat.java @@ -0,0 +1,177 @@ +package net.irisshaders.iris.compat.dh; + +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.Minecraft; +import org.joml.Matrix4f; + +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.lang.reflect.InvocationTargetException; + +public class DHCompat { + private static boolean dhPresent = true; + private static boolean lastIncompatible; + private static MethodHandle setupEventHandlers; + private static MethodHandle deletePipeline; + private static MethodHandle incompatible; + private static MethodHandle getDepthTex; + private static MethodHandle getFarPlane; + private static MethodHandle getNearPlane; + private static MethodHandle getDepthTexNoTranslucent; + private static MethodHandle checkFrame; + private static MethodHandle getRenderDistance; + private Object compatInternalInstance; + + public DHCompat(IrisRenderingPipeline pipeline, boolean renderDHShadow) { + try { + if (dhPresent) { + compatInternalInstance = Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal").getDeclaredConstructor(pipeline.getClass(), boolean.class).newInstance(pipeline, renderDHShadow); + lastIncompatible = (boolean) incompatible.invoke(compatInternalInstance); + } + } catch (Throwable e) { + lastIncompatible = false; + if (e.getCause() instanceof ShaderCompileException sce) { + throw sce; + } else if (e instanceof InvocationTargetException ite) { + throw new RuntimeException("Unknown error loading Distant Horizons compatibility.", ite.getCause()); + } else { + throw new RuntimeException("Unknown error loading Distant Horizons compatibility.", e); + } + } + + } + + public static Matrix4f getProjection() { + if (!dhPresent) { + return new Matrix4f(CapturedRenderingState.INSTANCE.getGbufferProjection()); + } + + Matrix4f projection = new Matrix4f(CapturedRenderingState.INSTANCE.getGbufferProjection()); + return new Matrix4f().setPerspective(projection.perspectiveFov(), projection.m11() / projection.m00(), DHCompat.getNearPlane(), DHCompat.getFarPlane()); + } + + public static void run() { + try { + if (FabricLoader.getInstance().isModLoaded("distanthorizons")) { + deletePipeline = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "clear", MethodType.methodType(void.class)); + setupEventHandlers = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.LodRendererEvents"), "setupEventHandlers", MethodType.methodType(void.class)); + getDepthTex = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getStoredDepthTex", MethodType.methodType(int.class)); + getRenderDistance = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getRenderDistance", MethodType.methodType(int.class)); + incompatible = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "incompatiblePack", MethodType.methodType(boolean.class)); + getFarPlane = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getFarPlane", MethodType.methodType(float.class)); + getNearPlane = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getNearPlane", MethodType.methodType(float.class)); + getDepthTexNoTranslucent = MethodHandles.lookup().findVirtual(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "getDepthTexNoTranslucent", MethodType.methodType(int.class)); + checkFrame = MethodHandles.lookup().findStatic(Class.forName("net.irisshaders.iris.compat.dh.DHCompatInternal"), "checkFrame", MethodType.methodType(boolean.class)); + + setupEventHandlers.invoke(); + } else { + dhPresent = false; + } + } catch (Throwable e) { + dhPresent = false; + + if (FabricLoader.getInstance().isModLoaded("distanthorizons")) { + if (e instanceof ExceptionInInitializerError eiie) { + throw new RuntimeException("Failure loading DH compat.", eiie.getCause()); + } else { + throw new RuntimeException("DH 2.0 not found, yet Fabric claims it's there. Curious.", e); + } + } else { + Iris.logger.info("DH not found, and classes not found."); + } + } + } + + public static boolean lastPackIncompatible() { + return dhPresent && hasRenderingEnabled() && lastIncompatible; + } + + public static float getFarPlane() { + if (!dhPresent) return 0.01f; + + try { + return (float) getFarPlane.invoke(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static float getNearPlane() { + if (!dhPresent) return 0.01f; + + try { + return (float) getNearPlane.invoke(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static int getRenderDistance() { + if (!dhPresent) return Minecraft.getInstance().options.getEffectiveRenderDistance(); + + try { + return (int) getRenderDistance.invoke(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static boolean checkFrame() { + if (!dhPresent) { + return false; + } + + try { + return (boolean) checkFrame.invoke(); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public static boolean hasRenderingEnabled() { + if (!dhPresent) { + return false; + } + + return checkFrame(); + } + + public void clearPipeline() { + if (compatInternalInstance == null) return; + + try { + deletePipeline.invoke(compatInternalInstance); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public int getDepthTex() { + if (compatInternalInstance == null) return -1; + + try { + return (int) getDepthTex.invoke(compatInternalInstance); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public int getDepthTexNoTranslucent() { + if (compatInternalInstance == null) return -1; + + try { + return (int) getDepthTexNoTranslucent.invoke(compatInternalInstance); + } catch (Throwable e) { + throw new RuntimeException(e); + } + } + + public Object getInstance() { + return compatInternalInstance; + } +} diff --git a/src/main/java/net/irisshaders/iris/compat/dh/DHCompatInternal.java b/src/main/java/net/irisshaders/iris/compat/dh/DHCompatInternal.java new file mode 100644 index 0000000000..619c1b1eed --- /dev/null +++ b/src/main/java/net/irisshaders/iris/compat/dh/DHCompatInternal.java @@ -0,0 +1,265 @@ +package net.irisshaders.iris.compat.dh; + +import com.mojang.blaze3d.systems.RenderSystem; +import com.seibel.distanthorizons.api.DhApi; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiFramebuffer; +import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector; +import com.seibel.distanthorizons.coreapi.util.math.Vec3f; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.gl.texture.DepthCopyStrategy; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.targets.Blaze3dRenderTargetExt; +import net.irisshaders.iris.targets.DepthTexture; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.Minecraft; +import org.lwjgl.opengl.GL20C; + +import java.io.IOException; + +public class DHCompatInternal { + public static final DHCompatInternal SHADERLESS = new DHCompatInternal(null, false); + static boolean dhEnabled; + private static int guiScale = -1; + private final IrisRenderingPipeline pipeline; + public boolean shouldOverrideShadow; + public boolean shouldOverride; + private IrisLodRenderProgram solidProgram; + private IrisLodRenderProgram translucentProgram; + private IrisLodRenderProgram shadowProgram; + private GlFramebuffer dhTerrainFramebuffer; + private DhFrameBufferWrapper dhTerrainFramebufferWrapper; + private GlFramebuffer dhWaterFramebuffer; + private GlFramebuffer dhShadowFramebuffer; + private DhFrameBufferWrapper dhShadowFramebufferWrapper; + private DepthTexture depthTexNoTranslucent; + private boolean translucentDepthDirty; + private int storedDepthTex; + private boolean incompatible = false; + private int cachedVersion; + + public DHCompatInternal(IrisRenderingPipeline pipeline, boolean dhShadowEnabled) { + this.pipeline = pipeline; + + if (pipeline == null || !DhApi.Delayed.configs.graphics().renderingEnabled().getValue()) { + return; + } + + if (pipeline.getDHTerrainShader().isEmpty() && pipeline.getDHWaterShader().isEmpty()) { + Iris.logger.warn("No DH shader found in this pack."); + incompatible = true; + return; + } + cachedVersion = ((Blaze3dRenderTargetExt) Minecraft.getInstance().getMainRenderTarget()).iris$getDepthBufferVersion(); + + createDepthTex(Minecraft.getInstance().getMainRenderTarget().width, Minecraft.getInstance().getMainRenderTarget().height); + translucentDepthDirty = true; + + ProgramSource terrain = pipeline.getDHTerrainShader().get(); + solidProgram = IrisLodRenderProgram.createProgram(terrain.getName(), false, false, terrain, pipeline.getCustomUniforms(), pipeline); + + if (pipeline.getDHWaterShader().isPresent()) { + ProgramSource water = pipeline.getDHWaterShader().get(); + translucentProgram = IrisLodRenderProgram.createProgram(water.getName(), false, true, water, pipeline.getCustomUniforms(), pipeline); + dhWaterFramebuffer = pipeline.createDHFramebuffer(water, true); + } + + if (pipeline.getDHShadowShader().isPresent() && dhShadowEnabled) { + ProgramSource shadow = pipeline.getDHShadowShader().get(); + shadowProgram = IrisLodRenderProgram.createProgram(shadow.getName(), true, false, shadow, pipeline.getCustomUniforms(), pipeline); + if (pipeline.hasShadowRenderTargets()) { + dhShadowFramebuffer = pipeline.createDHFramebufferShadow(shadow); + dhShadowFramebufferWrapper = new DhFrameBufferWrapper(dhShadowFramebuffer); + } + shouldOverrideShadow = true; + } else { + shouldOverrideShadow = false; + } + + dhTerrainFramebuffer = pipeline.createDHFramebuffer(terrain, false); + dhTerrainFramebufferWrapper = new DhFrameBufferWrapper(dhTerrainFramebuffer); + + if (translucentProgram == null) { + translucentProgram = solidProgram; + } + + shouldOverride = true; + } + + public static int getDhBlockRenderDistance() { + if (DhApi.Delayed.configs == null) { + // Called before DH has finished setup + return 0; + } + + return DhApi.Delayed.configs.graphics().chunkRenderDistance().getValue() * 16; + } + + public static int getRenderDistance() { + return getDhBlockRenderDistance(); + } + + public static float getFarPlane() { + if (DhApi.Delayed.configs == null) { + // Called before DH has finished setup + return 0; + } + + int lodChunkDist = DhApi.Delayed.configs.graphics().chunkRenderDistance().getValue(); + int lodBlockDist = lodChunkDist * 16; + // sqrt 2 to prevent the corners from being cut off + return (float) ((lodBlockDist + 512) * Math.sqrt(2)); + } + + public static float getNearPlane() { + if (DhApi.Delayed.renderProxy == null) { + // Called before DH has finished setup + return 0; + } + + return DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(CapturedRenderingState.INSTANCE.getRealTickDelta()); + } + + public static boolean checkFrame() { + if (guiScale == -1) { + guiScale = Minecraft.getInstance().options.guiScale().get(); + } + + if ((dhEnabled != DhApi.Delayed.configs.graphics().renderingEnabled().getValue() || guiScale != Minecraft.getInstance().options.guiScale().get()) + && IrisApi.getInstance().isShaderPackInUse()) { + guiScale = Minecraft.getInstance().options.guiScale().get(); + dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue(); + try { + Iris.reload(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + return dhEnabled; + } + + public boolean incompatiblePack() { + return incompatible; + } + + public void reconnectDHTextures(int depthTex) { + if (((Blaze3dRenderTargetExt) Minecraft.getInstance().getMainRenderTarget()).iris$getDepthBufferVersion() != cachedVersion) { + cachedVersion = ((Blaze3dRenderTargetExt) Minecraft.getInstance().getMainRenderTarget()).iris$getDepthBufferVersion(); + createDepthTex(Minecraft.getInstance().getMainRenderTarget().width, Minecraft.getInstance().getMainRenderTarget().height); + } + if (storedDepthTex != depthTex && dhTerrainFramebuffer != null) { + storedDepthTex = depthTex; + dhTerrainFramebuffer.addDepthAttachment(depthTex); + if (dhWaterFramebuffer != null) { + dhWaterFramebuffer.addDepthAttachment(depthTex); + } + } + } + + public void createDepthTex(int width, int height) { + if (depthTexNoTranslucent != null) { + depthTexNoTranslucent.destroy(); + depthTexNoTranslucent = null; + } + + translucentDepthDirty = true; + + depthTexNoTranslucent = new DepthTexture("DH depth tex", width, height, DepthBufferFormat.DEPTH32F); + } + + public void clear() { + if (solidProgram != null) { + solidProgram.free(); + solidProgram = null; + } + if (translucentProgram != null) { + translucentProgram.free(); + translucentProgram = null; + } + if (shadowProgram != null) { + shadowProgram.free(); + shadowProgram = null; + } + shouldOverrideShadow = false; + shouldOverride = false; + dhTerrainFramebuffer = null; + dhWaterFramebuffer = null; + dhShadowFramebuffer = null; + storedDepthTex = -1; + translucentDepthDirty = true; + + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, dhTerrainFramebufferWrapper); + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, dhShadowFramebufferWrapper); + dhTerrainFramebufferWrapper = null; + dhShadowFramebufferWrapper = null; + } + + public void setModelPos(Vec3f modelPos) { + solidProgram.bind(); + solidProgram.setModelPos(modelPos); + translucentProgram.bind(); + translucentProgram.setModelPos(modelPos); + solidProgram.bind(); + } + + public IrisLodRenderProgram getSolidShader() { + return solidProgram; + } + + public GlFramebuffer getSolidFB() { + return dhTerrainFramebuffer; + } + + public DhFrameBufferWrapper getSolidFBWrapper() { + return dhTerrainFramebufferWrapper; + } + + public IrisLodRenderProgram getShadowShader() { + return shadowProgram; + } + + public GlFramebuffer getShadowFB() { + return dhShadowFramebuffer; + } + + public DhFrameBufferWrapper getShadowFBWrapper() { + return dhShadowFramebufferWrapper; + } + + public IrisLodRenderProgram getTranslucentShader() { + if (translucentProgram == null) { + return solidProgram; + } + return translucentProgram; + } + + public int getStoredDepthTex() { + return storedDepthTex; + } + + public void copyTranslucents(int width, int height) { + if (translucentDepthDirty) { + translucentDepthDirty = false; + RenderSystem.bindTexture(depthTexNoTranslucent.getTextureId()); + dhTerrainFramebuffer.bindAsReadBuffer(); + IrisRenderSystem.copyTexImage2D(GL20C.GL_TEXTURE_2D, 0, DepthBufferFormat.DEPTH32F.getGlInternalFormat(), 0, 0, width, height, 0); + } else { + DepthCopyStrategy.fastest(false).copy(dhTerrainFramebuffer, storedDepthTex, null, depthTexNoTranslucent.getTextureId(), width, height); + } + } + + public GlFramebuffer getTranslucentFB() { + return dhWaterFramebuffer; + } + + public int getDepthTexNoTranslucent() { + if (depthTexNoTranslucent == null) return 0; + + return depthTexNoTranslucent.getTextureId(); + } +} diff --git a/src/main/java/net/irisshaders/iris/compat/dh/DhFrameBufferWrapper.java b/src/main/java/net/irisshaders/iris/compat/dh/DhFrameBufferWrapper.java new file mode 100644 index 0000000000..dd34a05ef1 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/compat/dh/DhFrameBufferWrapper.java @@ -0,0 +1,54 @@ +package net.irisshaders.iris.compat.dh; + +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiFramebuffer; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import org.lwjgl.opengl.GL32; + +public class DhFrameBufferWrapper implements IDhApiFramebuffer { + private final GlFramebuffer framebuffer; + + + public DhFrameBufferWrapper(GlFramebuffer framebuffer) { + this.framebuffer = framebuffer; + } + + + @Override + public boolean overrideThisFrame() { + return true; + } + + @Override + public void bind() { + this.framebuffer.bind(); + } + + @Override + public void addDepthAttachment(int i, boolean b) { + // ignore + } + + @Override + public int getId() { + return this.framebuffer.getId(); + } + + @Override + public int getStatus() { + this.bind(); + int status = GL32.glCheckFramebufferStatus(GL32.GL_FRAMEBUFFER); + return status; + } + + @Override + public void addColorAttachment(int i, int i1) { + // ignore + } + + @Override + public void destroy() { + // ignore + //this.framebuffer.destroy(); + } + +} diff --git a/src/main/java/net/irisshaders/iris/compat/dh/IrisLodRenderProgram.java b/src/main/java/net/irisshaders/iris/compat/dh/IrisLodRenderProgram.java new file mode 100644 index 0000000000..3a37048d69 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/compat/dh/IrisLodRenderProgram.java @@ -0,0 +1,260 @@ +package net.irisshaders.iris.compat.dh; + +import com.google.common.primitives.Ints; +import com.mojang.blaze3d.systems.RenderSystem; +import com.seibel.distanthorizons.api.DhApi; +import com.seibel.distanthorizons.coreapi.util.math.Vec3f; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.shader.GlShader; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; +import net.minecraft.client.Minecraft; +import org.joml.Matrix3f; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL32; +import org.lwjgl.opengl.GL43C; +import org.lwjgl.system.MemoryStack; + +import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class IrisLodRenderProgram { + // Uniforms + public final int modelOffsetUniform; + public final int worldYOffsetUniform; + public final int mircoOffsetUniform; + public final int modelViewUniform; + public final int modelViewInverseUniform; + public final int projectionUniform; + public final int projectionInverseUniform; + public final int normalMatrix3fUniform; + // Fog/Clip Uniforms + public final int clipDistanceUniform; + private final int id; + private final ProgramUniforms uniforms; + private final CustomUniforms customUniforms; + private final ProgramSamplers samplers; + private final ProgramImages images; + private final BlendModeOverride blend; + private final BufferBlendOverride[] bufferBlendOverrides; + + // This will bind AbstractVertexAttribute + private IrisLodRenderProgram(String name, boolean isShadowPass, boolean translucent, BlendModeOverride override, BufferBlendOverride[] bufferBlendOverrides, String vertex, String tessControl, String tessEval, String geometry, String fragment, CustomUniforms customUniforms, IrisRenderingPipeline pipeline) { + id = GL43C.glCreateProgram(); + + GL32.glBindAttribLocation(this.id, 0, "vPosition"); + GL32.glBindAttribLocation(this.id, 1, "iris_color"); + GL32.glBindAttribLocation(this.id, 2, "irisExtra"); + + this.bufferBlendOverrides = bufferBlendOverrides; + + GlShader vert = new GlShader(ShaderType.VERTEX, name + ".vsh", vertex); + GL43C.glAttachShader(id, vert.getHandle()); + + GlShader tessCont = null; + if (tessControl != null) { + tessCont = new GlShader(ShaderType.TESSELATION_CONTROL, name + ".tcs", tessControl); + GL43C.glAttachShader(id, tessCont.getHandle()); + } + + GlShader tessE = null; + if (tessEval != null) { + tessE = new GlShader(ShaderType.TESSELATION_EVAL, name + ".tes", tessEval); + GL43C.glAttachShader(id, tessE.getHandle()); + } + + GlShader geom = null; + if (geometry != null) { + geom = new GlShader(ShaderType.GEOMETRY, name + ".gsh", geometry); + GL43C.glAttachShader(id, geom.getHandle()); + } + + GlShader frag = new GlShader(ShaderType.FRAGMENT, name + ".fsh", fragment); + GL43C.glAttachShader(id, frag.getHandle()); + + GL32.glLinkProgram(this.id); + int status = GL32.glGetProgrami(this.id, 35714); + if (status != 1) { + String message = "Shader link error in Iris DH program! Details: " + GL32.glGetProgramInfoLog(this.id); + this.free(); + throw new RuntimeException(message); + } else { + GL32.glUseProgram(this.id); + } + + vert.destroy(); + frag.destroy(); + + if (tessCont != null) tessCont.destroy(); + if (tessE != null) tessE.destroy(); + if (geom != null) geom.destroy(); + + blend = override; + ProgramUniforms.Builder uniformBuilder = ProgramUniforms.builder(name, id); + ProgramSamplers.Builder samplerBuilder = ProgramSamplers.builder(id, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); + CommonUniforms.addDynamicUniforms(uniformBuilder, FogMode.PER_VERTEX); + customUniforms.assignTo(uniformBuilder); + BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniformBuilder); + ProgramImages.Builder builder = ProgramImages.builder(id); + pipeline.addGbufferOrShadowSamplers(samplerBuilder, builder, isShadowPass ? pipeline::getFlippedBeforeShadow : () -> translucent ? pipeline.getFlippedAfterTranslucent() : pipeline.getFlippedAfterPrepare(), isShadowPass, false, true, false); + customUniforms.mapholderToPass(uniformBuilder, this); + this.uniforms = uniformBuilder.buildUniforms(); + this.customUniforms = customUniforms; + samplers = samplerBuilder.build(); + images = builder.build(); + + modelOffsetUniform = tryGetUniformLocation2("modelOffset"); + worldYOffsetUniform = tryGetUniformLocation2("worldYOffset"); + mircoOffsetUniform = tryGetUniformLocation2("mircoOffset"); + projectionUniform = tryGetUniformLocation2("iris_ProjectionMatrix"); + projectionInverseUniform = tryGetUniformLocation2("iris_ProjectionMatrixInverse"); + modelViewUniform = tryGetUniformLocation2("iris_ModelViewMatrix"); + modelViewInverseUniform = tryGetUniformLocation2("iris_ModelViewMatrixInverse"); + normalMatrix3fUniform = tryGetUniformLocation2("iris_NormalMatrix"); + + // Fog/Clip Uniforms + clipDistanceUniform = tryGetUniformLocation2("clipDistance"); + } + + public static IrisLodRenderProgram createProgram(String name, boolean isShadowPass, boolean translucent, ProgramSource source, CustomUniforms uniforms, IrisRenderingPipeline pipeline) { + Map transformed = TransformPatcher.patchDH( + name, + source.getVertexSource().orElseThrow(RuntimeException::new), + source.getTessControlSource().orElse(null), + source.getTessEvalSource().orElse(null), + source.getGeometrySource().orElse(null), + source.getFragmentSource().orElseThrow(RuntimeException::new), + pipeline.getTextureMap()); + String vertex = transformed.get(PatchShaderType.VERTEX); + String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); + String tessEval = transformed.get(PatchShaderType.TESS_EVAL); + String geometry = transformed.get(PatchShaderType.GEOMETRY); + String fragment = transformed.get(PatchShaderType.FRAGMENT); + ShaderPrinter.printProgram(name) + .addSources(transformed) + .setName("dh_" + name) + .print(); + + List bufferOverrides = new ArrayList<>(); + + source.getDirectives().getBufferBlendOverrides().forEach(information -> { + int index = Ints.indexOf(source.getDirectives().getDrawBuffers(), information.index()); + if (index > -1) { + bufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); + } + }); + + return new IrisLodRenderProgram(name, isShadowPass, translucent, source.getDirectives().getBlendModeOverride().orElse(null), bufferOverrides.toArray(BufferBlendOverride[]::new), vertex, tessControl, tessEval, geometry, fragment, uniforms, pipeline); + } + + // Noise Uniforms + + public int tryGetUniformLocation2(CharSequence name) { + return GL32.glGetUniformLocation(this.id, name); + } + + public void setUniform(int index, Matrix4f matrix) { + if (index == -1 || matrix == null) return; + + try (MemoryStack stack = MemoryStack.stackPush()) { + FloatBuffer buffer = stack.callocFloat(16); + matrix.get(buffer); + buffer.rewind(); + + RenderSystem.glUniformMatrix4(index, false, buffer); + } + } + + public void setUniform(int index, Matrix3f matrix) { + if (index == -1) return; + + try (MemoryStack stack = MemoryStack.stackPush()) { + FloatBuffer buffer = stack.callocFloat(9); + matrix.get(buffer); + buffer.rewind(); + + RenderSystem.glUniformMatrix3(index, false, buffer); + } + } + + // Override ShaderProgram.bind() + public void bind() { + GL43C.glUseProgram(id); + if (blend != null) blend.apply(); + + for (BufferBlendOverride override : bufferBlendOverrides) { + override.apply(); + } + } + + public void unbind() { + GL43C.glUseProgram(0); + ProgramUniforms.clearActiveUniforms(); + ProgramSamplers.clearActiveSamplers(); + BlendModeOverride.restore(); + } + + public void free() { + GL43C.glDeleteProgram(id); + } + + public void fillUniformData(Matrix4f projection, Matrix4f modelView, int worldYOffset, float partialTicks) { + GL43C.glUseProgram(id); + + Minecraft.getInstance().gameRenderer.lightTexture().turnOnLightLayer(); + IrisRenderSystem.bindTextureToUnit(TextureType.TEXTURE_2D.getGlType(), IrisSamplers.LIGHTMAP_TEXTURE_UNIT, RenderSystem.getShaderTexture(2)); + setUniform(modelViewUniform, modelView); + setUniform(modelViewInverseUniform, modelView.invert(new Matrix4f())); + setUniform(projectionUniform, projection); + setUniform(projectionInverseUniform, projection.invert(new Matrix4f())); + setUniform(normalMatrix3fUniform, new Matrix4f(modelView).invert().transpose3x3(new Matrix3f())); + + setUniform(mircoOffsetUniform, 0.01f); // 0.01 block offset + + // setUniform(skyLightUniform, skyLight); + + if (worldYOffsetUniform != -1) setUniform(worldYOffsetUniform, (float) worldYOffset); + + // Fog/Clip Uniforms + float dhNearClipDistance = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks); + setUniform(clipDistanceUniform, dhNearClipDistance); + + samplers.update(); + uniforms.update(); + + customUniforms.push(this); + + images.update(); + } + + private void setUniform(int index, float value) { + GL43C.glUniform1f(index, value); + } + + public void setModelPos(Vec3f modelPos) { + setUniform(modelOffsetUniform, modelPos); + } + + private void setUniform(int index, Vec3f pos) { + GL43C.glUniform3f(index, pos.x, pos.y, pos.z); + } + +} diff --git a/src/main/java/net/irisshaders/iris/compat/dh/LodRendererEvents.java b/src/main/java/net/irisshaders/iris/compat/dh/LodRendererEvents.java new file mode 100644 index 0000000000..5185f28008 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/compat/dh/LodRendererEvents.java @@ -0,0 +1,349 @@ +package net.irisshaders.iris.compat.dh; + +import com.seibel.distanthorizons.api.DhApi; +import com.seibel.distanthorizons.api.enums.rendering.EDhApiFogDrawMode; +import com.seibel.distanthorizons.api.enums.rendering.EDhApiRenderPass; +import com.seibel.distanthorizons.api.interfaces.override.IDhApiOverrideable; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiFramebuffer; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiAfterDhInitEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeApplyShaderRenderEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeBufferRenderEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeDeferredRenderEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeRenderCleanupEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeRenderEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeRenderPassEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeRenderSetupEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiBeforeTextureClearEvent; +import com.seibel.distanthorizons.api.methods.events.abstractEvents.DhApiColorDepthTextureCreatedEvent; +import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiCancelableEventParam; +import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiEventParam; +import com.seibel.distanthorizons.api.methods.events.sharedParameterObjects.DhApiRenderParam; +import com.seibel.distanthorizons.coreapi.DependencyInjection.OverrideInjector; +import com.seibel.distanthorizons.coreapi.util.math.Vec3f; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shadows.ShadowRenderer; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import org.joml.Matrix4f; +import org.lwjgl.opengl.GL43C; +import org.lwjgl.opengl.GL46C; + +public class LodRendererEvents { + private static boolean eventHandlersBound = false; + + private static boolean atTranslucent = false; + private static int textureWidth; + private static int textureHeight; + + + // constructor // + + public static void setupEventHandlers() { + if (!eventHandlersBound) { + eventHandlersBound = true; + Iris.logger.info("Queuing DH event binding..."); + + DhApiAfterDhInitEvent beforeCleanupEvent = new DhApiAfterDhInitEvent() { + @Override + public void afterDistantHorizonsInit(DhApiEventParam event) { + Iris.logger.info("DH Ready, binding Iris event handlers..."); + + setupSetDeferredBeforeRenderingEvent(); + setupReconnectDepthTextureEvent(); + setupCreateDepthTextureEvent(); + setupTransparentRendererEventCancling(); + setupBeforeBufferClearEvent(); + setupBeforeRenderCleanupEvent(); + beforeBufferRenderEvent(); + setupBeforeRenderFrameBufferBinding(); + setupBeforeRenderPassEvent(); + setupBeforeApplyShaderEvent(); + DHCompatInternal.dhEnabled = DhApi.Delayed.configs.graphics().renderingEnabled().getValue(); + Iris.logger.info("DH Iris events bound."); + } + }; + DhApi.events.bind(DhApiAfterDhInitEvent.class, beforeCleanupEvent); + } + } + + + // setup event handlers // + + + private static void setupSetDeferredBeforeRenderingEvent() { + DhApiBeforeRenderEvent beforeRenderEvent = new DhApiBeforeRenderEvent() { + // this event is called before DH starts any rendering prep + // canceling it will prevent DH from rendering for that frame + @Override + public void beforeRender(DhApiCancelableEventParam event) { + + DhApi.Delayed.renderProxy.setDeferTransparentRendering(IrisApi.getInstance().isShaderPackInUse() && getInstance().shouldOverride); + DhApi.Delayed.configs.graphics().fog().drawMode().setValue(getInstance().shouldOverride ? EDhApiFogDrawMode.FOG_DISABLED : EDhApiFogDrawMode.FOG_ENABLED); + } + }; + + DhApi.events.bind(DhApiBeforeRenderEvent.class, beforeRenderEvent); + } + + private static void setupReconnectDepthTextureEvent() { + DhApiBeforeTextureClearEvent beforeRenderEvent = new DhApiBeforeTextureClearEvent() { + @Override + public void beforeClear(DhApiCancelableEventParam event) { + var getResult = DhApi.Delayed.renderProxy.getDhDepthTextureId(); + if (getResult.success) { + int depthTextureId = getResult.payload; + getInstance().reconnectDHTextures(depthTextureId); + } + } + }; + + DhApi.events.bind(DhApiBeforeTextureClearEvent.class, beforeRenderEvent); + } + + private static DHCompatInternal getInstance() { + return (DHCompatInternal) Iris.getPipelineManager().getPipeline().map(WorldRenderingPipeline::getDHCompat).map(DHCompat::getInstance).orElse(DHCompatInternal.SHADERLESS); + } + + private static void setupCreateDepthTextureEvent() { + DhApiColorDepthTextureCreatedEvent beforeRenderEvent = new DhApiColorDepthTextureCreatedEvent() { + @Override + public void onResize(DhApiEventParam input) { + textureWidth = input.value.newWidth; + textureHeight = input.value.newHeight; + } + }; + + DhApi.events.bind(DhApiColorDepthTextureCreatedEvent.class, beforeRenderEvent); + } + + private static void setupTransparentRendererEventCancling() { + DhApiBeforeRenderEvent beforeRenderEvent = new DhApiBeforeRenderEvent() { + @Override + public void beforeRender(DhApiCancelableEventParam event) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered() && (!getInstance().shouldOverrideShadow)) { + event.cancelEvent(); + } + } + }; + DhApiBeforeDeferredRenderEvent beforeRenderEvent2 = new DhApiBeforeDeferredRenderEvent() { + @Override + public void beforeRender(DhApiCancelableEventParam event) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered() && (!getInstance().shouldOverrideShadow)) { + event.cancelEvent(); + } + } + }; + + DhApi.events.bind(DhApiBeforeRenderEvent.class, beforeRenderEvent); + DhApi.events.bind(DhApiBeforeDeferredRenderEvent.class, beforeRenderEvent2); + } + + private static void setupBeforeRenderCleanupEvent() { + DhApiBeforeRenderCleanupEvent beforeCleanupEvent = new DhApiBeforeRenderCleanupEvent() { + @Override + public void beforeCleanup(DhApiEventParam event) { + if (getInstance().shouldOverride) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + getInstance().getShadowShader().unbind(); + } else { + getInstance().getSolidShader().unbind(); + } + } + } + }; + + DhApi.events.bind(DhApiBeforeRenderCleanupEvent.class, beforeCleanupEvent); + } + + private static void setupBeforeBufferClearEvent() { + DhApiBeforeTextureClearEvent beforeCleanupEvent = new DhApiBeforeTextureClearEvent() { + @Override + public void beforeClear(DhApiCancelableEventParam event) { + if (event.value.renderPass == EDhApiRenderPass.OPAQUE) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + event.cancelEvent(); + } else if (getInstance().shouldOverride) { + GL43C.glClear(GL43C.GL_DEPTH_BUFFER_BIT); + event.cancelEvent(); + } + } + } + }; + + DhApi.events.bind(DhApiBeforeTextureClearEvent.class, beforeCleanupEvent); + } + + private static void beforeBufferRenderEvent() { + DhApiBeforeBufferRenderEvent beforeCleanupEvent = new DhApiBeforeBufferRenderEvent() { + @Override + public void beforeRender(DhApiEventParam input) { + DHCompatInternal instance = getInstance(); + if (instance.shouldOverride) { + Vec3f modelPos = input.value.modelPos; + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + instance.getShadowShader().bind(); + instance.getShadowShader().setModelPos(modelPos); + } else if (atTranslucent) { + instance.getTranslucentShader().bind(); + instance.getTranslucentShader().setModelPos(modelPos); + } else { + instance.getSolidShader().bind(); + instance.getSolidShader().setModelPos(modelPos); + } + } + } + }; + + DhApi.events.bind(DhApiBeforeBufferRenderEvent.class, beforeCleanupEvent); + } + + private static void setupBeforeRenderFrameBufferBinding() { + DhApiBeforeRenderSetupEvent beforeRenderPassEvent = new DhApiBeforeRenderSetupEvent() { + @Override + public void beforeSetup(DhApiEventParam event) { + DHCompatInternal instance = getInstance(); + + OverrideInjector.INSTANCE.unbind(IDhApiShadowCullingFrustum.class, (IDhApiOverrideable) ShadowRenderer.FRUSTUM); + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, instance.getShadowFBWrapper()); + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, instance.getSolidFBWrapper()); + + if (instance.shouldOverride) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered() && instance.shouldOverrideShadow) { + OverrideInjector.INSTANCE.bind(IDhApiFramebuffer.class, instance.getShadowFBWrapper()); + OverrideInjector.INSTANCE.bind(IDhApiShadowCullingFrustum.class, (IDhApiOverrideable) ShadowRenderer.FRUSTUM); + } else { + OverrideInjector.INSTANCE.bind(IDhApiFramebuffer.class, instance.getSolidFBWrapper()); + } + } + } + }; + DhApi.events.bind(DhApiBeforeRenderSetupEvent.class, beforeRenderPassEvent); + + } + + private static void setupBeforeRenderPassEvent() { + DhApiBeforeRenderPassEvent beforeCleanupEvent = new DhApiBeforeRenderPassEvent() { + @Override + public void beforeRender(DhApiEventParam event) { + DHCompatInternal instance = getInstance(); + + // config overrides + if (instance.shouldOverride) { + DhApi.Delayed.configs.graphics().ambientOcclusion().enabled().setValue(false); + DhApi.Delayed.configs.graphics().fog().drawMode().setValue(EDhApiFogDrawMode.FOG_DISABLED); + + if (event.value.renderPass == EDhApiRenderPass.OPAQUE_AND_TRANSPARENT) { + Iris.logger.error("Unexpected; somehow the Opaque + Translucent pass ran with shaders on."); + } + } else { + DhApi.Delayed.configs.graphics().ambientOcclusion().enabled().clearValue(); + DhApi.Delayed.configs.graphics().fog().drawMode().clearValue(); + } + + + // cleanup + if (event.value.renderPass == EDhApiRenderPass.OPAQUE) { + if (instance.shouldOverride) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + instance.getShadowShader().bind(); + } else { + instance.getSolidShader().bind(); + } + atTranslucent = false; + } + } + + + // opaque + if (event.value.renderPass == EDhApiRenderPass.OPAQUE) { + float partialTicks = event.value.partialTicks; + + if (instance.shouldOverride) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + instance.getShadowShader().fillUniformData( + ShadowRenderer.PROJECTION, ShadowRenderer.MODELVIEW, + -1000, //MC.getWrappedClientLevel().getMinHeight(), + partialTicks); + } else { + Matrix4f projection = CapturedRenderingState.INSTANCE.getGbufferProjection(); + //float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks); + //float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0)); + + //Iris.logger.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+ + // " \niris near clip: "+nearClip+" iris far clip: "+farClip); + + instance.getSolidShader().fillUniformData( + new Matrix4f().setPerspective(projection.perspectiveFov(), projection.m11() / projection.m00(), event.value.nearClipPlane, event.value.farClipPlane), + CapturedRenderingState.INSTANCE.getGbufferModelView(), + -1000, //MC.getWrappedClientLevel().getMinHeight(), + partialTicks); + } + } + } + + + // transparent + if (event.value.renderPass == EDhApiRenderPass.TRANSPARENT) { + float partialTicks = event.value.partialTicks; + int depthTextureId = DhApi.Delayed.renderProxy.getDhDepthTextureId().payload; + + if (instance.shouldOverrideShadow && ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + instance.getShadowShader().bind(); + instance.getShadowFB().bind(); + atTranslucent = true; + + return; + } + + if (instance.shouldOverride && instance.getTranslucentFB() != null) { + instance.copyTranslucents(textureWidth, textureHeight); + instance.getTranslucentShader().bind(); + Matrix4f projection = CapturedRenderingState.INSTANCE.getGbufferProjection(); + //float nearClip = DhApi.Delayed.renderProxy.getNearClipPlaneDistanceInBlocks(partialTicks); + //float farClip = (float) ((double) (DHCompatInternal.getDhBlockRenderDistance() + 512) * Math.sqrt(2.0)); + GL46C.glDisable(GL46C.GL_CULL_FACE); + //Iris.logger.info("event near clip: "+event.value.nearClipPlane+" event far clip: "+event.value.farClipPlane+ + // " \niris near clip: "+nearClip+" iris far clip: "+farClip); + + instance.getTranslucentShader().fillUniformData( + new Matrix4f().setPerspective(projection.perspectiveFov(), projection.m11() / projection.m00(), event.value.nearClipPlane, event.value.farClipPlane), + CapturedRenderingState.INSTANCE.getGbufferModelView(), + -1000, //MC.getWrappedClientLevel().getMinHeight(), + partialTicks); + + instance.getTranslucentFB().bind(); + } + + atTranslucent = true; + } + + } + }; + + DhApi.events.bind(DhApiBeforeRenderPassEvent.class, beforeCleanupEvent); + } + + private static void setupBeforeApplyShaderEvent() { + DhApiBeforeApplyShaderRenderEvent beforeApplyShaderEvent = new DhApiBeforeApplyShaderRenderEvent() { + @Override + public void beforeRender(DhApiCancelableEventParam event) { + if (IrisApi.getInstance().isShaderPackInUse()) { + DHCompatInternal instance = getInstance(); + + OverrideInjector.INSTANCE.unbind(IDhApiShadowCullingFrustum.class, (IDhApiOverrideable) ShadowRenderer.FRUSTUM); + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, instance.getShadowFBWrapper()); + OverrideInjector.INSTANCE.unbind(IDhApiFramebuffer.class, instance.getSolidFBWrapper()); + + event.cancelEvent(); + } + } + }; + + DhApi.events.bind(DhApiBeforeApplyShaderRenderEvent.class, beforeApplyShaderEvent); + } + + +} diff --git a/src/main/java/net/coderbot/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java b/src/main/java/net/irisshaders/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java similarity index 96% rename from src/main/java/net/coderbot/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java rename to src/main/java/net/irisshaders/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java index bb833dd852..4b6dcd6a98 100644 --- a/src/main/java/net/coderbot/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java +++ b/src/main/java/net/irisshaders/iris/compat/indigo/mixin/IrisIndigoCompatMixinPlugin.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.indigo.mixin; +package net.irisshaders.iris.compat.indigo.mixin; import net.minecraftforge.fml.loading.FMLLoader; import org.objectweb.asm.tree.ClassNode; diff --git a/src/main/java/net/coderbot/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java b/src/main/java/net/irisshaders/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java similarity index 74% rename from src/main/java/net/coderbot/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java rename to src/main/java/net/irisshaders/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java index e77e669f66..7b9fab3498 100644 --- a/src/main/java/net/coderbot/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java +++ b/src/main/java/net/irisshaders/iris/compat/indigo/mixin/MixinAbstractBlockRenderContext.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.compat.indigo.mixin; +package net.irisshaders.iris.compat.indigo.mixin; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Group; import org.spongepowered.asm.mixin.injection.Redirect; /** @@ -12,13 +11,24 @@ */ @Mixin(targets = "net/fabricmc/fabric/impl/client/indigo/renderer/render/AbstractBlockRenderContext", remap = false) @Pseudo +@SuppressWarnings("all") public class MixinAbstractBlockRenderContext { + // Copied from ColorHelper from Indigo, licensed under the Apache v2 license. + private static int iris$multiplyRGB(int color, float shade) { + final int alpha = ((color >> 24) & 0xFF); + final int red = (int) (((color >> 16) & 0xFF) * shade); + final int green = (int) (((color >> 8) & 0xFF) * shade); + final int blue = (int) ((color & 0xFF) * shade); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + // One of these injections must pass, or else the game will crash. @Redirect(method = {"shadeQuad", "shadeFlatQuad"}, - at = @At(value = "INVOKE", - target = "Lnet/fabricmc/fabric/impl/client/indigo/renderer/helper/ColorHelper;multiplyRGB(IF)I"), require = 0) + at = @At(value = "INVOKE", + target = "Lnet/fabricmc/fabric/impl/client/indigo/renderer/helper/ColorHelper;multiplyRGB(IF)I"), require = 0) private int iris$separateAoColorMultiply(int color, float ao) { - if (BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { + if (WorldRenderingSettings.INSTANCE.shouldUseSeparateAo()) { color &= 0x00FFFFFF; color |= ((int) (ao * 255.0f)) << 24; @@ -27,14 +37,4 @@ public class MixinAbstractBlockRenderContext { return iris$multiplyRGB(color, ao); } } - - // Copied from ColorHelper from Indigo, licensed under the Apache v2 license. - private static int iris$multiplyRGB(int color, float shade) { - final int alpha = ((color >> 24) & 0xFF); - final int red = (int) (((color >> 16) & 0xFF) * shade); - final int green = (int) (((color >> 8) & 0xFF) * shade); - final int blue = (int) ((color & 0xFF) * shade); - - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } } diff --git a/src/main/java/net/coderbot/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java b/src/main/java/net/irisshaders/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java similarity index 96% rename from src/main/java/net/coderbot/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java rename to src/main/java/net/irisshaders/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java index eb3dcd2695..8a17b5a1a0 100644 --- a/src/main/java/net/coderbot/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java +++ b/src/main/java/net/irisshaders/iris/compat/indium/mixin/IrisIndiumCompatMixinPlugin.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.indium.mixin; +package net.irisshaders.iris.compat.indium.mixin; import net.minecraftforge.fml.loading.FMLLoader; import org.objectweb.asm.tree.ClassNode; diff --git a/src/main/java/net/coderbot/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java b/src/main/java/net/irisshaders/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java similarity index 86% rename from src/main/java/net/coderbot/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java rename to src/main/java/net/irisshaders/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java index da29134c83..12f0f94a0d 100644 --- a/src/main/java/net/coderbot/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java +++ b/src/main/java/net/irisshaders/iris/compat/indium/mixin/MixinAbstractBlockRenderContext.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.compat.indium.mixin; +package net.irisshaders.iris.compat.indium.mixin; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; import org.spongepowered.asm.mixin.injection.At; @@ -11,14 +11,25 @@ */ @Mixin(targets = "link/infra/indium/renderer/render/AbstractBlockRenderContext", remap = false) @Pseudo +@SuppressWarnings("all") public class MixinAbstractBlockRenderContext { + // Copied from ColorHelper from Indigo, licensed under the Apache v2 license. + private static int iris$multiplyRGB(int color, float shade) { + final int alpha = ((color >> 24) & 0xFF); + final int red = (int) (((color >> 16) & 0xFF) * shade); + final int green = (int) (((color >> 8) & 0xFF) * shade); + final int blue = (int) ((color & 0xFF) * shade); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + // One of these injections must pass, or else the game will crash. //@Group(name = "iris_separateIndiumAO", min = 2, max = 3) @Redirect(method = {"shadeQuad", "shadeFlatQuad"}, at = @At(value = "INVOKE", target = "Llink/infra/indium/renderer/helper/ColorHelper;multiplyRGB(IF)I"), require = 0) private int iris$separateAoColorMultiply(int color, float ao) { - if (BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { + if (WorldRenderingSettings.INSTANCE.shouldUseSeparateAo()) { color &= 0x00FFFFFF; color |= ((int) (ao * 255.0f)) << 24; @@ -27,14 +38,4 @@ public class MixinAbstractBlockRenderContext { return iris$multiplyRGB(color, ao); } } - - // Copied from ColorHelper from Indigo, licensed under the Apache v2 license. - private static int iris$multiplyRGB(int color, float shade) { - final int alpha = ((color >> 24) & 0xFF); - final int red = (int) (((color >> 16) & 0xFF) * shade); - final int green = (int) (((color >> 8) & 0xFF) * shade); - final int blue = (int) ((color & 0xFF) * shade); - - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } } diff --git a/src/main/java/net/coderbot/iris/compliance/ComplianceVersion.java b/src/main/java/net/irisshaders/iris/compliance/ComplianceVersion.java similarity index 88% rename from src/main/java/net/coderbot/iris/compliance/ComplianceVersion.java rename to src/main/java/net/irisshaders/iris/compliance/ComplianceVersion.java index a0a3c16d4a..81c7990e80 100644 --- a/src/main/java/net/coderbot/iris/compliance/ComplianceVersion.java +++ b/src/main/java/net/irisshaders/iris/compliance/ComplianceVersion.java @@ -1,11 +1,21 @@ -package net.coderbot.iris.compliance; +package net.irisshaders.iris.compliance; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; public enum ComplianceVersion { NO_COMPLIANCE, v1; + public static ComplianceVersion getComplianceLevel(String compliance) { + try { + int complianceL = Integer.parseInt(compliance); + return ComplianceVersion.valueOf("v" + complianceL); + } catch (IllegalArgumentException e) { + Iris.logger.warn("Unknown compliance: " + compliance + "; defaulting to NONCOMPLIANT."); + return NO_COMPLIANCE; + } + } + public int getInternalComplianceLevel() { switch (this) { case NO_COMPLIANCE -> { @@ -13,18 +23,8 @@ public int getInternalComplianceLevel() { } case v1 -> { return 1; - } + } default -> throw new IllegalStateException("Impossible, compliance is not existing? " + this.name()); } } - - public static ComplianceVersion getComplianceLevel(String compliance) { - try { - int complianceL = Integer.parseInt(compliance); - return ComplianceVersion.valueOf("v" + complianceL); - } catch (IllegalArgumentException e) { - Iris.logger.warn("Unknown compliance: " + compliance + "; defaulting to NONCOMPLIANT."); - return NO_COMPLIANCE; - } - } } diff --git a/src/main/java/net/coderbot/iris/config/IrisConfig.java b/src/main/java/net/irisshaders/iris/config/IrisConfig.java similarity index 96% rename from src/main/java/net/coderbot/iris/config/IrisConfig.java rename to src/main/java/net/irisshaders/iris/config/IrisConfig.java index 48e5fb0044..2a18c9f9cf 100644 --- a/src/main/java/net/coderbot/iris/config/IrisConfig.java +++ b/src/main/java/net/irisshaders/iris/config/IrisConfig.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.config; +package net.irisshaders.iris.config; -import net.coderbot.iris.Iris; -import net.coderbot.iris.colorspace.ColorSpace; -import net.coderbot.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.pathways.colorspace.ColorSpace; import java.io.IOException; import java.io.InputStream; @@ -18,29 +18,24 @@ public class IrisConfig { private static final String COMMENT = "This file stores configuration options for Iris, such as the currently active shaderpack"; - + private final Path propertiesPath; /** * The path to the current shaderpack. Null if the internal shaderpack is being used. */ private String shaderPackName; - /** * Whether or not shaders are used for rendering. False to disable all shader-based rendering, true to enable it. */ private boolean enableShaders; - /** * If debug features should be enabled. Gives much more detailed OpenGL error outputs at the cost of performance. */ private boolean enableDebugOptions; - /** * If the update notification should be disabled or not. */ private boolean disableUpdateMessage; - private final Path propertiesPath; - public IrisConfig(Path propertiesPath) { shaderPackName = null; enableShaders = true; diff --git a/src/main/java/net/coderbot/iris/fantastic/IrisParticleRenderTypes.java b/src/main/java/net/irisshaders/iris/fantastic/IrisParticleRenderTypes.java similarity index 96% rename from src/main/java/net/coderbot/iris/fantastic/IrisParticleRenderTypes.java rename to src/main/java/net/irisshaders/iris/fantastic/IrisParticleRenderTypes.java index 8f7a9f69d1..68f6a14338 100644 --- a/src/main/java/net/coderbot/iris/fantastic/IrisParticleRenderTypes.java +++ b/src/main/java/net/irisshaders/iris/fantastic/IrisParticleRenderTypes.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.fantastic; +package net.irisshaders.iris.fantastic; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; diff --git a/src/main/java/net/coderbot/iris/fantastic/ParticleRenderingPhase.java b/src/main/java/net/irisshaders/iris/fantastic/ParticleRenderingPhase.java similarity index 65% rename from src/main/java/net/coderbot/iris/fantastic/ParticleRenderingPhase.java rename to src/main/java/net/irisshaders/iris/fantastic/ParticleRenderingPhase.java index ee5d4980a4..18859b0f2f 100644 --- a/src/main/java/net/coderbot/iris/fantastic/ParticleRenderingPhase.java +++ b/src/main/java/net/irisshaders/iris/fantastic/ParticleRenderingPhase.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.fantastic; +package net.irisshaders.iris.fantastic; public enum ParticleRenderingPhase { EVERYTHING, diff --git a/src/main/java/net/coderbot/iris/fantastic/PhasedParticleEngine.java b/src/main/java/net/irisshaders/iris/fantastic/PhasedParticleEngine.java similarity index 72% rename from src/main/java/net/coderbot/iris/fantastic/PhasedParticleEngine.java rename to src/main/java/net/irisshaders/iris/fantastic/PhasedParticleEngine.java index fee55dce70..5f6e6a80f2 100644 --- a/src/main/java/net/coderbot/iris/fantastic/PhasedParticleEngine.java +++ b/src/main/java/net/irisshaders/iris/fantastic/PhasedParticleEngine.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.fantastic; +package net.irisshaders.iris.fantastic; public interface PhasedParticleEngine { void setParticleRenderingPhase(ParticleRenderingPhase phase); diff --git a/src/main/java/net/coderbot/iris/features/FeatureFlags.java b/src/main/java/net/irisshaders/iris/features/FeatureFlags.java similarity index 89% rename from src/main/java/net/coderbot/iris/features/FeatureFlags.java rename to src/main/java/net/irisshaders/iris/features/FeatureFlags.java index 01ca0059ff..89ca843804 100644 --- a/src/main/java/net/coderbot/iris/features/FeatureFlags.java +++ b/src/main/java/net/irisshaders/iris/features/FeatureFlags.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.features; +package net.irisshaders.iris.features; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; import net.minecraft.client.resources.language.I18n; -import org.apache.commons.lang3.text.WordUtils; +import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Locale; @@ -17,6 +17,7 @@ public enum FeatureFlags { TESSELATION_SHADERS(() -> true, IrisRenderSystem::supportsTesselation), ENTITY_TRANSLUCENT(() -> true, () -> true), REVERSED_CULLING(() -> true, () -> true), + BLOCK_EMISSION_ATTRIBUTE(() -> true, () -> true), SSBO(() -> true, IrisRenderSystem::supportsSSBO), UNKNOWN(() -> false, () -> false); @@ -49,14 +50,6 @@ public static String getInvalidStatus(List invalidFeatureFlags) { } } - public String getHumanReadableName() { - return WordUtils.capitalize(name().replace("_", " ").toLowerCase()); - } - - public boolean isUsable() { - return irisRequirement.getAsBoolean() && hardwareRequirement.getAsBoolean(); - } - public static boolean isInvalid(String name) { try { return !FeatureFlags.valueOf(name.toUpperCase(Locale.US)).isUsable(); @@ -72,4 +65,12 @@ public static FeatureFlags getValue(String value) { return FeatureFlags.UNKNOWN; } } + + public String getHumanReadableName() { + return StringUtils.capitalize(name().replace("_", " ").toLowerCase()); + } + + public boolean isUsable() { + return irisRequirement.getAsBoolean() && hardwareRequirement.getAsBoolean(); + } } diff --git a/src/main/java/net/coderbot/iris/gl/BooleanStateExtended.java b/src/main/java/net/irisshaders/iris/gl/BooleanStateExtended.java similarity index 67% rename from src/main/java/net/coderbot/iris/gl/BooleanStateExtended.java rename to src/main/java/net/irisshaders/iris/gl/BooleanStateExtended.java index 6abb45414d..e1020485cd 100644 --- a/src/main/java/net/coderbot/iris/gl/BooleanStateExtended.java +++ b/src/main/java/net/irisshaders/iris/gl/BooleanStateExtended.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl; +package net.irisshaders.iris.gl; public interface BooleanStateExtended { void setUnknownState(); diff --git a/src/main/java/net/coderbot/iris/gl/GLDebug.java b/src/main/java/net/irisshaders/iris/gl/GLDebug.java similarity index 73% rename from src/main/java/net/coderbot/iris/gl/GLDebug.java rename to src/main/java/net/irisshaders/iris/gl/GLDebug.java index c315ee2a8a..b7d664459c 100644 --- a/src/main/java/net/coderbot/iris/gl/GLDebug.java +++ b/src/main/java/net/irisshaders/iris/gl/GLDebug.java @@ -3,9 +3,9 @@ * License terms: https://www.lwjgl.org/license */ -package net.coderbot.iris.gl; +package net.irisshaders.iris.gl; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import org.lwjgl.opengl.AMDDebugOutput; import org.lwjgl.opengl.ARBDebugOutput; import org.lwjgl.opengl.GL; @@ -21,11 +21,16 @@ import java.util.function.Consumer; public final class GLDebug { + private static DebugState debugState; + /** * Sets up debug callbacks + * * @return 0 for failure, 1 for success, 2 for restart required. */ public static int setupDebugMessageCallback() { + reloadDebugState(); + return setupDebugMessageCallback(APIUtil.DEBUG_STREAM); } @@ -45,10 +50,6 @@ public static Throwable filterStackTrace(Throwable throwable, int offset) { StackTraceElement[] filtered = new StackTraceElement[elems.length]; int j = 0; for (int i = offset; i < elems.length; i++) { - String className = elems[i].getClassName(); - if (className == null) { - className = ""; - } filtered[j++] = elems[i]; } StackTraceElement[] newElems = new StackTraceElement[j]; @@ -58,7 +59,7 @@ public static Throwable filterStackTrace(Throwable throwable, int offset) { } private static void printTrace(PrintStream stream) { - trace(new Consumer() { + trace(new Consumer<>() { boolean first = true; public void accept(String str) { @@ -85,10 +86,10 @@ public static int setupDebugMessageCallback(PrintStream stream) { printDetail(stream, "Message", GLDebugMessageCallback.getMessage(length, message)); printTrace(stream); }); - GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[])null, true); - GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[])null, false); - GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[])null, false); - GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[])null, false); + GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[]) null, true); + GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[]) null, false); + GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[]) null, false); + GL43C.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[]) null, false); GL43C.glDebugMessageCallback(proc, 0L); if ((GL43C.glGetInteger(33310) & 2) == 0) { Iris.logger.warn("[GL] Warning: A non-debug context may not produce any debug output."); @@ -107,10 +108,10 @@ public static int setupDebugMessageCallback(PrintStream stream) { printDetail(stream, "Message", GLDebugMessageCallback.getMessage(length, message)); printTrace(stream); }); - KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[])null, true); - KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[])null, false); - KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[])null, false); - KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[])null, false); + KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[]) null, true); + KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[]) null, false); + KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[]) null, false); + KHRDebug.glDebugMessageControl(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[]) null, false); KHRDebug.glDebugMessageCallback(proc, 0L); if (caps.OpenGL30 && (GL43C.glGetInteger(33310) & 2) == 0) { Iris.logger.warn("[GL] Warning: A non-debug context may not produce any debug output."); @@ -129,10 +130,10 @@ public static int setupDebugMessageCallback(PrintStream stream) { printDetail(stream, "Message", GLDebugMessageARBCallback.getMessage(length, message)); printTrace(stream); }); - ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[])null, true); - ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[])null, false); - ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[])null, false); - ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[])null, false); + ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[]) null, true); + ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[]) null, false); + ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_LOW, (int[]) null, false); + ARBDebugOutput.glDebugMessageControlARB(4352, 4352, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[]) null, false); ARBDebugOutput.glDebugMessageCallbackARB(proc, 0L); return 1; } else if (caps.GL_AMD_debug_output) { @@ -145,10 +146,10 @@ public static int setupDebugMessageCallback(PrintStream stream) { printDetail(stream, "Message", GLDebugMessageAMDCallback.getMessage(length, message)); printTrace(stream); }); - AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[])null, true); - AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[])null, false); - AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_LOW, (int[])null, false); - AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[])null, false); + AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_HIGH, (int[]) null, true); + AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_MEDIUM, (int[]) null, false); + AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_LOW, (int[]) null, false); + AMDDebugOutput.glDebugMessageEnableAMD(0, GL43C.GL_DEBUG_SEVERITY_NOTIFICATION, (int[]) null, false); AMDDebugOutput.glDebugMessageCallbackAMD(proc, 0L); return 1; } else { @@ -193,157 +194,140 @@ private static void printDetailLine(PrintStream stream, String type, String mess } private static String getDebugSource(int source) { - switch(source) { - case 33350: + switch (source) { + case 33350 -> { return "API"; - case 33351: + } + case 33351 -> { return "WINDOW SYSTEM"; - case 33352: + } + case 33352 -> { return "SHADER COMPILER"; - case 33353: + } + case 33353 -> { return "THIRD PARTY"; - case 33354: + } + case 33354 -> { return "APPLICATION"; - case 33355: + } + case 33355 -> { return "OTHER"; - default: + } + default -> { return APIUtil.apiUnknownToken(source); + } } } private static String getDebugType(int type) { - switch(type) { - case 33356: - return "ERROR"; - case 33357: - return "DEPRECATED BEHAVIOR"; - case 33358: - return "UNDEFINED BEHAVIOR"; - case 33359: - return "PORTABILITY"; - case 33360: - return "PERFORMANCE"; - case 33361: - return "OTHER"; - case 33384: - return "MARKER"; - default: - return APIUtil.apiUnknownToken(type); - } + return switch (type) { + case 33356 -> "ERROR"; + case 33357 -> "DEPRECATED BEHAVIOR"; + case 33358 -> "UNDEFINED BEHAVIOR"; + case 33359 -> "PORTABILITY"; + case 33360 -> "PERFORMANCE"; + case 33361 -> "OTHER"; + case 33384 -> "MARKER"; + default -> APIUtil.apiUnknownToken(type); + }; } private static String getDebugSeverity(int severity) { - switch(severity) { - case 33387: - return "NOTIFICATION"; - case 37190: - return "HIGH"; - case 37191: - return "MEDIUM"; - case 37192: - return "LOW"; - default: - return APIUtil.apiUnknownToken(severity); - } + return switch (severity) { + case 33387 -> "NOTIFICATION"; + case 37190 -> "HIGH"; + case 37191 -> "MEDIUM"; + case 37192 -> "LOW"; + default -> APIUtil.apiUnknownToken(severity); + }; } private static String getSourceARB(int source) { - switch(source) { - case 33350: - return "API"; - case 33351: - return "WINDOW SYSTEM"; - case 33352: - return "SHADER COMPILER"; - case 33353: - return "THIRD PARTY"; - case 33354: - return "APPLICATION"; - case 33355: - return "OTHER"; - default: - return APIUtil.apiUnknownToken(source); - } + return switch (source) { + case 33350 -> "API"; + case 33351 -> "WINDOW SYSTEM"; + case 33352 -> "SHADER COMPILER"; + case 33353 -> "THIRD PARTY"; + case 33354 -> "APPLICATION"; + case 33355 -> "OTHER"; + default -> APIUtil.apiUnknownToken(source); + }; } private static String getTypeARB(int type) { - switch(type) { - case 33356: - return "ERROR"; - case 33357: - return "DEPRECATED BEHAVIOR"; - case 33358: - return "UNDEFINED BEHAVIOR"; - case 33359: - return "PORTABILITY"; - case 33360: - return "PERFORMANCE"; - case 33361: - return "OTHER"; - default: - return APIUtil.apiUnknownToken(type); - } + return switch (type) { + case 33356 -> "ERROR"; + case 33357 -> "DEPRECATED BEHAVIOR"; + case 33358 -> "UNDEFINED BEHAVIOR"; + case 33359 -> "PORTABILITY"; + case 33360 -> "PERFORMANCE"; + case 33361 -> "OTHER"; + default -> APIUtil.apiUnknownToken(type); + }; } private static String getSeverityARB(int severity) { - switch(severity) { - case 37190: - return "HIGH"; - case 37191: - return "MEDIUM"; - case 37192: - return "LOW"; - default: - return APIUtil.apiUnknownToken(severity); - } + return switch (severity) { + case 37190 -> "HIGH"; + case 37191 -> "MEDIUM"; + case 37192 -> "LOW"; + default -> APIUtil.apiUnknownToken(severity); + }; } private static String getCategoryAMD(int category) { - switch(category) { - case 37193: - return "API ERROR"; - case 37194: - return "WINDOW SYSTEM"; - case 37195: - return "DEPRECATION"; - case 37196: - return "UNDEFINED BEHAVIOR"; - case 37197: - return "PERFORMANCE"; - case 37198: - return "SHADER COMPILER"; - case 37199: - return "APPLICATION"; - case 37200: - return "OTHER"; - default: - return APIUtil.apiUnknownToken(category); - } + return switch (category) { + case 37193 -> "API ERROR"; + case 37194 -> "WINDOW SYSTEM"; + case 37195 -> "DEPRECATION"; + case 37196 -> "UNDEFINED BEHAVIOR"; + case 37197 -> "PERFORMANCE"; + case 37198 -> "SHADER COMPILER"; + case 37199 -> "APPLICATION"; + case 37200 -> "OTHER"; + default -> APIUtil.apiUnknownToken(category); + }; } private static String getSeverityAMD(int severity) { - switch(severity) { - case 37190: - return "HIGH"; - case 37191: - return "MEDIUM"; - case 37192: - return "LOW"; - default: - return APIUtil.apiUnknownToken(severity); + return switch (severity) { + case 37190 -> "HIGH"; + case 37191 -> "MEDIUM"; + case 37192 -> "LOW"; + default -> APIUtil.apiUnknownToken(severity); + }; + } + + public static void reloadDebugState() { + if (Iris.getIrisConfig().areDebugOptionsEnabled() && (GL.getCapabilities().GL_KHR_debug || GL.getCapabilities().OpenGL43)) { + debugState = new KHRDebugState(); + } else { + debugState = new UnsupportedDebugState(); } } - private static DebugState debugState; + public static void nameObject(int id, int object, String name) { + debugState.nameObject(id, object, name); + } + + public static void pushGroup(int id, String name) { + debugState.pushGroup(id, name); + } + + public static void popGroup() { + debugState.popGroup(); + } - private static interface DebugState { + private interface DebugState { void nameObject(int id, int object, String name); + void pushGroup(int id, String name); + void popGroup(); } private static class KHRDebugState implements DebugState { - private boolean hasGroup; + private int stackSize; @Override public void nameObject(int id, int object, String name) { @@ -353,14 +337,14 @@ public void nameObject(int id, int object, String name) { @Override public void pushGroup(int id, String name) { KHRDebug.glPushDebugGroup(KHRDebug.GL_DEBUG_SOURCE_APPLICATION, id, name); - hasGroup = true; + stackSize += 1; } @Override public void popGroup() { - if (hasGroup) { + if (stackSize != 0) { KHRDebug.glPopDebugGroup(); - hasGroup = false; + stackSize -= 1; } } } @@ -378,16 +362,4 @@ public void pushGroup(int id, String name) { public void popGroup() { } } - - public static void initRenderer() { - if (GL.getCapabilities().GL_KHR_debug || GL.getCapabilities().OpenGL43) { - debugState = new KHRDebugState(); - } else { - debugState = new UnsupportedDebugState(); - } - } - - public static void nameObject(int id, int object, String name) { - debugState.nameObject(id, object, name); - } } diff --git a/src/main/java/net/coderbot/iris/gl/GlResource.java b/src/main/java/net/irisshaders/iris/gl/GlResource.java similarity index 93% rename from src/main/java/net/coderbot/iris/gl/GlResource.java rename to src/main/java/net/irisshaders/iris/gl/GlResource.java index 7cf0a4fff3..5b21e88b2a 100644 --- a/src/main/java/net/coderbot/iris/gl/GlResource.java +++ b/src/main/java/net/irisshaders/iris/gl/GlResource.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl; +package net.irisshaders.iris.gl; public abstract class GlResource { private final int id; diff --git a/src/main/java/net/coderbot/iris/gl/GlVersion.java b/src/main/java/net/irisshaders/iris/gl/GlVersion.java similarity index 63% rename from src/main/java/net/coderbot/iris/gl/GlVersion.java rename to src/main/java/net/irisshaders/iris/gl/GlVersion.java index 7a72e007a3..d0e8dcc496 100644 --- a/src/main/java/net/coderbot/iris/gl/GlVersion.java +++ b/src/main/java/net/irisshaders/iris/gl/GlVersion.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl; +package net.irisshaders.iris.gl; public enum GlVersion { GL_11, diff --git a/src/main/java/net/coderbot/iris/shaderpack/IrisLimits.java b/src/main/java/net/irisshaders/iris/gl/IrisLimits.java similarity index 89% rename from src/main/java/net/coderbot/iris/shaderpack/IrisLimits.java rename to src/main/java/net/irisshaders/iris/gl/IrisLimits.java index b97143a94c..0687f5462f 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/IrisLimits.java +++ b/src/main/java/net/irisshaders/iris/gl/IrisLimits.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.gl; public class IrisLimits { /** * The maximum number of color textures that a shader pack can write to and read from in gbuffer and composite * programs. - * + *

    * It's not recommended to raise this higher than 16 until code for avoiding allocation of unused color textures * is implemented. */ diff --git a/src/main/java/net/coderbot/iris/gl/IrisRenderSystem.java b/src/main/java/net/irisshaders/iris/gl/IrisRenderSystem.java similarity index 95% rename from src/main/java/net/coderbot/iris/gl/IrisRenderSystem.java rename to src/main/java/net/irisshaders/iris/gl/IrisRenderSystem.java index 0a1042dff5..71957ad77f 100644 --- a/src/main/java/net/coderbot/iris/gl/IrisRenderSystem.java +++ b/src/main/java/net/irisshaders/iris/gl/IrisRenderSystem.java @@ -1,12 +1,11 @@ -package net.coderbot.iris.gl; +package net.irisshaders.iris.gl; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexSorting; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.sampler.GlSampler; -import net.coderbot.iris.gl.sampler.SamplerLimits; -import net.coderbot.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.joml.Vector3i; @@ -14,19 +13,14 @@ import org.lwjgl.opengl.ARBDrawBuffersBlend; import org.lwjgl.opengl.EXTShaderImageLoadStore; import org.lwjgl.opengl.GL; -import org.lwjgl.opengl.GL32C; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL11C; -import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL32C; import org.lwjgl.opengl.GL33C; -import org.lwjgl.opengl.GL40C; import org.lwjgl.opengl.GL42C; import org.lwjgl.opengl.GL43C; import org.lwjgl.opengl.GL45C; +import org.lwjgl.opengl.GL46C; import org.lwjgl.opengl.NVXGPUMemoryInfo; -import org.lwjgl.opengl.GL45C; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -37,8 +31,8 @@ * This class is responsible for abstracting calls to OpenGL and asserting that calls are run on the render thread. */ public class IrisRenderSystem { + private static final int[] emptyArray = new int[SamplerLimits.get().getMaxTextureUnits()]; private static Matrix4f backupProjection; - private static DSAAccess dsaState; private static boolean hasMultibind; private static boolean supportsCompute; @@ -321,14 +315,14 @@ public static void enableBufferBlend(int buffer) { public static void blendFuncSeparatei(int buffer, int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) { RenderSystem.assertOnRenderThreadOrInit(); ARBDrawBuffersBlend.glBlendFuncSeparateiARB(buffer, srcRGB, dstRGB, srcAlpha, dstAlpha); - } + } + + // These functions are deprecated and unavailable in the core profile. public static void bindTextureToUnit(int target, int unit, int texture) { dsaState.bindTextureToUnit(target, unit, texture); } - // These functions are deprecated and unavailable in the core profile. - public static int getUniformBlockIndex(int program, String uniformBlockName) { RenderSystem.assertOnRenderThreadOrInit(); return GL32C.glGetUniformBlockIndex(program, uniformBlockName); @@ -373,9 +367,9 @@ public static boolean supportsTesselation() { return supportsTesselation; } - public static int genSampler() { + public static int genSampler() { return GL33C.glGenSamplers(); - } + } public static void destroySampler(int glId) { GL33C.glDeleteSamplers(glId); @@ -391,8 +385,6 @@ public static void bindSamplerToUnit(int unit, int sampler) { samplers[unit] = sampler; } - private static int[] emptyArray = new int[SamplerLimits.get().getMaxTextureUnits()]; - public static void unbindAllSamplers() { boolean usedASampler = false; for (int i = 0; i < samplers.length; i++) { @@ -428,17 +420,17 @@ public static long getVRAM() { } } - public static void deleteBuffers(int glId) { + public static void deleteBuffers(int glId) { RenderSystem.assertOnRenderThreadOrInit(); GL43C.glDeleteBuffers(glId); - } + } - public static void setPolygonMode(int mode) { + public static void setPolygonMode(int mode) { if (mode != polygonMode) { polygonMode = mode; GL43C.glPolygonMode(GL43C.GL_FRONT_AND_BACK, mode); } - } + } public static void overridePolygonMode() { backupPolygonMode = polygonMode; @@ -450,11 +442,25 @@ public static void restorePolygonMode() { backupPolygonMode = GL43C.GL_FILL; } - public interface DSAAccess { + public static void dispatchComputeIndirect(long offset) { + GL43C.glDispatchComputeIndirect(offset); + } + + public static void bindBuffer(int target, int buffer) { + GL46C.glBindBuffer(target, buffer); + } + + public static int createBuffers() { + return dsaState.createBuffers(); + } + + public interface DSAAccess { void generateMipmaps(int texture, int target); void texParameteri(int texture, int target, int pname, int param); + void texParameterf(int texture, int target, int pname, float param); + void texParameteriv(int texture, int target, int pname, int[] params); void readBuffer(int framebuffer, int buffer); @@ -474,7 +480,10 @@ public interface DSAAccess { void framebufferTexture2D(int fb, int fbtarget, int attachment, int target, int texture, int levels); int createFramebuffer(); + int createTexture(int target); + + int createBuffers(); } public static class DSACore extends DSAARB { @@ -542,6 +551,11 @@ public int bufferStorage(int target, float[] data, int usage) { return buffer; } + @Override + public int createBuffers() { + return ARBDirectStateAccess.glCreateBuffers(); + } + @Override public void blitFramebuffer(int source, int dest, int offsetX, int offsetY, int width, int height, int offsetX2, int offsetY2, int width2, int height2, int bufferChoice, int filter) { ARBDirectStateAccess.glBlitNamedFramebuffer(source, dest, offsetX, offsetY, width, height, offsetX2, offsetY2, width2, height2, bufferChoice, filter); @@ -658,6 +672,12 @@ public int createTexture(int target) { GlStateManager._bindTexture(texture); return texture; } + + @Override + public int createBuffers() { + int value = GlStateManager._glGenBuffers(); + return value; + } } /* diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTest.java similarity index 57% rename from src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java rename to src/main/java/net/irisshaders/iris/gl/blending/AlphaTest.java index 89b279708d..0006b4a288 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTest.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTest.java @@ -1,19 +1,10 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; -import net.coderbot.iris.pipeline.newshader.AlphaTests; - -public class AlphaTest { +public record AlphaTest(AlphaTestFunction function, float reference) { public static final AlphaTest ALWAYS = new AlphaTest(AlphaTestFunction.ALWAYS, 0.0f); - private final AlphaTestFunction function; - private final float reference; // WARNING: adding new fields requires updating hashCode and equals methods! - public AlphaTest(AlphaTestFunction function, float reference) { - this.function = function; - this.reference = reference; - } - public String toExpression(String indentation) { return toExpression("gl_FragData[0].a", "iris_currentAlphaTest", indentation); } @@ -25,33 +16,17 @@ public String toExpression(String alphaAccessor, String alphaThreshold, String i return "// alpha test disabled\n"; } else if (this == AlphaTests.VERTEX_ALPHA) { return indentation + "if (!(" + alphaAccessor + " > iris_vertexColorAlpha)) {\n" + - indentation + " discard;\n" + - indentation + "}\n"; + indentation + " discard;\n" + + indentation + "}\n"; } else if (function == AlphaTestFunction.NEVER) { return "discard;\n"; } return indentation + "if (!(" + alphaAccessor + " " + expr + " " + alphaThreshold + ")) {\n" + - indentation + " discard;\n" + - indentation + "}\n"; + indentation + " discard;\n" + + indentation + "}\n"; } - public AlphaTestFunction getFunction() { - return function; - } - - public float getReference() { - return reference; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((function == null) ? 0 : function.hashCode()); - result = prime * result + Float.floatToIntBits(reference); - return result; - } @Override public boolean equals(Object obj) { @@ -64,8 +39,6 @@ public boolean equals(Object obj) { AlphaTest other = (AlphaTest) obj; if (function != other.function) return false; - if (Float.floatToIntBits(reference) != Float.floatToIntBits(other.reference)) - return false; - return true; + return Float.floatToIntBits(reference) == Float.floatToIntBits(other.reference); } } diff --git a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTestFunction.java similarity index 70% rename from src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java rename to src/main/java/net/irisshaders/iris/gl/blending/AlphaTestFunction.java index 177ab94ecc..cc3abb3840 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/AlphaTestFunction.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTestFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; import org.lwjgl.opengl.GL11; @@ -23,26 +23,17 @@ public enum AlphaTestFunction { } public static Optional fromGlId(int glId) { - switch(glId) { - case GL11.GL_NEVER: - return Optional.of(NEVER); - case GL11.GL_LESS: - return Optional.of(LESS); - case GL11.GL_EQUAL: - return Optional.of(EQUAL); - case GL11.GL_LEQUAL: - return Optional.of(LEQUAL); - case GL11.GL_GREATER: - return Optional.of(GREATER); - case GL11.GL_NOTEQUAL: - return Optional.of(NOTEQUAL); - case GL11.GL_GEQUAL: - return Optional.of(GEQUAL); - case GL11.GL_ALWAYS: - return Optional.of(ALWAYS); - default: - return Optional.empty(); - } + return switch (glId) { + case GL11.GL_NEVER -> Optional.of(NEVER); + case GL11.GL_LESS -> Optional.of(LESS); + case GL11.GL_EQUAL -> Optional.of(EQUAL); + case GL11.GL_LEQUAL -> Optional.of(LEQUAL); + case GL11.GL_GREATER -> Optional.of(GREATER); + case GL11.GL_NOTEQUAL -> Optional.of(NOTEQUAL); + case GL11.GL_GEQUAL -> Optional.of(GEQUAL); + case GL11.GL_ALWAYS -> Optional.of(ALWAYS); + default -> Optional.empty(); + }; } public static Optional fromString(String name) { diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/AlphaTests.java b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTests.java similarity index 71% rename from src/main/java/net/coderbot/iris/pipeline/newshader/AlphaTests.java rename to src/main/java/net/irisshaders/iris/gl/blending/AlphaTests.java index 9f0b0933d9..811617505f 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/AlphaTests.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/AlphaTests.java @@ -1,7 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; - -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.blending.AlphaTestFunction; +package net.irisshaders.iris.gl.blending; public class AlphaTests { public static final AlphaTest OFF = AlphaTest.ALWAYS; diff --git a/src/main/java/net/irisshaders/iris/gl/blending/BlendMode.java b/src/main/java/net/irisshaders/iris/gl/blending/BlendMode.java new file mode 100644 index 0000000000..8e10fded8e --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/blending/BlendMode.java @@ -0,0 +1,6 @@ +package net.irisshaders.iris.gl.blending; + +public record BlendMode(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha) { + + +} diff --git a/src/main/java/net/coderbot/iris/gl/blending/BlendModeFunction.java b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeFunction.java similarity index 92% rename from src/main/java/net/coderbot/iris/gl/blending/BlendModeFunction.java rename to src/main/java/net/irisshaders/iris/gl/blending/BlendModeFunction.java index 44ab9b141f..67a0fc4904 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/BlendModeFunction.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeFunction.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import org.lwjgl.opengl.GL11; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/gl/blending/BlendModeOverride.java b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeOverride.java similarity index 90% rename from src/main/java/net/coderbot/iris/gl/blending/BlendModeOverride.java rename to src/main/java/net/irisshaders/iris/gl/blending/BlendModeOverride.java index ab8de89a1f..22cb8f238d 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/BlendModeOverride.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeOverride.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; public class BlendModeOverride { public static final BlendModeOverride OFF = new BlendModeOverride(null); @@ -9,11 +9,11 @@ public BlendModeOverride(BlendMode blendMode) { this.blendMode = blendMode; } - public void apply() { - BlendModeStorage.overrideBlend(this.blendMode); - } - public static void restore() { BlendModeStorage.restoreBlend(); } + + public void apply() { + BlendModeStorage.overrideBlend(this.blendMode); + } } diff --git a/src/main/java/net/coderbot/iris/gl/blending/BlendModeStorage.java b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeStorage.java similarity index 75% rename from src/main/java/net/coderbot/iris/gl/blending/BlendModeStorage.java rename to src/main/java/net/irisshaders/iris/gl/blending/BlendModeStorage.java index d2c6c864a1..0f8b40c3e6 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/BlendModeStorage.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/BlendModeStorage.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.mixin.statelisteners.BooleanStateAccessor; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.statelisteners.BooleanStateAccessor; public class BlendModeStorage { private static boolean originalBlendEnable; @@ -29,7 +29,7 @@ public static void overrideBlend(BlendMode override) { GlStateManager._disableBlend(); } else { GlStateManager._enableBlend(); - GlStateManager._blendFuncSeparate(override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha()); + GlStateManager._blendFuncSeparate(override.srcRgb(), override.dstRgb(), override.srcAlpha(), override.dstAlpha()); } blendLocked = true; @@ -48,7 +48,7 @@ public static void overrideBufferBlend(int index, BlendMode override) { IrisRenderSystem.disableBufferBlend(index); } else { IrisRenderSystem.enableBufferBlend(index); - IrisRenderSystem.blendFuncSeparatei(index, override.getSrcRgb(), override.getDstRgb(), override.getSrcAlpha(), override.getDstAlpha()); + IrisRenderSystem.blendFuncSeparatei(index, override.srcRgb(), override.dstRgb(), override.srcAlpha(), override.dstAlpha()); } blendLocked = true; @@ -75,7 +75,7 @@ public static void restoreBlend() { GlStateManager._disableBlend(); } - GlStateManager._blendFuncSeparate(originalBlend.getSrcRgb(), originalBlend.getDstRgb(), - originalBlend.getSrcAlpha(), originalBlend.getDstAlpha()); + GlStateManager._blendFuncSeparate(originalBlend.srcRgb(), originalBlend.dstRgb(), + originalBlend.srcAlpha(), originalBlend.dstAlpha()); } } diff --git a/src/main/java/net/irisshaders/iris/gl/blending/BufferBlendInformation.java b/src/main/java/net/irisshaders/iris/gl/blending/BufferBlendInformation.java new file mode 100644 index 0000000000..578635e2a6 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/blending/BufferBlendInformation.java @@ -0,0 +1,6 @@ +package net.irisshaders.iris.gl.blending; + +public record BufferBlendInformation(int index, BlendMode blendMode) { + + +} diff --git a/src/main/java/net/coderbot/iris/gl/blending/BufferBlendOverride.java b/src/main/java/net/irisshaders/iris/gl/blending/BufferBlendOverride.java similarity index 88% rename from src/main/java/net/coderbot/iris/gl/blending/BufferBlendOverride.java rename to src/main/java/net/irisshaders/iris/gl/blending/BufferBlendOverride.java index ca3fbb8010..cac40c64a1 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/BufferBlendOverride.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/BufferBlendOverride.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; public class BufferBlendOverride { private final int drawBuffer; diff --git a/src/main/java/net/coderbot/iris/gl/blending/ColorMask.java b/src/main/java/net/irisshaders/iris/gl/blending/ColorMask.java similarity index 92% rename from src/main/java/net/coderbot/iris/gl/blending/ColorMask.java rename to src/main/java/net/irisshaders/iris/gl/blending/ColorMask.java index 73e6a174be..17949a8c1a 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/ColorMask.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/ColorMask.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; public class ColorMask { private final boolean red; diff --git a/src/main/java/net/coderbot/iris/gl/blending/DepthColorStorage.java b/src/main/java/net/irisshaders/iris/gl/blending/DepthColorStorage.java similarity index 87% rename from src/main/java/net/coderbot/iris/gl/blending/DepthColorStorage.java rename to src/main/java/net/irisshaders/iris/gl/blending/DepthColorStorage.java index 68674e2672..3f3b5cf94d 100644 --- a/src/main/java/net/coderbot/iris/gl/blending/DepthColorStorage.java +++ b/src/main/java/net/irisshaders/iris/gl/blending/DepthColorStorage.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.gl.blending; +package net.irisshaders.iris.gl.blending; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; public class DepthColorStorage { private static boolean originalDepthEnable; @@ -45,11 +45,7 @@ public static void unlockDepthColor() { depthColorLocked = false; - if (originalDepthEnable) { - GlStateManager._depthMask(true); - } else { - GlStateManager._depthMask(false); - } + GlStateManager._depthMask(originalDepthEnable); GlStateManager._colorMask(originalColor.isRedMasked(), originalColor.isGreenMasked(), originalColor.isBlueMasked(), originalColor.isAlphaMasked()); } diff --git a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBuffer.java similarity index 86% rename from src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java rename to src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBuffer.java index 0fc06b5b25..a63d182d4f 100644 --- a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBuffer.java +++ b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBuffer.java @@ -1,17 +1,19 @@ -package net.coderbot.iris.gl.buffer; +package net.irisshaders.iris.gl.buffer; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL43C; // Do not extend GlResource, this is immutable. public class ShaderStorageBuffer { - protected int id; protected final int index; protected final ShaderStorageInfo info; + protected int id; public ShaderStorageBuffer(int index, ShaderStorageInfo info) { - this.id = GlStateManager._glGenBuffers(); + this.id = IrisRenderSystem.createBuffers(); + GLDebug.nameObject(GL43C.GL_BUFFER, id, "SSBO " + index); this.index = index; this.info = info; } @@ -46,7 +48,7 @@ public void resizeIfRelative(int width, int height) { int newHeight = (int) (height * info.scaleY()); int finalSize = (newHeight * newWidth) * info.size(); IrisRenderSystem.bufferStorage(GL43C.GL_SHADER_STORAGE_BUFFER, finalSize, 0); - IrisRenderSystem.clearBufferSubData(GL43C.GL_SHADER_STORAGE_BUFFER, GL43C.GL_R8, 0, finalSize, GL43C.GL_RED, GL43C.GL_BYTE, new int[] {0}); + IrisRenderSystem.clearBufferSubData(GL43C.GL_SHADER_STORAGE_BUFFER, GL43C.GL_R8, 0, finalSize, GL43C.GL_RED, GL43C.GL_BYTE, new int[]{0}); IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, index, newId); id = newId; } diff --git a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBufferHolder.java b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBufferHolder.java similarity index 81% rename from src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBufferHolder.java rename to src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBufferHolder.java index 888e5d15d3..342e1a1109 100644 --- a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageBufferHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageBufferHolder.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.gl.buffer; +package net.irisshaders.iris.gl.buffer; import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.sampler.SamplerLimits; import org.lwjgl.opengl.GL43C; import java.util.Collections; @@ -36,40 +36,53 @@ public ShaderStorageBufferHolder(Int2ObjectArrayMap overrides } else { GlStateManager._glBindBuffer(GL43C.GL_SHADER_STORAGE_BUFFER, buffer); IrisRenderSystem.bufferStorage(GL43C.GL_SHADER_STORAGE_BUFFER, bufferInfo.size(), 0); - IrisRenderSystem.clearBufferSubData(GL43C.GL_SHADER_STORAGE_BUFFER, GL43C.GL_R8, 0, bufferInfo.size(), GL43C.GL_RED, GL43C.GL_BYTE, new int[] {0}); + IrisRenderSystem.clearBufferSubData(GL43C.GL_SHADER_STORAGE_BUFFER, GL43C.GL_R8, 0, bufferInfo.size(), GL43C.GL_RED, GL43C.GL_BYTE, new int[]{0}); IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, index, buffer); } }); GlStateManager._glBindBuffer(GL43C.GL_SHADER_STORAGE_BUFFER, 0); } + private static long toMib(long x) { + return x / 1024L / 1024L; + } + public void hasResizedScreen(int width, int height) { if (width != cachedWidth || height != cachedHeight) { cachedWidth = width; cachedHeight = height; for (ShaderStorageBuffer buffer : buffers) { - buffer.resizeIfRelative(width, height); + if (buffer != null) { + buffer.resizeIfRelative(width, height); + } } } } - private static long toMib(long x) { - return x / 1024L / 1024L; - } - public void setupBuffers() { if (destroyed) { throw new IllegalStateException("Tried to use destroyed buffer objects"); } for (ShaderStorageBuffer buffer : buffers) { - buffer.bind(); + if (buffer != null) { + buffer.bind(); + } } } + public int getBufferIndex(int index) { + if (buffers.length < index || buffers[index] == null) + throw new RuntimeException("Tried to query a buffer for indirect dispatch that doesn't exist!"); + + return buffers[index].getId(); + } + public void destroyBuffers() { for (ShaderStorageBuffer buffer : buffers) { - buffer.destroy(); + if (buffer != null) { + buffer.destroy(); + } } buffers = null; destroyed = true; diff --git a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageInfo.java similarity index 69% rename from src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java rename to src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageInfo.java index 5f7e78aead..2b95080a6c 100644 --- a/src/main/java/net/coderbot/iris/gl/buffer/ShaderStorageInfo.java +++ b/src/main/java/net/irisshaders/iris/gl/buffer/ShaderStorageInfo.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.buffer; +package net.irisshaders.iris.gl.buffer; public record ShaderStorageInfo(int size, boolean relative, float scaleX, float scaleY) { } diff --git a/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java b/src/main/java/net/irisshaders/iris/gl/framebuffer/GlFramebuffer.java similarity index 88% rename from src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java rename to src/main/java/net/irisshaders/iris/gl/framebuffer/GlFramebuffer.java index 4053cb6f33..46f6fa1719 100644 --- a/src/main/java/net/coderbot/iris/gl/framebuffer/GlFramebuffer.java +++ b/src/main/java/net/irisshaders/iris/gl/framebuffer/GlFramebuffer.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.gl.framebuffer; +package net.irisshaders.iris.gl.framebuffer; import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; import it.unimi.dsi.fastutil.ints.Int2IntMap; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.texture.TextureInfoCache; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.texture.TextureInfoCache; import org.lwjgl.opengl.GL30C; public class GlFramebuffer extends GlResource { @@ -47,7 +47,7 @@ public void addColorAttachment(int index, int texture) { } public void noDrawBuffers() { - IrisRenderSystem.drawBuffers(getGlId(), new int[] { GL30C.GL_NONE }); + IrisRenderSystem.drawBuffers(getGlId(), new int[]{GL30C.GL_NONE}); } public void drawBuffers(int[] buffers) { @@ -99,9 +99,8 @@ protected void destroyInternal() { public int getStatus() { bind(); - int status = GlStateManager.glCheckFramebufferStatus(GL30C.GL_FRAMEBUFFER); - return status; + return GlStateManager.glCheckFramebufferStatus(GL30C.GL_FRAMEBUFFER); } public int getId() { diff --git a/src/main/java/net/coderbot/iris/gl/framebuffer/ViewportData.java b/src/main/java/net/irisshaders/iris/gl/framebuffer/ViewportData.java similarity index 53% rename from src/main/java/net/coderbot/iris/gl/framebuffer/ViewportData.java rename to src/main/java/net/irisshaders/iris/gl/framebuffer/ViewportData.java index 0b33fdbd69..41f763d38d 100644 --- a/src/main/java/net/coderbot/iris/gl/framebuffer/ViewportData.java +++ b/src/main/java/net/irisshaders/iris/gl/framebuffer/ViewportData.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.gl.framebuffer; +package net.irisshaders.iris.gl.framebuffer; public record ViewportData(float scale, float viewportX, float viewportY) { - private static ViewportData DEFAULT = new ViewportData(1.0f, 0.0f, 0.0f); + private static final ViewportData DEFAULT = new ViewportData(1.0f, 0.0f, 0.0f); public static ViewportData defaultValue() { return DEFAULT; diff --git a/src/main/java/net/coderbot/iris/gl/image/GlImage.java b/src/main/java/net/irisshaders/iris/gl/image/GlImage.java similarity index 89% rename from src/main/java/net/coderbot/iris/gl/image/GlImage.java rename to src/main/java/net/irisshaders/iris/gl/image/GlImage.java index 8fe063aa79..f9f52ea6ee 100644 --- a/src/main/java/net/coderbot/iris/gl/image/GlImage.java +++ b/src/main/java/net/irisshaders/iris/gl/image/GlImage.java @@ -1,17 +1,19 @@ -package net.coderbot.iris.gl.image; +package net.irisshaders.iris.gl.image; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; -import net.coderbot.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.PixelFormat; +import net.irisshaders.iris.gl.texture.PixelType; +import net.irisshaders.iris.gl.texture.TextureType; import org.lwjgl.opengl.ARBClearTexture; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; +import org.lwjgl.opengl.GL43C; public class GlImage extends GlResource { protected final String name; @@ -33,6 +35,8 @@ public GlImage(String name, String samplerName, TextureType target, PixelFormat this.pixelType = pixelType; this.clear = clear; + GLDebug.nameObject(GL43C.GL_TEXTURE, getGlId(), name); + IrisRenderSystem.bindTextureForSetup(target.getGlType(), getGlId()); target.apply(getGlId(), width, height, depth, internalFormat.getGlFormat(), format.getGlFormat(), pixelType.getGlFormat(), null); @@ -59,7 +63,7 @@ protected void setup(int texture, int width, int height, int depth) { IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LEVEL, 0); IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MIN_LOD, 0); - IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LOD,0); + IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LOD, 0); IrisRenderSystem.texParameterf(texture, target.getGlType(), GL20C.GL_TEXTURE_LOD_BIAS, 0.0F); ARBClearTexture.glClearTexImage(texture, 0, format.getGlFormat(), pixelType.getGlFormat(), (int[]) null); @@ -87,7 +91,8 @@ public int getId() { /** * This makes the image aware of a new render target. Depending on the image's properties, it may not follow these targets. - * @param width The width of the main render target. + * + * @param width The width of the main render target. * @param height The height of the main render target. */ public void updateNewSize(int width, int height) { diff --git a/src/main/java/net/coderbot/iris/gl/image/ImageBinding.java b/src/main/java/net/irisshaders/iris/gl/image/ImageBinding.java similarity index 90% rename from src/main/java/net/coderbot/iris/gl/image/ImageBinding.java rename to src/main/java/net/irisshaders/iris/gl/image/ImageBinding.java index d6feb02418..882ef48eef 100644 --- a/src/main/java/net/coderbot/iris/gl/image/ImageBinding.java +++ b/src/main/java/net/irisshaders/iris/gl/image/ImageBinding.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.image; +package net.irisshaders.iris.gl.image; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL42C; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java b/src/main/java/net/irisshaders/iris/gl/image/ImageHolder.java similarity index 66% rename from src/main/java/net/coderbot/iris/gl/image/ImageHolder.java rename to src/main/java/net/irisshaders/iris/gl/image/ImageHolder.java index 9b9f66d8a1..3c966a1fea 100644 --- a/src/main/java/net/coderbot/iris/gl/image/ImageHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/image/ImageHolder.java @@ -1,10 +1,11 @@ -package net.coderbot.iris.gl.image; +package net.irisshaders.iris.gl.image; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; import java.util.function.IntSupplier; public interface ImageHolder { boolean hasImage(String name); + void addTextureImage(IntSupplier textureID, InternalTextureFormat internalFormat, String name); } diff --git a/src/main/java/net/coderbot/iris/gl/image/ImageLimits.java b/src/main/java/net/irisshaders/iris/gl/image/ImageLimits.java similarity index 80% rename from src/main/java/net/coderbot/iris/gl/image/ImageLimits.java rename to src/main/java/net/irisshaders/iris/gl/image/ImageLimits.java index 64e784c57e..395848880a 100644 --- a/src/main/java/net/coderbot/iris/gl/image/ImageLimits.java +++ b/src/main/java/net/irisshaders/iris/gl/image/ImageLimits.java @@ -1,19 +1,15 @@ -package net.coderbot.iris.gl.image; +package net.irisshaders.iris.gl.image; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; public class ImageLimits { - private final int maxImageUnits; private static ImageLimits instance; + private final int maxImageUnits; private ImageLimits() { this.maxImageUnits = IrisRenderSystem.getMaxImageUnits(); } - public int getMaxImageUnits() { - return maxImageUnits; - } - public static ImageLimits get() { if (instance == null) { instance = new ImageLimits(); @@ -21,4 +17,8 @@ public static ImageLimits get() { return instance; } + + public int getMaxImageUnits() { + return maxImageUnits; + } } diff --git a/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java b/src/main/java/net/irisshaders/iris/gl/program/ComputeProgram.java similarity index 76% rename from src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java rename to src/main/java/net/irisshaders/iris/gl/program/ComputeProgram.java index e77cbf2ce1..c6f4bd0aa4 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ComputeProgram.java +++ b/src/main/java/net/irisshaders/iris/gl/program/ComputeProgram.java @@ -1,26 +1,28 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.shaders.ProgramManager; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.FilledIndirectPointer; import org.joml.Vector2f; import org.joml.Vector3i; import org.lwjgl.opengl.GL43C; +import org.lwjgl.opengl.GL46C; public final class ComputeProgram extends GlResource { private final ProgramUniforms uniforms; private final ProgramSamplers samplers; private final ProgramImages images; + private final int[] localSize; private Vector3i absoluteWorkGroups; private Vector2f relativeWorkGroups; - private int[] localSize; private float cachedWidth; private float cachedHeight; private Vector3i cachedWorkGroups; + private FilledIndirectPointer indirectPointer; ComputeProgram(int program, ProgramUniforms uniforms, ProgramSamplers samplers, ProgramImages images) { super(program); @@ -32,12 +34,20 @@ public final class ComputeProgram extends GlResource { this.images = images; } - public void setWorkGroupInfo(Vector2f relativeWorkGroups, Vector3i absoluteWorkGroups) { + public static void unbind() { + ProgramUniforms.clearActiveUniforms(); + ProgramManager.glUseProgram(0); + } + + public void setWorkGroupInfo(Vector2f relativeWorkGroups, Vector3i absoluteWorkGroups, FilledIndirectPointer indirectPointer) { this.relativeWorkGroups = relativeWorkGroups; this.absoluteWorkGroups = absoluteWorkGroups; + this.indirectPointer = indirectPointer; } public Vector3i getWorkGroups(float width, float height) { + if (indirectPointer != null) return null; + if (cachedWidth != width || cachedHeight != height || cachedWorkGroups == null) { this.cachedWidth = width; this.cachedHeight = height; @@ -67,12 +77,12 @@ public void dispatch(float width, float height) { IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT); } - IrisRenderSystem.dispatchCompute(getWorkGroups(width, height)); - } - - public static void unbind() { - ProgramUniforms.clearActiveUniforms(); - ProgramManager.glUseProgram(0); + if (indirectPointer != null) { + IrisRenderSystem.bindBuffer(GL46C.GL_DISPATCH_INDIRECT_BUFFER, indirectPointer.buffer()); + IrisRenderSystem.dispatchComputeIndirect(indirectPointer.offset()); + } else { + IrisRenderSystem.dispatchCompute(getWorkGroups(width, height)); + } } public void destroyInternal() { diff --git a/src/main/java/net/irisshaders/iris/gl/program/GlUniform1iCall.java b/src/main/java/net/irisshaders/iris/gl/program/GlUniform1iCall.java new file mode 100644 index 0000000000..dff5f5d296 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/program/GlUniform1iCall.java @@ -0,0 +1,6 @@ +package net.irisshaders.iris.gl.program; + +public record GlUniform1iCall(int location, int value) { + + +} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/IrisProgramTypes.java b/src/main/java/net/irisshaders/iris/gl/program/IrisProgramTypes.java similarity index 81% rename from src/main/java/net/coderbot/iris/pipeline/newshader/IrisProgramTypes.java rename to src/main/java/net/irisshaders/iris/gl/program/IrisProgramTypes.java index 2ab068c930..7db4edbed9 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/IrisProgramTypes.java +++ b/src/main/java/net/irisshaders/iris/gl/program/IrisProgramTypes.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.gl.program; import com.mojang.blaze3d.shaders.Program; diff --git a/src/main/java/net/coderbot/iris/gl/program/Program.java b/src/main/java/net/irisshaders/iris/gl/program/Program.java similarity index 88% rename from src/main/java/net/coderbot/iris/gl/program/Program.java rename to src/main/java/net/irisshaders/iris/gl/program/Program.java index 1a935e7128..e1bbfe8fee 100644 --- a/src/main/java/net/coderbot/iris/gl/program/Program.java +++ b/src/main/java/net/irisshaders/iris/gl/program/Program.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.shaders.ProgramManager; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL43C; public final class Program extends GlResource { @@ -20,22 +19,21 @@ public final class Program extends GlResource { this.images = images; } + public static void unbind() { + ProgramUniforms.clearActiveUniforms(); + ProgramSamplers.clearActiveSamplers(); + ProgramManager.glUseProgram(0); + } + public void use() { IrisRenderSystem.memoryBarrier(GL43C.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL43C.GL_TEXTURE_FETCH_BARRIER_BIT | GL43C.GL_SHADER_STORAGE_BARRIER_BIT); ProgramManager.glUseProgram(getGlId()); - uniforms.update(); samplers.update(); images.update(); } - public static void unbind() { - ProgramUniforms.clearActiveUniforms(); - ProgramSamplers.clearActiveSamplers(); - ProgramManager.glUseProgram(0); - } - public void destroyInternal() { GlStateManager.glDeleteProgram(getGlId()); } diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java b/src/main/java/net/irisshaders/iris/gl/program/ProgramBuilder.java similarity index 87% rename from src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java rename to src/main/java/net/irisshaders/iris/gl/program/ProgramBuilder.java index d8f311765b..dd2a991b00 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramBuilder.java +++ b/src/main/java/net/irisshaders/iris/gl/program/ProgramBuilder.java @@ -1,18 +1,18 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.google.common.collect.ImmutableSet; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.image.ImageHolder; -import net.coderbot.iris.gl.sampler.GlSampler; -import net.coderbot.iris.gl.sampler.SamplerHolder; -import net.coderbot.iris.gl.shader.GlShader; -import net.coderbot.iris.gl.shader.ProgramCreator; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.image.ImageHolder; +import net.irisshaders.iris.gl.sampler.GlSampler; +import net.irisshaders.iris.gl.sampler.SamplerHolder; +import net.irisshaders.iris.gl.shader.GlShader; +import net.irisshaders.iris.gl.shader.ProgramCreator; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.TextureType; import org.jetbrains.annotations.Nullable; import java.util.function.IntSupplier; @@ -30,10 +30,6 @@ private ProgramBuilder(String name, int program, ImmutableSet reservedT this.images = ProgramImages.builder(program); } - public void bindAttributeLocation(int index, String name) { - IrisRenderSystem.bindAttributeLocation(program, index, name); - } - public static ProgramBuilder begin(String name, @Nullable String vertexSource, @Nullable String geometrySource, @Nullable String fragmentSource, ImmutableSet reservedTextureUnits) { RenderSystem.assertOnRenderThread(); @@ -87,14 +83,6 @@ public static ProgramBuilder beginCompute(String name, @Nullable String source, return new ProgramBuilder(name, programId, reservedTextureUnits); } - public Program build() { - return new Program(program, super.buildUniforms(), this.samplers.build(), this.images.build()); - } - - public ComputeProgram buildCompute() { - return new ComputeProgram(program, super.buildUniforms(), this.samplers.build(), this.images.build()); - } - private static GlShader buildShader(ShaderType shaderType, String name, @Nullable String source) { try { return new GlShader(shaderType, name, source); @@ -105,6 +93,18 @@ private static GlShader buildShader(ShaderType shaderType, String name, @Nullabl } } + public void bindAttributeLocation(int index, String name) { + IrisRenderSystem.bindAttributeLocation(program, index, name); + } + + public Program build() { + return new Program(program, super.buildUniforms(), this.samplers.build(), this.images.build()); + } + + public ComputeProgram buildCompute() { + return new ComputeProgram(program, super.buildUniforms(), this.samplers.build(), this.images.build()); + } + @Override public void addExternalSampler(int textureUnit, String... names) { samplers.addExternalSampler(textureUnit, names); diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java b/src/main/java/net/irisshaders/iris/gl/program/ProgramImages.java similarity index 85% rename from src/main/java/net/coderbot/iris/gl/program/ProgramImages.java rename to src/main/java/net/irisshaders/iris/gl/program/ProgramImages.java index 95c898b103..2027cad8eb 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramImages.java +++ b/src/main/java/net/irisshaders/iris/gl/program/ProgramImages.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.image.ImageBinding; -import net.coderbot.iris.gl.image.ImageHolder; -import net.coderbot.iris.gl.image.ImageLimits; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.image.ImageBinding; +import net.irisshaders.iris.gl.image.ImageHolder; +import net.irisshaders.iris.gl.image.ImageLimits; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; import java.util.ArrayList; import java.util.List; @@ -21,10 +21,14 @@ private ProgramImages(ImmutableList imageBindings, List images; private final List calls; - private int nextImageUnit; private final int maxImageUnits; + private int nextImageUnit; private Builder(int program) { this.program = program; @@ -74,10 +74,10 @@ public void addTextureImage(IntSupplier textureID, InternalTextureFormat interna if (nextImageUnit >= maxImageUnits) { if (maxImageUnits == 0) { throw new IllegalStateException("Image units are not supported on this platform, but a shader" + - " program attempted to reference " + name + "."); + " program attempted to reference " + name + "."); } else { throw new IllegalStateException("No more available texture units while activating image " + name + "." + - " Only " + maxImageUnits + " image units are available."); + " Only " + maxImageUnits + " image units are available."); } } diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java b/src/main/java/net/irisshaders/iris/gl/program/ProgramSamplers.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java rename to src/main/java/net/irisshaders/iris/gl/program/ProgramSamplers.java index 4187cfadc1..745f117815 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramSamplers.java +++ b/src/main/java/net/irisshaders/iris/gl/program/ProgramSamplers.java @@ -1,23 +1,20 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import it.unimi.dsi.fastutil.objects.Object2IntArrayMap; -import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.sampler.GlSampler; -import net.coderbot.iris.gl.sampler.SamplerBinding; -import net.coderbot.iris.gl.sampler.SamplerHolder; -import net.coderbot.iris.gl.sampler.SamplerLimits; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.sampler.GlSampler; +import net.irisshaders.iris.gl.sampler.SamplerBinding; +import net.irisshaders.iris.gl.sampler.SamplerHolder; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; import org.lwjgl.opengl.GL20C; import java.util.ArrayList; @@ -37,6 +34,26 @@ private ProgramSamplers(ImmutableList samplerBindings, Immutable this.initializer = initializer; } + public static void clearActiveSamplers() { + if (active != null) { + active.removeListeners(); + } + + IrisRenderSystem.unbindAllSamplers(); + } + + public static Builder builder(int program, Set reservedTextureUnits) { + return new Builder(program, reservedTextureUnits); + } + + public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap customTextureIds) { + return customTextureSamplerInterceptor(samplerHolder, customTextureIds, ImmutableSet.of()); + } + + public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap customTextureIds, ImmutableSet flippedAtLeastOnceSnapshot) { + return new CustomTextureSamplerInterceptor(samplerHolder, customTextureIds, flippedAtLeastOnceSnapshot); + } + public void update() { if (active != null) { active.removeListeners(); @@ -46,7 +63,7 @@ public void update() { if (initializer != null) { for (GlUniform1iCall call : initializer) { - RenderSystem.glUniform1i(call.getLocation(), call.getValue()); + RenderSystem.glUniform1i(call.location(), call.value()); } initializer = null; @@ -71,26 +88,6 @@ public void removeListeners() { } } - public static void clearActiveSamplers() { - if (active != null) { - active.removeListeners(); - } - - IrisRenderSystem.unbindAllSamplers(); - } - - public static Builder builder(int program, Set reservedTextureUnits) { - return new Builder(program, reservedTextureUnits); - } - - public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap customTextureIds) { - return customTextureSamplerInterceptor(samplerHolder, customTextureIds, ImmutableSet.of()); - } - - public static CustomTextureSamplerInterceptor customTextureSamplerInterceptor(SamplerHolder samplerHolder, Object2ObjectMap customTextureIds, ImmutableSet flippedAtLeastOnceSnapshot) { - return new CustomTextureSamplerInterceptor(samplerHolder, customTextureIds, flippedAtLeastOnceSnapshot); - } - public static final class Builder implements SamplerHolder { private final int program; private final ImmutableSet reservedTextureUnits; @@ -112,8 +109,8 @@ private Builder(int program, Set reservedTextureUnits) { for (int unit : reservedTextureUnits) { if (unit >= maxTextureUnits) { throw new IllegalStateException("Cannot mark texture unit " + unit + " as reserved because that " + - "texture unit isn't available on this system! Only " + maxTextureUnits + - " texture units are available."); + "texture unit isn't available on this system! Only " + maxTextureUnits + + " texture units are available."); } } @@ -131,7 +128,7 @@ private Builder(int program, Set reservedTextureUnits) { public void addExternalSampler(int textureUnit, String... names) { if (!reservedTextureUnits.contains(textureUnit)) { throw new IllegalArgumentException("Cannot add an externally-managed sampler for texture unit " + - textureUnit + " since it isn't in the set of reserved texture units."); + textureUnit + " since it isn't in the set of reserved texture units."); } for (String name : names) { @@ -165,6 +162,7 @@ public boolean addDefaultSampler(TextureType type, IntSupplier texture, ValueUpd /** * Adds a sampler + * * @return false if this sampler is not active, true if at least one of the names referred to an active sampler */ @Override @@ -179,6 +177,7 @@ public boolean addDynamicSampler(TextureType type, IntSupplier texture, ValueUpd /** * Adds a sampler + * * @return false if this sampler is not active, true if at least one of the names referred to an active sampler */ private boolean addDynamicSampler(TextureType type, IntSupplier texture, GlSampler sampler, boolean used, ValueUpdateNotifier notifier, String... names) { diff --git a/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java b/src/main/java/net/irisshaders/iris/gl/program/ProgramUniforms.java similarity index 92% rename from src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java rename to src/main/java/net/irisshaders/iris/gl/program/ProgramUniforms.java index b4f928c9f7..6e7751e8dc 100644 --- a/src/main/java/net/coderbot/iris/gl/program/ProgramUniforms.java +++ b/src/main/java/net/irisshaders/iris/gl/program/ProgramUniforms.java @@ -1,16 +1,16 @@ -package net.coderbot.iris.gl.program; +package net.irisshaders.iris.gl.program; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder; -import net.coderbot.iris.gl.uniform.Uniform; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.uniform.DynamicLocationalUniformHolder; +import net.irisshaders.iris.gl.uniform.Uniform; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.ARBShaderImageLoadStore; @@ -31,10 +31,9 @@ public class ProgramUniforms { private final ImmutableList perFrame; private final ImmutableList dynamic; private final ImmutableList notifiersToReset; - - private ImmutableList once; long lastTick = -1; int lastFrame = -1; + private ImmutableList once; public ProgramUniforms(ImmutableList once, ImmutableList perTick, ImmutableList perFrame, ImmutableList dynamic, ImmutableList notifiersToReset) { @@ -45,12 +44,6 @@ public ProgramUniforms(ImmutableList once, ImmutableList perTi this.notifiersToReset = notifiersToReset; } - private void updateStage(ImmutableList uniforms) { - for (Uniform uniform : uniforms) { - uniform.update(); - } - } - private static long getCurrentTick() { if (Minecraft.getInstance().level == null) { return 0L; @@ -59,6 +52,152 @@ private static long getCurrentTick() { } } + public static void clearActiveUniforms() { + if (active != null) { + active.removeListeners(); + } + } + + public static Builder builder(String name, int program) { + return new Builder(name, program); + } + + private static String getTypeName(int type) { + String typeName; + + if (type == GL20C.GL_FLOAT) { + typeName = "float"; + } else if (type == GL20C.GL_INT) { + typeName = "int"; + } else if (type == GL20C.GL_FLOAT_MAT4) { + typeName = "mat4"; + } else if (type == GL20C.GL_FLOAT_VEC4) { + typeName = "vec4"; + } else if (type == GL20C.GL_FLOAT_MAT3) { + typeName = "mat3"; + } else if (type == GL20C.GL_FLOAT_VEC3) { + typeName = "vec3"; + } else if (type == GL20C.GL_FLOAT_MAT2) { + typeName = "mat2"; + } else if (type == GL20C.GL_FLOAT_VEC2) { + typeName = "vec2"; + } else if (type == GL20C.GL_INT_VEC2) { + typeName = "ivec2"; + } else if (type == GL20C.GL_INT_VEC4) { + typeName = "ivec4"; + } else if (type == GL20C.GL_SAMPLER_3D) { + typeName = "sampler3D"; + } else if (type == GL20C.GL_SAMPLER_2D) { + typeName = "sampler2D"; + } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D) { + typeName = "usampler2D"; + } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D) { + typeName = "usampler3D"; + } else if (type == GL20C.GL_SAMPLER_1D) { + typeName = "sampler1D"; + } else if (type == GL20C.GL_SAMPLER_2D_SHADOW) { + typeName = "sampler2DShadow"; + } else if (type == GL20C.GL_SAMPLER_1D_SHADOW) { + typeName = "sampler1DShadow"; + } else if (type == ARBShaderImageLoadStore.GL_IMAGE_1D) { + typeName = "image1D"; + } else if (type == ARBShaderImageLoadStore.GL_IMAGE_2D) { + typeName = "image2D"; + } else if (type == ARBShaderImageLoadStore.GL_IMAGE_3D) { + typeName = "image3D"; + } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_1D) { + typeName = "iimage1D"; + } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_2D) { + typeName = "iimage2D"; + } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_3D) { + typeName = "iimage3D"; + } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_1D) { + typeName = "uimage1D"; + } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_2D) { + typeName = "uimage2D"; + } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_3D) { + typeName = "uimage3D"; + } else { + typeName = "(unknown:" + type + ")"; + } + + return typeName; + } + + private static UniformType getExpectedType(int type) { + if (type == GL20C.GL_FLOAT) { + return UniformType.FLOAT; + } else if (type == GL20C.GL_INT) { + return UniformType.INT; + } else if (type == GL20C.GL_BOOL) { + return UniformType.INT; + } else if (type == GL20C.GL_FLOAT_MAT4) { + return UniformType.MAT4; + } else if (type == GL20C.GL_FLOAT_VEC4) { + return UniformType.VEC4; + } else if (type == GL20C.GL_INT_VEC4) { + return UniformType.VEC4I; + } else if (type == GL20C.GL_FLOAT_MAT3) { + return UniformType.MAT3; + } else if (type == GL20C.GL_FLOAT_VEC3) { + return UniformType.VEC3; + } else if (type == GL20C.GL_INT_VEC3) { + return UniformType.VEC3I; + } else if (type == GL20C.GL_FLOAT_MAT2) { + return null; + } else if (type == GL20C.GL_FLOAT_VEC2) { + return UniformType.VEC2; + } else if (type == GL20C.GL_INT_VEC2) { + return UniformType.VEC2I; + } else if (type == GL20C.GL_SAMPLER_3D) { + return UniformType.INT; + } else if (type == GL20C.GL_SAMPLER_2D) { + return UniformType.INT; + } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D) { + return UniformType.INT; + } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D) { + return UniformType.INT; + } else if (type == GL20C.GL_SAMPLER_1D) { + return UniformType.INT; + } else if (type == GL20C.GL_SAMPLER_2D_SHADOW) { + return UniformType.INT; + } else if (type == GL20C.GL_SAMPLER_1D_SHADOW) { + return UniformType.INT; + } else { + return null; + } + } + + private static boolean isSampler(int type) { + return type == GL20C.GL_SAMPLER_1D + || type == GL20C.GL_SAMPLER_2D + || type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D + || type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D + || type == GL20C.GL_SAMPLER_3D + || type == GL20C.GL_SAMPLER_1D_SHADOW + || type == GL20C.GL_SAMPLER_2D_SHADOW; + } + + private static boolean isImage(int type) { + return type == ARBShaderImageLoadStore.GL_IMAGE_1D + || type == ARBShaderImageLoadStore.GL_IMAGE_2D + || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_1D + || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_2D + || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_3D + || type == ARBShaderImageLoadStore.GL_INT_IMAGE_1D + || type == ARBShaderImageLoadStore.GL_INT_IMAGE_2D + || type == ARBShaderImageLoadStore.GL_INT_IMAGE_3D + || type == ARBShaderImageLoadStore.GL_IMAGE_3D + || type == ARBShaderImageLoadStore.GL_IMAGE_1D_ARRAY + || type == ARBShaderImageLoadStore.GL_IMAGE_2D_ARRAY; + } + + private void updateStage(ImmutableList uniforms) { + for (Uniform uniform : uniforms) { + uniform.update(); + } + } + public void update() { if (active != null) { active.removeListeners(); @@ -104,16 +243,6 @@ public void removeListeners() { } } - public static void clearActiveUniforms() { - if (active != null) { - active.removeListeners(); - } - } - - public static Builder builder(String name, int program) { - return new Builder(name, program); - } - public static class Builder implements DynamicLocationalUniformHolder { private final String name; private final int program; @@ -220,7 +349,7 @@ public ProgramUniforms buildUniforms() { } return new ProgramUniforms(ImmutableList.copyOf(once.values()), ImmutableList.copyOf(perTick.values()), ImmutableList.copyOf(perFrame.values()), - ImmutableList.copyOf(dynamic.values()), ImmutableList.copyOf(notifiersToReset)); + ImmutableList.copyOf(dynamic.values()), ImmutableList.copyOf(notifiersToReset)); } @Override @@ -241,134 +370,4 @@ public UniformHolder externallyManagedUniform(String name, UniformType type) { return this; } } - - private static String getTypeName(int type) { - String typeName; - - if (type == GL20C.GL_FLOAT) { - typeName = "float"; - } else if (type == GL20C.GL_INT) { - typeName = "int"; - } else if (type == GL20C.GL_FLOAT_MAT4) { - typeName = "mat4"; - } else if (type == GL20C.GL_FLOAT_VEC4) { - typeName = "vec4"; - } else if (type == GL20C.GL_FLOAT_MAT3) { - typeName = "mat3"; - } else if (type == GL20C.GL_FLOAT_VEC3) { - typeName = "vec3"; - } else if (type == GL20C.GL_FLOAT_MAT2) { - typeName = "mat2"; - } else if (type == GL20C.GL_FLOAT_VEC2) { - typeName = "vec2"; - } else if (type == GL20C.GL_INT_VEC2) { - typeName = "ivec2"; - } else if (type == GL20C.GL_INT_VEC4) { - typeName = "ivec4"; - } else if (type == GL20C.GL_SAMPLER_3D) { - typeName = "sampler3D"; - } else if (type == GL20C.GL_SAMPLER_2D) { - typeName = "sampler2D"; - } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D) { - typeName = "usampler2D"; - } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D) { - typeName = "usampler3D"; - } else if (type == GL20C.GL_SAMPLER_1D) { - typeName = "sampler1D"; - } else if (type == GL20C.GL_SAMPLER_2D_SHADOW) { - typeName = "sampler2DShadow"; - } else if (type == GL20C.GL_SAMPLER_1D_SHADOW) { - typeName = "sampler1DShadow"; - } else if (type == ARBShaderImageLoadStore.GL_IMAGE_1D) { - typeName = "image1D"; - } else if (type == ARBShaderImageLoadStore.GL_IMAGE_2D) { - typeName = "image2D"; - } else if (type == ARBShaderImageLoadStore.GL_IMAGE_3D) { - typeName = "image3D"; - } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_1D) { - typeName = "iimage1D"; - } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_2D) { - typeName = "iimage2D"; - } else if (type == ARBShaderImageLoadStore.GL_INT_IMAGE_3D) { - typeName = "iimage3D"; - } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_1D) { - typeName = "uimage1D"; - } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_2D) { - typeName = "uimage2D"; - } else if (type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_3D) { - typeName = "uimage3D"; - } else { - typeName = "(unknown:" + type + ")"; - } - - return typeName; - } - - private static UniformType getExpectedType(int type) { - if (type == GL20C.GL_FLOAT) { - return UniformType.FLOAT; - } else if (type == GL20C.GL_INT) { - return UniformType.INT; - } else if (type == GL20C.GL_BOOL) { - return UniformType.INT; - } else if (type == GL20C.GL_FLOAT_MAT4) { - return UniformType.MAT4; - } else if (type == GL20C.GL_FLOAT_VEC4) { - return UniformType.VEC4; - } else if (type == GL20C.GL_INT_VEC4) { - return UniformType.VEC4I; - } else if (type == GL20C.GL_FLOAT_MAT3) { - return UniformType.MAT3; - } else if (type == GL20C.GL_FLOAT_VEC3) { - return UniformType.VEC3; - } else if (type == GL20C.GL_INT_VEC3) { - return UniformType.VEC3I; - } else if (type == GL20C.GL_FLOAT_MAT2) { - return null; - } else if (type == GL20C.GL_FLOAT_VEC2) { - return UniformType.VEC2; - } else if (type == GL20C.GL_INT_VEC2) { - return UniformType.VEC2I; - } else if (type == GL20C.GL_SAMPLER_3D) { - return UniformType.INT; - } else if (type == GL20C.GL_SAMPLER_2D) { - return UniformType.INT; - } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D) { - return UniformType.INT; - } else if (type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D) { - return UniformType.INT; - } else if (type == GL20C.GL_SAMPLER_1D) { - return UniformType.INT; - } else if (type == GL20C.GL_SAMPLER_2D_SHADOW) { - return UniformType.INT; - } else if (type == GL20C.GL_SAMPLER_1D_SHADOW) { - return UniformType.INT; - } else { - return null; - } - } - - private static boolean isSampler(int type) { - return type == GL20C.GL_SAMPLER_1D - || type == GL20C.GL_SAMPLER_2D - || type == GL30C.GL_UNSIGNED_INT_SAMPLER_2D - || type == GL30C.GL_UNSIGNED_INT_SAMPLER_3D - || type == GL20C.GL_SAMPLER_3D - || type == GL20C.GL_SAMPLER_1D_SHADOW - || type == GL20C.GL_SAMPLER_2D_SHADOW; - } - - private static boolean isImage(int type) { - return type == ARBShaderImageLoadStore.GL_IMAGE_1D - || type == ARBShaderImageLoadStore.GL_IMAGE_2D - || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_1D - || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_2D - || type == ARBShaderImageLoadStore.GL_UNSIGNED_INT_IMAGE_3D - || type == ARBShaderImageLoadStore.GL_INT_IMAGE_1D - || type == ARBShaderImageLoadStore.GL_INT_IMAGE_2D - || type == ARBShaderImageLoadStore.GL_INT_IMAGE_3D - || type == ARBShaderImageLoadStore.GL_IMAGE_3D - || type == ARBShaderImageLoadStore.GL_IMAGE_1D_ARRAY - || type == ARBShaderImageLoadStore.GL_IMAGE_2D_ARRAY; - } } diff --git a/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java b/src/main/java/net/irisshaders/iris/gl/sampler/GlSampler.java similarity index 87% rename from src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java rename to src/main/java/net/irisshaders/iris/gl/sampler/GlSampler.java index 97bd9693fe..7a0e33270e 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/GlSampler.java +++ b/src/main/java/net/irisshaders/iris/gl/sampler/GlSampler.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.gl.sampler; +package net.irisshaders.iris.gl.sampler; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import org.lwjgl.opengl.ARBTextureSwizzle; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL20C; diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerBinding.java similarity index 73% rename from src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java rename to src/main/java/net/irisshaders/iris/gl/sampler/SamplerBinding.java index 7c3b669676..ba74e6c9cc 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerBinding.java +++ b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerBinding.java @@ -1,11 +1,8 @@ -package net.coderbot.iris.gl.sampler; +package net.irisshaders.iris.gl.sampler; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.program.GlUniform1iCall; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureType; -import org.lwjgl.opengl.GL20C; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.texture.TextureType; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerHolder.java similarity index 89% rename from src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java rename to src/main/java/net/irisshaders/iris/gl/sampler/SamplerHolder.java index 1ef4a6b4f0..5a73677585 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerHolder.java @@ -1,18 +1,19 @@ -package net.coderbot.iris.gl.sampler; +package net.irisshaders.iris.gl.sampler; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.texture.TextureType; import java.util.function.IntSupplier; public interface SamplerHolder { void addExternalSampler(int textureUnit, String... names); + boolean hasSampler(String name); /** * Like addDynamicSampler, but also ensures that any unrecognized / unbound samplers sample from this * sampler. - * + *

    * Throws an exception if texture unit 0 is already allocated or reserved in some way. Do not call this * function after calls to addDynamicSampler, it must be called before any calls to addDynamicSampler. */ diff --git a/src/main/java/net/coderbot/iris/gl/sampler/SamplerLimits.java b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerLimits.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/sampler/SamplerLimits.java rename to src/main/java/net/irisshaders/iris/gl/sampler/SamplerLimits.java index 6ffb4be43a..5eb8415539 100644 --- a/src/main/java/net/coderbot/iris/gl/sampler/SamplerLimits.java +++ b/src/main/java/net/irisshaders/iris/gl/sampler/SamplerLimits.java @@ -1,15 +1,15 @@ -package net.coderbot.iris.gl.sampler; +package net.irisshaders.iris.gl.sampler; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL45C; public class SamplerLimits { + private static SamplerLimits instance; private final int maxTextureUnits; private final int maxDrawBuffers; private final int maxShaderStorageUnits; - private static SamplerLimits instance; private SamplerLimits() { this.maxTextureUnits = GlStateManager._getInteger(GL20C.GL_MAX_TEXTURE_IMAGE_UNITS); @@ -17,6 +17,14 @@ private SamplerLimits() { this.maxShaderStorageUnits = IrisRenderSystem.supportsSSBO() ? GlStateManager._getInteger(GL45C.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS) : 0; } + public static SamplerLimits get() { + if (instance == null) { + instance = new SamplerLimits(); + } + + return instance; + } + public int getMaxTextureUnits() { return maxTextureUnits; } @@ -28,12 +36,4 @@ public int getMaxDrawBuffers() { public int getMaxShaderStorageUnits() { return maxShaderStorageUnits; } - - public static SamplerLimits get() { - if (instance == null) { - instance = new SamplerLimits(); - } - - return instance; - } } diff --git a/src/main/java/net/coderbot/iris/gl/shader/GlShader.java b/src/main/java/net/irisshaders/iris/gl/shader/GlShader.java similarity index 63% rename from src/main/java/net/coderbot/iris/gl/shader/GlShader.java rename to src/main/java/net/irisshaders/iris/gl/shader/GlShader.java index 8b7b2c7988..fd1d758353 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/GlShader.java +++ b/src/main/java/net/irisshaders/iris/gl/shader/GlShader.java @@ -1,11 +1,11 @@ // This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license. -package net.coderbot.iris.gl.shader; +package net.irisshaders.iris.gl.shader; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.GLDebug; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL20C; @@ -17,17 +17,17 @@ * A compiled OpenGL shader object. */ public class GlShader extends GlResource { - private static final Logger LOGGER = LogManager.getLogger(GlShader.class); + private static final Logger LOGGER = LogManager.getLogger(GlShader.class); - private final String name; + private final String name; - public GlShader(ShaderType type, String name, String src) { - super(createShader(type, name, src)); + public GlShader(ShaderType type, String name, String src) { + super(createShader(type, name, src)); - this.name = name; - } + this.name = name; + } - private static int createShader(ShaderType type, String name, String src) { + private static int createShader(ShaderType type, String name, String src) { int handle = GlStateManager.glCreateShader(type.id); ShaderWorkarounds.safeShaderSource(handle, src); GlStateManager.glCompileShader(handle); @@ -49,15 +49,15 @@ private static int createShader(ShaderType type, String name, String src) { return handle; } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public int getHandle() { - return this.getGlId(); + public int getHandle() { + return this.getGlId(); } - @Override + @Override protected void destroyInternal() { GlStateManager.glDeleteShader(this.getGlId()); } diff --git a/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java b/src/main/java/net/irisshaders/iris/gl/shader/ProgramCreator.java similarity index 83% rename from src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java rename to src/main/java/net/irisshaders/iris/gl/shader/ProgramCreator.java index 5a18b09465..d86989103c 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/ProgramCreator.java +++ b/src/main/java/net/irisshaders/iris/gl/shader/ProgramCreator.java @@ -1,10 +1,10 @@ // This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license. -package net.coderbot.iris.gl.shader; +package net.irisshaders.iris.gl.shader; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.GLDebug; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.GL20C; @@ -26,6 +26,8 @@ public static int create(String name, GlShader... shaders) { GlStateManager._glBindAttribLocation(program, 1, "UV0"); for (GlShader shader : shaders) { + GLDebug.nameObject(KHRDebug.GL_SHADER, shader.getHandle(), shader.getName()); + GlStateManager.glAttachShader(program, shader.getHandle()); } @@ -34,9 +36,9 @@ public static int create(String name, GlShader... shaders) { GLDebug.nameObject(KHRDebug.GL_PROGRAM, program, name); //Always detach shaders according to https://www.khronos.org/opengl/wiki/Shader_Compilation#Cleanup - for (GlShader shader : shaders) { - IrisRenderSystem.detachShader(program, shader.getHandle()); - } + for (GlShader shader : shaders) { + IrisRenderSystem.detachShader(program, shader.getHandle()); + } String log = IrisRenderSystem.getProgramInfoLog(program); diff --git a/src/main/java/net/coderbot/iris/gl/shader/ShaderCompileException.java b/src/main/java/net/irisshaders/iris/gl/shader/ShaderCompileException.java similarity index 93% rename from src/main/java/net/coderbot/iris/gl/shader/ShaderCompileException.java rename to src/main/java/net/irisshaders/iris/gl/shader/ShaderCompileException.java index 04f441e5b0..b30e16be5d 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/ShaderCompileException.java +++ b/src/main/java/net/irisshaders/iris/gl/shader/ShaderCompileException.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.shader; +package net.irisshaders.iris.gl.shader; public class ShaderCompileException extends RuntimeException { private final String filename; diff --git a/src/main/java/net/irisshaders/iris/gl/shader/ShaderType.java b/src/main/java/net/irisshaders/iris/gl/shader/ShaderType.java new file mode 100644 index 0000000000..93e587a6fe --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/shader/ShaderType.java @@ -0,0 +1,25 @@ +// This file is based on code from Sodium by JellySquid, licensed under the LGPLv3 license. + +package net.irisshaders.iris.gl.shader; + +import org.lwjgl.opengl.GL20; +import org.lwjgl.opengl.GL32C; +import org.lwjgl.opengl.GL43C; + +/** + * An enumeration over the supported OpenGL shader types. + */ +public enum ShaderType { + VERTEX(GL20.GL_VERTEX_SHADER), + GEOMETRY(GL32C.GL_GEOMETRY_SHADER), + FRAGMENT(GL20.GL_FRAGMENT_SHADER), + COMPUTE(GL43C.GL_COMPUTE_SHADER), + TESSELATION_CONTROL(GL43C.GL_TESS_CONTROL_SHADER), + TESSELATION_EVAL(GL43C.GL_TESS_EVALUATION_SHADER); + + public final int id; + + ShaderType(int id) { + this.id = id; + } +} diff --git a/src/main/java/net/coderbot/iris/gl/shader/ShaderWorkarounds.java b/src/main/java/net/irisshaders/iris/gl/shader/ShaderWorkarounds.java similarity index 90% rename from src/main/java/net/coderbot/iris/gl/shader/ShaderWorkarounds.java rename to src/main/java/net/irisshaders/iris/gl/shader/ShaderWorkarounds.java index 9d2137664c..1892bcfa93 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/ShaderWorkarounds.java +++ b/src/main/java/net/irisshaders/iris/gl/shader/ShaderWorkarounds.java @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package net.coderbot.iris.gl.shader; +package net.irisshaders.iris.gl.shader; import org.lwjgl.PointerBuffer; import org.lwjgl.opengl.GL20C; @@ -22,8 +22,8 @@ import java.nio.ByteBuffer; /** - * Contains a workaround for a crash in nglShaderSource on some AMD drivers. Copied from the following Canvas commit: - * https://github.com/grondag/canvas/commit/820bf754092ccaf8d0c169620c2ff575722d7d96 + * Contains a workaround for a crash in nglShaderSource on some AMD drivers. Copied from + * the following Canvas commit. */ public class ShaderWorkarounds { /** diff --git a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java b/src/main/java/net/irisshaders/iris/gl/shader/StandardMacros.java similarity index 81% rename from src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java rename to src/main/java/net/irisshaders/iris/gl/shader/StandardMacros.java index 515761e18c..c1e164a907 100644 --- a/src/main/java/net/coderbot/iris/gl/shader/StandardMacros.java +++ b/src/main/java/net/irisshaders/iris/gl/shader/StandardMacros.java @@ -1,15 +1,16 @@ -package net.coderbot.iris.gl.shader; +package net.irisshaders.iris.gl.shader; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlUtil; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.HandRenderer; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.coderbot.iris.shaderpack.StringPair; -import net.coderbot.iris.texture.format.TextureFormat; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.minecraft.SharedConstants; +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.pathways.HandRenderer; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.texture.format.TextureFormat; +import net.irisshaders.iris.texture.format.TextureFormatLoader; import net.minecraft.Util; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20C; @@ -49,6 +50,28 @@ public static ImmutableList createStandardEnvironmentDefines() { define(standardDefines, getRenderer()); define(standardDefines, "IS_IRIS"); + + if (FabricLoader.getInstance().isModLoaded("distanthorizons") && DHCompat.hasRenderingEnabled()) { + define(standardDefines, "DISTANT_HORIZONS"); + } + + define(standardDefines, "DH_BLOCK_UNKNOWN", String.valueOf(0)); + define(standardDefines, "DH_BLOCK_LEAVES", String.valueOf(1)); + define(standardDefines, "DH_BLOCK_STONE", String.valueOf(2)); + define(standardDefines, "DH_BLOCK_WOOD", String.valueOf(3)); + define(standardDefines, "DH_BLOCK_METAL", String.valueOf(4)); + define(standardDefines, "DH_BLOCK_DIRT", String.valueOf(5)); + define(standardDefines, "DH_BLOCK_LAVA", String.valueOf(6)); + define(standardDefines, "DH_BLOCK_DEEPSLATE", String.valueOf(7)); + define(standardDefines, "DH_BLOCK_SNOW", String.valueOf(8)); + define(standardDefines, "DH_BLOCK_SAND", String.valueOf(9)); + define(standardDefines, "DH_BLOCK_TERRACOTTA", String.valueOf(10)); + define(standardDefines, "DH_BLOCK_NETHER_STONE", String.valueOf(11)); + define(standardDefines, "DH_BLOCK_WATER", String.valueOf(12)); + define(standardDefines, "DH_BLOCK_GRASS", String.valueOf(13)); + define(standardDefines, "DH_BLOCK_AIR", String.valueOf(14)); + define(standardDefines, "DH_BLOCK_ILLUMINATED", String.valueOf(15)); + for (String glExtension : getGlExtensions()) { define(standardDefines, glExtension); } @@ -91,7 +114,7 @@ public static String getMcVersion() { String[] splitVersion = version.split("\\."); if (splitVersion.length < 2) { - Iris.logger.error("Could not parse game version \"" + version + "\""); + Iris.logger.error("Could not parse game version \"" + version + "\""); splitVersion = Iris.getBackupVersionNumber().split("\\."); } @@ -171,18 +194,13 @@ public static String group(Matcher matcher, String name) { * @see Optifine Doc */ public static String getOsString() { - switch (Util.getPlatform()) { - case OSX: - return "MC_OS_MAC"; - case LINUX: - return "MC_OS_LINUX"; - case WINDOWS: - return "MC_OS_WINDOWS"; - case SOLARIS: // Note: Optifine doesn't have a macro for Solaris. https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714 - case UNKNOWN: - default: - return "MC_OS_UNKNOWN"; - } + return switch (Util.getPlatform()) { + case OSX -> "MC_OS_MAC"; + case LINUX -> "MC_OS_LINUX"; + case WINDOWS -> + "MC_OS_WINDOWS"; // Note: Optifine doesn't have a macro for Solaris. https://github.com/sp614x/optifine/blob/9c6a5b5326558ccc57c6490b66b3be3b2dc8cbef/OptiFineDoc/doc/shaders.txt#L709-L714 + default -> "MC_OS_UNKNOWN"; + }; } /** @@ -243,7 +261,7 @@ public static String getRenderer() { * Returns the list of currently enabled GL extensions * This is done by calling {@link GL11#glGetString} with the arg {@link GL11#GL_EXTENSIONS} * - * @return list of activated extensions prefixed with "MC_" + * @return set of activated extensions prefixed with "MC_" * @see Optifine Doc */ public static Set getGlExtensions() { diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/FogMode.java b/src/main/java/net/irisshaders/iris/gl/state/FogMode.java similarity index 83% rename from src/main/java/net/coderbot/iris/pipeline/newshader/FogMode.java rename to src/main/java/net/irisshaders/iris/gl/state/FogMode.java index f744554433..242dd6ccf0 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/FogMode.java +++ b/src/main/java/net/irisshaders/iris/gl/state/FogMode.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.gl.state; public enum FogMode { /** diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderAttributeInputs.java b/src/main/java/net/irisshaders/iris/gl/state/ShaderAttributeInputs.java similarity index 90% rename from src/main/java/net/coderbot/iris/pipeline/newshader/ShaderAttributeInputs.java rename to src/main/java/net/irisshaders/iris/gl/state/ShaderAttributeInputs.java index b24822da01..1dd4a90d1e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderAttributeInputs.java +++ b/src/main/java/net/irisshaders/iris/gl/state/ShaderAttributeInputs.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.gl.state; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; public class ShaderAttributeInputs { private boolean color; @@ -82,10 +81,6 @@ public boolean isGlint() { return glint; } - public InputAvailability toAvailability() { - return new InputAvailability(tex, light, overlay); - } - @Override public int hashCode() { final int prime = 31; @@ -124,9 +119,7 @@ public boolean equals(Object obj) { return false; if (glint != other.glint) return false; - if (text != other.text) - return false; - return true; + return text == other.text; } public boolean isText() { diff --git a/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java b/src/main/java/net/irisshaders/iris/gl/state/StateUpdateNotifiers.java similarity index 89% rename from src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java rename to src/main/java/net/irisshaders/iris/gl/state/StateUpdateNotifiers.java index e9230d7ca4..92312ec134 100644 --- a/src/main/java/net/coderbot/iris/gl/state/StateUpdateNotifiers.java +++ b/src/main/java/net/irisshaders/iris/gl/state/StateUpdateNotifiers.java @@ -1,6 +1,4 @@ -package net.coderbot.iris.gl.state; - -import java.util.function.IntSupplier; +package net.irisshaders.iris.gl.state; /** * Holds some standard update notifiers for various elements of GL state. Currently, this class has a few listeners for diff --git a/src/main/java/net/irisshaders/iris/gl/state/ValueUpdateNotifier.java b/src/main/java/net/irisshaders/iris/gl/state/ValueUpdateNotifier.java new file mode 100644 index 0000000000..94e3d07226 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/state/ValueUpdateNotifier.java @@ -0,0 +1,11 @@ +package net.irisshaders.iris.gl.state; + +/** + * A + */ +public interface ValueUpdateNotifier { + /** + * Sets up a listener with this notifier. + */ + void setListener(Runnable listener); +} diff --git a/src/main/java/net/irisshaders/iris/gl/texture/DepthBufferFormat.java b/src/main/java/net/irisshaders/iris/gl/texture/DepthBufferFormat.java new file mode 100644 index 0000000000..165707ee70 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/texture/DepthBufferFormat.java @@ -0,0 +1,78 @@ +package net.irisshaders.iris.gl.texture; + +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL30C; +import org.lwjgl.opengl.GL43C; + +import java.util.Objects; + +public enum DepthBufferFormat { + DEPTH(false), + DEPTH16(false), + DEPTH24(false), + DEPTH32(false), + DEPTH32F(false), + DEPTH_STENCIL(true), + DEPTH24_STENCIL8(true), + DEPTH32F_STENCIL8(true); + + private final boolean combinedStencil; + + DepthBufferFormat(boolean combinedStencil) { + this.combinedStencil = combinedStencil; + } + + @Nullable + public static DepthBufferFormat fromGlEnum(int glenum) { + return switch (glenum) { + case GL30C.GL_DEPTH_COMPONENT -> DepthBufferFormat.DEPTH; + case GL30C.GL_DEPTH_COMPONENT16 -> DepthBufferFormat.DEPTH16; + case GL30C.GL_DEPTH_COMPONENT24 -> DepthBufferFormat.DEPTH24; + case GL30C.GL_DEPTH_COMPONENT32 -> DepthBufferFormat.DEPTH32; + case GL30C.GL_DEPTH_COMPONENT32F -> DepthBufferFormat.DEPTH32F; + case GL30C.GL_DEPTH_STENCIL -> DepthBufferFormat.DEPTH_STENCIL; + case GL30C.GL_DEPTH24_STENCIL8 -> DepthBufferFormat.DEPTH24_STENCIL8; + case GL30C.GL_DEPTH32F_STENCIL8 -> DepthBufferFormat.DEPTH32F_STENCIL8; + default -> null; + }; + } + + public static DepthBufferFormat fromGlEnumOrDefault(int glenum) { + DepthBufferFormat format = fromGlEnum(glenum); + // yolo, just assume it's GL_DEPTH_COMPONENT + return Objects.requireNonNullElse(format, DepthBufferFormat.DEPTH); + } + + public int getGlInternalFormat() { + return switch (this) { + case DEPTH -> GL30C.GL_DEPTH_COMPONENT; + case DEPTH16 -> GL30C.GL_DEPTH_COMPONENT16; + case DEPTH24 -> GL30C.GL_DEPTH_COMPONENT24; + case DEPTH32 -> GL30C.GL_DEPTH_COMPONENT32; + case DEPTH32F -> GL30C.GL_DEPTH_COMPONENT32F; + case DEPTH_STENCIL -> GL30C.GL_DEPTH_STENCIL; + case DEPTH24_STENCIL8 -> GL30C.GL_DEPTH24_STENCIL8; + case DEPTH32F_STENCIL8 -> GL30C.GL_DEPTH32F_STENCIL8; + }; + + } + + public int getGlType() { + return isCombinedStencil() ? GL30C.GL_DEPTH_STENCIL : GL30C.GL_DEPTH_COMPONENT; + } + + public int getGlFormat() { + return switch (this) { + case DEPTH, DEPTH16 -> GL43C.GL_UNSIGNED_SHORT; + case DEPTH24, DEPTH32 -> GL43C.GL_UNSIGNED_INT; + case DEPTH32F -> GL30C.GL_FLOAT; + case DEPTH_STENCIL, DEPTH24_STENCIL8 -> GL30C.GL_UNSIGNED_INT_24_8; + case DEPTH32F_STENCIL8 -> GL30C.GL_FLOAT_32_UNSIGNED_INT_24_8_REV; + }; + + } + + public boolean isCombinedStencil() { + return combinedStencil; + } +} diff --git a/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java b/src/main/java/net/irisshaders/iris/gl/texture/DepthCopyStrategy.java similarity index 93% rename from src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java rename to src/main/java/net/irisshaders/iris/gl/texture/DepthCopyStrategy.java index bd88d8afb9..2c12bfb3b0 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/DepthCopyStrategy.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/DepthCopyStrategy.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; -import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; import org.lwjgl.opengl.GL; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; @@ -12,6 +11,36 @@ import org.lwjgl.system.MemoryUtil; public interface DepthCopyStrategy { + static DepthCopyStrategy fastest(boolean combinedStencilRequired) { + // Check whether glCopyImageSubData is available by checking the function directly... + // Gl.getCapabilities().OpenGL43 can be false even if OpenGL 4.3 functions are supported, + // because Minecraft requests an OpenGL 3.2 forward compatible function. + // + // Perhaps calling GL43.isAvailable would be a different option, but we only need one + // function, so we just check for that function. + if (GL.getCapabilities().glCopyImageSubData != MemoryUtil.NULL) { + return new Gl43CopyImage(); + } + + if (combinedStencilRequired) { + return new Gl30BlitFbCombinedDepthStencil(); + } else { + return new Gl20CopyTexture(); + } + } + + boolean needsDestFramebuffer(); + + /** + * Executes the copy. May or may not clobber GL_READ_FRAMEBUFFER and GL_DRAW_FRAMEBUFFER bindings - the caller is + * responsible for ensuring that they are restored to sensible values, or that the previous values are not relied + * on. The callee is responsible for ensuring that texture bindings are not modified. + * + * @param destFb The destination framebuffer. If {@link #needsDestFramebuffer()} returns false, then this param + * will not be used, and it can be null. + */ + void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height); + // FB -> T class Gl20CopyTexture implements DepthCopyStrategy { private Gl20CopyTexture() { @@ -101,34 +130,4 @@ public void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb ); } } - - static DepthCopyStrategy fastest(boolean combinedStencilRequired) { - // Check whether glCopyImageSubData is available by checking the function directly... - // Gl.getCapabilities().OpenGL43 can be false even if OpenGL 4.3 functions are supported, - // because Minecraft requests an OpenGL 3.2 forward compatible function. - // - // Perhaps calling GL43.isAvailable would be a different option, but we only need one - // function, so we just check for that function. - if (GL.getCapabilities().glCopyImageSubData != MemoryUtil.NULL) { - return new Gl43CopyImage(); - } - - if (combinedStencilRequired) { - return new Gl30BlitFbCombinedDepthStencil(); - } else { - return new Gl20CopyTexture(); - } - } - - boolean needsDestFramebuffer(); - - /** - * Executes the copy. May or may not clobber GL_READ_FRAMEBUFFER and GL_DRAW_FRAMEBUFFER bindings - the caller is - * responsible for ensuring that they are restored to sensible values, or that the previous values are not relied - * on. The callee is responsible for ensuring that texture bindings are not modified. - * - * @param destFb The destination framebuffer. If {@link #needsDestFramebuffer()} returns false, then this param - * will not be used, and it can be null. - */ - void copy(GlFramebuffer sourceFb, int sourceTexture, GlFramebuffer destFb, int destTexture, int width, int height); } diff --git a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java b/src/main/java/net/irisshaders/iris/gl/texture/GlTexture.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/texture/GlTexture.java rename to src/main/java/net/irisshaders/iris/gl/texture/GlTexture.java index 68f7f922a4..285d30e2b8 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/GlTexture.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/GlTexture.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.shaderpack.texture.TextureFilteringData; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.shaderpack.texture.TextureFilteringData; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL20C; @@ -45,7 +44,7 @@ public GlTexture(TextureType target, int sizeX, int sizeY, int sizeZ, int intern IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LEVEL, 0); IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MIN_LOD, 0); - IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LOD,0); + IrisRenderSystem.texParameteri(texture, target.getGlType(), GL20C.GL_TEXTURE_MAX_LOD, 0); IrisRenderSystem.texParameterf(texture, target.getGlType(), GL20C.GL_TEXTURE_LOD_BIAS, 0.0F); IrisRenderSystem.bindTextureForSetup(target.getGlType(), 0); diff --git a/src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java b/src/main/java/net/irisshaders/iris/gl/texture/InternalTextureFormat.java similarity index 96% rename from src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java rename to src/main/java/net/irisshaders/iris/gl/texture/InternalTextureFormat.java index f22d59bf6b..2a4b7462b8 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/InternalTextureFormat.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/InternalTextureFormat.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; -import net.coderbot.iris.gl.GlVersion; +import net.irisshaders.iris.gl.GlVersion; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL31C; @@ -101,7 +101,9 @@ public int getGlFormat() { return glFormat; } - public PixelFormat getPixelFormat() { return expectedPixelFormat; } + public PixelFormat getPixelFormat() { + return expectedPixelFormat; + } public GlVersion getMinimumGlVersion() { return minimumGlVersion; diff --git a/src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java b/src/main/java/net/irisshaders/iris/gl/texture/PixelFormat.java similarity index 94% rename from src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java rename to src/main/java/net/irisshaders/iris/gl/texture/PixelFormat.java index 6966917304..b3116715b2 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/PixelFormat.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/PixelFormat.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; -import net.coderbot.iris.gl.GlVersion; +import net.irisshaders.iris.gl.GlVersion; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL12C; import org.lwjgl.opengl.GL30C; diff --git a/src/main/java/net/coderbot/iris/gl/texture/PixelType.java b/src/main/java/net/irisshaders/iris/gl/texture/PixelType.java similarity index 96% rename from src/main/java/net/coderbot/iris/gl/texture/PixelType.java rename to src/main/java/net/irisshaders/iris/gl/texture/PixelType.java index f0c2e09254..440cbd9f9c 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/PixelType.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/PixelType.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; -import net.coderbot.iris.gl.GlVersion; +import net.irisshaders.iris.gl.GlVersion; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL12C; import org.lwjgl.opengl.GL30C; diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureAccess.java similarity index 75% rename from src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureAccess.java index 807edc727e..18a5ef9a92 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureAccess.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureAccess.java @@ -1,8 +1,9 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; import java.util.function.IntSupplier; public interface TextureAccess { TextureType getType(); + IntSupplier getTextureId(); } diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureDefinition.java similarity index 97% rename from src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureDefinition.java index e82f9e8407..b548dbd02a 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureDefinition.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureDefinition.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; public class TextureDefinition { protected String name; diff --git a/src/main/java/net/irisshaders/iris/gl/texture/TexturePair.java b/src/main/java/net/irisshaders/iris/gl/texture/TexturePair.java new file mode 100644 index 0000000000..1cf550aa37 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gl/texture/TexturePair.java @@ -0,0 +1,8 @@ +package net.irisshaders.iris.gl.texture; + +import java.util.function.IntSupplier; + +public record TexturePair(TextureType type, IntSupplier id) { + + +} diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureScaleOverride.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureScaleOverride.java similarity index 95% rename from src/main/java/net/coderbot/iris/gl/texture/TextureScaleOverride.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureScaleOverride.java index e978ba1b56..df1e696d14 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureScaleOverride.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureScaleOverride.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; public class TextureScaleOverride { + public final boolean isXRelative, isYRelative; public float relativeX, relativeY; public int sizeX, sizeY; - public final boolean isXRelative, isYRelative; public TextureScaleOverride(String xValue, String yValue) { if (xValue.contains(".")) { diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureType.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureType.java similarity index 93% rename from src/main/java/net/coderbot/iris/gl/texture/TextureType.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureType.java index 35d26c978e..7da9752f24 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureType.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureType.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.lwjgl.opengl.GL30C; import java.nio.ByteBuffer; @@ -18,6 +18,14 @@ public enum TextureType { this.glType = glType; } + public static Optional fromString(String name) { + try { + return Optional.of(TextureType.valueOf(name)); + } catch (IllegalArgumentException e) { + return Optional.empty(); + } + } + public int getGlType() { return glType; } @@ -35,12 +43,4 @@ public void apply(int texture, int sizeX, int sizeY, int sizeZ, int internalForm break; } } - - public static Optional fromString(String name) { - try { - return Optional.of(TextureType.valueOf(name)); - } catch (IllegalArgumentException e) { - return Optional.empty(); - } - } } diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureUploadHelper.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureUploadHelper.java similarity index 95% rename from src/main/java/net/coderbot/iris/gl/texture/TextureUploadHelper.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureUploadHelper.java index 7f19b2a578..0867a58b4a 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureUploadHelper.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureUploadHelper.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; import com.mojang.blaze3d.platform.GlStateManager; import org.lwjgl.opengl.GL20C; diff --git a/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java b/src/main/java/net/irisshaders/iris/gl/texture/TextureWrapper.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java rename to src/main/java/net/irisshaders/iris/gl/texture/TextureWrapper.java index 3621cf8dc8..b9e9597686 100644 --- a/src/main/java/net/coderbot/iris/gl/texture/TextureWrapper.java +++ b/src/main/java/net/irisshaders/iris/gl/texture/TextureWrapper.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.texture; +package net.irisshaders.iris.gl.texture; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/BooleanUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/BooleanUniform.java similarity index 83% rename from src/main/java/net/coderbot/iris/gl/uniform/BooleanUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/BooleanUniform.java index 340575a692..3af402eea9 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/BooleanUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/BooleanUniform.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import java.util.function.BooleanSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java b/src/main/java/net/irisshaders/iris/gl/uniform/DynamicLocationalUniformHolder.java similarity index 97% rename from src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java rename to src/main/java/net/irisshaders/iris/gl/uniform/DynamicLocationalUniformHolder.java index a37bf11d25..604ee4986b 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/DynamicLocationalUniformHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/DynamicLocationalUniformHolder.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Matrix4f; import org.joml.Vector2f; import org.joml.Vector2i; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/DynamicUniformHolder.java b/src/main/java/net/irisshaders/iris/gl/uniform/DynamicUniformHolder.java similarity index 92% rename from src/main/java/net/coderbot/iris/gl/uniform/DynamicUniformHolder.java rename to src/main/java/net/irisshaders/iris/gl/uniform/DynamicUniformHolder.java index b550668d00..6d68dff424 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/DynamicUniformHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/DynamicUniformHolder.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Matrix4f; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector2f; import org.joml.Vector2i; import org.joml.Vector3f; @@ -14,15 +14,25 @@ public interface DynamicUniformHolder extends UniformHolder { DynamicUniformHolder uniform1f(String name, FloatSupplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform1f(String name, IntSupplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform1f(String name, DoubleSupplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform1i(String name, IntSupplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform2f(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform2i(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform3f(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform4f(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform4fArray(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniform4i(String name, Supplier value, ValueUpdateNotifier notifier); + DynamicUniformHolder uniformMatrix(String name, Supplier value, ValueUpdateNotifier notifier); } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/FloatSupplier.java b/src/main/java/net/irisshaders/iris/gl/uniform/FloatSupplier.java similarity index 65% rename from src/main/java/net/coderbot/iris/gl/uniform/FloatSupplier.java rename to src/main/java/net/irisshaders/iris/gl/uniform/FloatSupplier.java index 9a8ccd4f80..3872cbd230 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/FloatSupplier.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/FloatSupplier.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; @FunctionalInterface public interface FloatSupplier { diff --git a/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/FloatUniform.java similarity index 82% rename from src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/FloatUniform.java index 4de68e7105..95bded1dc2 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/FloatUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/FloatUniform.java @@ -1,11 +1,11 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; public class FloatUniform extends Uniform { - private float cachedValue; private final FloatSupplier value; + private float cachedValue; FloatUniform(int location, FloatSupplier value) { this(location, value, null); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/IntUniform.java similarity index 88% rename from src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/IntUniform.java index 643210c573..cf0a71fa1f 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/IntUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/IntUniform.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import java.util.function.IntSupplier; public class IntUniform extends Uniform { - private int cachedValue; private final IntSupplier value; + private int cachedValue; IntUniform(int location, IntSupplier value) { this(location, value, null); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java b/src/main/java/net/irisshaders/iris/gl/uniform/LocationalUniformHolder.java similarity index 99% rename from src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java rename to src/main/java/net/irisshaders/iris/gl/uniform/LocationalUniformHolder.java index 3d9777a01c..1fa87a7ad1 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/LocationalUniformHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/LocationalUniformHolder.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import org.joml.Matrix4f; import org.joml.Vector2f; import org.joml.Vector2i; import org.joml.Vector3d; import org.joml.Vector3f; -import org.joml.Vector4f; import org.joml.Vector3i; +import org.joml.Vector4f; import java.util.OptionalInt; import java.util.function.BooleanSupplier; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/MatrixFromFloatArrayUniform.java similarity index 95% rename from src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/MatrixFromFloatArrayUniform.java index ddf6f1691c..e1be4a4d1f 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/MatrixFromFloatArrayUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/MatrixFromFloatArrayUniform.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import com.mojang.blaze3d.systems.RenderSystem; import org.lwjgl.BufferUtils; @@ -9,8 +9,8 @@ public class MatrixFromFloatArrayUniform extends Uniform { private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); - private float[] cachedValue; private final Supplier value; + private float[] cachedValue; MatrixFromFloatArrayUniform(int location, Supplier value) { super(location); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/MatrixUniform.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/MatrixUniform.java index 381b5d6f17..cbdb2bb56e 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/MatrixUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/MatrixUniform.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import com.mojang.blaze3d.systems.RenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Matrix4f; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; import org.lwjgl.BufferUtils; import java.nio.FloatBuffer; @@ -10,8 +10,8 @@ public class MatrixUniform extends Uniform { private final FloatBuffer buffer = BufferUtils.createFloatBuffer(16); - private Matrix4f cachedValue; private final Supplier value; + private Matrix4f cachedValue; MatrixUniform(int location, Supplier value) { super(location); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Uniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Uniform.java similarity index 81% rename from src/main/java/net/coderbot/iris/gl/uniform/Uniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Uniform.java index 520b278907..20c9a7f719 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Uniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Uniform.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; public abstract class Uniform { protected final int location; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java b/src/main/java/net/irisshaders/iris/gl/uniform/UniformHolder.java similarity index 97% rename from src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java rename to src/main/java/net/irisshaders/iris/gl/uniform/UniformHolder.java index 4e276fe50f..bdf8ce2cac 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/UniformHolder.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/UniformHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; import org.joml.Matrix4f; import org.joml.Vector2f; @@ -29,6 +29,7 @@ public interface UniformHolder { UniformHolder uniform2i(UniformUpdateFrequency updateFrequency, String name, Supplier value); UniformHolder uniform3f(UniformUpdateFrequency updateFrequency, String name, Supplier value); + UniformHolder uniform3i(UniformUpdateFrequency updateFrequency, String name, Supplier value); UniformHolder uniformTruncated3f(UniformUpdateFrequency updateFrequency, String name, Supplier value); @@ -36,6 +37,7 @@ public interface UniformHolder { UniformHolder uniform3d(UniformUpdateFrequency updateFrequency, String name, Supplier value); UniformHolder uniform4f(UniformUpdateFrequency updateFrequency, String name, Supplier value); + UniformHolder uniform4fArray(UniformUpdateFrequency updateFrequency, String name, Supplier value); UniformHolder uniformMatrix(UniformUpdateFrequency updateFrequency, String name, Supplier value); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformType.java b/src/main/java/net/irisshaders/iris/gl/uniform/UniformType.java similarity index 71% rename from src/main/java/net/coderbot/iris/gl/uniform/UniformType.java rename to src/main/java/net/irisshaders/iris/gl/uniform/UniformType.java index 47f9c73316..59d15cc403 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/UniformType.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/UniformType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; public enum UniformType { INT, diff --git a/src/main/java/net/coderbot/iris/gl/uniform/UniformUpdateFrequency.java b/src/main/java/net/irisshaders/iris/gl/uniform/UniformUpdateFrequency.java similarity index 65% rename from src/main/java/net/coderbot/iris/gl/uniform/UniformUpdateFrequency.java rename to src/main/java/net/irisshaders/iris/gl/uniform/UniformUpdateFrequency.java index e4d5838286..bd97a90596 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/UniformUpdateFrequency.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/UniformUpdateFrequency.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; public enum UniformUpdateFrequency { ONCE, diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector2IntegerJomlUniform.java similarity index 79% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector2IntegerJomlUniform.java index 785ef87d4e..8e3a912e69 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector2IntegerJomlUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector2IntegerJomlUniform.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector2i; import java.util.function.Supplier; public class Vector2IntegerJomlUniform extends Uniform { - private Vector2i cachedValue; private final Supplier value; + private Vector2i cachedValue; Vector2IntegerJomlUniform(int location, Supplier value) { this(location, value, null); @@ -33,7 +33,7 @@ public void update() { private void updateValue() { Vector2i newValue = value.get(); - if (cachedValue == null || !newValue.equals(cachedValue)) { + if (!newValue.equals(cachedValue)) { cachedValue = newValue; IrisRenderSystem.uniform2i(this.location, newValue.x, newValue.y); } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector2Uniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector2Uniform.java similarity index 79% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector2Uniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector2Uniform.java index 3aeda4fa3d..5eed001313 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector2Uniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector2Uniform.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector2f; import java.util.function.Supplier; public class Vector2Uniform extends Uniform { - private Vector2f cachedValue; private final Supplier value; + private Vector2f cachedValue; Vector2Uniform(int location, Supplier value) { super(location); @@ -37,7 +37,7 @@ public void update() { private void updateValue() { Vector2f newValue = value.get(); - if (cachedValue == null || !newValue.equals(cachedValue)) { + if (!newValue.equals(cachedValue)) { cachedValue = newValue; IrisRenderSystem.uniform2f(this.location, newValue.x, newValue.y); } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector3IntegerUniform.java similarity index 81% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector3IntegerUniform.java index 207c91d1b1..74ef83401b 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector3IntegerUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector3IntegerUniform.java @@ -1,11 +1,8 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import org.joml.Vector3d; -import org.joml.Vector3f; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector3i; -import org.joml.Vector4f; import java.util.function.Supplier; @@ -26,6 +23,7 @@ public class Vector3IntegerUniform extends Uniform { this.cachedValue = new Vector3i(); this.value = value; } + @Override public void update() { updateValue(); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector3Uniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector3Uniform.java similarity index 91% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector3Uniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector3Uniform.java index 243d75a2e5..a0a3a117f6 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector3Uniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector3Uniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector3d; import org.joml.Vector3f; import org.joml.Vector4f; diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4ArrayUniform.java similarity index 83% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector4ArrayUniform.java index 4448aaf1f8..73384882d3 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4ArrayUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4ArrayUniform.java @@ -1,15 +1,14 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import org.joml.Vector4f; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import java.util.Arrays; import java.util.function.Supplier; public class Vector4ArrayUniform extends Uniform { - private float[] cachedValue; private final Supplier value; + private float[] cachedValue; Vector4ArrayUniform(int location, Supplier value) { this(location, value, null); diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4IntegerJomlUniform.java similarity index 80% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector4IntegerJomlUniform.java index b373fa7664..77725d231b 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4IntegerJomlUniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4IntegerJomlUniform.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector4i; import java.util.function.Supplier; public class Vector4IntegerJomlUniform extends Uniform { - private Vector4i cachedValue; private final Supplier value; + private Vector4i cachedValue; Vector4IntegerJomlUniform(int location, Supplier value) { this(location, value, null); @@ -33,7 +33,7 @@ public void update() { private void updateValue() { Vector4i newValue = value.get(); - if (cachedValue == null || !newValue.equals(cachedValue)) { + if (!newValue.equals(cachedValue)) { cachedValue = newValue; IrisRenderSystem.uniform4i(this.location, newValue.x, newValue.y, newValue.z, newValue.w); } diff --git a/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4Uniform.java similarity index 85% rename from src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java rename to src/main/java/net/irisshaders/iris/gl/uniform/Vector4Uniform.java index 41a9d61f32..43b3b5bd39 100644 --- a/src/main/java/net/coderbot/iris/gl/uniform/Vector4Uniform.java +++ b/src/main/java/net/irisshaders/iris/gl/uniform/Vector4Uniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.gl.uniform; +package net.irisshaders.iris.gl.uniform; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector4f; import java.util.function.Supplier; diff --git a/src/main/java/net/coderbot/iris/gui/FeatureMissingErrorScreen.java b/src/main/java/net/irisshaders/iris/gui/FeatureMissingErrorScreen.java similarity index 91% rename from src/main/java/net/coderbot/iris/gui/FeatureMissingErrorScreen.java rename to src/main/java/net/irisshaders/iris/gui/FeatureMissingErrorScreen.java index a3e2861861..bfbef2699b 100644 --- a/src/main/java/net/coderbot/iris/gui/FeatureMissingErrorScreen.java +++ b/src/main/java/net/irisshaders/iris/gui/FeatureMissingErrorScreen.java @@ -1,10 +1,8 @@ -package net.coderbot.iris.gui; +package net.irisshaders.iris.gui; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.client.gui.screens.ErrorScreen; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; @@ -12,8 +10,8 @@ public class FeatureMissingErrorScreen extends Screen { private final Screen parent; - private MultiLineLabel message; private final FormattedText messageTemp; + private MultiLineLabel message; public FeatureMissingErrorScreen(Screen parent, Component title, Component message) { super(title); diff --git a/src/main/java/net/coderbot/iris/gui/FileDialogUtil.java b/src/main/java/net/irisshaders/iris/gui/FileDialogUtil.java similarity index 82% rename from src/main/java/net/coderbot/iris/gui/FileDialogUtil.java rename to src/main/java/net/irisshaders/iris/gui/FileDialogUtil.java index 11020e5786..201a1f257e 100644 --- a/src/main/java/net/coderbot/iris/gui/FileDialogUtil.java +++ b/src/main/java/net/irisshaders/iris/gui/FileDialogUtil.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.gui; +package net.irisshaders.iris.gui; import org.jetbrains.annotations.Nullable; import org.lwjgl.PointerBuffer; @@ -18,19 +18,20 @@ public final class FileDialogUtil { private static final ExecutorService FILE_DIALOG_EXECUTOR = Executors.newSingleThreadExecutor(); - private FileDialogUtil() {} + private FileDialogUtil() { + } /** * Opens an asynchronous file select dialog window. * - * @param dialog Whether to open a "save" dialog or an "open" dialog - * @param title The title of the dialog window - * @param origin The path that the window should start at + * @param dialog Whether to open a "save" dialog or an "open" dialog + * @param title The title of the dialog window + * @param origin The path that the window should start at * @param filterLabel A label used to describe what file extensions are allowed and their purpose - * @param filters The file extension filters used by the dialog, each formatted as {@code "*.extension"} + * @param filters The file extension filters used by the dialog, each formatted as {@code "*.extension"} * @return a {@link CompletableFuture} which is completed once a file is selected or the dialog is cancelled. */ - public static CompletableFuture> fileSelectDialog(DialogType dialog, String title, @Nullable Path origin, @Nullable String filterLabel, String ... filters) { + public static CompletableFuture> fileSelectDialog(DialogType dialog, String title, @Nullable Path origin, @Nullable String filterLabel, String... filters) { CompletableFuture> future = new CompletableFuture<>(); FILE_DIALOG_EXECUTOR.submit(() -> { diff --git a/src/main/java/net/coderbot/iris/gui/GuiUtil.java b/src/main/java/net/irisshaders/iris/gui/GuiUtil.java similarity index 87% rename from src/main/java/net/coderbot/iris/gui/GuiUtil.java rename to src/main/java/net/irisshaders/iris/gui/GuiUtil.java index 82ab0fb8e5..035f9b4c9b 100644 --- a/src/main/java/net/coderbot/iris/gui/GuiUtil.java +++ b/src/main/java/net/irisshaders/iris/gui/GuiUtil.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.gui; +package net.irisshaders.iris.gui; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; @@ -10,8 +9,6 @@ import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; - - import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; @@ -19,7 +16,7 @@ * Class serving as abstraction and * centralization for common GUI * rendering/other code calls. - * + *

    * Helps allow for easier portability * to Minecraft 1.17 by abstracting * some code that will be changed. @@ -28,7 +25,8 @@ public final class GuiUtil { public static final ResourceLocation IRIS_WIDGETS_TEX = new ResourceLocation("iris", "textures/gui/widgets.png"); private static final Component ELLIPSIS = Component.literal("..."); - private GuiUtil() {} + private GuiUtil() { + } private static Minecraft client() { return Minecraft.getInstance(); @@ -46,11 +44,11 @@ public static void bindIrisWidgetsTexture() { * Draws a button. Button textures must be mapped with the * same coordinates as those on the vanilla widgets texture. * - * @param x X position of the left of the button - * @param y Y position of the top of the button - * @param width Width of the button, maximum 398 - * @param height Height of the button, maximum 20 - * @param hovered Whether the button is being hovered over with the mouse + * @param x X position of the left of the button + * @param y Y position of the top of the button + * @param width Width of the button, maximum 398 + * @param height Height of the button, maximum 20 + * @param hovered Whether the button is being hovered over with the mouse * @param disabled Whether the button should use the "disabled" texture */ public static void drawButton(GuiGraphics guiGraphics, int x, int y, int width, int height, boolean hovered, boolean disabled) { @@ -80,9 +78,9 @@ public static void drawButton(GuiGraphics guiGraphics, int x, int y, int width, * Draws a translucent black panel * with a light border. * - * @param x The x position of the panel - * @param y The y position of the panel - * @param width The width of the panel + * @param x The x position of the panel + * @param y The y position of the panel + * @param width The width of the panel * @param height The height of the panel */ public static void drawPanel(GuiGraphics guiGraphics, int x, int y, int width, int height) { @@ -105,8 +103,8 @@ public static void drawPanel(GuiGraphics guiGraphics, int x, int y, int width, i * Draws a text with a panel behind it. * * @param text The text component to draw - * @param x The x position of the panel - * @param y The y position of the panel + * @param x The x position of the panel + * @param y The y position of the panel */ public static void drawTextPanel(Font font, GuiGraphics guiGraphics, Component text, int x, int y) { drawPanel(guiGraphics, x, y, font.width(text) + 8, 16); @@ -116,11 +114,11 @@ public static void drawTextPanel(Font font, GuiGraphics guiGraphics, Component t /** * Shorten a text to a specific length, adding an ellipsis (...) * to the end if shortened. - * + *

    * Text may lose formatting. * - * @param font Font to use for determining the width of text - * @param text Text to shorten + * @param font Font to use for determining the width of text + * @param text Text to shorten * @param width Width to shorten text to * @return a shortened text */ @@ -136,12 +134,12 @@ public static MutableComponent shortenText(Font font, MutableComponent text, int * is present. If not, will return the default text * component passed. * - * @param defaultText Default text to use if no translation is found + * @param defaultText Default text to use if no translation is found * @param translationDesc Translation key to try and use - * @param format Formatting arguments for the translated text, if created + * @param format Formatting arguments for the translated text, if created * @return the translated text if found, otherwise the default provided */ - public static MutableComponent translateOrDefault(MutableComponent defaultText, String translationDesc, Object ... format) { + public static MutableComponent translateOrDefault(MutableComponent defaultText, String translationDesc, Object... format) { if (I18n.exists(translationDesc)) { return Component.translatable(translationDesc, format); } @@ -151,7 +149,7 @@ public static MutableComponent translateOrDefault(MutableComponent defaultText, /** * Plays the {@code UI_BUTTON_CLICK} sound event as a * master sound effect. - * + *

    * Used in non-{@code ButtonWidget} UI elements upon click * or other action. */ diff --git a/src/main/java/net/coderbot/iris/gui/NavigationController.java b/src/main/java/net/irisshaders/iris/gui/NavigationController.java similarity index 80% rename from src/main/java/net/coderbot/iris/gui/NavigationController.java rename to src/main/java/net/irisshaders/iris/gui/NavigationController.java index 0c7aa8481f..79076c3f4e 100644 --- a/src/main/java/net/coderbot/iris/gui/NavigationController.java +++ b/src/main/java/net/irisshaders/iris/gui/NavigationController.java @@ -1,27 +1,26 @@ -package net.coderbot.iris.gui; +package net.irisshaders.iris.gui; -import net.coderbot.iris.gui.element.ShaderPackOptionList; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuContainer; +import net.irisshaders.iris.gui.element.ShaderPackOptionList; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer; import java.util.ArrayDeque; import java.util.Deque; public class NavigationController { private final OptionMenuContainer container; + private final Deque history = new ArrayDeque<>(); private ShaderPackOptionList optionList; - private String currentScreen = null; - private final Deque history = new ArrayDeque<>(); public NavigationController(OptionMenuContainer container) { this.container = container; } public void back() { - if (history.size() > 0) { + if (!history.isEmpty()) { history.removeLast(); - if (history.size() > 0) { + if (!history.isEmpty()) { currentScreen = history.getLast(); } else { currentScreen = null; @@ -53,7 +52,7 @@ public void refresh() { } public boolean hasHistory() { - return this.history.size() > 0; + return !this.history.isEmpty(); } public void setActiveOptionList(ShaderPackOptionList optionList) { diff --git a/src/main/java/net/coderbot/iris/gui/OldImageButton.java b/src/main/java/net/irisshaders/iris/gui/OldImageButton.java similarity index 80% rename from src/main/java/net/coderbot/iris/gui/OldImageButton.java rename to src/main/java/net/irisshaders/iris/gui/OldImageButton.java index 77207abc44..923d8bf7be 100644 --- a/src/main/java/net/coderbot/iris/gui/OldImageButton.java +++ b/src/main/java/net/irisshaders/iris/gui/OldImageButton.java @@ -1,5 +1,6 @@ -package net.coderbot.iris.gui; +package net.irisshaders.iris.gui; +import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.network.chat.CommonComponents; @@ -92,4 +93,28 @@ public void renderWidget(GuiGraphics pImageButton0, int pInt1, int pInt2, float this.textureHeight ); } + + public void renderTexture( + GuiGraphics pAbstractWidget0, + ResourceLocation pResourceLocation1, + int pInt2, + int pInt3, + int pInt4, + int pInt5, + int pInt6, + int pInt7, + int pInt8, + int pInt9, + int pInt10 + ) { + int lvInt12 = pInt5; + if (!this.isActive()) { + lvInt12 = pInt5 + pInt6 * 2; + } else if (this.isHoveredOrFocused()) { + lvInt12 = pInt5 + pInt6; + } + + RenderSystem.enableDepthTest(); + pAbstractWidget0.blit(pResourceLocation1, pInt2, pInt3, (float) pInt4, (float) lvInt12, pInt7, pInt8, pInt9, pInt10); + } } diff --git a/src/main/java/net/coderbot/iris/gui/debug/DebugLoadFailedGridScreen.java b/src/main/java/net/irisshaders/iris/gui/debug/DebugLoadFailedGridScreen.java similarity index 83% rename from src/main/java/net/coderbot/iris/gui/debug/DebugLoadFailedGridScreen.java rename to src/main/java/net/irisshaders/iris/gui/debug/DebugLoadFailedGridScreen.java index 112e8a077e..a46a36fb9b 100644 --- a/src/main/java/net/coderbot/iris/gui/debug/DebugLoadFailedGridScreen.java +++ b/src/main/java/net/irisshaders/iris/gui/debug/DebugLoadFailedGridScreen.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.gui.debug; +package net.irisshaders.iris.gui.debug; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.layouts.FrameLayout; import net.minecraft.client.gui.layouts.GridLayout; @@ -33,9 +32,7 @@ protected void init() { LayoutSettings layoutSettings3 = widget.newCellSettings().alignVerticallyTop().paddingTop(30).alignHorizontallyRight(); int numWidgets = 0; widget.addChild(new DebugTextWidget(0, 0, this.width - 80, font.lineHeight * 15, font, exception), ++numWidgets, 0, 1, 2, layoutSettings); - widget.addChild(Button.builder(Component.translatable("menu.returnToGame"), arg2 -> { - this.minecraft.setScreen(parent); - }).width(100).build(), ++numWidgets, 0, 1, 2, layoutSettings2); + widget.addChild(Button.builder(Component.translatable("menu.returnToGame"), arg2 -> this.minecraft.setScreen(parent)).width(100).build(), ++numWidgets, 0, 1, 2, layoutSettings2); widget.addChild(Button.builder(Component.literal("Reload pack"), arg2 -> { Minecraft.getInstance().setScreen(parent); try { @@ -45,9 +42,7 @@ protected void init() { } }).width(100).build(), numWidgets, 0, 1, 2, layoutSettings3); - widget.addChild(Button.builder(Component.literal("Copy error"), arg2 -> { - this.minecraft.keyboardHandler.setClipboard(ExceptionUtils.getStackTrace(exception)); - }).width(100).build(), numWidgets, 0, 1, 2, layoutSettings4); + widget.addChild(Button.builder(Component.literal("Copy error"), arg2 -> this.minecraft.keyboardHandler.setClipboard(ExceptionUtils.getStackTrace(exception))).width(100).build(), numWidgets, 0, 1, 2, layoutSettings4); widget.arrangeElements(); FrameLayout.centerInRectangle(widget, 0, 0, this.width, this.height); diff --git a/src/main/java/net/coderbot/iris/gui/debug/DebugTextWidget.java b/src/main/java/net/irisshaders/iris/gui/debug/DebugTextWidget.java similarity index 95% rename from src/main/java/net/coderbot/iris/gui/debug/DebugTextWidget.java rename to src/main/java/net/irisshaders/iris/gui/debug/DebugTextWidget.java index a407674dcd..efc61d1bc9 100644 --- a/src/main/java/net/coderbot/iris/gui/debug/DebugTextWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/debug/DebugTextWidget.java @@ -1,8 +1,6 @@ -package net.coderbot.iris.gui.debug; +package net.irisshaders.iris.gui.debug; -import com.mojang.blaze3d.vertex.PoseStack; - -import net.coderbot.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractScrollWidget; @@ -18,7 +16,7 @@ public class DebugTextWidget extends AbstractScrollWidget { private final Font font; - private Content content; + private final Content content; public DebugTextWidget(int i, int j, int k, int l, Font arg, Exception exception) { super(i, j, k, l, Component.empty()); @@ -44,7 +42,7 @@ private Content buildContent(Exception exception) { for (int i = 0; i < elements.length; ++i) { StackTraceElement element = elements[i]; - if (element == null) continue;; + if (element == null) continue; lv.addLine(font, Component.literal(element.toString())); if (i >= elements.length - 1) continue; lv.addSpacer(this.font.lineHeight); diff --git a/src/main/java/net/coderbot/iris/gui/element/IrisContainerObjectSelectionList.java b/src/main/java/net/irisshaders/iris/gui/element/IrisContainerObjectSelectionList.java similarity index 77% rename from src/main/java/net/coderbot/iris/gui/element/IrisContainerObjectSelectionList.java rename to src/main/java/net/irisshaders/iris/gui/element/IrisContainerObjectSelectionList.java index ec1a70589d..9382b99a6d 100644 --- a/src/main/java/net/coderbot/iris/gui/element/IrisContainerObjectSelectionList.java +++ b/src/main/java/net/irisshaders/iris/gui/element/IrisContainerObjectSelectionList.java @@ -1,10 +1,7 @@ -package net.coderbot.iris.gui.element; +package net.irisshaders.iris.gui.element; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.AbstractSelectionList; import net.minecraft.client.gui.components.ContainerObjectSelectionList; -import net.minecraft.client.gui.components.ObjectSelectionList; -import net.minecraft.client.gui.narration.NarrationElementOutput; public class IrisContainerObjectSelectionList> extends ContainerObjectSelectionList { public IrisContainerObjectSelectionList(Minecraft client, int width, int height, int top, int bottom, int left, int right, int itemHeight) { diff --git a/src/main/java/net/coderbot/iris/gui/element/IrisElementRow.java b/src/main/java/net/irisshaders/iris/gui/element/IrisElementRow.java similarity index 90% rename from src/main/java/net/coderbot/iris/gui/element/IrisElementRow.java rename to src/main/java/net/irisshaders/iris/gui/element/IrisElementRow.java index d5b58a8123..8be9827782 100644 --- a/src/main/java/net/coderbot/iris/gui/element/IrisElementRow.java +++ b/src/main/java/net/irisshaders/iris/gui/element/IrisElementRow.java @@ -1,17 +1,14 @@ -package net.coderbot.iris.gui.element; +package net.irisshaders.iris.gui.element; import com.google.common.collect.ImmutableList; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.GuiUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; -import net.minecraft.client.gui.components.events.ContainerEventHandler; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.client.gui.navigation.ScreenRectangle; -import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -48,7 +45,7 @@ public IrisElementRow() { * Adds an element to the right of this row. * * @param element The element to add - * @param width The width of the element in this row + * @param width The width of the element in this row * @return {@code this}, to be used for chaining statements */ public IrisElementRow add(Element element, int width) { @@ -66,7 +63,7 @@ public IrisElementRow add(Element element, int width) { * Modifies the width of an element. * * @param element The element whose width to modify - * @param width The width to be assigned to the specified element + * @param width The width to be assigned to the specified element */ public void setWidth(Element element, int width) { if (!this.elements.containsKey(element)) { @@ -92,7 +89,7 @@ public void render(GuiGraphics guiGraphics, int x, int y, int height, int mouseX int currentWidth = this.elements.get(element); element.render(guiGraphics, currentX, y, currentWidth, height, mouseX, mouseY, tickDelta, - rowHovered && sectionHovered(currentX, currentWidth, mouseX, mouseY)); + rowHovered && sectionHovered(currentX, currentWidth, mouseX, mouseY)); currentX += currentWidth + this.spacing; } @@ -107,7 +104,7 @@ public void renderRightAligned(GuiGraphics guiGraphics, int x, int y, int height private boolean sectionHovered(int sectionX, int sectionWidth, double mx, double my) { return mx > sectionX && mx < sectionX + sectionWidth && - my > this.y && my < this.y + this.height; + my > this.y && my < this.y + this.height; } private Optional getHovered(double mx, double my) { @@ -220,7 +217,7 @@ public boolean keyPressed(int keycode, int scancode, int modifiers) { } /** - * A clickable button element that uses a {@link net.coderbot.iris.gui.GuiUtil.Icon} as its label. + * A clickable button element that uses a {@link net.irisshaders.iris.gui.GuiUtil.Icon} as its label. */ public static class IconButtonElement extends ButtonElement { public GuiUtil.Icon icon; @@ -238,8 +235,8 @@ public IconButtonElement(GuiUtil.Icon icon, Function @Override public void renderLabel(GuiGraphics guiGraphics, int x, int y, int width, int height, int mouseX, int mouseY, float tickDelta, boolean hovered) { - int iconX = x + (int)((width - this.icon.getWidth()) * 0.5); - int iconY = y + (int)((height - this.icon.getHeight()) * 0.5); + int iconX = x + (int) ((width - this.icon.getWidth()) * 0.5); + int iconY = y + (int) ((height - this.icon.getHeight()) * 0.5); GuiUtil.bindIrisWidgetsTexture(); if (!this.disabled && (hovered || isFocused())) { @@ -266,8 +263,8 @@ public TextButtonElement(Component text, Function on @Override public void renderLabel(GuiGraphics guiGraphics, int x, int y, int width, int height, int mouseX, int mouseY, float tickDelta, boolean hovered) { - int textX = x + (int)((width - this.font.width(this.text)) * 0.5); - int textY = y + (int)((height - 8) * 0.5); + int textX = x + (int) ((width - this.font.width(this.text)) * 0.5); + int textY = y + (int) ((height - 8) * 0.5); guiGraphics.drawString(this.font, this.text, textX, textY, 0xFFFFFF); } diff --git a/src/main/java/net/coderbot/iris/gui/element/IrisObjectSelectionList.java b/src/main/java/net/irisshaders/iris/gui/element/IrisObjectSelectionList.java similarity index 83% rename from src/main/java/net/coderbot/iris/gui/element/IrisObjectSelectionList.java rename to src/main/java/net/irisshaders/iris/gui/element/IrisObjectSelectionList.java index 91f48c415d..a6a1ab63b7 100644 --- a/src/main/java/net/coderbot/iris/gui/element/IrisObjectSelectionList.java +++ b/src/main/java/net/irisshaders/iris/gui/element/IrisObjectSelectionList.java @@ -1,9 +1,7 @@ -package net.coderbot.iris.gui.element; +package net.irisshaders.iris.gui.element; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.AbstractSelectionList; -import net.minecraft.client.gui.components.ContainerObjectSelectionList; -import net.minecraft.client.gui.components.ObjectSelectionList; import net.minecraft.client.gui.narration.NarrationElementOutput; public class IrisObjectSelectionList> extends AbstractSelectionList { diff --git a/src/main/java/net/coderbot/iris/gui/element/ShaderPackOptionList.java b/src/main/java/net/irisshaders/iris/gui/element/ShaderPackOptionList.java similarity index 81% rename from src/main/java/net/coderbot/iris/gui/element/ShaderPackOptionList.java rename to src/main/java/net/irisshaders/iris/gui/element/ShaderPackOptionList.java index 3fbbbe2cc3..f939b390a6 100644 --- a/src/main/java/net/coderbot/iris/gui/element/ShaderPackOptionList.java +++ b/src/main/java/net/irisshaders/iris/gui/element/ShaderPackOptionList.java @@ -1,23 +1,21 @@ -package net.coderbot.iris.gui.element; +package net.irisshaders.iris.gui.element; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.FileDialogUtil; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.element.widget.AbstractElementWidget; -import net.coderbot.iris.gui.element.widget.OptionMenuConstructor; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.ShaderPack; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuContainer; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.FileDialogUtil; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.element.widget.AbstractElementWidget; +import net.irisshaders.iris.gui.element.widget.OptionMenuConstructor; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.ContainerObjectSelectionList; -import net.minecraft.client.gui.components.ObjectSelectionList; import net.minecraft.client.gui.components.events.GuiEventListener; import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.navigation.ScreenDirection; @@ -89,7 +87,7 @@ public void addWidgets(int columns, List> elements) { } } - if (row.size() > 0) { + if (!row.isEmpty()) { while (row.size() < columns) { row.add(AbstractElementWidget.EMPTY); } @@ -118,9 +116,9 @@ public static class HeaderEntry extends BaseEntry { public static final MutableComponent RESET_HOLD_SHIFT_TOOLTIP = Component.translatable("options.iris.reset.tooltip.holdShift").withStyle(ChatFormatting.GOLD); public static final MutableComponent RESET_TOOLTIP = Component.translatable("options.iris.reset.tooltip").withStyle(ChatFormatting.RED); public static final MutableComponent IMPORT_TOOLTIP = Component.translatable("options.iris.importSettings.tooltip") - .withStyle(style -> style.withColor(TextColor.fromRgb(0x4da6ff))); + .withStyle(style -> style.withColor(TextColor.fromRgb(0x4da6ff))); public static final MutableComponent EXPORT_TOOLTIP = Component.translatable("options.iris.exportSettings.tooltip") - .withStyle(style -> style.withColor(TextColor.fromRgb(0xfc7d3d))); + .withStyle(style -> style.withColor(TextColor.fromRgb(0xfc7d3d))); private static final int MIN_SIDE_BUTTON_WIDTH = 42; private static final int BUTTON_HEIGHT = 16; @@ -138,24 +136,24 @@ public HeaderEntry(ShaderPackScreen screen, NavigationController navigation, Com if (hasBackButton) { this.backButton = new IrisElementRow().add( - new IrisElementRow.TextButtonElement(BACK_BUTTON_TEXT, this::backButtonClicked), - Math.max(MIN_SIDE_BUTTON_WIDTH, Minecraft.getInstance().font.width(BACK_BUTTON_TEXT) + 8) + new IrisElementRow.TextButtonElement(BACK_BUTTON_TEXT, this::backButtonClicked), + Math.max(MIN_SIDE_BUTTON_WIDTH, Minecraft.getInstance().font.width(BACK_BUTTON_TEXT) + 8) ); } else { this.backButton = null; } this.resetButton = new IrisElementRow.TextButtonElement( - RESET_BUTTON_TEXT_INACTIVE, this::resetButtonClicked); + RESET_BUTTON_TEXT_INACTIVE, this::resetButtonClicked); this.importButton = new IrisElementRow.IconButtonElement( - GuiUtil.Icon.IMPORT, GuiUtil.Icon.IMPORT_COLORED, this::importSettingsButtonClicked); + GuiUtil.Icon.IMPORT, GuiUtil.Icon.IMPORT_COLORED, this::importSettingsButtonClicked); this.exportButton = new IrisElementRow.IconButtonElement( - GuiUtil.Icon.EXPORT, GuiUtil.Icon.EXPORT_COLORED, this::exportSettingsButtonClicked); + GuiUtil.Icon.EXPORT, GuiUtil.Icon.EXPORT_COLORED, this::exportSettingsButtonClicked); this.utilityButtons - .add(this.importButton, 15) - .add(this.exportButton, 15) - .add(this.resetButton, Math.max(MIN_SIDE_BUTTON_WIDTH, Minecraft.getInstance().font.width(RESET_BUTTON_TEXT_INACTIVE) + 8)); + .add(this.importButton, 15) + .add(this.exportButton, 15) + .add(this.resetButton, Math.max(MIN_SIDE_BUTTON_WIDTH, Minecraft.getInstance().font.width(RESET_BUTTON_TEXT_INACTIVE) + 8)); this.screen = screen; this.text = text; @@ -169,7 +167,7 @@ public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWi Font font = Minecraft.getInstance().font; // Draw header text - guiGraphics.drawCenteredString(font, text, x + (int)(entryWidth * 0.5), y + 5, 0xFFFFFF); + guiGraphics.drawCenteredString(font, text, x + (int) (entryWidth * 0.5), y + 5, 0xFFFFFF); GuiUtil.bindIrisWidgetsTexture(); @@ -203,8 +201,8 @@ public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWi private void queueBottomRightAnchoredTooltip(GuiGraphics guiGraphics, int x, int y, Font font, Component text) { ShaderPackScreen.TOP_LAYER_RENDER_QUEUE.add(() -> GuiUtil.drawTextPanel( - font, guiGraphics, text, - x - (font.width(text) + 10), y - 16 + font, guiGraphics, text, + x - (font.width(text) + 10), y - 16 )); } @@ -278,18 +276,18 @@ private boolean importSettingsButtonClicked(IrisElementRow.IconButtonElement but FileDialogUtil.fileSelectDialog( FileDialogUtil.DialogType.OPEN, "Import Shader Settings from File", Iris.getShaderpacksDirectory().resolve(Iris.getCurrentPackName() + ".txt"), - "Shader Pack Settings (.txt)", "*.txt") - .whenComplete((path, err) -> { - if (err != null) { - Iris.logger.error("Error selecting shader settings from file", err); + "Shader Pack Settings (.txt)", "*.txt") + .whenComplete((path, err) -> { + if (err != null) { + Iris.logger.error("Error selecting shader settings from file", err); - return; - } + return; + } - if (Minecraft.getInstance().screen == originalScreen) { - path.ifPresent(originalScreen::importPackOptions); - } - }); + if (Minecraft.getInstance().screen == originalScreen) { + path.ifPresent(originalScreen::importPackOptions); + } + }); return true; } @@ -315,33 +313,34 @@ private boolean exportSettingsButtonClicked(IrisElementRow.IconButtonElement but FileDialogUtil.DialogType.SAVE, "Export Shader Settings to File", Iris.getShaderpacksDirectory().resolve(Iris.getCurrentPackName() + ".txt"), "Shader Pack Settings (.txt)", "*.txt") - .whenComplete((path, err) -> { - if (err != null) { - Iris.logger.error("Error selecting file to export shader settings", err); - - return; - } - - path.ifPresent(p -> { - Properties toSave = new Properties(); - - // Dirty way of getting the currently applied settings as a Properties, directly - // opens and copies out of the saved settings file if it is present - Path sourceTxtPath = Iris.getShaderpacksDirectory().resolve(Iris.getCurrentPackName() + ".txt"); - if (Files.exists(sourceTxtPath)) { - try (InputStream in = Files.newInputStream(sourceTxtPath)) { - toSave.load(in); - } catch (IOException ignored) {} - } + .whenComplete((path, err) -> { + if (err != null) { + Iris.logger.error("Error selecting file to export shader settings", err); - // Save properties to user determined file - try (OutputStream out = Files.newOutputStream(p)) { - toSave.store(out, null); - } catch (IOException e) { - Iris.logger.error("Error saving properties to \"" + p + "\"", e); + return; } + + path.ifPresent(p -> { + Properties toSave = new Properties(); + + // Dirty way of getting the currently applied settings as a Properties, directly + // opens and copies out of the saved settings file if it is present + Path sourceTxtPath = Iris.getShaderpacksDirectory().resolve(Iris.getCurrentPackName() + ".txt"); + if (Files.exists(sourceTxtPath)) { + try (InputStream in = Files.newInputStream(sourceTxtPath)) { + toSave.load(in); + } catch (IOException ignored) { + } + } + + // Save properties to user determined file + try (OutputStream out = Files.newOutputStream(p)) { + toSave.store(out, null); + } catch (IOException e) { + Iris.logger.error("Error saving properties to \"" + p + "\"", e); + } + }); }); - }); return true; } @@ -378,7 +377,7 @@ public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWi AbstractElementWidget widget = widgets.get(i); boolean widgetHovered = (hovered && (getHoveredWidget(mouseX) == i)) || getFocused() == widget; - widget.bounds = new ScreenRectangle(x + (int)((singleWidgetWidth + 2) * i), y, (int) singleWidgetWidth, entryHeight + 2); + widget.bounds = new ScreenRectangle(x + (int) ((singleWidgetWidth + 2) * i), y, (int) singleWidgetWidth, entryHeight + 2); widget.render(guiGraphics, mouseX, mouseY, tickDelta, widgetHovered); screen.setElementHoveredStatus(widget, widgetHovered); diff --git a/src/main/java/net/coderbot/iris/gui/element/ShaderPackSelectionList.java b/src/main/java/net/irisshaders/iris/gui/element/ShaderPackSelectionList.java similarity index 87% rename from src/main/java/net/coderbot/iris/gui/element/ShaderPackSelectionList.java rename to src/main/java/net/irisshaders/iris/gui/element/ShaderPackSelectionList.java index dbd6d4ee4e..9978a7d515 100644 --- a/src/main/java/net/coderbot/iris/gui/element/ShaderPackSelectionList.java +++ b/src/main/java/net/irisshaders/iris/gui/element/ShaderPackSelectionList.java @@ -1,38 +1,27 @@ -package net.coderbot.iris.gui.element; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.screen.ShaderPackScreen; +package net.irisshaders.iris.gui.element; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractSelectionList; -import net.minecraft.client.gui.components.ContainerObjectSelectionList; -import net.minecraft.client.gui.components.ObjectSelectionList; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarratableEntry; import net.minecraft.client.gui.navigation.FocusNavigationEvent; import net.minecraft.client.gui.navigation.ScreenRectangle; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.TextColor; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; - import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; -import java.util.Collection; import java.util.List; import java.util.function.Function; @@ -106,6 +95,7 @@ public void close() throws IOException { watcher.close(); } } + @Override public int getRowWidth() { return Math.min(308, width - 50); @@ -130,16 +120,16 @@ public void refresh() { // We're just trying to get more information on a seemingly untraceable bug: // - https://github.com/IrisShaders/Iris/issues/785 this.addLabelEntries( - Component.empty(), - Component.literal("There was an error reading your shaderpacks directory") - .withStyle(ChatFormatting.RED, ChatFormatting.BOLD), - Component.empty(), - Component.literal("Check your logs for more information."), - Component.literal("Please file an issue report including a log file."), - Component.literal("If you are able to identify the file causing this, " + - "please include it in your report as well."), - Component.literal("Note that this might be an issue with folder " + - "permissions; ensure those are correct first.") + Component.empty(), + Component.literal("There was an error reading your shaderpacks directory") + .withStyle(ChatFormatting.RED, ChatFormatting.BOLD), + Component.empty(), + Component.literal("Check your logs for more information."), + Component.literal("Please file an issue report including a log file."), + Component.literal("If you are able to identify the file causing this, " + + "please include it in your report as well."), + Component.literal("Note that this might be an issue with folder " + + "permissions; ensure those are correct first.") ); return; @@ -149,7 +139,7 @@ public void refresh() { // Only allow the enable/disable shaders button if the user has // added a shader pack. Otherwise, the button will be disabled. - topButtonRow.allowEnableShadersButton = names.size() > 0; + topButtonRow.allowEnableShadersButton = !names.isEmpty(); int index = 0; @@ -176,7 +166,7 @@ public void addPackEntry(int index, String name) { this.addEntry(entry); } - public void addLabelEntries(Component ... lines) { + public void addLabelEntries(Component... lines) { for (Component text : lines) { this.addEntry(new LabelEntry(text)); } @@ -186,7 +176,7 @@ public void select(String name) { for (int i = 0; i < getItemCount(); i++) { BaseEntry entry = getEntry(i); - if (entry instanceof ShaderPackEntry && ((ShaderPackEntry)entry).packName.equals(name)) { + if (entry instanceof ShaderPackEntry && ((ShaderPackEntry) entry).packName.equals(name)) { setSelected(entry); return; @@ -194,20 +184,118 @@ public void select(String name) { } } - public void setApplied(ShaderPackEntry entry) { - this.applied = entry; - } - public ShaderPackEntry getApplied() { return this.applied; } + public void setApplied(ShaderPackEntry entry) { + this.applied = entry; + } + public TopButtonRowEntry getTopButtonRow() { return topButtonRow; } public static abstract class BaseEntry extends AbstractSelectionList.Entry { - protected BaseEntry() {} + protected BaseEntry() { + } + } + + public static class LabelEntry extends BaseEntry { + private final Component label; + + public LabelEntry(Component label) { + this.label = label; + } + + @Override + public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + guiGraphics.drawCenteredString(Minecraft.getInstance().font, label, (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xC2C2C2); + } + } + + public static class TopButtonRowEntry extends BaseEntry { + private static final Component NONE_PRESENT_LABEL = Component.translatable("options.iris.shaders.nonePresent").withStyle(ChatFormatting.GRAY); + private static final Component SHADERS_DISABLED_LABEL = Component.translatable("options.iris.shaders.disabled"); + private static final Component SHADERS_ENABLED_LABEL = Component.translatable("options.iris.shaders.enabled"); + + private final ShaderPackSelectionList list; + + public boolean allowEnableShadersButton = true; + public boolean shadersEnabled; + + public TopButtonRowEntry(ShaderPackSelectionList list, boolean shadersEnabled) { + this.list = list; + this.shadersEnabled = shadersEnabled; + } + + public void setShadersEnabled(boolean shadersEnabled) { + this.shadersEnabled = shadersEnabled; + this.list.screen.refreshScreenSwitchButton(); + } + + @Override + public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { + GuiUtil.bindIrisWidgetsTexture(); + GuiUtil.drawButton(guiGraphics, x - 2, y - 2, entryWidth, entryHeight + 2, hovered, !allowEnableShadersButton); + guiGraphics.drawCenteredString(Minecraft.getInstance().font, getEnableDisableLabel(), (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xFFFFFF); + } + + private Component getEnableDisableLabel() { + return this.allowEnableShadersButton ? this.shadersEnabled ? SHADERS_ENABLED_LABEL : SHADERS_DISABLED_LABEL : NONE_PRESENT_LABEL; + } + + @Override + public boolean mouseClicked(double mouseX, double mouseY, int button) { + if (this.allowEnableShadersButton) { + setShadersEnabled(!this.shadersEnabled); + GuiUtil.playButtonClickSound(); + return true; + } + + return false; + } + + @Override + public boolean keyPressed(int keycode, int scancode, int modifiers) { + if (keycode == GLFW.GLFW_KEY_ENTER) { + if (this.allowEnableShadersButton) { + setShadersEnabled(!this.shadersEnabled); + GuiUtil.playButtonClickSound(); + return true; + } + } + + return false; + } + + @Nullable + @Override + public ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { + return (!isFocused()) ? ComponentPath.leaf(this) : null; + } + + + public boolean isFocused() { + return this.list.getFocused() == this; + } + + // Renders the label at an offset as to not look misaligned with the rest of the menu + public static class EnableShadersButtonElement extends IrisElementRow.TextButtonElement { + private int centerX; + + public EnableShadersButtonElement(Component text, Function onClick) { + super(text, onClick); + } + + @Override + public void renderLabel(GuiGraphics guiGraphics, int x, int y, int width, int height, int mouseX, int mouseY, float tickDelta, boolean hovered) { + int textX = this.centerX - (int) (this.font.width(this.text) * 0.5); + int textY = y + (int) ((height - 8) * 0.5); + + guiGraphics.drawString(this.font, this.text, textX, textY, 0xFFFFFF); + } + } } public class ShaderPackEntry extends BaseEntry { @@ -217,11 +305,6 @@ public class ShaderPackEntry extends BaseEntry { private ScreenRectangle bounds; private boolean focused; - @Override - public ScreenRectangle getRectangle() { - return bounds; - } - public ShaderPackEntry(int index, ShaderPackSelectionList list, String packName) { this.bounds = ScreenRectangle.empty(); this.packName = packName; @@ -229,6 +312,10 @@ public ShaderPackEntry(int index, ShaderPackSelectionList list, String packName) this.index = index; } + @Override + public ScreenRectangle getRectangle() { + return bounds; + } public boolean isApplied() { return list.getApplied() == this; @@ -327,107 +414,8 @@ public ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { } - public boolean isFocused() { return this.list.getFocused() == this; } } - - public static class LabelEntry extends BaseEntry { - private final Component label; - - public LabelEntry(Component label) { - this.label = label; - } - - @Override - public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { - guiGraphics.drawCenteredString(Minecraft.getInstance().font, label, (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xC2C2C2); - } - } - - public class TopButtonRowEntry extends BaseEntry { - private static final Component NONE_PRESENT_LABEL = Component.translatable("options.iris.shaders.nonePresent").withStyle(ChatFormatting.GRAY); - private static final Component SHADERS_DISABLED_LABEL = Component.translatable("options.iris.shaders.disabled"); - private static final Component SHADERS_ENABLED_LABEL = Component.translatable("options.iris.shaders.enabled"); - - private final ShaderPackSelectionList list; - - public boolean allowEnableShadersButton = true; - public boolean shadersEnabled; - - public TopButtonRowEntry(ShaderPackSelectionList list, boolean shadersEnabled) { - this.list = list; - this.shadersEnabled = shadersEnabled; - } - - public void setShadersEnabled(boolean shadersEnabled) { - this.shadersEnabled = shadersEnabled; - this.list.screen.refreshScreenSwitchButton(); - } - - @Override - public void render(GuiGraphics guiGraphics, int index, int y, int x, int entryWidth, int entryHeight, int mouseX, int mouseY, boolean hovered, float tickDelta) { - GuiUtil.bindIrisWidgetsTexture(); - GuiUtil.drawButton(guiGraphics, x - 2, y - 2, entryWidth, entryHeight + 2, hovered, !allowEnableShadersButton); - guiGraphics.drawCenteredString(Minecraft.getInstance().font, getEnableDisableLabel(), (x + entryWidth / 2) - 2, y + (entryHeight - 11) / 2, 0xFFFFFF); - } - - private Component getEnableDisableLabel() { - return this.allowEnableShadersButton ? this.shadersEnabled ? SHADERS_ENABLED_LABEL : SHADERS_DISABLED_LABEL : NONE_PRESENT_LABEL; - } - - @Override - public boolean mouseClicked(double mouseX, double mouseY, int button) { - if (this.allowEnableShadersButton) { - setShadersEnabled(!this.shadersEnabled); - GuiUtil.playButtonClickSound(); - return true; - } - - return false; - } - - @Override - public boolean keyPressed(int keycode, int scancode, int modifiers) { - if (keycode == GLFW.GLFW_KEY_ENTER) { - if (this.allowEnableShadersButton) { - setShadersEnabled(!this.shadersEnabled); - GuiUtil.playButtonClickSound(); - return true; - } - } - - return false; - } - - @Nullable - @Override - public ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { - return (!isFocused()) ? ComponentPath.leaf(this) : null; - } - - - - public boolean isFocused() { - return this.list.getFocused() == this; - } - - // Renders the label at an offset as to not look misaligned with the rest of the menu - public static class EnableShadersButtonElement extends IrisElementRow.TextButtonElement { - private int centerX; - - public EnableShadersButtonElement(Component text, Function onClick) { - super(text, onClick); - } - - @Override - public void renderLabel(GuiGraphics guiGraphics, int x, int y, int width, int height, int mouseX, int mouseY, float tickDelta, boolean hovered) { - int textX = this.centerX - (int)(this.font.width(this.text) * 0.5); - int textY = y + (int)((height - 8) * 0.5); - - guiGraphics.drawString(this.font, this.text, textX, textY, 0xFFFFFF); - } - } - } } diff --git a/src/main/java/net/irisshaders/iris/gui/element/screen/ElementWidgetScreenData.java b/src/main/java/net/irisshaders/iris/gui/element/screen/ElementWidgetScreenData.java new file mode 100644 index 0000000000..7ab5346beb --- /dev/null +++ b/src/main/java/net/irisshaders/iris/gui/element/screen/ElementWidgetScreenData.java @@ -0,0 +1,9 @@ +package net.irisshaders.iris.gui.element.screen; + +import net.minecraft.network.chat.Component; + + +public record ElementWidgetScreenData(Component heading, boolean backButton) { + public static final ElementWidgetScreenData EMPTY = new ElementWidgetScreenData(Component.empty(), true); + +} diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/AbstractElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/AbstractElementWidget.java similarity index 85% rename from src/main/java/net/coderbot/iris/gui/element/widget/AbstractElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/AbstractElementWidget.java index 4d88621515..6bf3e4170f 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/AbstractElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/AbstractElementWidget.java @@ -1,9 +1,8 @@ -package net.coderbot.iris.gui.element.widget; +package net.irisshaders.iris.gui.element.widget; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuElement; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuElement; import net.minecraft.client.gui.ComponentPath; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.events.GuiEventListener; @@ -15,13 +14,10 @@ import org.jetbrains.annotations.Nullable; public abstract class AbstractElementWidget implements GuiEventListener, NarratableEntry { - protected final T element; - private boolean focused; - public ScreenRectangle bounds = ScreenRectangle.empty(); - - public static final AbstractElementWidget EMPTY = new AbstractElementWidget(null) { + public static final AbstractElementWidget EMPTY = new AbstractElementWidget<>(null) { @Override - public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDelta, boolean hovered) {} + public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDelta, boolean hovered) { + } @Override public @Nullable ComponentPath nextFocusPath(FocusNavigationEvent pGuiEventListener0) { @@ -33,12 +29,16 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDe return ScreenRectangle.empty(); } }; + protected final T element; + public ScreenRectangle bounds = ScreenRectangle.empty(); + private boolean focused; public AbstractElementWidget(T element) { this.element = element; } - public void init(ShaderPackScreen screen, NavigationController navigation) {} + public void init(ShaderPackScreen screen, NavigationController navigation) { + } public abstract void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDelta, boolean hovered); diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/BaseOptionElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/BaseOptionElementWidget.java similarity index 91% rename from src/main/java/net/coderbot/iris/gui/element/widget/BaseOptionElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/BaseOptionElementWidget.java index f2cfc50b69..fc3baf0e8d 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/BaseOptionElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/BaseOptionElementWidget.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.gui.element.widget; +package net.irisshaders.iris.gui.element.widget; import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuElement; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuElement; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; @@ -28,15 +27,13 @@ public abstract class BaseOptionElementWidget exten protected MutableComponent unmodifiedLabel; protected ShaderPackScreen screen; protected NavigationController navigation; - private MutableComponent label; - protected Component trimmedLabel; protected Component valueLabel; - + protected boolean usedKeyboard; + private MutableComponent label; private boolean isLabelTrimmed; private int maxLabelWidth; private int valueSectionWidth; - protected boolean usedKeyboard; public BaseOptionElementWidget(T element) { super(element); @@ -95,7 +92,7 @@ protected final void renderOptionWithValue(GuiGraphics guiGraphics, boolean hove int sliderSpace = (this.valueSectionWidth - 4) - sliderWidth; // Position of slider - int sliderPos = (bounds.getBoundInDirection(ScreenDirection.RIGHT) - this.valueSectionWidth) + (int)(sliderPosition * sliderSpace); + int sliderPos = (bounds.getBoundInDirection(ScreenDirection.RIGHT) - this.valueSectionWidth) + (int) (sliderPosition * sliderSpace); GuiUtil.drawButton(guiGraphics, sliderPos, bounds.position().y() + 4, sliderWidth, bounds.height() - 8, false, false); } @@ -105,7 +102,7 @@ protected final void renderOptionWithValue(GuiGraphics guiGraphics, boolean hove // Draw the label guiGraphics.drawString(font, this.trimmedLabel, bounds.position().x() + 6, bounds.position().y() + 7, 0xFFFFFF); // Draw the value label - guiGraphics.drawString(font, this.valueLabel, (bounds.getBoundInDirection(ScreenDirection.RIGHT) - 2) - (int)(this.valueSectionWidth * 0.5) - (int)(font.width(this.valueLabel) * 0.5), bounds.position().y() + 7, 0xFFFFFF); + guiGraphics.drawString(font, this.valueLabel, (bounds.getBoundInDirection(ScreenDirection.RIGHT) - 2) - (int) (this.valueSectionWidth * 0.5) - (int) (font.width(this.valueLabel) * 0.5), bounds.position().y() + 7, 0xFFFFFF); } protected final void renderOptionWithValue(GuiGraphics guiGraphics, boolean hovered) { @@ -133,9 +130,9 @@ protected final void updateLabels() { protected final Component createTrimmedLabel() { MutableComponent label = GuiUtil.shortenText( - Minecraft.getInstance().font, - this.label.copy(), - this.maxLabelWidth); + Minecraft.getInstance().font, + this.label.copy(), + this.maxLabelWidth); if (this.isValueModified()) { label = label.withStyle(style -> style.withColor(TextColor.fromRgb(0xffc94a))); diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/BooleanElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/BooleanElementWidget.java similarity index 88% rename from src/main/java/net/coderbot/iris/gui/element/widget/BooleanElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/BooleanElementWidget.java index 4954b3c499..28941b683c 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/BooleanElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/BooleanElementWidget.java @@ -1,16 +1,14 @@ -package net.coderbot.iris.gui.element.widget; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.BooleanOption; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuBooleanOptionElement; +package net.irisshaders.iris.gui.element.widget; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.BooleanOption; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuBooleanOptionElement; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TextColor; public class BooleanElementWidget extends BaseOptionElementWidget { private static final Component TEXT_TRUE = Component.translatable("label.iris.true").withStyle(ChatFormatting.GREEN); diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/CommentedElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/CommentedElementWidget.java similarity index 75% rename from src/main/java/net/coderbot/iris/gui/element/widget/CommentedElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/CommentedElementWidget.java index 3fca3a480b..b43c37116d 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/CommentedElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/CommentedElementWidget.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.gui.element.widget; +package net.irisshaders.iris.gui.element.widget; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuElement; import net.minecraft.network.chat.Component; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/LinkElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/LinkElementWidget.java similarity index 87% rename from src/main/java/net/coderbot/iris/gui/element/widget/LinkElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/LinkElementWidget.java index 09b414de1d..2da64c7066 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/LinkElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/LinkElementWidget.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.gui.element.widget; +package net.irisshaders.iris.gui.element.widget; import com.mojang.blaze3d.platform.InputConstants; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuLinkElement; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuLinkElement; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; @@ -14,8 +13,6 @@ import net.minecraft.client.resources.language.I18n; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; - - import org.lwjgl.glfw.GLFW; import java.util.Optional; @@ -61,7 +58,7 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDe int labelWidth = font.width(this.trimmedLabel); - guiGraphics.drawString(font, this.trimmedLabel, bounds.getCenterInAxis(ScreenAxis.HORIZONTAL) - (int)(labelWidth * 0.5) - (int)(0.5 * Math.max(labelWidth - (bounds.width() - 18), 0)), bounds.position().y() + 7, 0xFFFFFF); + guiGraphics.drawString(font, this.trimmedLabel, bounds.getCenterInAxis(ScreenAxis.HORIZONTAL) - (int) (labelWidth * 0.5) - (int) (0.5 * Math.max(labelWidth - (bounds.width() - 18), 0)), bounds.position().y() + 7, 0xFFFFFF); guiGraphics.drawString(font, ARROW, bounds.getBoundInDirection(ScreenDirection.RIGHT) - 9, bounds.position().y() + 7, 0xFFFFFF); if (hovered && this.isLabelTrimmed) { diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/OptionMenuConstructor.java b/src/main/java/net/irisshaders/iris/gui/element/widget/OptionMenuConstructor.java similarity index 65% rename from src/main/java/net/coderbot/iris/gui/element/widget/OptionMenuConstructor.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/OptionMenuConstructor.java index 955ae86be1..f3979ff677 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/OptionMenuConstructor.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/OptionMenuConstructor.java @@ -1,24 +1,23 @@ -package net.coderbot.iris.gui.element.widget; - -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.element.ShaderPackOptionList; -import net.coderbot.iris.gui.element.screen.ElementWidgetScreenData; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuBooleanOptionElement; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuContainer; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuElement; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuElementScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuLinkElement; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuMainElementScreen; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuProfileElement; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuStringOptionElement; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuSubElementScreen; +package net.irisshaders.iris.gui.element.widget; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.element.ShaderPackOptionList; +import net.irisshaders.iris.gui.element.screen.ElementWidgetScreenData; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuBooleanOptionElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuElementScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuLinkElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuMainElementScreen; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuProfileElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuStringOptionElement; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuSubElementScreen; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; - import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; @@ -27,7 +26,23 @@ public final class OptionMenuConstructor { private static final Map, WidgetProvider> WIDGET_CREATORS = new HashMap<>(); private static final Map, ScreenDataProvider> SCREEN_DATA_CREATORS = new HashMap<>(); - private OptionMenuConstructor() {} + static { + registerScreen(OptionMenuMainElementScreen.class, screen -> + new ElementWidgetScreenData(Component.literal(Iris.getCurrentPackName()).append(Iris.isFallback() ? " (fallback)" : "").withStyle(ChatFormatting.BOLD), false)); + + registerScreen(OptionMenuSubElementScreen.class, screen -> + new ElementWidgetScreenData(GuiUtil.translateOrDefault(Component.literal(screen.screenId), "screen." + screen.screenId), true)); + + registerWidget(OptionMenuBooleanOptionElement.class, BooleanElementWidget::new); + registerWidget(OptionMenuProfileElement.class, ProfileElementWidget::new); + registerWidget(OptionMenuLinkElement.class, LinkElementWidget::new); + + registerWidget(OptionMenuStringOptionElement.class, element -> + element.slider ? new SliderElementWidget(element) : new StringElementWidget(element)); + } + + private OptionMenuConstructor() { + } @SuppressWarnings("unchecked") public static void registerWidget(Class element, WidgetProvider widget) { @@ -57,7 +72,7 @@ public static void constructAndApplyToScreen(OptionMenuContainer container, Shad ElementWidgetScreenData data = createScreenData(screen); - optionList.addHeader(data.heading, data.backButton); + optionList.addHeader(data.heading(), data.backButton()); optionList.addWidgets(screen.getColumnCount(), screen.elements.stream().map(element -> { AbstractElementWidget widget = (AbstractElementWidget) createWidget(element); widget.init(packScreen, navigation); @@ -65,21 +80,6 @@ public static void constructAndApplyToScreen(OptionMenuContainer container, Shad }).collect(Collectors.toList())); } - static { - registerScreen(OptionMenuMainElementScreen.class, screen -> - new ElementWidgetScreenData(Component.literal(Iris.getCurrentPackName()).append(Iris.isFallback() ? " (fallback)" : "").withStyle(ChatFormatting.BOLD), false)); - - registerScreen(OptionMenuSubElementScreen.class, screen -> - new ElementWidgetScreenData(GuiUtil.translateOrDefault(Component.literal(screen.screenId), "screen." + screen.screenId), true)); - - registerWidget(OptionMenuBooleanOptionElement.class, BooleanElementWidget::new); - registerWidget(OptionMenuProfileElement.class, ProfileElementWidget::new); - registerWidget(OptionMenuLinkElement.class, LinkElementWidget::new); - - registerWidget(OptionMenuStringOptionElement.class, element -> - element.slider ? new SliderElementWidget(element) : new StringElementWidget(element)); - } - public interface WidgetProvider { AbstractElementWidget create(T element); } diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/ProfileElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/ProfileElementWidget.java similarity index 81% rename from src/main/java/net/coderbot/iris/gui/element/widget/ProfileElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/ProfileElementWidget.java index 870cb080c0..086204a5ec 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/ProfileElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/ProfileElementWidget.java @@ -1,23 +1,20 @@ -package net.coderbot.iris.gui.element.widget; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.OptionSet; -import net.coderbot.iris.shaderpack.option.Profile; -import net.coderbot.iris.shaderpack.option.ProfileSet; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuProfileElement; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +package net.irisshaders.iris.gui.element.widget; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.shaderpack.option.Profile; +import net.irisshaders.iris.shaderpack.option.ProfileSet; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuProfileElement; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; - - import java.util.Optional; public class ProfileElementWidget extends BaseOptionElementWidget { diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/SliderElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/SliderElementWidget.java similarity index 85% rename from src/main/java/net/coderbot/iris/gui/element/widget/SliderElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/SliderElementWidget.java index 969b290b57..8cab8d4e76 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/SliderElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/SliderElementWidget.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.gui.element.widget; +package net.irisshaders.iris.gui.element.widget; -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuStringOptionElement; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuStringOptionElement; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.GuiGraphics; @@ -32,7 +31,7 @@ public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float tickDe usedKeyboard = false; mouseDown = false; } - this.renderOptionWithValue(guiGraphics, false, (float)valueIndex / (valueCount - 1), PREVIEW_SLIDER_WIDTH); + this.renderOptionWithValue(guiGraphics, false, (float) valueIndex / (valueCount - 1), PREVIEW_SLIDER_WIDTH); } else { this.renderSlider(guiGraphics); } @@ -79,19 +78,19 @@ private void renderSlider(GuiGraphics guiGraphics) { // Range of x values the slider can occupy int sliderSpace = (bounds.width() - 8) - ACTIVE_SLIDER_WIDTH; // Position of slider - int sliderPos = (bounds.position().x() + 4) + (int)(((float)valueIndex / (valueCount - 1)) * sliderSpace); + int sliderPos = (bounds.position().x() + 4) + (int) (((float) valueIndex / (valueCount - 1)) * sliderSpace); // Draw slider GuiUtil.drawButton(guiGraphics, sliderPos, bounds.position().y() + 4, ACTIVE_SLIDER_WIDTH, bounds.height() - 8, this.mouseDown, false); // Draw value label Font font = Minecraft.getInstance().font; - guiGraphics.drawString(font, this.valueLabel, bounds.getCenterInAxis(ScreenAxis.HORIZONTAL) - (int)(font.width(this.valueLabel) * 0.5), bounds.position().y() + 7, 0xFFFFFF); + guiGraphics.drawString(font, this.valueLabel, bounds.getCenterInAxis(ScreenAxis.HORIZONTAL) - (int) (font.width(this.valueLabel) * 0.5), bounds.position().y() + 7, 0xFFFFFF); } private void whileDragging(int mouseX) { - float mousePositionAcrossWidget = Mth.clamp((float)(mouseX - (bounds.position().x() + 4)) / (bounds.width() - 8), 0, 1); + float mousePositionAcrossWidget = Mth.clamp((float) (mouseX - (bounds.position().x() + 4)) / (bounds.width() - 8), 0, 1); - int newValueIndex = Math.min(valueCount - 1, (int)(mousePositionAcrossWidget * valueCount)); + int newValueIndex = Math.min(valueCount - 1, (int) (mousePositionAcrossWidget * valueCount)); if (valueIndex != newValueIndex) { this.valueIndex = newValueIndex; diff --git a/src/main/java/net/coderbot/iris/gui/element/widget/StringElementWidget.java b/src/main/java/net/irisshaders/iris/gui/element/widget/StringElementWidget.java similarity index 84% rename from src/main/java/net/coderbot/iris/gui/element/widget/StringElementWidget.java rename to src/main/java/net/irisshaders/iris/gui/element/widget/StringElementWidget.java index 71b72a9f29..ae931abaef 100644 --- a/src/main/java/net/coderbot/iris/gui/element/widget/StringElementWidget.java +++ b/src/main/java/net/irisshaders/iris/gui/element/widget/StringElementWidget.java @@ -1,21 +1,18 @@ -package net.coderbot.iris.gui.element.widget; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.shaderpack.option.StringOption; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuStringOptionElement; +package net.irisshaders.iris.gui.element.widget; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.shaderpack.option.StringOption; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuStringOptionElement; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.navigation.ScreenDirection; -import net.minecraft.client.gui.screens.Screen; import net.minecraft.locale.Language; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.chat.TextColor; - import java.util.List; public class StringElementWidget extends BaseOptionElementWidget { @@ -75,8 +72,8 @@ private void increment(int amount) { @Override protected Component createValueLabel() { return prefix.copy().append(GuiUtil.translateOrDefault( - Component.literal(getValue()), - "value." + this.option.getName() + "." + getValue())).append(suffix).withStyle(style -> style.withColor(TextColor.fromRgb(0x6688ff))); + Component.literal(getValue()).append(suffix), + "value." + this.option.getName() + "." + getValue())).withStyle(style -> style.withColor(TextColor.fromRgb(0x6688ff))); } @Override diff --git a/src/main/java/net/coderbot/iris/gui/option/IrisVideoSettings.java b/src/main/java/net/irisshaders/iris/gui/option/IrisVideoSettings.java similarity index 69% rename from src/main/java/net/coderbot/iris/gui/option/IrisVideoSettings.java rename to src/main/java/net/irisshaders/iris/gui/option/IrisVideoSettings.java index ded44a6519..39dc83195d 100644 --- a/src/main/java/net/coderbot/iris/gui/option/IrisVideoSettings.java +++ b/src/main/java/net/irisshaders/iris/gui/option/IrisVideoSettings.java @@ -1,43 +1,20 @@ -package net.coderbot.iris.gui.option; +package net.irisshaders.iris.gui.option; -import com.mojang.serialization.Codec; -import net.coderbot.iris.Iris; -import net.coderbot.iris.colorspace.ColorSpace; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.minecraft.client.Minecraft; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pathways.colorspace.ColorSpace; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.OptionInstance; -import net.minecraft.client.Options; import net.minecraft.client.gui.components.Tooltip; -import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.util.Mth; - import java.io.IOException; -import java.util.List; public class IrisVideoSettings { - public static int shadowDistance = 32; - private static final Tooltip DISABLED_TOOLTIP = Tooltip.create(Component.translatable("options.iris.shadowDistance.disabled")); private static final Tooltip ENABLED_TOOLTIP = Tooltip.create(Component.translatable("options.iris.shadowDistance.enabled")); + public static int shadowDistance = 32; public static ColorSpace colorSpace = ColorSpace.SRGB; - - public static int getOverriddenShadowDistance(int base) { - return Iris.getPipelineManager().getPipeline() - .map(pipeline -> pipeline.getForcedShadowRenderDistanceChunksForDisplay().orElse(base)) - .orElse(base); - } - - public static boolean isShadowDistanceSliderEnabled() { - return Iris.getPipelineManager().getPipeline() - .map(pipeline -> !pipeline.getForcedShadowRenderDistanceChunksForDisplay().isPresent()) - .orElse(true); - } - // TODO 22w12a fix this - - public static final OptionInstance RENDER_DISTANCE = new ShadowDistanceOption("options.iris.shadowDistance", + public static final OptionInstance RENDER_DISTANCE = new ShadowDistanceOption<>("options.iris.shadowDistance", mc -> { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); @@ -77,7 +54,19 @@ public static boolean isShadowDistanceSliderEnabled() { try { Iris.getIrisConfig().save(); } catch (IOException e) { - e.printStackTrace(); + Iris.logger.fatal("Failed to save config!", e); } }); + + public static int getOverriddenShadowDistance(int base) { + return Iris.getPipelineManager().getPipeline() + .map(pipeline -> pipeline.getForcedShadowRenderDistanceChunksForDisplay().orElse(base)) + .orElse(base); + } + + public static boolean isShadowDistanceSliderEnabled() { + return Iris.getPipelineManager().getPipeline() + .map(pipeline -> !pipeline.getForcedShadowRenderDistanceChunksForDisplay().isPresent()) + .orElse(true); + } } diff --git a/src/main/java/net/coderbot/iris/gui/option/ShaderPackSelectionButtonOption.java b/src/main/java/net/irisshaders/iris/gui/option/ShaderPackSelectionButtonOption.java similarity index 54% rename from src/main/java/net/coderbot/iris/gui/option/ShaderPackSelectionButtonOption.java rename to src/main/java/net/irisshaders/iris/gui/option/ShaderPackSelectionButtonOption.java index 056073ed81..30855b98e7 100644 --- a/src/main/java/net/coderbot/iris/gui/option/ShaderPackSelectionButtonOption.java +++ b/src/main/java/net/irisshaders/iris/gui/option/ShaderPackSelectionButtonOption.java @@ -1,11 +1,6 @@ -package net.coderbot.iris.gui.option; +package net.irisshaders.iris.gui.option; -import net.coderbot.iris.gui.screen.ShaderPackScreen; import net.minecraft.client.Minecraft; -import net.minecraft.client.OptionInstance; -import net.minecraft.client.Options; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.Screen; diff --git a/src/main/java/net/coderbot/iris/gui/option/ShadowDistanceOption.java b/src/main/java/net/irisshaders/iris/gui/option/ShadowDistanceOption.java similarity index 91% rename from src/main/java/net/coderbot/iris/gui/option/ShadowDistanceOption.java rename to src/main/java/net/irisshaders/iris/gui/option/ShadowDistanceOption.java index 661c61c82f..f06c7f09cd 100644 --- a/src/main/java/net/coderbot/iris/gui/option/ShadowDistanceOption.java +++ b/src/main/java/net/irisshaders/iris/gui/option/ShadowDistanceOption.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.gui.option; +package net.irisshaders.iris.gui.option; -import net.minecraft.client.Minecraft; import net.minecraft.client.OptionInstance; import net.minecraft.client.Options; import net.minecraft.client.gui.components.AbstractWidget; + import java.util.function.Consumer; public class ShadowDistanceOption extends OptionInstance { diff --git a/src/main/java/net/coderbot/iris/gui/screen/HudHideable.java b/src/main/java/net/irisshaders/iris/gui/screen/HudHideable.java similarity index 74% rename from src/main/java/net/coderbot/iris/gui/screen/HudHideable.java rename to src/main/java/net/irisshaders/iris/gui/screen/HudHideable.java index 71a88e4e29..0f0f215e61 100644 --- a/src/main/java/net/coderbot/iris/gui/screen/HudHideable.java +++ b/src/main/java/net/irisshaders/iris/gui/screen/HudHideable.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.gui.screen; +package net.irisshaders.iris.gui.screen; /** * Screens implementing this will hide the player hand and HUD - * + *

    * Only used for instanceof checks */ public interface HudHideable { diff --git a/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java b/src/main/java/net/irisshaders/iris/gui/screen/ShaderPackScreen.java similarity index 90% rename from src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java rename to src/main/java/net/irisshaders/iris/gui/screen/ShaderPackScreen.java index a45aa9051c..55a8437c5d 100644 --- a/src/main/java/net/coderbot/iris/gui/screen/ShaderPackScreen.java +++ b/src/main/java/net/irisshaders/iris/gui/screen/ShaderPackScreen.java @@ -1,31 +1,29 @@ -package net.coderbot.iris.gui.screen; +package net.irisshaders.iris.gui.screen; import com.mojang.blaze3d.platform.InputConstants; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.GuiUtil; -import net.coderbot.iris.gui.NavigationController; -import net.coderbot.iris.gui.OldImageButton; -import net.coderbot.iris.gui.element.ShaderPackOptionList; -import net.coderbot.iris.gui.element.ShaderPackSelectionList; -import net.coderbot.iris.gui.element.widget.AbstractElementWidget; -import net.coderbot.iris.gui.element.widget.CommentedElementWidget; -import net.coderbot.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.gui.GuiUtil; +import net.irisshaders.iris.gui.NavigationController; +import net.irisshaders.iris.gui.OldImageButton; +import net.irisshaders.iris.gui.element.ShaderPackOptionList; +import net.irisshaders.iris.gui.element.ShaderPackSelectionList; +import net.irisshaders.iris.gui.element.widget.AbstractElementWidget; +import net.irisshaders.iris.gui.element.widget.CommentedElementWidget; +import net.irisshaders.iris.shaderpack.ShaderPack; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.ImageButton; import net.minecraft.client.gui.components.Tooltip; import net.minecraft.client.gui.screens.ConfirmScreen; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; - - import net.minecraft.util.FormattedCharSequence; +import net.minecraftforge.fml.loading.FMLEnvironment; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; @@ -53,28 +51,21 @@ public class ShaderPackScreen extends Screen implements HudHideable { private static final Component SELECT_TITLE = Component.translatable("pack.iris.select.title").withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC); private static final Component CONFIGURE_TITLE = Component.translatable("pack.iris.configure.title").withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC); private static final int COMMENT_PANEL_WIDTH = 314; - + private static final String development = "Development Environment"; private final Screen parent; private final MutableComponent irisTextComponent; - private ShaderPackSelectionList shaderPackList; - private @Nullable ShaderPackOptionList shaderOptionList = null; private @Nullable NavigationController navigation = null; private Button screenSwitchButton; - private Component notificationDialog = null; private int notificationDialogTimer = 0; - private @Nullable AbstractElementWidget hoveredElement = null; private Optional hoveredElementCommentTitle = Optional.empty(); private List hoveredElementCommentBody = new ArrayList<>(); private int hoveredElementCommentTimer = 0; - private boolean optionMenuOpen = false; - private boolean dropChanges = false; - private static String development = "Development Environment"; private MutableComponent developmentComponent; private MutableComponent updateComponent; @@ -89,9 +80,8 @@ public ShaderPackScreen(Screen parent) { String irisName = Iris.MODNAME + " " + Iris.getVersion(); - if (irisName.contains("-development-environment")) { + if (!FMLEnvironment.production) { this.developmentComponent = Component.literal("Development Environment").withStyle(ChatFormatting.GOLD); - irisName = irisName.replace("-development-environment", ""); } this.irisTextComponent = Component.literal(irisName).withStyle(ChatFormatting.GRAY); @@ -218,13 +208,13 @@ protected void init() { } this.addRenderableWidget(Button.builder(CommonComponents.GUI_DONE, button -> onClose()).bounds(bottomCenter + 104, this.height - 27, 100, 20 - ).build()); + ).build()); this.addRenderableWidget(Button.builder(Component.translatable("options.iris.apply"), button -> this.applyChanges()).bounds(bottomCenter, this.height - 27, 100, 20 - ).build()); + ).build()); this.addRenderableWidget(Button.builder(CommonComponents.GUI_CANCEL, button -> this.dropChangesAndClose()).bounds(bottomCenter - 104, this.height - 27, 100, 20 - ).build()); + ).build()); this.openFolderButton = Button.builder(Component.translatable("options.iris.openShaderPackFolder"), button -> openShaderPackFolder()).bounds(topCenter - 78, this.height - 51, 152, 20 ).build(); @@ -243,7 +233,7 @@ protected void init() { this.init(); } ).bounds(topCenter + 78, this.height - 51, 152, 20 - ).build()); + ).build()); refreshScreenSwitchButton(); } @@ -309,9 +299,9 @@ public void refreshForChangedPack() { public void refreshScreenSwitchButton() { if (this.screenSwitchButton != null) { this.screenSwitchButton.setMessage( - optionMenuOpen ? - Component.translatable("options.iris.shaderPackList") - : Component.translatable("options.iris.shaderPackSettings") + optionMenuOpen ? + Component.translatable("options.iris.shaderPackList") + : Component.translatable("options.iris.shaderPackSettings") ); this.screenSwitchButton.active = optionMenuOpen || shaderPackList.getTopButtonRow().shadersEnabled; } @@ -382,7 +372,7 @@ public void onFilesDrop(List paths) { } public void onPackListFilesDrop(List paths) { - List packs = paths.stream().filter(Iris::isValidShaderpack).collect(Collectors.toList()); + List packs = paths.stream().filter(Iris::isValidShaderpack).toList(); for (Path pack : packs) { String fileName = pack.getFileName().toString(); @@ -391,8 +381,8 @@ public void onPackListFilesDrop(List paths) { Iris.getShaderpacksDirectoryManager().copyPackIntoDirectory(fileName, pack); } catch (FileAlreadyExistsException e) { this.notificationDialog = Component.translatable( - "options.iris.shaderPackSelection.copyErrorAlreadyExists", - fileName + "options.iris.shaderPackSelection.copyErrorAlreadyExists", + fileName ).withStyle(ChatFormatting.ITALIC, ChatFormatting.RED); this.notificationDialogTimer = 100; @@ -403,8 +393,8 @@ public void onPackListFilesDrop(List paths) { Iris.logger.warn("Error copying dragged shader pack", e); this.notificationDialog = Component.translatable( - "options.iris.shaderPackSelection.copyError", - fileName + "options.iris.shaderPackSelection.copyError", + fileName ).withStyle(ChatFormatting.ITALIC, ChatFormatting.RED); this.notificationDialogTimer = 100; @@ -417,7 +407,7 @@ public void onPackListFilesDrop(List paths) { // After copying the relevant files over to the folder, make sure to refresh the shader pack list. this.shaderPackList.refresh(); - if (packs.size() == 0) { + if (packs.isEmpty()) { // If zero packs were added, then notify the user that the files that they added weren't actually shader // packs. @@ -442,8 +432,8 @@ public void onPackListFilesDrop(List paths) { String packName = packs.get(0).getFileName().toString(); this.notificationDialog = Component.translatable( - "options.iris.shaderPackSelection.addedPack", - packName + "options.iris.shaderPackSelection.addedPack", + packName ).withStyle(ChatFormatting.ITALIC, ChatFormatting.YELLOW); // Select the pack that the user just added, since if a user just dragged a pack in, they'll probably want @@ -453,8 +443,8 @@ public void onPackListFilesDrop(List paths) { // We also support multiple packs being dragged and dropped at a time. Just show a generic success message // in that case. this.notificationDialog = Component.translatable( - "options.iris.shaderPackSelection.addedPacks", - packs.size() + "options.iris.shaderPackSelection.addedPacks", + packs.size() ).withStyle(ChatFormatting.ITALIC, ChatFormatting.YELLOW); } @@ -472,7 +462,7 @@ public void onOptionMenuFilesDrop(List paths) { // as only one option file should be imported at a time if (paths.size() != 1) { this.notificationDialog = Component.translatable( - "options.iris.shaderPackOptions.tooManyFiles" + "options.iris.shaderPackOptions.tooManyFiles" ).withStyle(ChatFormatting.ITALIC, ChatFormatting.RED); this.notificationDialogTimer = 100; // 5 seconds (100 ticks) @@ -490,8 +480,8 @@ public void importPackOptions(Path settingFile) { Iris.queueShaderPackOptionsFromProperties(properties); this.notificationDialog = Component.translatable( - "options.iris.shaderPackOptions.importedSettings", - settingFile.getFileName().toString() + "options.iris.shaderPackOptions.importedSettings", + settingFile.getFileName().toString() ).withStyle(ChatFormatting.ITALIC, ChatFormatting.YELLOW); this.notificationDialogTimer = 100; // 5 seconds (100 ticks) @@ -501,11 +491,11 @@ public void importPackOptions(Path settingFile) { } catch (Exception e) { // If the file could not be properly parsed or loaded, // log the error and display a message to the user - Iris.logger.error("Error importing shader settings file \""+ settingFile.toString() +"\"", e); + Iris.logger.error("Error importing shader settings file \"" + settingFile.toString() + "\"", e); this.notificationDialog = Component.translatable( - "options.iris.shaderPackOptions.failedImport", - settingFile.getFileName().toString() + "options.iris.shaderPackOptions.failedImport", + settingFile.getFileName().toString() ).withStyle(ChatFormatting.ITALIC, ChatFormatting.RED); this.notificationDialogTimer = 100; // 5 seconds (100 ticks) } @@ -542,11 +532,10 @@ public void applyChanges() { IrisApi.getInstance().getConfig().setShadersEnabledAndApply(enabled); } - if (!(base instanceof ShaderPackSelectionList.ShaderPackEntry)) { + if (!(base instanceof ShaderPackSelectionList.ShaderPackEntry entry)) { return; } - ShaderPackSelectionList.ShaderPackEntry entry = (ShaderPackSelectionList.ShaderPackEntry)base; this.shaderPackList.setApplied(entry); String name = entry.getPackName(); @@ -597,7 +586,7 @@ public void setElementHoveredStatus(AbstractElementWidget widget, boolean hov rawCommentBody = rawCommentBody.substring(0, rawCommentBody.length() - 1); } // Split comment body into lines by separator ". " - List splitByPeriods = Arrays.stream(rawCommentBody.split("\\. [ ]*")).map(Component::literal).collect(Collectors.toList()); + List splitByPeriods = Arrays.stream(rawCommentBody.split("\\. [ ]*")).map(Component::literal).toList(); // Line wrap this.hoveredElementCommentBody = new ArrayList<>(); for (MutableComponent text : splitByPeriods) { @@ -620,8 +609,8 @@ public void setElementHoveredStatus(AbstractElementWidget widget, boolean hov public boolean isDisplayingComment() { return this.hoveredElementCommentTimer > 20 && - this.hoveredElementCommentTitle.isPresent() && - !this.hoveredElementCommentBody.isEmpty(); + this.hoveredElementCommentTitle.isPresent() && + !this.hoveredElementCommentBody.isEmpty(); } public Button getBottomRowOption() { diff --git a/src/main/java/net/coderbot/iris/helpers/ColorSRGB.java b/src/main/java/net/irisshaders/iris/helpers/ColorSRGB.java similarity index 97% rename from src/main/java/net/coderbot/iris/helpers/ColorSRGB.java rename to src/main/java/net/irisshaders/iris/helpers/ColorSRGB.java index 0da0b7bfd4..77e23b9fce 100644 --- a/src/main/java/net/coderbot/iris/helpers/ColorSRGB.java +++ b/src/main/java/net/irisshaders/iris/helpers/ColorSRGB.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.helpers; +package net.irisshaders.iris.helpers; -import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.util.FastColor; /** @@ -10,7 +9,7 @@ * The source code is provided under both the MIT and Apache-2.0 licenses, whichever is more suitable for your purposes. */ public class ColorSRGB { - private static final int[] TO_SRGB8_TABLE = new int[] { + private static final int[] TO_SRGB8_TABLE = new int[]{ 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d, 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a, 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033, @@ -26,7 +25,7 @@ public class ColorSRGB { 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723, }; - private static final float[] FROM_SRGB8_TABLE = new float[] { + private static final float[] FROM_SRGB8_TABLE = new float[]{ 0.0f, 0.000303527f, 0.000607054f, 0.00091058103f, 0.001214108f, 0.001517635f, 0.0018211621f, 0.002124689f, 0.002428216f, 0.002731743f, 0.00303527f, 0.0033465356f, 0.003676507f, 0.004024717f, 0.004391442f, 0.0047769533f, 0.005181517f, 0.0056053917f, 0.0060488326f, 0.006512091f, 0.00699541f, 0.0074990317f, @@ -69,6 +68,7 @@ public class ColorSRGB { /** * Converts a linear sRGB component into a non-linear RGB component. + * * @param c The non-linear sRGB component (0 to 255) * @return The linear RGB component (0.0 to 1.0) */ @@ -78,6 +78,7 @@ public static float srgbToLinear(int c) { /** * Converts the linear RGB components into non-linear sRGB space, and then packs them alongside a non-linear alpha. + * * @param r The red-component in non-linear sRGB space (0.0 to 1.0) * @param g The green-component in non-linear sRGB space (0.0 to 1.0) * @param b The blue-component in non-linear sRGB space (0.0 to 1.0) @@ -89,6 +90,7 @@ public static int linearToSrgb(float r, float g, float b, int a) { /** * Converts a linear RGB component into a non-linear SRGB8 component. + * * @param c The linear RGB component (0.0 to 1.0) * @return The non-linear SRGB8 component (0 to 255) */ diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/FakeChainedJsonException.java b/src/main/java/net/irisshaders/iris/helpers/FakeChainedJsonException.java similarity index 77% rename from src/main/java/net/coderbot/iris/pipeline/newshader/FakeChainedJsonException.java rename to src/main/java/net/irisshaders/iris/helpers/FakeChainedJsonException.java index 5d387a45b9..3224c8f88f 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/FakeChainedJsonException.java +++ b/src/main/java/net/irisshaders/iris/helpers/FakeChainedJsonException.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.helpers; -import net.coderbot.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.minecraft.server.ChainedJsonException; public class FakeChainedJsonException extends ChainedJsonException { diff --git a/src/main/java/net/coderbot/iris/JomlConversions.java b/src/main/java/net/irisshaders/iris/helpers/JomlConversions.java similarity index 83% rename from src/main/java/net/coderbot/iris/JomlConversions.java rename to src/main/java/net/irisshaders/iris/helpers/JomlConversions.java index dad3b68906..7c96c6dc31 100644 --- a/src/main/java/net/coderbot/iris/JomlConversions.java +++ b/src/main/java/net/irisshaders/iris/helpers/JomlConversions.java @@ -1,4 +1,4 @@ -package net.coderbot.iris; +package net.irisshaders.iris.helpers; import net.minecraft.world.phys.Vec3; import org.joml.Vector3d; diff --git a/src/main/java/net/coderbot/iris/shaderpack/OptionalBoolean.java b/src/main/java/net/irisshaders/iris/helpers/OptionalBoolean.java similarity index 90% rename from src/main/java/net/coderbot/iris/shaderpack/OptionalBoolean.java rename to src/main/java/net/irisshaders/iris/helpers/OptionalBoolean.java index 390eac4ec2..98563ecf61 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/OptionalBoolean.java +++ b/src/main/java/net/irisshaders/iris/helpers/OptionalBoolean.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.helpers; import java.util.function.BooleanSupplier; diff --git a/src/main/java/net/coderbot/iris/shaderpack/StringPair.java b/src/main/java/net/irisshaders/iris/helpers/StringPair.java similarity index 69% rename from src/main/java/net/coderbot/iris/shaderpack/StringPair.java rename to src/main/java/net/irisshaders/iris/helpers/StringPair.java index dc3fbc3768..ce8c248c68 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/StringPair.java +++ b/src/main/java/net/irisshaders/iris/helpers/StringPair.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.helpers; import org.jetbrains.annotations.NotNull; @@ -7,22 +7,21 @@ /** * An absurdly simple class for storing pairs of strings because Java lacks pair / tuple types. */ -public class StringPair { - private final String key; - private final String value; - +public record StringPair(String key, String value) { public StringPair(@NotNull String key, @NotNull String value) { this.key = Objects.requireNonNull(key); this.value = Objects.requireNonNull(value); } + @Override @NotNull - public String getKey() { + public String key() { return key; } + @Override @NotNull - public String getValue() { + public String value() { return value; } } diff --git a/src/main/java/net/irisshaders/iris/helpers/Tri.java b/src/main/java/net/irisshaders/iris/helpers/Tri.java new file mode 100644 index 0000000000..e0a6b383bc --- /dev/null +++ b/src/main/java/net/irisshaders/iris/helpers/Tri.java @@ -0,0 +1,17 @@ +package net.irisshaders.iris.helpers; + +public record Tri(X first, Y second, Z third) { + + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (!(obj instanceof Tri tri)) return false; + return tri.first == this.first && tri.second == this.second && tri.third == this.third; + } + + @Override + public String toString() { + return "First: " + first.toString() + " Second: " + second.toString() + " Third: " + third.toString(); + } +} diff --git a/src/main/java/net/coderbot/iris/fantastic/VertexBufferHelper.java b/src/main/java/net/irisshaders/iris/helpers/VertexBufferHelper.java similarity index 68% rename from src/main/java/net/coderbot/iris/fantastic/VertexBufferHelper.java rename to src/main/java/net/irisshaders/iris/helpers/VertexBufferHelper.java index bd77ec0151..94768c13cd 100644 --- a/src/main/java/net/coderbot/iris/fantastic/VertexBufferHelper.java +++ b/src/main/java/net/irisshaders/iris/helpers/VertexBufferHelper.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.fantastic; +package net.irisshaders.iris.helpers; public interface VertexBufferHelper { void saveBinding(); + void restoreBinding(); } diff --git a/src/main/java/net/coderbot/iris/layer/BlockEntityRenderStateShard.java b/src/main/java/net/irisshaders/iris/layer/BlockEntityRenderStateShard.java similarity index 91% rename from src/main/java/net/coderbot/iris/layer/BlockEntityRenderStateShard.java rename to src/main/java/net/irisshaders/iris/layer/BlockEntityRenderStateShard.java index 713bc33a05..b6390d063b 100644 --- a/src/main/java/net/coderbot/iris/layer/BlockEntityRenderStateShard.java +++ b/src/main/java/net/irisshaders/iris/layer/BlockEntityRenderStateShard.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; import net.minecraft.client.renderer.RenderStateShard; diff --git a/src/main/java/net/coderbot/iris/layer/EntityRenderStateShard.java b/src/main/java/net/irisshaders/iris/layer/EntityRenderStateShard.java similarity index 90% rename from src/main/java/net/coderbot/iris/layer/EntityRenderStateShard.java rename to src/main/java/net/irisshaders/iris/layer/EntityRenderStateShard.java index 6646a7d509..f76550cdbe 100644 --- a/src/main/java/net/coderbot/iris/layer/EntityRenderStateShard.java +++ b/src/main/java/net/irisshaders/iris/layer/EntityRenderStateShard.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; import net.minecraft.client.renderer.RenderStateShard; diff --git a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java b/src/main/java/net/irisshaders/iris/layer/GbufferPrograms.java similarity index 81% rename from src/main/java/net/coderbot/iris/layer/GbufferPrograms.java rename to src/main/java/net/irisshaders/iris/layer/GbufferPrograms.java index 4bb458598b..5a9306b088 100644 --- a/src/main/java/net/coderbot/iris/layer/GbufferPrograms.java +++ b/src/main/java/net/irisshaders/iris/layer/GbufferPrograms.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; public class GbufferPrograms { private static boolean entities; @@ -13,6 +12,11 @@ public class GbufferPrograms { private static Runnable phaseChangeListener; private static Runnable fallbackEntityListener; + static { + StateUpdateNotifiers.phaseChangeNotifier = listener -> phaseChangeListener = listener; + StateUpdateNotifiers.fallbackEntityNotifier = listener -> fallbackEntityListener = listener; + } + private static void checkReentrancy() { if (entities || blockEntities || outline) { throw new IllegalStateException("GbufferPrograms in weird state, tried to call begin function when entities = " @@ -103,19 +107,7 @@ public static void runFallbackEntityListener() { } } - public static void setupSpecialRenderCondition(SpecialCondition override) { - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(override)); - } - - public static void teardownSpecialRenderCondition(SpecialCondition override) { - Iris.getPipelineManager().getPipeline().ifPresent(p -> p.setSpecialCondition(null)); - } - - static { - StateUpdateNotifiers.phaseChangeNotifier = listener -> phaseChangeListener = listener; - StateUpdateNotifiers.fallbackEntityNotifier = listener -> fallbackEntityListener = listener; - } - + @SuppressWarnings("all") public static void init() { // Empty initializer to run static } diff --git a/src/main/java/net/coderbot/iris/layer/InnerWrappedRenderType.java b/src/main/java/net/irisshaders/iris/layer/InnerWrappedRenderType.java similarity index 89% rename from src/main/java/net/coderbot/iris/layer/InnerWrappedRenderType.java rename to src/main/java/net/irisshaders/iris/layer/InnerWrappedRenderType.java index 8b52114b0b..3f4e0dbf14 100644 --- a/src/main/java/net/coderbot/iris/layer/InnerWrappedRenderType.java +++ b/src/main/java/net/irisshaders/iris/layer/InnerWrappedRenderType.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import net.coderbot.iris.mixin.rendertype.RenderTypeAccessor; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.WrappableRenderType; +import net.irisshaders.iris.mixin.rendertype.RenderTypeAccessor; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; import org.jetbrains.annotations.Nullable; @@ -31,6 +31,10 @@ public static InnerWrappedRenderType wrapExactlyOnce(String name, RenderType wra return new InnerWrappedRenderType(name, wrapped, extra); } + private static boolean shouldSortOnUpload(RenderType type) { + return ((RenderTypeAccessor) type).shouldSortOnUpload(); + } + @Override public void setupRenderState() { super.setupRenderState(); @@ -87,10 +91,6 @@ public String toString() { return "iris_wrapped:" + this.wrapped.toString(); } - private static boolean shouldSortOnUpload(RenderType type) { - return ((RenderTypeAccessor) type).shouldSortOnUpload(); - } - @Override public TransparencyType getTransparencyType() { return ((BlendingStateHolder) wrapped).getTransparencyType(); diff --git a/src/main/java/net/coderbot/iris/layer/IsOutlineRenderStateShard.java b/src/main/java/net/irisshaders/iris/layer/IsOutlineRenderStateShard.java similarity index 90% rename from src/main/java/net/coderbot/iris/layer/IsOutlineRenderStateShard.java rename to src/main/java/net/irisshaders/iris/layer/IsOutlineRenderStateShard.java index 1163fb67c5..67f6300769 100644 --- a/src/main/java/net/coderbot/iris/layer/IsOutlineRenderStateShard.java +++ b/src/main/java/net/irisshaders/iris/layer/IsOutlineRenderStateShard.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; import net.minecraft.client.renderer.RenderStateShard; diff --git a/src/main/java/net/coderbot/iris/layer/LightningRenderStateShard.java b/src/main/java/net/irisshaders/iris/layer/LightningRenderStateShard.java similarity index 64% rename from src/main/java/net/coderbot/iris/layer/LightningRenderStateShard.java rename to src/main/java/net/irisshaders/iris/layer/LightningRenderStateShard.java index 309b3f17ce..6c909bc0d1 100644 --- a/src/main/java/net/coderbot/iris/layer/LightningRenderStateShard.java +++ b/src/main/java/net/irisshaders/iris/layer/LightningRenderStateShard.java @@ -1,25 +1,24 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.RenderStateShard; public class LightningRenderStateShard extends RenderStateShard { public static final LightningRenderStateShard INSTANCE = new LightningRenderStateShard(); - private static int backupValue = 0; - private static final NamespacedId LIGHT = new NamespacedId("minecraft", "lightning_bolt"); + private static int backupValue = 0; public LightningRenderStateShard() { super("iris:lightning", () -> { - if (BlockRenderingSettings.INSTANCE.getEntityIds() != null) { + if (WorldRenderingSettings.INSTANCE.getEntityIds() != null) { backupValue = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(); - CapturedRenderingState.INSTANCE.setCurrentEntity(BlockRenderingSettings.INSTANCE.getEntityIds().applyAsInt(LIGHT)); + CapturedRenderingState.INSTANCE.setCurrentEntity(WorldRenderingSettings.INSTANCE.getEntityIds().applyAsInt(LIGHT)); GbufferPrograms.runFallbackEntityListener(); } }, () -> { - if (BlockRenderingSettings.INSTANCE.getEntityIds() != null) { + if (WorldRenderingSettings.INSTANCE.getEntityIds() != null) { CapturedRenderingState.INSTANCE.setCurrentEntity(backupValue); backupValue = 0; GbufferPrograms.runFallbackEntityListener(); diff --git a/src/main/java/net/coderbot/iris/layer/OuterWrappedRenderType.java b/src/main/java/net/irisshaders/iris/layer/OuterWrappedRenderType.java similarity index 89% rename from src/main/java/net/coderbot/iris/layer/OuterWrappedRenderType.java rename to src/main/java/net/irisshaders/iris/layer/OuterWrappedRenderType.java index 6f9056004a..f695c6be94 100644 --- a/src/main/java/net/coderbot/iris/layer/OuterWrappedRenderType.java +++ b/src/main/java/net/irisshaders/iris/layer/OuterWrappedRenderType.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.layer; +package net.irisshaders.iris.layer; -import net.coderbot.batchedentityrendering.impl.BlendingStateHolder; -import net.coderbot.batchedentityrendering.impl.TransparencyType; -import net.coderbot.batchedentityrendering.impl.WrappableRenderType; -import net.coderbot.iris.mixin.rendertype.RenderTypeAccessor; +import net.irisshaders.batchedentityrendering.impl.BlendingStateHolder; +import net.irisshaders.batchedentityrendering.impl.TransparencyType; +import net.irisshaders.batchedentityrendering.impl.WrappableRenderType; +import net.irisshaders.iris.mixin.rendertype.RenderTypeAccessor; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType; import org.jetbrains.annotations.Nullable; @@ -31,6 +31,10 @@ public static OuterWrappedRenderType wrapExactlyOnce(String name, RenderType wra return new OuterWrappedRenderType(name, wrapped, extra); } + private static boolean shouldSortOnUpload(RenderType type) { + return ((RenderTypeAccessor) type).shouldSortOnUpload(); + } + @Override public void setupRenderState() { extra.setupRenderState(); @@ -87,10 +91,6 @@ public String toString() { return "iris_wrapped:" + this.wrapped.toString(); } - private static boolean shouldSortOnUpload(RenderType type) { - return ((RenderTypeAccessor) type).shouldSortOnUpload(); - } - @Override public TransparencyType getTransparencyType() { return ((BlendingStateHolder) wrapped).getTransparencyType(); diff --git a/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java b/src/main/java/net/irisshaders/iris/layer/WrappingMultiBufferSource.java similarity index 87% rename from src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java rename to src/main/java/net/irisshaders/iris/layer/WrappingMultiBufferSource.java index 009482b5e5..b1a167b424 100644 --- a/src/main/java/net/coderbot/iris/fantastic/WrappingMultiBufferSource.java +++ b/src/main/java/net/irisshaders/iris/layer/WrappingMultiBufferSource.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.fantastic; +package net.irisshaders.iris.layer; import net.minecraft.client.renderer.RenderType; @@ -6,6 +6,8 @@ public interface WrappingMultiBufferSource { void pushWrappingFunction(Function wrappingFunction); + void popWrappingFunction(); + void assertWrapStackEmpty(); } diff --git a/src/main/java/net/coderbot/iris/mixin/DimensionTypeAccessor.java b/src/main/java/net/irisshaders/iris/mixin/DimensionTypeAccessor.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/DimensionTypeAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/DimensionTypeAccessor.java index bf97e535da..e92406fc5d 100644 --- a/src/main/java/net/coderbot/iris/mixin/DimensionTypeAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/DimensionTypeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import net.minecraft.world.level.dimension.DimensionType; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/GameRendererAccessor.java b/src/main/java/net/irisshaders/iris/mixin/GameRendererAccessor.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/GameRendererAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/GameRendererAccessor.java index 88d4e837dc..d51bcd3412 100644 --- a/src/main/java/net/coderbot/iris/mixin/GameRendererAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/GameRendererAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Camera; @@ -22,5 +22,5 @@ public interface GameRendererAccessor { void invokeBobHurt(PoseStack poseStack, float tickDelta); @Invoker - double invokeGetFov(Camera camera, float tickDelta, boolean b); + double invokeGetFov(Camera camera, float tickDelta, boolean b); } diff --git a/src/main/java/net/coderbot/iris/mixin/GlStateManagerAccessor.java b/src/main/java/net/irisshaders/iris/mixin/GlStateManagerAccessor.java similarity index 96% rename from src/main/java/net/coderbot/iris/mixin/GlStateManagerAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/GlStateManagerAccessor.java index af1104c4dc..85a1abc4c6 100644 --- a/src/main/java/net/coderbot/iris/mixin/GlStateManagerAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/GlStateManagerAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/LevelRendererAccessor.java b/src/main/java/net/irisshaders/iris/mixin/LevelRendererAccessor.java similarity index 97% rename from src/main/java/net/coderbot/iris/mixin/LevelRendererAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/LevelRendererAccessor.java index 5ee95095aa..9fd9d7ce01 100644 --- a/src/main/java/net/coderbot/iris/mixin/LevelRendererAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/LevelRendererAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.ObjectList; diff --git a/src/main/java/net/coderbot/iris/mixin/LightTextureAccessor.java b/src/main/java/net/irisshaders/iris/mixin/LightTextureAccessor.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/LightTextureAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/LightTextureAccessor.java index 63f7342fbe..5790e063a1 100644 --- a/src/main/java/net/coderbot/iris/mixin/LightTextureAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/LightTextureAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.texture.DynamicTexture; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinBiome.java b/src/main/java/net/irisshaders/iris/mixin/MixinBiome.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/MixinBiome.java rename to src/main/java/net/irisshaders/iris/mixin/MixinBiome.java index 784ac4a0e9..836a85d16f 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinBiome.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinBiome.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.parsing.ExtendedBiome; +import net.irisshaders.iris.parsing.ExtendedBiome; import net.minecraft.world.level.biome.Biome; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -14,13 +14,13 @@ public class MixinBiome implements ExtendedBiome { private int biomeCategory = -1; @Override - public void setBiomeCategory(int biomeCategory) { - this.biomeCategory = biomeCategory; + public int getBiomeCategory() { + return biomeCategory; } @Override - public int getBiomeCategory() { - return biomeCategory; + public void setBiomeCategory(int biomeCategory) { + this.biomeCategory = biomeCategory; } @Override diff --git a/src/main/java/net/coderbot/iris/mixin/MixinBiomes.java b/src/main/java/net/irisshaders/iris/mixin/MixinBiomes.java similarity index 79% rename from src/main/java/net/coderbot/iris/mixin/MixinBiomes.java rename to src/main/java/net/irisshaders/iris/mixin/MixinBiomes.java index ced624948c..f045b9e984 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinBiomes.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinBiomes.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.uniforms.BiomeParameters; +import net.irisshaders.iris.uniforms.BiomeUniforms; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; @@ -15,6 +15,6 @@ public class MixinBiomes { @Inject(method = "register", at = @At("TAIL")) private static void iris$registerBiome(String string, CallbackInfoReturnable> cir) { - BiomeParameters.getBiomeMap().put(cir.getReturnValue(), currentId++); + BiomeUniforms.getBiomeMap().put(cir.getReturnValue(), currentId++); } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinBlockStateBehavior.java b/src/main/java/net/irisshaders/iris/mixin/MixinBlockStateBehavior.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/MixinBlockStateBehavior.java rename to src/main/java/net/irisshaders/iris/mixin/MixinBlockStateBehavior.java index c56eb15de5..a5e5941dbc 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinBlockStateBehavior.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinBlockStateBehavior.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.Block; @@ -43,7 +43,7 @@ public abstract class MixinBlockStateBehavior { @SuppressWarnings("deprecation") public float getShadeBrightness(BlockGetter blockGetter, BlockPos blockPos) { float originalValue = this.getBlock().getShadeBrightness(this.asState(), blockGetter, blockPos); - float aoLightValue = BlockRenderingSettings.INSTANCE.getAmbientOcclusionLevel(); + float aoLightValue = WorldRenderingSettings.INSTANCE.getAmbientOcclusionLevel(); return 1.0F - aoLightValue * (1.0F - originalValue); } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinBooleanState.java b/src/main/java/net/irisshaders/iris/mixin/MixinBooleanState.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/MixinBooleanState.java rename to src/main/java/net/irisshaders/iris/mixin/MixinBooleanState.java index edb1815624..a25beda3b0 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinBooleanState.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinBooleanState.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.BooleanStateExtended; +import net.irisshaders.iris.gl.BooleanStateExtended; import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -13,11 +13,11 @@ @Mixin(GlStateManager.BooleanState.class) public class MixinBooleanState implements BooleanStateExtended { + @Shadow + public boolean enabled; @Shadow @Final private int state; - @Shadow - public boolean enabled; @Unique private boolean stateUnknown; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinChainedJsonException.java b/src/main/java/net/irisshaders/iris/mixin/MixinChainedJsonException.java similarity index 80% rename from src/main/java/net/coderbot/iris/mixin/MixinChainedJsonException.java rename to src/main/java/net/irisshaders/iris/mixin/MixinChainedJsonException.java index 858c14ad4b..33f3d2a3d8 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinChainedJsonException.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinChainedJsonException.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.pipeline.newshader.FakeChainedJsonException; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.helpers.FakeChainedJsonException; import net.minecraft.server.ChainedJsonException; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinClientLanguage.java b/src/main/java/net/irisshaders/iris/mixin/MixinClientLanguage.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/MixinClientLanguage.java rename to src/main/java/net/irisshaders/iris/mixin/MixinClientLanguage.java index dd2e6e5b2f..624cb75180 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinClientLanguage.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinClientLanguage.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.LanguageMap; -import net.coderbot.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.LanguageMap; +import net.irisshaders.iris.shaderpack.ShaderPack; import net.minecraft.client.resources.language.ClientLanguage; -import net.minecraft.client.resources.language.LanguageInfo; import net.minecraft.locale.Language; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; @@ -19,8 +18,6 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; @@ -31,8 +28,9 @@ * *

    We "sideload" the language entries with an override system to avoid having to reload the * resource manager on shader pack changes, since reloading the resource manager is very slow.

    - * + *

    * Uses a lower priority to inject before Incubus-Core to prevent translations from breaking + * * @see Incubus-Core translation mixin */ @Mixin(value = ClientLanguage.class, priority = 990) @@ -57,6 +55,15 @@ private static void injectFrom(String string, List list, Map definitions, boolean bl, CallbackInfoReturnable cir) { + // Make sure the language codes don't carry over! + languageCodes.clear(); + + // Reverse order due to how minecraft has English and then the primary language in the language definitions list + new LinkedList<>(definitions).descendingIterator().forEachRemaining(languageCodes::add); + } + @Inject(method = "getOrDefault", at = @At("HEAD"), cancellable = true) private void iris$addLanguageEntries(String key, String value, CallbackInfoReturnable cir) { String override = iris$lookupOverriddenEntry(key); @@ -111,15 +118,4 @@ private static void injectFrom(String string, List list, Map definitions, boolean bl, CallbackInfoReturnable cir) { - // Make sure the language codes don't carry over! - languageCodes.clear(); - - // Reverse order due to how minecraft has English and then the primary language in the language definitions list - new LinkedList<>(definitions).descendingIterator().forEachRemaining(languageDefinition -> { - languageCodes.add(languageDefinition); - }); - } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinClientPacketListener.java b/src/main/java/net/irisshaders/iris/mixin/MixinClientPacketListener.java similarity index 67% rename from src/main/java/net/coderbot/iris/mixin/MixinClientPacketListener.java rename to src/main/java/net/irisshaders/iris/mixin/MixinClientPacketListener.java index 8446e81652..0e91393315 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinClientPacketListener.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinClientPacketListener.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.shader.ShaderCompileException; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientPacketListener; @@ -27,5 +27,12 @@ public class MixinClientPacketListener { Iris.getStoredError().ifPresent(e -> this.minecraft.player.displayClientMessage(Component.translatable(e instanceof ShaderCompileException ? "iris.load.failure.shader" : "iris.load.failure.generic").append(Component.literal("Copy Info").withStyle(arg -> arg.withUnderlined(true).withColor(ChatFormatting.BLUE).withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, e.getMessage())))), false)); - } + + if (Iris.loadedIncompatiblePack()) { + Minecraft.getInstance().gui.setTimes(10, 70, 140); + Iris.logger.warn("Incompatible pack for DH!"); + Minecraft.getInstance().player.displayClientMessage(Component.literal("This pack doesn't have DH support.").withStyle(ChatFormatting.BOLD, ChatFormatting.RED), false); + Minecraft.getInstance().player.displayClientMessage(Component.literal("Distant Horizons (DH) chunks won't show up. This isn't a bug, get another shader.").withStyle(ChatFormatting.RED), false); + } + } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinDebugScreenOverlay.java b/src/main/java/net/irisshaders/iris/mixin/MixinDebugScreenOverlay.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/MixinDebugScreenOverlay.java rename to src/main/java/net/irisshaders/iris/mixin/MixinDebugScreenOverlay.java index d7e960f579..5f51a10a17 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinDebugScreenOverlay.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinDebugScreenOverlay.java @@ -1,10 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.minecraft.ChatFormatting; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.option.IrisVideoSettings; import net.minecraft.client.gui.components.DebugScreenOverlay; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -39,9 +37,32 @@ public abstract class MixinDebugScreenOverlay { iris$directPool = Objects.requireNonNull(found); } - @Inject(method = "getSystemInformation", at = @At("RETURN")) - private void iris$appendShaderPackText(CallbackInfoReturnable> cir) { - List messages = cir.getReturnValue(); + // stackoverflow.com/a/3758880 + @Unique + private static String iris$humanReadableByteCountBin(long bytes) { + long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); + if (absB < 1024) { + return bytes + " B"; + } + long value = absB; + CharacterIterator ci = new StringCharacterIterator("KMGTPE"); + for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) { + value >>= 10; + ci.next(); + } + value *= Long.signum(bytes); + return String.format("%.3f %ciB", value / 1024.0, ci.current()); + } + + // From Sodium + @Unique + private static long iris$getNativeMemoryUsage() { + return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); + } + + @Inject(method = "getSystemInformation", at = @At("RETURN")) + private void iris$appendShaderPackText(CallbackInfoReturnable> cir) { + List messages = cir.getReturnValue(); messages.add(""); messages.add("[" + Iris.MODNAME + "] Version: " + Iris.getFormattedVersion()); @@ -75,27 +96,4 @@ public abstract class MixinDebugScreenOverlay { Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.addDebugText(messages)); } - - // stackoverflow.com/a/3758880 - @Unique - private static String iris$humanReadableByteCountBin(long bytes) { - long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); - if (absB < 1024) { - return bytes + " B"; - } - long value = absB; - CharacterIterator ci = new StringCharacterIterator("KMGTPE"); - for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) { - value >>= 10; - ci.next(); - } - value *= Long.signum(bytes); - return String.format("%.3f %ciB", value / 1024.0, ci.current()); - } - - // From Sodium - @Unique - private static long iris$getNativeMemoryUsage() { - return ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); - } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinEntityRenderDispatcher.java b/src/main/java/net/irisshaders/iris/mixin/MixinEntityRenderDispatcher.java similarity index 80% rename from src/main/java/net/coderbot/iris/mixin/MixinEntityRenderDispatcher.java rename to src/main/java/net/irisshaders/iris/mixin/MixinEntityRenderDispatcher.java index 742661ca7e..040cda5d60 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinEntityRenderDispatcher.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinEntityRenderDispatcher.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import it.unimi.dsi.fastutil.objects.Object2IntFunction; -import net.coderbot.iris.Iris; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; import net.minecraft.core.BlockPos; @@ -43,7 +43,7 @@ public class MixinEntityRenderDispatcher { Entity entity, float opacity, float tickDelta, LevelReader level, float radius, CallbackInfo ci) { if (!iris$maybeSuppressShadow(ci)) { - Object2IntFunction entityIds = BlockRenderingSettings.INSTANCE.getEntityIds(); + Object2IntFunction entityIds = WorldRenderingSettings.INSTANCE.getEntityIds(); if (entityIds == null) { return; @@ -60,24 +60,6 @@ private static void restoreShadow(PoseStack pPoseStack0, MultiBufferSource pMult cachedId = 0; } - @Inject(method = "renderFlame", at = @At("HEAD")) - private void iris$setFlameId(PoseStack pEntityRenderDispatcher0, MultiBufferSource pMultiBufferSource1, Entity pEntity2, CallbackInfo ci) { - Object2IntFunction entityIds = BlockRenderingSettings.INSTANCE.getEntityIds(); - - if (entityIds == null) { - return; - } - - cachedId = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(); - CapturedRenderingState.INSTANCE.setCurrentEntity(entityIds.getInt(flameId)); - } - - @Inject(method = "renderFlame", at = @At("RETURN")) - private void restoreFlameId(PoseStack pEntityRenderDispatcher0, MultiBufferSource pMultiBufferSource1, Entity pEntity2, CallbackInfo ci) { - CapturedRenderingState.INSTANCE.setCurrentEntity(cachedId); - cachedId = 0; - } - // The underlying method called by renderShadow. @Inject(method = "renderBlockShadow", at = @At("HEAD"), cancellable = true) private static void renderBlockShadow(PoseStack.Pose pPoseStack$Pose0, VertexConsumer pVertexConsumer1, ChunkAccess pChunkAccess2, LevelReader pLevelReader3, BlockPos pBlockPos4, double pDouble5, double pDouble6, double pDouble7, float pFloat8, float pFloat9, CallbackInfo ci) { @@ -87,8 +69,8 @@ private static void renderBlockShadow(PoseStack.Pose pPoseStack$Pose0, VertexCon // First Person Model by tr7zw compatibility, this is a method added by First Person Model: // https://github.com/tr7zw/FirstPersonModel/blob/172ab05368832df82e34ca9f9b06814672f69f59/FPShared/src/main/java/dev/tr7zw/firstperson/mixins/RenderDispatcherMixin.java#L68 // The renderBlockShadow injection will handle this, but it's easier to suppress it before all of the other calculations. - @SuppressWarnings("target") - @Inject(method = "renderOffsetShadow", at = @At("HEAD"), cancellable = true, require = 0, remap=false) + @SuppressWarnings("all") + @Inject(method = "renderOffsetShadow", at = @At("HEAD"), cancellable = true, require = 0, remap = false, expect = 0) private static void iris$maybeSuppressEntityShadow(PoseStack poseStack, MultiBufferSource bufferSource, Entity entity, float opacity, float tickDelta, LevelReader level, float radius, Vec3 offset, CallbackInfo ci) { @@ -106,4 +88,22 @@ private static void renderBlockShadow(PoseStack.Pose pPoseStack$Pose0, VertexCon return false; } + + @Inject(method = "renderFlame", at = @At("HEAD")) + private void iris$setFlameId(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, CallbackInfo ci) { + Object2IntFunction entityIds = WorldRenderingSettings.INSTANCE.getEntityIds(); + + if (entityIds == null) { + return; + } + + cachedId = CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(); + CapturedRenderingState.INSTANCE.setCurrentEntity(entityIds.getInt(flameId)); + } + + @Inject(method = "renderFlame", at = @At("RETURN")) + private void restoreFlameId(PoseStack poseStack, MultiBufferSource multiBufferSource, Entity entity, CallbackInfo ci) { + CapturedRenderingState.INSTANCE.setCurrentEntity(cachedId); + cachedId = 0; + } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinFogRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinFogRenderer.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/MixinFogRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinFogRenderer.java index 6c0d53c50e..356f63655f 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinFogRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinFogRenderer.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.Camera; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; @@ -18,7 +18,8 @@ @Mixin(FogRenderer.class) public class MixinFogRenderer { - @Shadow private static float fogRed, fogGreen, fogBlue; + @Shadow + private static float fogRed, fogGreen, fogBlue; @Inject(method = "setupFog", at = @At("HEAD")) private static void iris$setupLegacyWaterFog(Camera camera, FogRenderer.FogMode $$1, float $$2, boolean $$3, float $$4, CallbackInfo ci) { @@ -27,8 +28,7 @@ public class MixinFogRenderer { float density = 0.05F; - if (entity instanceof LocalPlayer) { - LocalPlayer localPlayer = (LocalPlayer)entity; + if (entity instanceof LocalPlayer localPlayer) { density -= localPlayer.getWaterVision() * localPlayer.getWaterVision() * 0.03F; Holder biome = localPlayer.level().getBiome(localPlayer.blockPosition()); diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGameRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer.java similarity index 88% rename from src/main/java/net/coderbot/iris/mixin/MixinGameRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer.java index e24901c098..f1304692bb 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGameRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer.java @@ -1,35 +1,32 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.google.common.collect.Lists; import com.mojang.blaze3d.platform.GlUtil; import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.vertex.PoseStack; - -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.HandRenderer; -import net.coderbot.iris.pipeline.ShadowRenderer; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.CoreWorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.IrisProgramTypes; -import net.coderbot.iris.pipeline.newshader.ShaderKey; - +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApi; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - +import net.irisshaders.iris.gl.program.IrisProgramTypes; +import net.irisshaders.iris.pathways.HandRenderer; +import net.irisshaders.iris.pipeline.ShaderRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.pipeline.programs.ShaderKey; +import net.irisshaders.iris.shadows.ShadowRenderer; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ItemInHandRenderer; -import net.minecraft.client.renderer.RenderBuffers; import net.minecraft.client.renderer.MultiBufferSource.BufferSource; +import net.minecraft.client.renderer.RenderBuffers; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.server.packs.resources.ResourceManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.ArrayList; @@ -39,39 +36,6 @@ public class MixinGameRenderer { @Shadow private boolean renderHand; - @Inject(method = "", at = @At("TAIL")) - private void iris$logSystem(Minecraft arg, ItemInHandRenderer arg2, ResourceManager arg3, RenderBuffers arg4, CallbackInfo ci) { - Iris.logger.info("Hardware information:"); - Iris.logger.info("CPU: " + GlUtil.getCpuInfo()); - Iris.logger.info("GPU: " + GlUtil.getRenderer() + " (Supports OpenGL " + GlUtil.getOpenGLVersion() + ")"); - Iris.logger.info("OS: " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ")"); - } - - @Redirect(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderHandsWithItems(FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/player/LocalPlayer;I)V")) - private void iris$disableVanillaHandRendering(ItemInHandRenderer itemInHandRenderer, float tickDelta, PoseStack poseStack, BufferSource bufferSource, LocalPlayer localPlayer, int light) { - if (IrisApi.getInstance().isShaderPackInUse()) { - return; - } - - itemInHandRenderer.renderHandsWithItems(tickDelta, poseStack, bufferSource, localPlayer, light); - } - - @Inject(method = "renderLevel", at = @At("TAIL")) - private void iris$runColorSpace(float pGameRenderer0, long pLong1, PoseStack pPoseStack2, CallbackInfo ci) { - Iris.getPipelineManager().getPipeline().ifPresent(WorldRenderingPipeline::finalizeGameRendering); - } - - @Redirect(method = "reloadShaders", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Lists;newArrayList()Ljava/util/ArrayList;")) - private ArrayList iris$reloadGeometryShaders() { - ArrayList programs = Lists.newArrayList(); - programs.addAll(IrisProgramTypes.GEOMETRY.getPrograms().values()); - programs.addAll(IrisProgramTypes.TESS_CONTROL.getPrograms().values()); - programs.addAll(IrisProgramTypes.TESS_EVAL.getPrograms().values()); - return programs; - } - - //TODO: check cloud phase - @Inject(method = "getPositionShader", at = @At("HEAD"), cancellable = true) private static void iris$overridePositionShader(CallbackInfoReturnable cir) { if (isSky()) { @@ -115,11 +79,14 @@ public class MixinGameRenderer { override(ShaderKey.TEXTURED_COLOR, cir); } } + + //TODO: check cloud phase + @Inject(method = { - "getParticleShader" + "getParticleShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideParticleShader(CallbackInfoReturnable cir) { - if(isPhase(WorldRenderingPhase.RAIN_SNOW)) { + if (isPhase(WorldRenderingPhase.RAIN_SNOW)) { override(ShaderKey.WEATHER, cir); } else if (ShadowRenderer.ACTIVE) { override(ShaderKey.SHADOW_PARTICLES, cir); @@ -128,8 +95,6 @@ public class MixinGameRenderer { } } - // TODO: getPositionColorLightmapShader - @Inject(method = "getPositionTexColorNormalShader", at = @At("HEAD"), cancellable = true) private static void iris$overridePositionTexColorNormalShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -139,8 +104,6 @@ public class MixinGameRenderer { } } - // TODO: getPositionTexLightmapColorShader - @Inject(method = "getRendertypeSolidShader", at = @At("HEAD"), cancellable = true) private static void iris$overrideSolidShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -183,13 +146,15 @@ public class MixinGameRenderer { } } + // TODO: getPositionColorLightmapShader + @Inject(method = { - "getRendertypeEntityCutoutShader", - "getRendertypeEntityCutoutNoCullShader", - "getRendertypeEntityCutoutNoCullZOffsetShader", - "getRendertypeEntityDecalShader", - "getRendertypeEntitySmoothCutoutShader", - "getRendertypeArmorCutoutNoCullShader" + "getRendertypeEntityCutoutShader", + "getRendertypeEntityCutoutNoCullShader", + "getRendertypeEntityCutoutNoCullZOffsetShader", + "getRendertypeEntityDecalShader", + "getRendertypeEntitySmoothCutoutShader", + "getRendertypeArmorCutoutNoCullShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideEntityCutoutShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -203,6 +168,8 @@ public class MixinGameRenderer { } } + // TODO: getPositionTexLightmapColorShader + @Inject(method = { "getRendertypeEntityTranslucentShader", "getRendertypeEntityTranslucentCullShader", @@ -222,10 +189,10 @@ public class MixinGameRenderer { } } - @Inject(method = { - "getRendertypeEnergySwirlShader", - "getRendertypeEntityShadowShader" - }, at = @At("HEAD"), cancellable = true) + @Inject(method = { + "getRendertypeEnergySwirlShader", + "getRendertypeEntityShadowShader" + }, at = @At("HEAD"), cancellable = true) private static void iris$overrideEnergySwirlShadowShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { override(ShaderKey.SHADOW_ENTITIES_CUTOUT, cir); @@ -239,13 +206,13 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeGlintShader", - "getRendertypeGlintDirectShader", - "getRendertypeGlintTranslucentShader", - "getRendertypeArmorGlintShader", - "getRendertypeEntityGlintDirectShader", - "getRendertypeEntityGlintShader", - "getRendertypeArmorEntityGlintShader" + "getRendertypeGlintShader", + "getRendertypeGlintDirectShader", + "getRendertypeGlintTranslucentShader", + "getRendertypeArmorGlintShader", + "getRendertypeEntityGlintDirectShader", + "getRendertypeEntityGlintShader", + "getRendertypeArmorEntityGlintShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideGlintShader(CallbackInfoReturnable cir) { if (shouldOverrideShaders()) { @@ -254,7 +221,7 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeEntitySolidShader" + "getRendertypeEntitySolidShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideEntitySolidDiffuseShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -269,7 +236,7 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeWaterMaskShader" + "getRendertypeWaterMaskShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideEntitySolidShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -298,10 +265,9 @@ public class MixinGameRenderer { override(ShaderKey.ENTITIES_ALPHA, cir); } } - // NOTE: getRenderTypeOutlineShader should not be overriden. @Inject(method = { - "getRendertypeEyesShader" + "getRendertypeEyesShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideEntityEyesShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -328,7 +294,7 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeLeashShader" + "getRendertypeLeashShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideLeashShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -339,7 +305,7 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeLightningShader" + "getRendertypeLightningShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideLightningShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -348,9 +314,10 @@ public class MixinGameRenderer { override(ShaderKey.LIGHTNING, cir); } } + // NOTE: getRenderTypeOutlineShader should not be overriden. @Inject(method = { - "getRendertypeCrumblingShader" + "getRendertypeCrumblingShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideCrumblingShader(CallbackInfoReturnable cir) { if (shouldOverrideShaders() && !ShadowRenderer.ACTIVE) { @@ -359,9 +326,9 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeTextShader", - "getRendertypeTextSeeThroughShader", - "getPositionColorTexLightmapShader" + "getRendertypeTextShader", + "getRendertypeTextSeeThroughShader", + "getPositionColorTexLightmapShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideTextShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -388,8 +355,8 @@ public class MixinGameRenderer { } @Inject(method = { - "getRendertypeTextIntensityShader", - "getRendertypeTextIntensitySeeThroughShader" + "getRendertypeTextIntensityShader", + "getRendertypeTextIntensitySeeThroughShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideTextIntensityShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -403,11 +370,8 @@ public class MixinGameRenderer { } } - // ignored: getRendertypeEndGatewayShader (we replace the end portal rendering for shaders) - // ignored: getRendertypeEndPortalShader (we replace the end portal rendering for shaders) - @Inject(method = { - "getRendertypeLinesShader" + "getRendertypeLinesShader" }, at = @At("HEAD"), cancellable = true) private static void iris$overrideLinesShader(CallbackInfoReturnable cir) { if (ShadowRenderer.ACTIVE) { @@ -433,22 +397,18 @@ private static boolean isSky() { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); if (pipeline != null) { - switch (pipeline.getPhase()) { - case CUSTOM_SKY: - case SKY: - case SUNSET: - case SUN: - case STARS: - case VOID: - case MOON: - return true; - default: return false; - } + return switch (pipeline.getPhase()) { + case CUSTOM_SKY, SKY, SUNSET, SUN, STARS, VOID, MOON -> true; + default -> false; + }; } else { return false; } } + // ignored: getRendertypeEndGatewayShader (we replace the end portal rendering for shaders) + // ignored: getRendertypeEndPortalShader (we replace the end portal rendering for shaders) + private static boolean isPhase(WorldRenderingPhase phase) { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); @@ -462,8 +422,8 @@ private static boolean isPhase(WorldRenderingPhase phase) { private static boolean shouldOverrideShaders() { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); - if (pipeline instanceof CoreWorldRenderingPipeline) { - return ((CoreWorldRenderingPipeline) pipeline).shouldOverrideShaders(); + if (pipeline instanceof ShaderRenderingPipeline) { + return ((ShaderRenderingPipeline) pipeline).shouldOverrideShaders(); } else { return false; } @@ -472,12 +432,43 @@ private static boolean shouldOverrideShaders() { private static void override(ShaderKey key, CallbackInfoReturnable cir) { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); - if (pipeline instanceof CoreWorldRenderingPipeline) { - ShaderInstance override = ((CoreWorldRenderingPipeline) pipeline).getShaderMap().getShader(key); + if (pipeline instanceof ShaderRenderingPipeline) { + ShaderInstance override = ((ShaderRenderingPipeline) pipeline).getShaderMap().getShader(key); if (override != null) { cir.setReturnValue(override); } } } + + @Inject(method = "", at = @At("TAIL")) + private void iris$logSystem(Minecraft arg, ItemInHandRenderer arg2, ResourceManager arg3, RenderBuffers arg4, CallbackInfo ci) { + Iris.logger.info("Hardware information:"); + Iris.logger.info("CPU: " + GlUtil.getCpuInfo()); + Iris.logger.info("GPU: " + GlUtil.getRenderer() + " (Supports OpenGL " + GlUtil.getOpenGLVersion() + ")"); + Iris.logger.info("OS: " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ")"); + } + + @Redirect(method = "renderItemInHand", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/ItemInHandRenderer;renderHandsWithItems(FLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/player/LocalPlayer;I)V")) + private void iris$disableVanillaHandRendering(ItemInHandRenderer itemInHandRenderer, float tickDelta, PoseStack poseStack, BufferSource bufferSource, LocalPlayer localPlayer, int light) { + if (IrisApi.getInstance().isShaderPackInUse()) { + return; + } + + itemInHandRenderer.renderHandsWithItems(tickDelta, poseStack, bufferSource, localPlayer, light); + } + + @Inject(method = "renderLevel", at = @At("TAIL")) + private void iris$runColorSpace(float pGameRenderer0, long pLong1, PoseStack pPoseStack2, CallbackInfo ci) { + Iris.getPipelineManager().getPipeline().ifPresent(WorldRenderingPipeline::finalizeGameRendering); + } + + @Redirect(method = "reloadShaders", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Lists;newArrayList()Ljava/util/ArrayList;")) + private ArrayList iris$reloadGeometryShaders() { + ArrayList programs = Lists.newArrayList(); + programs.addAll(IrisProgramTypes.GEOMETRY.getPrograms().values()); + programs.addAll(IrisProgramTypes.TESS_CONTROL.getPrograms().values()); + programs.addAll(IrisProgramTypes.TESS_EVAL.getPrograms().values()); + return programs; + } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGameRenderer_NightVisionCompat.java b/src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer_NightVisionCompat.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/MixinGameRenderer_NightVisionCompat.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer_NightVisionCompat.java index 3d138c4f7b..229fd8c338 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGameRenderer_NightVisionCompat.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGameRenderer_NightVisionCompat.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.world.effect.MobEffects; @@ -18,10 +18,10 @@ public class MixinGameRenderer_NightVisionCompat { // It's optional because of Night Vision Flash Be Gone overwriting this method, but having this injection // succeed avoids a lot of spurious (but silently caught) NullPointerExceptions. @Inject(method = "getNightVisionScale", at = @At(value = "INVOKE", - target = "Lnet/minecraft/world/effect/MobEffectInstance;endsWithin(I)Z"), cancellable = true, - require = 0) + target = "Lnet/minecraft/world/effect/MobEffectInstance;endsWithin(I)Z"), cancellable = true, + require = 0) private static void iris$safecheckNightvisionStrength(LivingEntity livingEntity, float partialTicks, - CallbackInfoReturnable cir){ + CallbackInfoReturnable cir) { if (livingEntity.getEffect(MobEffects.NIGHT_VISION) == null) { cir.setReturnValue(0.0f); } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager.java b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager.java similarity index 88% rename from src/main/java/net/coderbot/iris/mixin/MixinGlStateManager.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager.java index 583f08861d..1f6f0622bf 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.sampler.SamplerLimits; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_BlendOverride.java b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_BlendOverride.java similarity index 86% rename from src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_BlendOverride.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_BlendOverride.java index a53a9f26d0..335f2f3d6e 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_BlendOverride.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_BlendOverride.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.blending.BlendModeStorage; +import net.irisshaders.iris.gl.blending.BlendModeStorage; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -19,7 +19,7 @@ public class MixinGlStateManager_BlendOverride { @Inject(method = "_enableBlend", at = @At("HEAD"), cancellable = true) private static void iris$blendEnableLock(CallbackInfo ci) { - if(BlendModeStorage.isBlendLocked()) { + if (BlendModeStorage.isBlendLocked()) { BlendModeStorage.deferBlendModeToggle(true); ci.cancel(); } @@ -27,7 +27,7 @@ public class MixinGlStateManager_BlendOverride { @Inject(method = "_blendFunc", at = @At("HEAD"), cancellable = true) private static void iris$blendFuncLock(int srcFactor, int dstFactor, CallbackInfo ci) { - if(BlendModeStorage.isBlendLocked()) { + if (BlendModeStorage.isBlendLocked()) { BlendModeStorage.deferBlendFunc(srcFactor, dstFactor, srcFactor, dstFactor); ci.cancel(); } @@ -35,7 +35,7 @@ public class MixinGlStateManager_BlendOverride { @Inject(method = "_blendFuncSeparate", at = @At("HEAD"), cancellable = true) private static void iris$blendFuncSeparateLock(int srcRgb, int dstRgb, int srcAlpha, int dstAlpha, CallbackInfo ci) { - if(BlendModeStorage.isBlendLocked()) { + if (BlendModeStorage.isBlendLocked()) { BlendModeStorage.deferBlendFunc(srcRgb, dstRgb, srcAlpha, dstAlpha); ci.cancel(); } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_DepthColorOverride.java b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_DepthColorOverride.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_DepthColorOverride.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_DepthColorOverride.java index 9b08affe82..0e60cf30ef 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_DepthColorOverride.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_DepthColorOverride.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.blending.DepthColorStorage; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.gl.blending.DepthColorStorage; +import net.irisshaders.iris.vertices.ImmediateState; import org.lwjgl.opengl.GL43C; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_FramebufferBinding.java b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_FramebufferBinding.java similarity index 98% rename from src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_FramebufferBinding.java rename to src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_FramebufferBinding.java index bc3fa85520..48c82bd441 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinGlStateManager_FramebufferBinding.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinGlStateManager_FramebufferBinding.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlConst; import com.mojang.blaze3d.platform.GlStateManager; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinItem.java b/src/main/java/net/irisshaders/iris/mixin/MixinItem.java similarity index 86% rename from src/main/java/net/coderbot/iris/mixin/MixinItem.java rename to src/main/java/net/irisshaders/iris/mixin/MixinItem.java index 0ff1ce5958..9eabe69909 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinItem.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinItem.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import net.irisshaders.iris.api.v0.item.IrisItemLightProvider; import net.minecraft.world.item.Item; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinItemBlockRenderTypes.java b/src/main/java/net/irisshaders/iris/mixin/MixinItemBlockRenderTypes.java similarity index 53% rename from src/main/java/net/coderbot/iris/mixin/MixinItemBlockRenderTypes.java rename to src/main/java/net/irisshaders/iris/mixin/MixinItemBlockRenderTypes.java index c719be9856..1ec44f6673 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinItemBlockRenderTypes.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinItemBlockRenderTypes.java @@ -1,13 +1,10 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.client.renderer.ItemBlockRenderTypes; import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Holder; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.registries.ForgeRegistries; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -17,14 +14,14 @@ @Mixin(ItemBlockRenderTypes.class) public class MixinItemBlockRenderTypes { - @Inject(method = "getRenderLayers", at = @At("HEAD"), cancellable = true, remap = false) - private static void iris$setCustomRenderType(BlockState arg, CallbackInfoReturnable cir) { - Map, ChunkRenderTypeSet> idMap = BlockRenderingSettings.INSTANCE.getBlockTypeIds(); + @Inject(method = "getChunkRenderType", at = @At("HEAD"), cancellable = true) + private static void iris$setCustomRenderType(BlockState arg, CallbackInfoReturnable cir) { + Map idMap = WorldRenderingSettings.INSTANCE.getBlockTypeIds(); if (idMap != null) { - ChunkRenderTypeSet type = idMap.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(arg.getBlock())); + RenderType type = idMap.get(arg.getBlock()); if (type != null) { cir.setReturnValue(type); } } } -} +} \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/mixin/MixinItemInHandRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinItemInHandRenderer.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/MixinItemInHandRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinItemInHandRenderer.java index 8ef79236a6..2e7c019d71 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinItemInHandRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinItemInHandRenderer.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.pipeline.HandRenderer; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.pathways.HandRenderer; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.renderer.ItemInHandRenderer; import net.minecraft.client.renderer.MultiBufferSource; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinLevelRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinLevelRenderer.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/MixinLevelRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinLevelRenderer.java index b3b539fe60..8a8c4dd575 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinLevelRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinLevelRenderer.java @@ -1,24 +1,27 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.layer.IsOutlineRenderStateShard; -import net.coderbot.iris.layer.OuterWrappedRenderType; -import net.coderbot.iris.pipeline.HandRenderer; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.IrisTimeUniforms; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.layer.IsOutlineRenderStateShard; +import net.irisshaders.iris.layer.OuterWrappedRenderType; +import net.irisshaders.iris.pathways.HandRenderer; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shadows.frustum.fallback.NonCullingFrustum; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.IrisTimeUniforms; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; +import net.minecraft.ChatFormatting; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.network.chat.Component; import org.jetbrains.annotations.Nullable; import org.joml.Matrix4f; import org.lwjgl.opengl.GL43C; @@ -62,8 +65,10 @@ public class MixinLevelRenderer { // all pixels. @Inject(method = "renderLevel", at = @At("HEAD")) private void iris$setupPipeline(PoseStack poseStack, float tickDelta, long startTime, boolean renderBlockOutline, - Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, - Matrix4f projection, CallbackInfo callback) { + Camera camera, GameRenderer gameRenderer, LightTexture lightTexture, + Matrix4f projection, CallbackInfo callback) { + DHCompat.checkFrame(); + IrisTimeUniforms.updateTime(); CapturedRenderingState.INSTANCE.setGbufferModelView(poseStack.last().pose()); CapturedRenderingState.INSTANCE.setGbufferProjection(projection); @@ -79,6 +84,8 @@ public class MixinLevelRenderer { this.cullingFrustum = new NonCullingFrustum(); } + Minecraft.getInstance().smartCull = !pipeline.shouldDisableOcclusionCulling(); + if (Iris.shouldActivateWireframe() && this.minecraft.isLocalServer()) { IrisRenderSystem.setPolygonMode(GL43C.GL_LINE); } @@ -170,7 +177,7 @@ public class MixinLevelRenderer { } @Inject(method = "renderSky", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/multiplayer/ClientLevel;getTimeOfDay(F)F"), - slice = @Slice(from = @At(value = "FIELD", target = "Lcom/mojang/math/Axis;YP:Lcom/mojang/math/Axis;"))) + slice = @Slice(from = @At(value = "FIELD", target = "Lcom/mojang/math/Axis;YP:Lcom/mojang/math/Axis;"))) private void iris$renderSky$tiltSun(PoseStack poseStack, Matrix4f projectionMatrix, float f, Camera camera, boolean bl, Runnable runnable, CallbackInfo ci) { poseStack.mulPose(Axis.ZP.rotationDegrees(pipeline.getSunPathRotation())); } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinLightTexture.java b/src/main/java/net/irisshaders/iris/mixin/MixinLightTexture.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/MixinLightTexture.java rename to src/main/java/net/irisshaders/iris/mixin/MixinLightTexture.java index 87d743e4fc..ea259a98d8 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinLightTexture.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinLightTexture.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LightTexture; import net.minecraft.world.entity.LivingEntity; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinLightningBoltRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinLightningBoltRenderer.java similarity index 65% rename from src/main/java/net/coderbot/iris/mixin/MixinLightningBoltRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinLightningBoltRenderer.java index 25728fdb12..37713e28ca 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinLightningBoltRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinLightningBoltRenderer.java @@ -1,15 +1,9 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.coderbot.iris.pipeline.LightningHandler; -import net.minecraft.client.renderer.LightTexture; +import net.irisshaders.iris.pathways.LightningHandler; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.LightningBoltRenderer; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinMaxFpsCrashFix.java b/src/main/java/net/irisshaders/iris/mixin/MixinMaxFpsCrashFix.java similarity index 96% rename from src/main/java/net/coderbot/iris/mixin/MixinMaxFpsCrashFix.java rename to src/main/java/net/irisshaders/iris/mixin/MixinMaxFpsCrashFix.java index 62fa786e54..ab68313455 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinMaxFpsCrashFix.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinMaxFpsCrashFix.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import net.minecraft.client.OptionInstance; import net.minecraft.client.Options; @@ -9,7 +9,7 @@ /** * A workaround for when OptiFine has set the maxFps to zero in options.txt - * + *

    * Fun. */ @Mixin(Options.class) diff --git a/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Images.java b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Images.java new file mode 100644 index 0000000000..b8df962999 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Images.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.mixin; + +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.texture.CustomTextureData; +import net.irisshaders.iris.shaderpack.texture.TextureFilteringData; +import net.irisshaders.iris.targets.backed.NativeImageBackedCustomTexture; +import net.minecraft.client.Minecraft; +import net.minecraft.client.main.GameConfig; +import net.minecraft.resources.ResourceLocation; +import org.apache.commons.io.IOUtils; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.io.IOException; + +/** + * This Mixin is responsible for registering the "widgets" texture used in Iris' GUI's. + * Normally Fabric API would do this automatically, but we don't use it here, so it must be done manually. + */ +@Mixin(Minecraft.class) +public class MixinMinecraft_Images { + @Inject(method = "", at = @At("TAIL")) + private void iris$setupImages(GameConfig arg, CallbackInfo ci) { + if (!FabricLoader.getInstance().isModLoaded("fabric-resource-loader-v0")) { + try { + Minecraft.getInstance().getTextureManager().register(new ResourceLocation("iris", "textures/gui/widgets.png"), new NativeImageBackedCustomTexture(new CustomTextureData.PngData(new TextureFilteringData(false, false), IOUtils.toByteArray(Iris.class.getResourceAsStream("/assets/iris/textures/gui/widgets.png"))))); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Keybinds.java b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Keybinds.java new file mode 100644 index 0000000000..a9df998ca1 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_Keybinds.java @@ -0,0 +1,32 @@ +package net.irisshaders.iris.mixin; + +import net.irisshaders.iris.Iris; +import net.minecraft.client.Minecraft; +import net.minecraft.util.profiling.ProfilerFiller; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * Small hook giving Iris a chance to check for keyboard input for its keybindings. + * + *

    This is equivalent to the END_CLIENT_TICK event in Fabric API, but since it's a super simple mixin and we + * only need this event (out of the many events provided by Fabric API) I've just implemented it myself. This + * alone shaves over 60kB off the released JAR size.

    + */ +@Mixin(Minecraft.class) +public class MixinMinecraft_Keybinds { + @Shadow + private ProfilerFiller profiler; + + @Inject(method = "tick()V", at = @At("RETURN")) + private void iris$onTick(CallbackInfo ci) { + this.profiler.push("iris_keybinds"); + + Iris.handleKeybinds((Minecraft) (Object) this); + + this.profiler.pop(); + } +} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinMinecraft_PipelineManagement.java b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_PipelineManagement.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/MixinMinecraft_PipelineManagement.java rename to src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_PipelineManagement.java index ce0b66e717..a770971ba6 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinMinecraft_PipelineManagement.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinMinecraft_PipelineManagement.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.multiplayer.ClientLevel; @@ -31,17 +31,17 @@ public class MixinMinecraft_PipelineManagement { /** * Injects before LevelRenderer receives the new level, or is notified of the level unload. - * + *

    * We destroy any pipelines here to guard against potential memory leaks related to pipelines for * other dimensions never being unloaded. - * + *

    * This injection point is needed so that we can reload the Iris shader pipeline before Sodium starts trying * to reload its world renderer. Otherwise, there will be inconsistent state since Sodium might initialize and * use the non-extended vertex format (since we do it based on whether the pipeline is available, * then Iris will switch on its pipeline, then code will assume that the extended vertex format * is used everywhere. - * - * See: https://github.com/IrisShaders/Iris/issues/1330 + *

    + * See: Issue 1330 */ @Inject(method = "updateLevelInEngines", at = @At("HEAD")) private void iris$resetPipeline(@Nullable ClientLevel level, CallbackInfo ci) { diff --git a/src/main/java/net/coderbot/iris/mixin/MixinModelViewBobbing.java b/src/main/java/net/irisshaders/iris/mixin/MixinModelViewBobbing.java similarity index 73% rename from src/main/java/net/coderbot/iris/mixin/MixinModelViewBobbing.java rename to src/main/java/net/irisshaders/iris/mixin/MixinModelViewBobbing.java index 64649221c2..5f2416be68 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinModelViewBobbing.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinModelViewBobbing.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import org.joml.Matrix3f; -import org.joml.Matrix4f; import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.client.renderer.GameRenderer; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -16,10 +15,10 @@ /** * This mixin makes the effects of view bobbing and nausea apply to the model view matrix, not the projection matrix. - * + *

    * Applying these effects to the projection matrix causes severe issues with most shaderpacks. As it turns out, OptiFine * applies these effects to the modelview matrix. As such, we must do the same to properly run shaderpacks. - * + *

    * This mixin makes use of the matrix stack in order to make these changes without more invasive changes. */ @Mixin(GameRenderer.class) @@ -36,8 +35,8 @@ public class MixinModelViewBobbing { } @ModifyArg(method = "renderLevel", index = 0, - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/GameRenderer;bobHurt(Lcom/mojang/blaze3d/vertex/PoseStack;F)V")) + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/GameRenderer;bobHurt(Lcom/mojang/blaze3d/vertex/PoseStack;F)V")) private PoseStack iris$separateViewBobbing(PoseStack stack) { if (!areShadersOn) return stack; @@ -48,10 +47,10 @@ public class MixinModelViewBobbing { } @Redirect(method = "renderLevel", - at = @At(value = "INVOKE", - target = "Lcom/mojang/blaze3d/vertex/PoseStack;last()Lcom/mojang/blaze3d/vertex/PoseStack$Pose;"), - slice = @Slice(from = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/GameRenderer;bobHurt(Lcom/mojang/blaze3d/vertex/PoseStack;F)V"), to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;resetProjectionMatrix(Lorg/joml/Matrix4f;)V"))) + at = @At(value = "INVOKE", + target = "Lcom/mojang/blaze3d/vertex/PoseStack;last()Lcom/mojang/blaze3d/vertex/PoseStack$Pose;"), + slice = @Slice(from = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/GameRenderer;bobHurt(Lcom/mojang/blaze3d/vertex/PoseStack;F)V"), to = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/GameRenderer;resetProjectionMatrix(Lorg/joml/Matrix4f;)V"))) private PoseStack.Pose iris$saveBobbing(PoseStack stack) { if (!areShadersOn) return stack.last(); @@ -63,8 +62,8 @@ public class MixinModelViewBobbing { } @Inject(method = "renderLevel", - at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/GameRenderer;resetProjectionMatrix(Lorg/joml/Matrix4f;)V")) + at = @At(value = "INVOKE", + target = "Lnet/minecraft/client/renderer/GameRenderer;resetProjectionMatrix(Lorg/joml/Matrix4f;)V")) private void iris$applyBobbingToModelView(float tickDelta, long limitTime, PoseStack matrix, CallbackInfo ci) { if (!areShadersOn) return; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinOptions_Entrypoint.java b/src/main/java/net/irisshaders/iris/mixin/MixinOptions_Entrypoint.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/MixinOptions_Entrypoint.java rename to src/main/java/net/irisshaders/iris/mixin/MixinOptions_Entrypoint.java index f052f82dc4..fe99490f54 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinOptions_Entrypoint.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinOptions_Entrypoint.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.Options; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinParticleEngine.java b/src/main/java/net/irisshaders/iris/mixin/MixinParticleEngine.java similarity index 68% rename from src/main/java/net/coderbot/iris/mixin/MixinParticleEngine.java rename to src/main/java/net/irisshaders/iris/mixin/MixinParticleEngine.java index a8562179f3..d1d5a4ac12 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinParticleEngine.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinParticleEngine.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; import net.minecraft.client.Camera; import net.minecraft.client.particle.ParticleEngine; import net.minecraft.client.renderer.LightTexture; @@ -19,19 +19,19 @@ @Mixin(value = ParticleEngine.class, remap = false) public class MixinParticleEngine { private static final String RENDER = - "Lnet/minecraft/client/particle/ParticleEngine;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;FLnet/minecraft/client/renderer/culling/Frustum;)V"; + "Lnet/minecraft/client/particle/ParticleEngine;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;F)V"; @Inject(method = RENDER, at = @At("HEAD")) private void iris$beginDrawingParticles(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, - LightTexture lightTexture, Camera camera, float f, Frustum frustum, - CallbackInfo ci) { + LightTexture lightTexture, Camera camera, float f, + CallbackInfo ci) { Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.setPhase(WorldRenderingPhase.PARTICLES)); } @Inject(method = RENDER, at = @At("RETURN")) private void iris$finishDrawingParticles(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource, - LightTexture lightTexture, Camera camera, float f, Frustum frustum, - CallbackInfo ci) { + LightTexture lightTexture, Camera camera, float f, + CallbackInfo ci) { Iris.getPipelineManager().getPipeline().ifPresent(pipeline -> pipeline.setPhase(WorldRenderingPhase.NONE)); } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinProgram.java b/src/main/java/net/irisshaders/iris/mixin/MixinProgram.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/MixinProgram.java rename to src/main/java/net/irisshaders/iris/mixin/MixinProgram.java index ad73cb137e..3facc26d0c 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinProgram.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinProgram.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.shader.ShaderCompileException; +import com.mojang.blaze3d.preprocessor.GlslPreprocessor; +import com.mojang.blaze3d.shaders.Program; +import net.irisshaders.iris.gl.shader.ShaderCompileException; 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.Redirect; -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import com.mojang.blaze3d.shaders.Program; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @@ -30,7 +30,7 @@ public class MixinProgram { return includeHandler.process(shaderSource); } - @Inject(method = "compileShaderInternal", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;glGetShaderInfoLog(II)Ljava/lang/String;"), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD) + @Inject(method = "compileShaderInternal", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;glGetShaderInfoLog(II)Ljava/lang/String;"), locals = LocalCapture.CAPTURE_FAILHARD) private static void iris$causeException(Program.Type arg, String string, InputStream inputStream, String string2, GlslPreprocessor arg2, CallbackInfoReturnable cir, String string3, int i) { cir.cancel(); throw new ShaderCompileException(string + arg.getExtension(), GlStateManager.glGetShaderInfoLog(i, 32768)); diff --git a/src/main/java/net/coderbot/iris/mixin/MixinProgramManager.java b/src/main/java/net/irisshaders/iris/mixin/MixinProgramManager.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/MixinProgramManager.java rename to src/main/java/net/irisshaders/iris/mixin/MixinProgramManager.java index a41ba8d0a9..c0fecf08c5 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinProgramManager.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinProgramManager.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.shaders.ProgramManager; import com.mojang.blaze3d.shaders.Shader; -import net.coderbot.iris.pipeline.newshader.ExtendedShader; +import net.irisshaders.iris.pipeline.programs.ExtendedShader; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/main/java/net/irisshaders/iris/mixin/MixinProgramType.java b/src/main/java/net/irisshaders/iris/mixin/MixinProgramType.java new file mode 100644 index 0000000000..546fe27f5c --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/MixinProgramType.java @@ -0,0 +1,35 @@ +package net.irisshaders.iris.mixin; + +import com.mojang.blaze3d.shaders.Program; +import net.irisshaders.iris.gl.program.IrisProgramTypes; +import org.apache.commons.lang3.ArrayUtils; +import org.lwjgl.opengl.GL32C; +import org.lwjgl.opengl.GL42C; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; + +@Mixin(Program.Type.class) +public class MixinProgramType { + @SuppressWarnings("target") + @Shadow + @Final + @Mutable + private static Program.Type[] $VALUES; + + static { + int baseOrdinal = $VALUES.length; + + IrisProgramTypes.GEOMETRY + = ProgramTypeAccessor.createProgramType("GEOMETRY", baseOrdinal, "geometry", ".gsh", GL32C.GL_GEOMETRY_SHADER); + + IrisProgramTypes.TESS_CONTROL + = ProgramTypeAccessor.createProgramType("TESS_CONTROL", baseOrdinal + 1, "tess_control", ".tcs", GL42C.GL_TESS_CONTROL_SHADER); + + IrisProgramTypes.TESS_EVAL + = ProgramTypeAccessor.createProgramType("TESS_EVAL", baseOrdinal + 2, "tess_eval", ".tes", GL42C.GL_TESS_EVALUATION_SHADER); + + $VALUES = ArrayUtils.addAll($VALUES, IrisProgramTypes.GEOMETRY, IrisProgramTypes.TESS_CONTROL, IrisProgramTypes.TESS_EVAL); + } +} diff --git a/src/main/java/net/coderbot/iris/mixin/MixinRenderSystem.java b/src/main/java/net/irisshaders/iris/mixin/MixinRenderSystem.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/MixinRenderSystem.java rename to src/main/java/net/irisshaders/iris/mixin/MixinRenderSystem.java index 1cac6c71aa..9aef3d90b4 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinRenderSystem.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinRenderSystem.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.GLDebug; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.texture.TextureTracker; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.texture.TextureTracker; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.resources.ResourceLocation; -import net.coderbot.iris.gl.IrisRenderSystem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -20,7 +20,7 @@ public class MixinRenderSystem { @Inject(method = "initRenderer", at = @At("RETURN"), remap = false) private static void iris$onRendererInit(int debugVerbosity, boolean alwaysFalse, CallbackInfo ci) { Iris.duringRenderSystemInit(); - GLDebug.initRenderer(); + GLDebug.reloadDebugState(); IrisRenderSystem.initRenderer(); IrisSamplers.initRenderer(); Iris.onRenderSystemInit(); diff --git a/src/main/java/net/coderbot/iris/mixin/MixinRenderTarget.java b/src/main/java/net/irisshaders/iris/mixin/MixinRenderTarget.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/MixinRenderTarget.java rename to src/main/java/net/irisshaders/iris/mixin/MixinRenderTarget.java index 906beb1de7..209f767a6d 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinRenderTarget.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinRenderTarget.java @@ -1,9 +1,10 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.pipeline.RenderTarget; -import net.coderbot.iris.rendertarget.Blaze3dRenderTargetExt; +import net.irisshaders.iris.targets.Blaze3dRenderTargetExt; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -15,9 +16,11 @@ @Mixin(RenderTarget.class) public class MixinRenderTarget implements Blaze3dRenderTargetExt { @Shadow - private int depthBufferId; + protected int depthBufferId; + @Unique private int iris$depthBufferVersion; + @Unique private int iris$colorBufferVersion; @Inject(method = "destroyBuffers()V", at = @At("HEAD")) diff --git a/src/main/java/net/coderbot/iris/mixin/MixinScreenEffectRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinScreenEffectRenderer.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/MixinScreenEffectRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinScreenEffectRenderer.java index 39cf59e23c..d6d2fbe395 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinScreenEffectRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinScreenEffectRenderer.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ScreenEffectRenderer; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinSystemReport.java b/src/main/java/net/irisshaders/iris/mixin/MixinSystemReport.java similarity index 60% rename from src/main/java/net/coderbot/iris/mixin/MixinSystemReport.java rename to src/main/java/net/irisshaders/iris/mixin/MixinSystemReport.java index c4fd134daf..cfe68947b4 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinSystemReport.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinSystemReport.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.SystemReport; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -19,16 +19,16 @@ public abstract class MixinSystemReport { public abstract void setDetail(String string, Supplier supplier); @Inject(at = @At("RETURN"), method = "") - private void fillSystemDetails(CallbackInfo ci) { - if (Iris.getCurrentPackName() == null) return; // this also gets called at startup for some reason + private void fillSystemDetails(CallbackInfo ci) { + if (Iris.getCurrentPackName() == null) return; // this also gets called at startup for some reason - this.setDetail("Loaded Shaderpack", () -> { + this.setDetail("Loaded Shaderpack", () -> { StringBuilder sb = new StringBuilder(Iris.getCurrentPackName() + (Iris.isFallback() ? " (fallback)" : "")); - Iris.getCurrentPack().ifPresent(pack -> { - sb.append("\n\t\t"); - sb.append(pack.getProfileInfo()); - }); - return sb.toString(); - }); - } + Iris.getCurrentPack().ifPresent(pack -> { + sb.append("\n\t\t"); + sb.append(pack.getProfileInfo()); + }); + return sb.toString(); + }); + } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinTheEndPortalRenderer.java b/src/main/java/net/irisshaders/iris/mixin/MixinTheEndPortalRenderer.java similarity index 68% rename from src/main/java/net/coderbot/iris/mixin/MixinTheEndPortalRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinTheEndPortalRenderer.java index fb52d8fb2a..54cddcc336 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinTheEndPortalRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinTheEndPortalRenderer.java @@ -1,16 +1,16 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; -import org.joml.Matrix3f; -import org.joml.Matrix4f; -import net.coderbot.iris.Iris; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.blockentity.TheEndPortalRenderer; import net.minecraft.core.Direction; import net.minecraft.world.level.block.entity.TheEndPortalBlockEntity; +import org.joml.Matrix3f; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; @@ -49,7 +49,7 @@ protected float getOffsetDown() { // POSITION_COLOR_TEXTURE_OVERLAY_LIGHT_NORMAL VertexConsumer vertexConsumer = - multiBufferSource.getBuffer(RenderType.entitySolid(TheEndPortalRenderer.END_PORTAL_LOCATION)); + multiBufferSource.getBuffer(RenderType.entitySolid(TheEndPortalRenderer.END_PORTAL_LOCATION)); Matrix4f pose = poseStack.last().pose(); Matrix3f normal = poseStack.last().normal(); @@ -61,40 +61,40 @@ protected float getOffsetDown() { float bottomHeight = getOffsetDown(); quad(entity, vertexConsumer, pose, normal, Direction.UP, progress, overlay, light, - 0.0f, topHeight, 1.0f, - 1.0f, topHeight, 1.0f, - 1.0f, topHeight, 0.0f, - 0.0f, topHeight, 0.0f); + 0.0f, topHeight, 1.0f, + 1.0f, topHeight, 1.0f, + 1.0f, topHeight, 0.0f, + 0.0f, topHeight, 0.0f); quad(entity, vertexConsumer, pose, normal, Direction.DOWN, progress, overlay, light, - 0.0f, bottomHeight, 1.0f, - 0.0f, bottomHeight, 0.0f, - 1.0f, bottomHeight, 0.0f, - 1.0f, bottomHeight, 1.0f); + 0.0f, bottomHeight, 1.0f, + 0.0f, bottomHeight, 0.0f, + 1.0f, bottomHeight, 0.0f, + 1.0f, bottomHeight, 1.0f); quad(entity, vertexConsumer, pose, normal, Direction.NORTH, progress, overlay, light, - 0.0f, topHeight, 0.0f, - 1.0f, topHeight, 0.0f, - 1.0f, bottomHeight, 0.0f, - 0.0f, bottomHeight, 0.0f); + 0.0f, topHeight, 0.0f, + 1.0f, topHeight, 0.0f, + 1.0f, bottomHeight, 0.0f, + 0.0f, bottomHeight, 0.0f); quad(entity, vertexConsumer, pose, normal, Direction.WEST, progress, overlay, light, - 0.0f, topHeight, 1.0f, - 0.0f, topHeight, 0.0f, - 0.0f, bottomHeight, 0.0f, - 0.0f, bottomHeight, 1.0f); + 0.0f, topHeight, 1.0f, + 0.0f, topHeight, 0.0f, + 0.0f, bottomHeight, 0.0f, + 0.0f, bottomHeight, 1.0f); quad(entity, vertexConsumer, pose, normal, Direction.SOUTH, progress, overlay, light, - 0.0f, topHeight, 1.0f, - 0.0f, bottomHeight, 1.0f, - 1.0f, bottomHeight, 1.0f, - 1.0f, topHeight, 1.0f); + 0.0f, topHeight, 1.0f, + 0.0f, bottomHeight, 1.0f, + 1.0f, bottomHeight, 1.0f, + 1.0f, topHeight, 1.0f); quad(entity, vertexConsumer, pose, normal, Direction.EAST, progress, overlay, light, - 1.0f, topHeight, 1.0f, - 1.0f, bottomHeight, 1.0f, - 1.0f, bottomHeight, 0.0f, - 1.0f, topHeight, 0.0f); + 1.0f, topHeight, 1.0f, + 1.0f, bottomHeight, 1.0f, + 1.0f, bottomHeight, 0.0f, + 1.0f, topHeight, 0.0f); } @Unique @@ -103,7 +103,7 @@ private void quad(TheEndPortalBlockEntity entity, VertexConsumer vertexConsumer, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, - float x4,float y4, float z4) { + float x4, float y4, float z4) { if (!entity.shouldRenderFace(direction)) { return; } @@ -113,19 +113,19 @@ private void quad(TheEndPortalBlockEntity entity, VertexConsumer vertexConsumer, float nz = direction.getStepZ(); vertexConsumer.vertex(pose, x1, y1, z1).color(RED, GREEN, BLUE, 1.0f) - .uv(0.0F + progress, 0.0F + progress).overlayCoords(overlay).uv2(light) - .normal(normal, nx, ny, nz).endVertex(); + .uv(0.0F + progress, 0.0F + progress).overlayCoords(overlay).uv2(light) + .normal(normal, nx, ny, nz).endVertex(); vertexConsumer.vertex(pose, x2, y2, z2).color(RED, GREEN, BLUE, 1.0f) - .uv(0.0F + progress, 0.2F + progress).overlayCoords(overlay).uv2(light) - .normal(normal, nx, ny, nz).endVertex(); + .uv(0.0F + progress, 0.2F + progress).overlayCoords(overlay).uv2(light) + .normal(normal, nx, ny, nz).endVertex(); vertexConsumer.vertex(pose, x3, y3, z3).color(RED, GREEN, BLUE, 1.0f) - .uv(0.2F + progress, 0.2F + progress).overlayCoords(overlay).uv2(light) - .normal(normal, nx, ny, nz).endVertex(); + .uv(0.2F + progress, 0.2F + progress).overlayCoords(overlay).uv2(light) + .normal(normal, nx, ny, nz).endVertex(); vertexConsumer.vertex(pose, x4, y4, z4).color(RED, GREEN, BLUE, 1.0f) - .uv(0.2F + progress, 0.0F + progress).overlayCoords(overlay).uv2(light) - .normal(normal, nx, ny, nz).endVertex(); + .uv(0.2F + progress, 0.0F + progress).overlayCoords(overlay).uv2(light) + .normal(normal, nx, ny, nz).endVertex(); } } diff --git a/src/main/java/net/coderbot/iris/mixin/MixinTitleScreen.java b/src/main/java/net/irisshaders/iris/mixin/MixinTitleScreen.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/MixinTitleScreen.java rename to src/main/java/net/irisshaders/iris/mixin/MixinTitleScreen.java index 0b98da271f..6c5bf72c4a 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinTitleScreen.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinTitleScreen.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.TitleScreen; import net.minecraft.network.chat.Component; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinTweakFarPlane.java b/src/main/java/net/irisshaders/iris/mixin/MixinTweakFarPlane.java similarity index 64% rename from src/main/java/net/coderbot/iris/mixin/MixinTweakFarPlane.java rename to src/main/java/net/irisshaders/iris/mixin/MixinTweakFarPlane.java index f67f9db3d2..ae4e2cb57d 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinTweakFarPlane.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinTweakFarPlane.java @@ -1,35 +1,33 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.renderer.GameRenderer; -import org.lwjgl.opengl.GL; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -/** - * Tweaks the far plane of the projection matrix to match OptiFine. - * - * As it turns out, OptiFine significantly reduces the far plane distance compared to vanilla. This is likely because - * vanilla chooses a far plane that is four times the render distance in blocks, which is a bit overkill. Instead, - * OptiFine makes the far plane only 1024 blocks above the render distance in blocks (two times the render distance in 1.16 and lower), and (in 1.16) to compensate, adds a minimum distance - * for the far plane to make it not appear too closely to the player. - * - * On 1.16 and lower, OptiFine also modifies the distance of the far plane based on the fog setting. - * - * So why is this needed? As it turns out, shaderpacks actually rely on this behavior to work properly. Most notably, - * the water reflection code in Sildur's Vibrant Shaders will often create impossible reflections with the default far - * plane, where things that are close to the player will be reflected in water that is very far away. - * - * A possible reason for this is that the value of the {@code far} uniform does not actually match the far plane - * distance, so shaderpacks one way or another have come to just bodge things to work around the issue, and in the - * process become subtly reliant on OptiFine implementation details. - * - * Fun. +/* + Tweaks the far plane of the projection matrix to match OptiFine. + + As it turns out, OptiFine significantly reduces the far plane distance compared to vanilla. This is likely because + vanilla chooses a far plane that is four times the render distance in blocks, which is a bit overkill. Instead, + OptiFine makes the far plane only 1024 blocks above the render distance in blocks (two times the render distance in 1.16 and lower), and (in 1.16) to compensate, adds a minimum distance + for the far plane to make it not appear too closely to the player. + + On 1.16 and lower, OptiFine also modifies the distance of the far plane based on the fog setting. + + So why is this needed? As it turns out, shaderpacks actually rely on this behavior to work properly. Most notably, + the water reflection code in Sildur's Vibrant Shaders will often create impossible reflections with the default far + plane, where things that are close to the player will be reflected in water that is very far away. + + A possible reason for this is that the value of the {@code far} uniform does not actually match the far plane + distance, so shaderpacks one way or another have come to just bodge things to work around the issue, and in the + process become subtly reliant on OptiFine implementation details. + + Fun. */ /** diff --git a/src/main/java/net/coderbot/iris/mixin/MixinUniform.java b/src/main/java/net/irisshaders/iris/mixin/MixinUniform.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/MixinUniform.java rename to src/main/java/net/irisshaders/iris/mixin/MixinUniform.java index 67fb558b1a..283e1bdc85 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinUniform.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinUniform.java @@ -1,16 +1,15 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.shaders.Uniform; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; /** * Tries to ensure that texture unit 0 ends up as the semantically default texture unit with Iris extended shaders. - * + *

    * Located in {@link Uniform} to avoid a conflict with a Sodium mixin to ShaderInstance. */ @Mixin(Uniform.class) diff --git a/src/main/java/net/coderbot/iris/mixin/MixinVertexBuffer.java b/src/main/java/net/irisshaders/iris/mixin/MixinVertexBuffer.java similarity index 89% rename from src/main/java/net/coderbot/iris/mixin/MixinVertexBuffer.java rename to src/main/java/net/irisshaders/iris/mixin/MixinVertexBuffer.java index e1858a199c..dc294d5ce1 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinVertexBuffer.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinVertexBuffer.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.vertex.VertexBuffer; -import net.coderbot.iris.fantastic.VertexBufferHelper; +import net.irisshaders.iris.helpers.VertexBufferHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -13,8 +13,13 @@ public class MixinVertexBuffer implements VertexBufferHelper { private static VertexBuffer current; private static VertexBuffer saved; + @Inject(method = "unbind()V", at = @At("HEAD")) + private static void unbindHelper(CallbackInfo ci) { + current = null; + } + @Shadow - private void bind() { + public void bind() { throw new IllegalStateException("not shadowed"); } @@ -23,11 +28,6 @@ private void bindHelper(CallbackInfo ci) { current = (VertexBuffer) (Object) this; } - @Inject(method = "unbind()V", at = @At("HEAD")) - private static void unbindHelper(CallbackInfo ci) { - current = null; - } - @Override public void saveBinding() { saved = current; diff --git a/src/main/java/net/coderbot/iris/mixin/MixinWindow.java b/src/main/java/net/irisshaders/iris/mixin/MixinWindow.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/MixinWindow.java rename to src/main/java/net/irisshaders/iris/mixin/MixinWindow.java index 2da4f60d54..06fc29a4b2 100644 --- a/src/main/java/net/coderbot/iris/mixin/MixinWindow.java +++ b/src/main/java/net/irisshaders/iris/mixin/MixinWindow.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.mixin; +package net.irisshaders.iris.mixin; import com.mojang.blaze3d.platform.DisplayData; import com.mojang.blaze3d.platform.ScreenManager; import com.mojang.blaze3d.platform.Window; import com.mojang.blaze3d.platform.WindowEventHandler; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import org.lwjgl.glfw.GLFW; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/net/coderbot/iris/mixin/OculusMixinPlugin.java b/src/main/java/net/irisshaders/iris/mixin/OculusMixinPlugin.java similarity index 100% rename from src/main/java/net/coderbot/iris/mixin/OculusMixinPlugin.java rename to src/main/java/net/irisshaders/iris/mixin/OculusMixinPlugin.java diff --git a/src/main/java/net/irisshaders/iris/mixin/ProgramTypeAccessor.java b/src/main/java/net/irisshaders/iris/mixin/ProgramTypeAccessor.java new file mode 100644 index 0000000000..1b2c433d00 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/ProgramTypeAccessor.java @@ -0,0 +1,13 @@ +package net.irisshaders.iris.mixin; + +import com.mojang.blaze3d.shaders.Program; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(Program.Type.class) +public interface ProgramTypeAccessor { + @Invoker(value = "") + static Program.Type createProgramType(String name, int ordinal, String typeName, String extension, int glId) { + throw new AssertionError(); + } +} diff --git a/src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinMipmapGenerator.java b/src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinMipmapGenerator.java similarity index 96% rename from src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinMipmapGenerator.java rename to src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinMipmapGenerator.java index 4216ee5ba0..ac11654f74 100644 --- a/src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinMipmapGenerator.java +++ b/src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinMipmapGenerator.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.mixin.bettermipmaps; +package net.irisshaders.iris.mixin.bettermipmaps; -import com.mojang.blaze3d.platform.NativeImage; -import net.coderbot.iris.helpers.ColorSRGB; +import net.irisshaders.iris.helpers.ColorSRGB; import net.minecraft.client.renderer.texture.MipmapGenerator; import net.minecraft.util.FastColor; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java b/src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java rename to src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java index 30dc72bb8c..16ad4d3da9 100644 --- a/src/main/java/net/coderbot/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java +++ b/src/main/java/net/irisshaders/iris/mixin/bettermipmaps/MixinTextureAtlasSprite.java @@ -1,11 +1,8 @@ -package net.coderbot.iris.mixin.bettermipmaps; +package net.irisshaders.iris.mixin.bettermipmaps; import com.mojang.blaze3d.platform.NativeImage; +import net.irisshaders.iris.helpers.ColorSRGB; import net.minecraft.client.renderer.texture.SpriteContents; -import net.coderbot.iris.helpers.ColorSRGB; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.metadata.animation.FrameSize; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FastColor; import org.lwjgl.system.MemoryUtil; @@ -16,19 +13,12 @@ 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.ModifyArg; -import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import java.util.Locale; -import java.util.Objects; @Mixin(SpriteContents.class) public class MixinTextureAtlasSprite { - @Mutable - @Shadow - @Final - private NativeImage originalImage; // Generate some color tables for gamma correction. private static final float[] SRGB_TO_LINEAR = new float[256]; @@ -38,33 +28,14 @@ public class MixinTextureAtlasSprite { } } - // While Fabric allows us to @Inject into the constructor here, that's just a specific detail of FabricMC's mixin - // fork. Upstream Mixin doesn't allow arbitrary @Inject usage in constructor. However, we can use @ModifyVariable - // just fine, in a way that hopefully doesn't conflict with other mods. - // - // By doing this, we can work with upstream Mixin as well, as is used on Forge. While we don't officially - // support Forge, since this works well on Fabric too, it's fine to ensure that the diff between Fabric and Forge - // can remain minimal. Being less dependent on specific details of Fabric is good, since it means we can be more - // cross-platform. - @Redirect(method = "", at = @At(value = "FIELD", target = "Lnet/minecraft/client/renderer/texture/SpriteContents;originalImage:Lcom/mojang/blaze3d/platform/NativeImage;", opcode = Opcodes.PUTFIELD)) - private void iris$beforeGenerateMipLevels(SpriteContents instance, NativeImage nativeImage, ResourceLocation resourceLocation) { - // We're injecting after the "info" field has been set, so this is safe even though we're in a constructor. - if (resourceLocation.getPath().contains("leaves")) { - // Don't ruin the textures of leaves on fast graphics, since they're supposed to have black pixels - // apparently. - this.originalImage = nativeImage; - return; - } - - - iris$fillInTransparentPixelColors(nativeImage); - - this.originalImage = nativeImage; - } + @Mutable + @Shadow + @Final + private NativeImage originalImage; /** * Fixes a common issue in image editing programs where fully transparent pixels are saved with fully black colors. - * + *

    * This causes issues with mipmapped texture filtering, since the black color is used to calculate the final color * even though the alpha value is zero. While ideally it would be disregarded, we do not control that. Instead, * this code tries to calculate a decent average color to assign to these fully-transparent pixels so that their @@ -84,7 +55,7 @@ public class MixinTextureAtlasSprite { float totalWeight = 0.0f; for (int pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) { - long pPixel = ppPixel + (pixelIndex * 4); + long pPixel = ppPixel + (pixelIndex * 4L); int color = MemoryUtil.memGetInt(pPixel); int alpha = FastColor.ABGR32.alpha(color); @@ -116,7 +87,7 @@ public class MixinTextureAtlasSprite { int averageColor = ColorSRGB.linearToSrgb(r, g, b, 0); for (int pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) { - long pPixel = ppPixel + (pixelIndex * 4); + long pPixel = ppPixel + (pixelIndex * 4L); int color = MemoryUtil.memGetInt(pPixel); int alpha = FastColor.ABGR32.alpha(color); @@ -136,4 +107,28 @@ private static long getPointerRGBA(NativeImage nativeImage) { return nativeImage.pixels; } + + // While Fabric allows us to @Inject into the constructor here, that's just a specific detail of FabricMC's mixin + // fork. Upstream Mixin doesn't allow arbitrary @Inject usage in constructor. However, we can use @ModifyVariable + // just fine, in a way that hopefully doesn't conflict with other mods. + // + // By doing this, we can work with upstream Mixin as well, as is used on Forge. While we don't officially + // support Forge, since this works well on Fabric too, it's fine to ensure that the diff between Fabric and Forge + // can remain minimal. Being less dependent on specific details of Fabric is good, since it means we can be more + // cross-platform. + @Redirect(method = "", at = @At(value = "FIELD", target = "Lnet/minecraft/client/renderer/texture/SpriteContents;originalImage:Lcom/mojang/blaze3d/platform/NativeImage;", opcode = Opcodes.PUTFIELD)) + private void iris$beforeGenerateMipLevels(SpriteContents instance, NativeImage nativeImage, ResourceLocation resourceLocation) { + // We're injecting after the "info" field has been set, so this is safe even though we're in a constructor. + if (resourceLocation.getPath().contains("leaves")) { + // Don't ruin the textures of leaves on fast graphics, since they're supposed to have black pixels + // apparently. + this.originalImage = nativeImage; + return; + } + + + iris$fillInTransparentPixelColors(nativeImage); + + this.originalImage = nativeImage; + } } diff --git a/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinMinecraft_NoAuthInDev.java b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinMinecraft_NoAuthInDev.java new file mode 100644 index 0000000000..8aea63c54c --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinMinecraft_NoAuthInDev.java @@ -0,0 +1,33 @@ +package net.irisshaders.iris.mixin.devenvironment; + +import com.mojang.authlib.minecraft.UserApiService; +import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService; +import net.minecraft.client.Minecraft; +import net.minecraft.client.main.GameConfig; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * Suppresses Minecraft's authentication check in development environments. It's unnecessary log spam, and there's no + * need to send off a network request to Microsoft telling them that we're using Fabric/Quilt every time we launch the + * game in the development environment. + * + *

    This also disables telemetry as a side-effect.

    + */ +@Mixin(Minecraft.class) +public class MixinMinecraft_NoAuthInDev { + @Shadow + @Final + private static Logger LOGGER; + + @Inject(method = "createUserApiService", at = @At("HEAD"), cancellable = true) + private void iris$noSocialInteractionsInDevelopment(YggdrasilAuthenticationService yggdrasilAuthenticationService, GameConfig arg, CallbackInfoReturnable cir) { + LOGGER.info("[Iris] Suppressing Yggdrasil authentication check because this is a development environment"); + cir.setReturnValue(UserApiService.OFFLINE); + } +} diff --git a/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinProfileKeyPairManager.java b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinProfileKeyPairManager.java new file mode 100644 index 0000000000..c6d6b3a676 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinProfileKeyPairManager.java @@ -0,0 +1,8 @@ +package net.irisshaders.iris.mixin.devenvironment; + +import net.minecraft.client.multiplayer.ProfileKeyPairManager; +import org.spongepowered.asm.mixin.Mixin; + +@Mixin(ProfileKeyPairManager.class) +public interface MixinProfileKeyPairManager { +} diff --git a/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinSharedConstants_LazyDfu.java b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinSharedConstants_LazyDfu.java new file mode 100644 index 0000000000..8cc4da9a91 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/devenvironment/MixinSharedConstants_LazyDfu.java @@ -0,0 +1,9 @@ +package net.irisshaders.iris.mixin.devenvironment; + +import net.minecraft.SharedConstants; +import org.spongepowered.asm.mixin.Mixin; + +// use a higher priority to apply after LazyDFU, to avoid a conflict. +@Mixin(value = SharedConstants.class, priority = 1010) +public class MixinSharedConstants_LazyDfu { +} diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java similarity index 83% rename from src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java rename to src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java index d0dcb19532..66f2f6ab13 100644 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinBlockEntityRenderDispatcher.java @@ -1,16 +1,14 @@ -package net.coderbot.iris.mixin.entity_render_context; +package net.irisshaders.iris.mixin.entity_render_context; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.coderbot.batchedentityrendering.impl.Groupable; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.fantastic.WrappingMultiBufferSource; -import net.coderbot.iris.layer.BlockEntityRenderStateShard; -import net.coderbot.iris.layer.OuterWrappedRenderType; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.batchedentityrendering.impl.Groupable; +import net.irisshaders.iris.layer.BlockEntityRenderStateShard; +import net.irisshaders.iris.layer.OuterWrappedRenderType; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; -import net.minecraft.world.entity.Entity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Mixin; @@ -39,7 +37,7 @@ public class MixinBlockEntityRenderDispatcher { // captured by the lambda shortly afterwards, and therefore our ModifyVariable call becomes ineffective! @ModifyVariable(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/entity/BlockEntityType;isValid(Lnet/minecraft/world/level/block/state/BlockState;)Z"), - allow = 1, require = 1) + allow = 1, require = 1, argsOnly = true) private MultiBufferSource iris$wrapBufferSource(MultiBufferSource bufferSource, BlockEntity blockEntity) { if (!(bufferSource instanceof Groupable)) { // Fully batched entity rendering is not being used, do not use this wrapper!!! @@ -48,7 +46,7 @@ public class MixinBlockEntityRenderDispatcher { BlockState state = blockEntity.getBlockState(); - Object2IntMap blockStateIds = BlockRenderingSettings.INSTANCE.getBlockStateIds(); + Object2IntMap blockStateIds = WorldRenderingSettings.INSTANCE.getBlockStateIds(); if (blockStateIds == null) { return bufferSource; diff --git a/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinCapeLayer.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinCapeLayer.java new file mode 100644 index 0000000000..7ec426b609 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinCapeLayer.java @@ -0,0 +1,32 @@ +package net.irisshaders.iris.mixin.entity_render_context; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.layers.CapeLayer; +import net.minecraft.world.item.ItemStack; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +@Mixin(CapeLayer.class) +public class MixinCapeLayer { + private static final NamespacedId CAPE_LOCATION = new NamespacedId("minecraft", "player_cape"); + + @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;FFFFFF)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;pushPose()V")) + private void changeId(PoseStack poseStack, MultiBufferSource multiBufferSource, int i, AbstractClientPlayer abstractClientPlayer, float f, float g, float h, float j, float k, float l, CallbackInfo ci) { + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; + + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(CAPE_LOCATION)); + } + + @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/client/player/AbstractClientPlayer;FFFFFF)V", at = @At(value = "RETURN")) + private void changeId2(CallbackInfo ci) { + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0); + } +} diff --git a/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinElytraLayer.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinElytraLayer.java new file mode 100644 index 0000000000..2e5fcfcbf1 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinElytraLayer.java @@ -0,0 +1,54 @@ +package net.irisshaders.iris.mixin.entity_render_context; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.minecraft.client.model.EntityModel; +import net.minecraft.client.player.AbstractClientPlayer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.entity.RenderLayerParent; +import net.minecraft.client.renderer.entity.layers.ElytraLayer; +import net.minecraft.client.renderer.entity.layers.RenderLayer; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.PlayerModelPart; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.LocalCapture; + +@Mixin(ElytraLayer.class) +public abstract class MixinElytraLayer> extends RenderLayer { + @Unique + private static final NamespacedId ELYTRA_CAPE_LOCATION = new NamespacedId("minecraft", "elytra_with_cape"); + + public MixinElytraLayer(RenderLayerParent pRenderLayer0) { + super(pRenderLayer0); + } + + @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/LivingEntity;FFFFFF)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/PoseStack;pushPose()V"), locals = LocalCapture.CAPTURE_FAILHARD) + private void changeId(PoseStack pElytraLayer0, MultiBufferSource pMultiBufferSource1, int pInt2, T pLivingEntity3, float pFloat4, float pFloat5, float pFloat6, float pFloat7, float pFloat8, float pFloat9, CallbackInfo ci, ItemStack lvItemStack11, ResourceLocation lvResourceLocation12) { + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; + + if (pLivingEntity3 instanceof AbstractClientPlayer player && player.getCloakTextureLocation() != null + && player.isModelPartShown(PlayerModelPart.CAPE)) { + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(ELYTRA_CAPE_LOCATION)); + return; + } + + ResourceLocation location = BuiltInRegistries.ITEM.getKey(Items.ELYTRA); + + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); + } + + @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/LivingEntity;FFFFFF)V", at = @At(value = "RETURN")) + private void changeId2(CallbackInfo ci) { + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0); + } +} diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java similarity index 76% rename from src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java rename to src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java index 319d3bcf23..dfa51953a9 100644 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinEntityRenderDispatcher.java @@ -1,20 +1,15 @@ -package net.coderbot.iris.mixin.entity_render_context; +package net.irisshaders.iris.mixin.entity_render_context; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.Object2IntFunction; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.coderbot.batchedentityrendering.impl.Groupable; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.fantastic.WrappingMultiBufferSource; -import net.coderbot.iris.layer.BlockEntityRenderStateShard; -import net.coderbot.iris.layer.EntityRenderStateShard; -import net.coderbot.iris.layer.OuterWrappedRenderType; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.batchedentityrendering.impl.Groupable; +import net.irisshaders.iris.layer.EntityRenderStateShard; +import net.irisshaders.iris.layer.OuterWrappedRenderType; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; @@ -41,7 +36,7 @@ public class MixinEntityRenderDispatcher { return bufferSource; } - Object2IntFunction entityIds = BlockRenderingSettings.INSTANCE.getEntityIds(); + Object2IntFunction entityIds = WorldRenderingSettings.INSTANCE.getEntityIds(); if (entityIds == null) { return bufferSource; @@ -49,8 +44,8 @@ public class MixinEntityRenderDispatcher { int intId; - if (entity instanceof ZombieVillager zombie && zombie.isConverting() && BlockRenderingSettings.INSTANCE.hasVillagerConversionId()) { - intId = entityIds.applyAsInt(new NamespacedId("minecraft", "zombie_villager_converting"));; + if (entity instanceof ZombieVillager zombie && zombie.isConverting() && WorldRenderingSettings.INSTANCE.hasVillagerConversionId()) { + intId = entityIds.applyAsInt(new NamespacedId("minecraft", "zombie_villager_converting")); } else { ResourceLocation entityId = BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()); intId = entityIds.applyAsInt(new NamespacedId(entityId.getNamespace(), entityId.getPath())); diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHorseArmorLayer.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHorseArmorLayer.java similarity index 68% rename from src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHorseArmorLayer.java rename to src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHorseArmorLayer.java index 850fbeb690..eedd409816 100644 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHorseArmorLayer.java +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHorseArmorLayer.java @@ -1,22 +1,16 @@ -package net.coderbot.iris.mixin.entity_render_context; +package net.irisshaders.iris.mixin.entity_render_context; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.entity.layers.HorseArmorLayer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.animal.horse.Horse; -import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.HorseArmorItem; -import net.minecraft.world.item.ItemStack; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -25,10 +19,11 @@ public class MixinHorseArmorLayer { @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/animal/horse/Horse;FFFFFF)V", at = @At(value = "HEAD")) private void changeId(PoseStack pHorseArmorLayer0, MultiBufferSource pMultiBufferSource1, int pInt2, Horse pHorse3, float pFloat4, float pFloat5, float pFloat6, float pFloat7, float pFloat8, float pFloat9, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null || !(pHorse3.getArmor().getItem() instanceof HorseArmorItem)) return; + if (WorldRenderingSettings.INSTANCE.getItemIds() == null || !(pHorse3.getArmor().getItem() instanceof HorseArmorItem)) + return; ResourceLocation location = BuiltInRegistries.ITEM.getKey((pHorse3.getArmor().getItem())); - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); } @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;ILnet/minecraft/world/entity/animal/horse/Horse;FFFFFF)V", at = @At(value = "TAIL")) diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java similarity index 80% rename from src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java rename to src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java index 22c86076f4..33319fc4f4 100644 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinHumanoidArmorLayer.java @@ -1,17 +1,15 @@ -package net.coderbot.iris.mixin.entity_render_context; +package net.irisshaders.iris.mixin.entity_render_context; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.model.HumanoidModel; +import net.minecraft.client.model.Model; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.entity.RenderLayerParent; import net.minecraft.client.renderer.entity.layers.HumanoidArmorLayer; import net.minecraft.client.renderer.entity.layers.RenderLayer; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.EquipmentSlot; @@ -29,33 +27,33 @@ @Mixin(HumanoidArmorLayer.class) public abstract class MixinHumanoidArmorLayer, A extends HumanoidModel> - extends RenderLayer { + extends RenderLayer { + private int backupValue = 0; + public MixinHumanoidArmorLayer(RenderLayerParent pRenderLayer0) { super(pRenderLayer0); } @Inject(method = "renderArmorPiece", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/HumanoidModel;copyPropertiesTo(Lnet/minecraft/client/model/HumanoidModel;)V"), locals = LocalCapture.CAPTURE_FAILHARD) private void changeId(PoseStack pHumanoidArmorLayer0, MultiBufferSource pMultiBufferSource1, T pLivingEntity2, EquipmentSlot pEquipmentSlot3, int pInt4, A pHumanoidModel5, CallbackInfo ci, ItemStack lvItemStack7, Item item, ArmorItem lvArmorItem8) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; ResourceLocation location = BuiltInRegistries.ITEM.getKey(lvArmorItem8); - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); } - private int backupValue = 0; - @Inject(method = "renderTrim", at = @At(value = "HEAD"), locals = LocalCapture.CAPTURE_FAILHARD) private void changeTrimTemp(ArmorMaterial pHumanoidArmorLayer0, PoseStack pPoseStack1, MultiBufferSource pMultiBufferSource2, int pInt3, ArmorTrim pArmorTrim4, A pHumanoidModel5, boolean pBoolean6, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; backupValue = CapturedRenderingState.INSTANCE.getCurrentRenderedItem(); - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId("minecraft", "trim_" + pArmorTrim4.material().value().assetName()))); + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId("minecraft", "trim_" + pArmorTrim4.material().value().assetName()))); } @Inject(method = "renderTrim", at = @At(value = "TAIL")) private void changeTrimTemp2(ArmorMaterial pHumanoidArmorLayer0, PoseStack pPoseStack1, MultiBufferSource pMultiBufferSource2, int pInt3, ArmorTrim pArmorTrim4, A pHumanoidModel5, boolean pBoolean6, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; CapturedRenderingState.INSTANCE.setCurrentRenderedItem(backupValue); backupValue = 0; } @@ -64,4 +62,4 @@ private void changeTrimTemp2(ArmorMaterial pHumanoidArmorLayer0, PoseStack pPose private void changeId2(CallbackInfo ci) { CapturedRenderingState.INSTANCE.setCurrentRenderedItem(0); } -} +} \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinItemRenderer.java b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinItemRenderer.java similarity index 72% rename from src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinItemRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinItemRenderer.java index 6797a15c3a..aec9179611 100644 --- a/src/main/java/net/coderbot/iris/mixin/entity_render_context/MixinItemRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/entity_render_context/MixinItemRenderer.java @@ -1,24 +1,23 @@ -package net.coderbot.iris.mixin.entity_render_context; +package net.irisshaders.iris.mixin.entity_render_context; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.entity.ItemRenderer; import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.*; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemDisplayContext; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.SolidBucketItem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; @Mixin(value = ItemRenderer.class, priority = 1010) public abstract class MixinItemRenderer { @@ -32,19 +31,19 @@ private void changeId(ItemStack pItemRenderer0, ItemDisplayContext pItemTransfor @Unique private void iris$setupId(ItemStack pItemRenderer0) { - if (BlockRenderingSettings.INSTANCE.getItemIds() == null) return; + if (WorldRenderingSettings.INSTANCE.getItemIds() == null) return; if (pItemRenderer0.getItem() instanceof BlockItem blockItem && !(pItemRenderer0.getItem() instanceof SolidBucketItem)) { - if (BlockRenderingSettings.INSTANCE.getBlockStateIds() == null) return; + if (WorldRenderingSettings.INSTANCE.getBlockStateIds() == null) return; previousBeValue = CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(); CapturedRenderingState.INSTANCE.setCurrentBlockEntity(1); - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getBlockStateIds().getOrDefault(blockItem.getBlock().defaultBlockState(), 0)); + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getBlockStateIds().getOrDefault(blockItem.getBlock().defaultBlockState(), 0)); } else { ResourceLocation location = BuiltInRegistries.ITEM.getKey(pItemRenderer0.getItem()); - CapturedRenderingState.INSTANCE.setCurrentRenderedItem(BlockRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); + CapturedRenderingState.INSTANCE.setCurrentRenderedItem(WorldRenderingSettings.INSTANCE.getItemIds().applyAsInt(new NamespacedId(location.getNamespace(), location.getPath()))); } } diff --git a/src/main/java/net/coderbot/iris/mixin/fabulous/MixinDisableFabulousGraphics.java b/src/main/java/net/irisshaders/iris/mixin/fabulous/MixinDisableFabulousGraphics.java similarity index 94% rename from src/main/java/net/coderbot/iris/mixin/fabulous/MixinDisableFabulousGraphics.java rename to src/main/java/net/irisshaders/iris/mixin/fabulous/MixinDisableFabulousGraphics.java index 04a239920f..6cc395a0d2 100644 --- a/src/main/java/net/coderbot/iris/mixin/fabulous/MixinDisableFabulousGraphics.java +++ b/src/main/java/net/irisshaders/iris/mixin/fabulous/MixinDisableFabulousGraphics.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin.fabulous; +package net.irisshaders.iris.mixin.fabulous; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.Options; diff --git a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinFireworkSparkParticle.java b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinFireworkSparkParticle.java similarity index 94% rename from src/main/java/net/coderbot/iris/mixin/fantastic/MixinFireworkSparkParticle.java rename to src/main/java/net/irisshaders/iris/mixin/fantastic/MixinFireworkSparkParticle.java index 82897faf37..14c441fb99 100644 --- a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinFireworkSparkParticle.java +++ b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinFireworkSparkParticle.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.fantastic; +package net.irisshaders.iris.mixin.fantastic; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.ParticleRenderType; diff --git a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinLevelRenderer.java b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinLevelRenderer.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/fantastic/MixinLevelRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/fantastic/MixinLevelRenderer.java index 250836bee8..cb15186c08 100644 --- a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinLevelRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinLevelRenderer.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.mixin.fantastic; +package net.irisshaders.iris.mixin.fantastic; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.renderer.culling.Frustum; import org.joml.Matrix4f; -import net.coderbot.iris.Iris; -import net.coderbot.iris.fantastic.ParticleRenderingPhase; -import net.coderbot.iris.fantastic.PhasedParticleEngine; -import net.coderbot.iris.shaderpack.ParticleRenderingSettings; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.fantastic.ParticleRenderingPhase; +import net.irisshaders.iris.fantastic.PhasedParticleEngine; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.ParticleEngine; @@ -16,6 +16,7 @@ import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderBuffers; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -26,7 +27,7 @@ /** * Uses the PhasedParticleManager changes to render opaque particles much earlier than other particles. - * + *

    * See the comments in {@link MixinParticleEngine} for more details. */ @Mixin(LevelRenderer.class) @@ -66,8 +67,8 @@ public class MixinLevelRenderer { if (settings == ParticleRenderingSettings.AFTER) { minecraft.particleEngine.render(poseStack, bufferSource, lightTexture, camera, f, frustum); } else if (settings == ParticleRenderingSettings.MIXED) { - ((PhasedParticleEngine) minecraft.particleEngine).setParticleRenderingPhase(ParticleRenderingPhase.TRANSLUCENT); - minecraft.particleEngine.render(poseStack, bufferSource, lightTexture, camera, f, frustum); + ((PhasedParticleEngine) minecraft.particleEngine).setParticleRenderingPhase(ParticleRenderingPhase.TRANSLUCENT); + minecraft.particleEngine.render(poseStack, bufferSource, lightTexture, camera, f); } } diff --git a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinParticleEngine.java b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinParticleEngine.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/fantastic/MixinParticleEngine.java rename to src/main/java/net/irisshaders/iris/mixin/fantastic/MixinParticleEngine.java index 0ab53fbba3..5881b2888b 100644 --- a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinParticleEngine.java +++ b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinParticleEngine.java @@ -1,15 +1,14 @@ -package net.coderbot.iris.mixin.fantastic; +package net.irisshaders.iris.mixin.fantastic; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.fantastic.ParticleRenderingPhase; -import net.coderbot.iris.fantastic.PhasedParticleEngine; -import net.coderbot.iris.pipeline.ShaderAccess; -import net.minecraft.client.Camera; import net.minecraft.client.particle.Particle; +import net.irisshaders.iris.fantastic.ParticleRenderingPhase; +import net.irisshaders.iris.fantastic.PhasedParticleEngine; +import net.irisshaders.iris.pipeline.programs.ShaderAccess; import net.minecraft.client.particle.ParticleEngine; import net.minecraft.client.particle.ParticleRenderType; import net.minecraft.client.renderer.LightTexture; @@ -30,40 +29,36 @@ /** * Extends the ParticleEngine class to allow multiple phases of particle rendering. - * + *

    * This is used to enable the rendering of known-opaque particles much earlier than other particles, most notably before * translucent content. Normally, particles behind translucent blocks are not visible on Fancy graphics, and a user must * enable the much more intensive Fabulous graphics option. This is not ideal because Fabulous graphics is fundamentally * incompatible with most shader packs. - * + *

    * So what causes this? Essentially, on Fancy graphics, all particles are rendered after translucent terrain. Aside from * causing problems with particles being invisible, this also causes particles to write to the translucent depth buffer, * even when they are not translucent. This notably causes problems with particles on Sildur's Enhanced Default when * underwater. - * + *

    * So, what these mixins do is try to render known-opaque particles right before entities are rendered and right after * opaque terrain has been rendered. This seems to be an acceptable injection point, and has worked in my testing. It * fixes issues with particles when underwater, fixes a vanilla bug, and doesn't have any significant performance hit. * A win-win! - * + *

    * Unfortunately, there are limitations. Some particles rendering in texture sheets where translucency is supported. So, * even if an individual particle from that sheet is not translucent, it will still be treated as translucent, and thus * will not be affected by this patch. Without making more invasive and sweeping changes, there isn't a great way to get * around this. - * + *

    * As the saying goes, "Work smarter, not harder." */ @Mixin(ParticleEngine.class) public class MixinParticleEngine implements PhasedParticleEngine { - @Unique - private ParticleRenderingPhase phase = ParticleRenderingPhase.EVERYTHING; - + private static final Set OPAQUE_PARTICLE_RENDER_TYPES; @Shadow @Final private Map> particles; - private static final Set OPAQUE_PARTICLE_RENDER_TYPES; - static { OPAQUE_PARTICLE_RENDER_TYPES = ImmutableSet.of( ParticleRenderType.PARTICLE_SHEET_OPAQUE, @@ -73,7 +68,10 @@ public class MixinParticleEngine implements PhasedParticleEngine { ); } - @Redirect(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;FLnet/minecraft/client/renderer/culling/Frustum;)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;setShader(Ljava/util/function/Supplier;)V"), remap = false) + @Unique + private ParticleRenderingPhase phase = ParticleRenderingPhase.EVERYTHING; + + @Redirect(remap = false, method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource$BufferSource;Lnet/minecraft/client/renderer/LightTexture;Lnet/minecraft/client/Camera;FLnet/minecraft/client/renderer/culling/Frustum;)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/systems/RenderSystem;setShader(Ljava/util/function/Supplier;)V")) private void iris$changeParticleShader(Supplier pSupplier0) { RenderSystem.setShader(phase == ParticleRenderingPhase.TRANSLUCENT ? ShaderAccess::getParticleTranslucentShader : pSupplier0); } diff --git a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinStationaryItemParticle.java b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinStationaryItemParticle.java similarity index 94% rename from src/main/java/net/coderbot/iris/mixin/fantastic/MixinStationaryItemParticle.java rename to src/main/java/net/irisshaders/iris/mixin/fantastic/MixinStationaryItemParticle.java index 27998c8264..1376b9993f 100644 --- a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinStationaryItemParticle.java +++ b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinStationaryItemParticle.java @@ -1,6 +1,5 @@ -package net.coderbot.iris.mixin.fantastic; +package net.irisshaders.iris.mixin.fantastic; -import net.coderbot.iris.fantastic.IrisParticleRenderTypes; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.BlockMarker; diff --git a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinTerrainParticle.java b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinTerrainParticle.java similarity index 95% rename from src/main/java/net/coderbot/iris/mixin/fantastic/MixinTerrainParticle.java rename to src/main/java/net/irisshaders/iris/mixin/fantastic/MixinTerrainParticle.java index 6d37b2b9bd..1aef7828a3 100644 --- a/src/main/java/net/coderbot/iris/mixin/fantastic/MixinTerrainParticle.java +++ b/src/main/java/net/irisshaders/iris/mixin/fantastic/MixinTerrainParticle.java @@ -1,6 +1,5 @@ -package net.coderbot.iris.mixin.fantastic; +package net.irisshaders.iris.mixin.fantastic; -import net.coderbot.iris.fantastic.IrisParticleRenderTypes; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.ParticleRenderType; diff --git a/src/main/java/net/coderbot/iris/mixin/gui/MixinForgeGui.java b/src/main/java/net/irisshaders/iris/mixin/gui/MixinForgeGui.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/gui/MixinForgeGui.java rename to src/main/java/net/irisshaders/iris/mixin/gui/MixinForgeGui.java index 1601a5e97d..08b95adb49 100644 --- a/src/main/java/net/coderbot/iris/mixin/gui/MixinForgeGui.java +++ b/src/main/java/net/irisshaders/iris/mixin/gui/MixinForgeGui.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin.gui; +package net.irisshaders.iris.mixin.gui; -import net.coderbot.iris.gui.screen.HudHideable; +import net.irisshaders.iris.gui.screen.HudHideable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.screens.Screen; diff --git a/src/main/java/net/coderbot/iris/mixin/gui/MixinGui.java b/src/main/java/net/irisshaders/iris/mixin/gui/MixinGui.java similarity index 58% rename from src/main/java/net/coderbot/iris/mixin/gui/MixinGui.java rename to src/main/java/net/irisshaders/iris/mixin/gui/MixinGui.java index 2ed9067366..90e2667008 100644 --- a/src/main/java/net/coderbot/iris/mixin/gui/MixinGui.java +++ b/src/main/java/net/irisshaders/iris/mixin/gui/MixinGui.java @@ -1,18 +1,35 @@ -package net.coderbot.iris.mixin.gui; +package net.irisshaders.iris.mixin.gui; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.screen.HudHideable; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; import net.minecraft.world.entity.Entity; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Gui.class) public class MixinGui { + @Shadow + @Final + private Minecraft minecraft; + + @Inject(method = "render", at = @At("HEAD"), cancellable = true) + public void iris$handleHudHidingScreens(GuiGraphics pGui0, float pFloat1, CallbackInfo ci) { + Screen screen = this.minecraft.screen; + + if (screen instanceof HudHideable) { + ci.cancel(); + } + } @Inject(method = "renderVignette", at = @At("HEAD"), cancellable = true) private void iris$disableVignetteRendering(GuiGraphics pGui0, Entity pEntity1, CallbackInfo ci) { diff --git a/src/main/java/net/coderbot/iris/mixin/gui/MixinVideoSettingsScreen.java b/src/main/java/net/irisshaders/iris/mixin/gui/MixinVideoSettingsScreen.java similarity index 70% rename from src/main/java/net/coderbot/iris/mixin/gui/MixinVideoSettingsScreen.java rename to src/main/java/net/irisshaders/iris/mixin/gui/MixinVideoSettingsScreen.java index ccba2f6923..41e26971d8 100644 --- a/src/main/java/net/coderbot/iris/mixin/gui/MixinVideoSettingsScreen.java +++ b/src/main/java/net/irisshaders/iris/mixin/gui/MixinVideoSettingsScreen.java @@ -1,14 +1,11 @@ -package net.coderbot.iris.mixin.gui; +package net.irisshaders.iris.mixin.gui; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.coderbot.iris.gui.option.ShaderPackSelectionButtonOption; -import net.coderbot.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; import net.minecraft.client.OptionInstance; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.VideoSettingsScreen; -import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; - import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @@ -20,12 +17,12 @@ protected MixinVideoSettingsScreen(Component title) { } @ModifyArg( - method = "init", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/client/gui/components/OptionsList;addSmall([Lnet/minecraft/client/OptionInstance;)V" - ), - index = 0 + method = "init", + at = @At( + value = "INVOKE", + target = "Lnet/minecraft/client/gui/components/OptionsList;addSmall([Lnet/minecraft/client/OptionInstance;)V" + ), + index = 0 ) private OptionInstance[] iris$addShaderPackScreenButton(OptionInstance[] $$0) { OptionInstance[] options = new OptionInstance[$$0.length + 2]; diff --git a/src/main/java/net/coderbot/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java b/src/main/java/net/irisshaders/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java similarity index 76% rename from src/main/java/net/coderbot/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java rename to src/main/java/net/irisshaders/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java index 319357451d..ba5a7249f8 100644 --- a/src/main/java/net/coderbot/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java +++ b/src/main/java/net/irisshaders/iris/mixin/integrationtest/MixinRenderTarget_StencilBufferTest.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.integrationtest; +package net.irisshaders.iris.mixin.integrationtest; import com.mojang.blaze3d.pipeline.RenderTarget; @@ -12,11 +12,11 @@ /** * Tests switching the depth texture of the main Minecraft render target to use a stencil buffer, to ensure that * Iris remains compatible. Iris should continue to have good performance & should not spam the log with errors. - * + *

    * This mixin is not enabled by default. To enable integration tests, add the mixins.iris.integrationtest.json file * to the fabric.mod.json mixins list. Note that you'll also want to test if this works with the GL 3.0 framebuffer * blit path, by manually disabling the GL 4.3 copy path. - * + *

    * Previous issues: * *

      @@ -24,15 +24,15 @@ *
    • Extreme low FPS caused by hitting a driver slow path. We're talking ~13 FPS on an RTX 2070 Super with * Sildur's Vibrant Medium.
    • *
    - * - * Based on https://gist.github.com/burgerguy/8233170683ad93eea6aa27ee02a5c4d1 + *

    + * Based on this Gist. */ -@Mixin (RenderTarget.class) +@Mixin(RenderTarget.class) public class MixinRenderTarget_StencilBufferTest { private static final boolean STENCIL = true; - @ModifyArgs (method = "createBuffers", - at = @At (value = "INVOKE", + @ModifyArgs(method = "createBuffers", + at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_texImage2D(IIIIIIIILjava/nio/IntBuffer;)V", ordinal = 0)) public void init(Args args) { @@ -49,9 +49,9 @@ public void init(Args args) { } } - @ModifyArgs (method = "createBuffers", - at = @At (value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glFramebufferTexture2D(IIIII)V"), - slice = @Slice (from = @At (value = "FIELD", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;useDepth:Z", ordinal = 1))) + @ModifyArgs(method = "createBuffers", + at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;_glFramebufferTexture2D(IIIII)V"), + slice = @Slice(from = @At(value = "FIELD", target = "Lcom/mojang/blaze3d/pipeline/RenderTarget;useDepth:Z", ordinal = 1))) public void init2(Args args) { if (STENCIL) { // attachment diff --git a/src/main/java/net/coderbot/iris/mixin/rendertype/RenderStateShardAccessor.java b/src/main/java/net/irisshaders/iris/mixin/rendertype/RenderStateShardAccessor.java similarity index 89% rename from src/main/java/net/coderbot/iris/mixin/rendertype/RenderStateShardAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/rendertype/RenderStateShardAccessor.java index ed32ceab78..400d2dcc4f 100644 --- a/src/main/java/net/coderbot/iris/mixin/rendertype/RenderStateShardAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/rendertype/RenderStateShardAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.rendertype; +package net.irisshaders.iris.mixin.rendertype; import net.minecraft.client.renderer.RenderStateShard; import org.spongepowered.asm.mixin.Mixin; @@ -6,11 +6,11 @@ @Mixin(RenderStateShard.class) public interface RenderStateShardAccessor { - @Accessor("name") - String getName(); - @Accessor("TRANSLUCENT_TRANSPARENCY") static RenderStateShard.TransparencyStateShard getTranslucentTransparency() { throw new AssertionError(); } + + @Accessor("name") + String getName(); } diff --git a/src/main/java/net/coderbot/iris/mixin/rendertype/RenderTypeAccessor.java b/src/main/java/net/irisshaders/iris/mixin/rendertype/RenderTypeAccessor.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/rendertype/RenderTypeAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/rendertype/RenderTypeAccessor.java index ab22d0faa1..39342e3642 100644 --- a/src/main/java/net/coderbot/iris/mixin/rendertype/RenderTypeAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/rendertype/RenderTypeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.rendertype; +package net.irisshaders.iris.mixin.rendertype; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/shadows/MixinBeaconRenderer.java b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinBeaconRenderer.java similarity index 89% rename from src/main/java/net/coderbot/iris/mixin/shadows/MixinBeaconRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/shadows/MixinBeaconRenderer.java index d581d0295b..57b6aa221c 100644 --- a/src/main/java/net/coderbot/iris/mixin/shadows/MixinBeaconRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinBeaconRenderer.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.shadows; +package net.irisshaders.iris.mixin.shadows; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.shadows.ShadowRenderingState; +import net.irisshaders.iris.shadows.ShadowRenderingState; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BeaconRenderer; import net.minecraft.resources.ResourceLocation; @@ -13,7 +13,7 @@ @Mixin(BeaconRenderer.class) public class MixinBeaconRenderer { @Inject(method = "renderBeaconBeam(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;Lnet/minecraft/resources/ResourceLocation;FFJII[FFF)V", - at = @At("HEAD"), cancellable = true) + at = @At("HEAD"), cancellable = true) private static void iris$noLightBeamInShadowPass(PoseStack poseStack, MultiBufferSource multiBufferSource, ResourceLocation resourceLocation, float f, float g, long l, int i, int j, float[] fs, float h, float k, CallbackInfo ci) { diff --git a/src/main/java/net/irisshaders/iris/mixin/shadows/MixinLevelRenderer.java b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinLevelRenderer.java new file mode 100644 index 0000000000..4a5ccfd2c7 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinLevelRenderer.java @@ -0,0 +1,29 @@ +package net.irisshaders.iris.mixin.shadows; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.irisshaders.iris.shadows.CullingDataCache; +import net.minecraft.client.renderer.LevelRenderer; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; + +@Mixin(LevelRenderer.class) +public class MixinLevelRenderer implements CullingDataCache { + + @Override + public void saveState() { + swap(); + } + + @Override + public void restoreState() { + swap(); + } + + @Unique + private void swap() { + + } +} diff --git a/src/main/java/net/irisshaders/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java new file mode 100644 index 0000000000..98bb75df9b --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/shadows/MixinPreventRebuildNearInShadowPass.java @@ -0,0 +1,29 @@ +package net.irisshaders.iris.mixin.shadows; + +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import net.irisshaders.iris.shadows.ShadowRenderer; +import net.minecraft.client.Camera; +import net.minecraft.client.renderer.LevelRenderer; +import net.minecraft.client.renderer.culling.Frustum; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * Prevent nearby chunks from being rebuilt on the main thread in the shadow pass. Aside from causing FPS to tank, + * this also causes weird chunk corruption! It's critical to make sure that it's disabled as a result. + *

    + * This patch is not relevant with Sodium installed since Sodium has a completely different build path for terrain + * setup. + *

    + * Uses a priority of 1010 to apply after Sodium's overwrite, to allow for the Group behavior to activate. Otherwise, + * if we apply with the same priority, then we'll just get a Mixin error due to the injects conflicting with the + * {@code @Overwrite}. Using {@code @Group} allows us to avoid a fragile Mixin plugin. + */ +@Mixin(value = LevelRenderer.class, priority = 1010) +public abstract class MixinPreventRebuildNearInShadowPass { + +} \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java b/src/main/java/net/irisshaders/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java rename to src/main/java/net/irisshaders/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java index 76ccc5c147..4f7907159a 100644 --- a/src/main/java/net/coderbot/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java +++ b/src/main/java/net/irisshaders/iris/mixin/sky/MixinClientLevelData_DisableVoidPlane.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.mixin.sky; +package net.irisshaders.iris.mixin.sky; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.FogType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -12,8 +11,8 @@ /** * Disables void plane rendering when submerged in a fluid, to avoid breaking the fog illusion in oceans * and lava. - * - * Inspired by https://github.com/CaffeineMC/sodium-fabric/pull/710, but this implementation + *

    + * Inspired by this Sodium PR, but this implementation * takes a far more conservative approach and only disables specific parts of sky rendering in high-fog * situations. */ diff --git a/src/main/java/net/coderbot/iris/mixin/sky/MixinDimensionSpecialEffects.java b/src/main/java/net/irisshaders/iris/mixin/sky/MixinDimensionSpecialEffects.java similarity index 88% rename from src/main/java/net/coderbot/iris/mixin/sky/MixinDimensionSpecialEffects.java rename to src/main/java/net/irisshaders/iris/mixin/sky/MixinDimensionSpecialEffects.java index 2e41ad2490..849bd09cfa 100644 --- a/src/main/java/net/coderbot/iris/mixin/sky/MixinDimensionSpecialEffects.java +++ b/src/main/java/net/irisshaders/iris/mixin/sky/MixinDimensionSpecialEffects.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.mixin.sky; +package net.irisshaders.iris.mixin.sky; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.DimensionSpecialEffects; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.FogType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -14,8 +13,8 @@ /** * Disables the sunrise / sunset effect when blindness is active or when submerged in a fluid. - * - * Inspired by https://github.com/CaffeineMC/sodium-fabric/pull/710, but this implementation + *

    + * Inspired by this Sodium PR, but this implementation * takes a far more conservative approach and only disables specific parts of sky rendering in high-fog * situations. */ diff --git a/src/main/java/net/coderbot/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java b/src/main/java/net/irisshaders/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java similarity index 94% rename from src/main/java/net/coderbot/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java rename to src/main/java/net/irisshaders/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java index 9968e82df3..b9a4e1e99d 100644 --- a/src/main/java/net/coderbot/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java +++ b/src/main/java/net/irisshaders/iris/mixin/sky/MixinLevelRenderer_SunMoonToggle.java @@ -1,16 +1,15 @@ -package net.coderbot.iris.mixin.sky; +package net.irisshaders.iris.mixin.sky; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; -import org.joml.Matrix4f; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.Camera; import net.minecraft.client.renderer.LevelRenderer; -import org.lwjgl.opengl.GL11C; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/net/coderbot/iris/mixin/sky/MixinOptions_CloudsOverride.java b/src/main/java/net/irisshaders/iris/mixin/sky/MixinOptions_CloudsOverride.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/sky/MixinOptions_CloudsOverride.java rename to src/main/java/net/irisshaders/iris/mixin/sky/MixinOptions_CloudsOverride.java index 77633b9fee..08d7b8508d 100644 --- a/src/main/java/net/coderbot/iris/mixin/sky/MixinOptions_CloudsOverride.java +++ b/src/main/java/net/irisshaders/iris/mixin/sky/MixinOptions_CloudsOverride.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.sky; +package net.irisshaders.iris.mixin.sky; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.CloudSetting; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.properties.CloudSetting; import net.minecraft.client.CloudStatus; import net.minecraft.client.OptionInstance; import net.minecraft.client.Options; @@ -14,7 +14,7 @@ /** * Allows the current pipeline to override the cloud video mode setting. - * + *

    * Uses a priority of 1010 to apply after Sodium's MixinGameOptions, which overwrites getCloudsType, so that we can * override its behavior. */ diff --git a/src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinPostChain.java b/src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinPostChain.java new file mode 100644 index 0000000000..59092b839e --- /dev/null +++ b/src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinPostChain.java @@ -0,0 +1,13 @@ +package net.irisshaders.iris.mixin.state_tracking; + +import net.irisshaders.iris.Iris; +import net.minecraft.client.renderer.PostChain; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(PostChain.class) +public class MixinPostChain { + +} diff --git a/src/main/java/net/coderbot/iris/mixin/state_tracking/MixinRenderTarget.java b/src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinRenderTarget.java similarity index 96% rename from src/main/java/net/coderbot/iris/mixin/state_tracking/MixinRenderTarget.java rename to src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinRenderTarget.java index a934e1ff4b..ae59adc81a 100644 --- a/src/main/java/net/coderbot/iris/mixin/state_tracking/MixinRenderTarget.java +++ b/src/main/java/net/irisshaders/iris/mixin/state_tracking/MixinRenderTarget.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.state_tracking; +package net.irisshaders.iris.mixin.state_tracking; import com.mojang.blaze3d.pipeline.RenderTarget; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -26,11 +26,11 @@ * Iris. *

  • Vanilla Minecraft: This allows us to handle the Glowing effect without any other special casing needed. We * automatically switch off shader rendering as needed when Minecraft is writing to the glowing framebuffer. - * + *

    * No shader packs implement the glowing effect correctly, and few even try to have a decent fallback. The issue * is that implementing it properly requires a separate depth buffer, and shader packs have limited control over * depth buffers. - * + *

    * As it turns out, the implementation of the Glowing effect in Vanilla works fine for the most part. It uses a * framebuffer that is completely separate from that of shader pack rendering, and the effect is only applied * once the world has finished rendering.

  • diff --git a/src/main/java/net/coderbot/iris/mixin/statelisteners/BooleanStateAccessor.java b/src/main/java/net/irisshaders/iris/mixin/statelisteners/BooleanStateAccessor.java similarity index 55% rename from src/main/java/net/coderbot/iris/mixin/statelisteners/BooleanStateAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/statelisteners/BooleanStateAccessor.java index 8490c1741b..e08071acd6 100644 --- a/src/main/java/net/coderbot/iris/mixin/statelisteners/BooleanStateAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/statelisteners/BooleanStateAccessor.java @@ -1,9 +1,10 @@ -package net.coderbot.iris.mixin.statelisteners; +package net.irisshaders.iris.mixin.statelisteners; +import com.mojang.blaze3d.platform.GlStateManager; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; -@Mixin(targets = "com/mojang/blaze3d/platform/GlStateManager$BooleanState") +@Mixin(GlStateManager.BooleanState.class) public interface BooleanStateAccessor { @Accessor("enabled") boolean isEnabled(); diff --git a/src/main/java/net/coderbot/iris/mixin/statelisteners/MixinGlStateManager.java b/src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinGlStateManager.java similarity index 83% rename from src/main/java/net/coderbot/iris/mixin/statelisteners/MixinGlStateManager.java rename to src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinGlStateManager.java index 3dd16087c4..4aa61d94cf 100644 --- a/src/main/java/net/coderbot/iris/mixin/statelisteners/MixinGlStateManager.java +++ b/src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinGlStateManager.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.statelisteners; +package net.irisshaders.iris.mixin.statelisteners; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -11,7 +11,11 @@ public class MixinGlStateManager { private static Runnable blendFuncListener; - @Inject(method = "_blendFunc", at = @At("RETURN")) + static { + StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener; + } + + @Inject(method = "_blendFunc", at = @At("RETURN"), remap = false) private static void iris$onBlendFunc(int srcRgb, int dstRgb, CallbackInfo ci) { if (blendFuncListener != null) { blendFuncListener.run(); @@ -24,8 +28,4 @@ public class MixinGlStateManager { blendFuncListener.run(); } } - - static { - StateUpdateNotifiers.blendFuncNotifier = listener -> blendFuncListener = listener; - } } diff --git a/src/main/java/net/coderbot/iris/mixin/statelisteners/MixinRenderSystem.java b/src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinRenderSystem.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/statelisteners/MixinRenderSystem.java rename to src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinRenderSystem.java index 87d5b86b2a..629c6bb723 100644 --- a/src/main/java/net/coderbot/iris/mixin/statelisteners/MixinRenderSystem.java +++ b/src/main/java/net/irisshaders/iris/mixin/statelisteners/MixinRenderSystem.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.statelisteners; +package net.irisshaders.iris.mixin.statelisteners; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -12,6 +12,11 @@ public class MixinRenderSystem { private static Runnable fogStartListener; private static Runnable fogEndListener; + static { + StateUpdateNotifiers.fogStartNotifier = listener -> fogStartListener = listener; + StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener; + } + @Inject(method = "_setShaderFogStart", at = @At(value = "FIELD", target = "Lcom/mojang/blaze3d/systems/RenderSystem;shaderFogStart:F", shift = At.Shift.AFTER)) private static void iris$onFogStart(float start, CallbackInfo ci) { if (fogStartListener != null) { @@ -25,9 +30,4 @@ public class MixinRenderSystem { fogEndListener.run(); } } - - static { - StateUpdateNotifiers.fogStartNotifier = listener -> fogStartListener = listener; - StateUpdateNotifiers.fogEndNotifier = listener -> fogEndListener = listener; - } } diff --git a/src/main/java/net/coderbot/iris/mixin/texture/AnimationMetadataSectionAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/AnimationMetadataSectionAccessor.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/texture/AnimationMetadataSectionAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/AnimationMetadataSectionAccessor.java index d29197cf2d..5a849b33a6 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/AnimationMetadataSectionAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/AnimationMetadataSectionAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/MixinAbstractTexture.java b/src/main/java/net/irisshaders/iris/mixin/texture/MixinAbstractTexture.java similarity index 90% rename from src/main/java/net/coderbot/iris/mixin/texture/MixinAbstractTexture.java rename to src/main/java/net/irisshaders/iris/mixin/texture/MixinAbstractTexture.java index 3b0980f6c8..08f7af9429 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/MixinAbstractTexture.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/MixinAbstractTexture.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; -import net.coderbot.iris.texture.TextureTracker; +import net.irisshaders.iris.texture.TextureTracker; import net.minecraft.client.renderer.texture.AbstractTexture; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/MixinGlStateManager.java b/src/main/java/net/irisshaders/iris/mixin/texture/MixinGlStateManager.java similarity index 85% rename from src/main/java/net/coderbot/iris/mixin/texture/MixinGlStateManager.java rename to src/main/java/net/irisshaders/iris/mixin/texture/MixinGlStateManager.java index a179dd2450..be59bbd625 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/MixinGlStateManager.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/MixinGlStateManager.java @@ -1,14 +1,13 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.texture.TextureInfoCache; -import net.coderbot.iris.texture.TextureTracker; -import net.coderbot.iris.texture.pbr.PBRTextureManager; +import net.irisshaders.iris.texture.TextureInfoCache; +import net.irisshaders.iris.texture.TextureTracker; +import net.irisshaders.iris.texture.pbr.PBRTextureManager; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.At.Shift; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/MixinResourceLocation.java b/src/main/java/net/irisshaders/iris/mixin/texture/MixinResourceLocation.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/texture/MixinResourceLocation.java rename to src/main/java/net/irisshaders/iris/mixin/texture/MixinResourceLocation.java index ebea488ff9..3d8349ade7 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/MixinResourceLocation.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/MixinResourceLocation.java @@ -1,7 +1,5 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.Iris; import net.minecraft.resources.ResourceLocation; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/MixinSpriteContents.java b/src/main/java/net/irisshaders/iris/mixin/texture/MixinSpriteContents.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/texture/MixinSpriteContents.java rename to src/main/java/net/irisshaders/iris/mixin/texture/MixinSpriteContents.java index ddbeae2523..673376c083 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/MixinSpriteContents.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/MixinSpriteContents.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import com.mojang.blaze3d.platform.NativeImage; -import net.coderbot.iris.Iris; -import net.coderbot.iris.texture.SpriteContentsExtension; -import net.coderbot.iris.texture.mipmap.CustomMipmapGenerator; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.texture.SpriteContentsExtension; +import net.irisshaders.iris.texture.mipmap.CustomMipmapGenerator; import net.minecraft.client.renderer.texture.MipmapGenerator; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.SpriteTicker; @@ -23,8 +23,7 @@ public class MixinSpriteContents implements SpriteContentsExtension { @Redirect(method = "increaseMipLevel", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/texture/MipmapGenerator;generateMipLevels([Lcom/mojang/blaze3d/platform/NativeImage;I)[Lcom/mojang/blaze3d/platform/NativeImage;")) private NativeImage[] iris$redirectMipmapGeneration(NativeImage[] nativeImages, int mipLevel) { - if (this instanceof CustomMipmapGenerator.Provider) { - CustomMipmapGenerator.Provider provider = (CustomMipmapGenerator.Provider) this; + if (this instanceof CustomMipmapGenerator.Provider provider) { CustomMipmapGenerator generator = provider.getMipmapGenerator(); if (generator != null) { try { diff --git a/src/main/java/net/coderbot/iris/mixin/texture/MixinTextureManager.java b/src/main/java/net/irisshaders/iris/mixin/texture/MixinTextureManager.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/texture/MixinTextureManager.java rename to src/main/java/net/irisshaders/iris/mixin/texture/MixinTextureManager.java index 271081df8a..ef746026d6 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/MixinTextureManager.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/MixinTextureManager.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.coderbot.iris.texture.pbr.PBRTextureManager; +import net.irisshaders.iris.texture.format.TextureFormatLoader; +import net.irisshaders.iris.texture.pbr.PBRTextureManager; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.server.packs.resources.ResourceManager; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/SimpleTextureAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/SimpleTextureAccessor.java similarity index 88% rename from src/main/java/net/coderbot/iris/mixin/texture/SimpleTextureAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/SimpleTextureAccessor.java index 45f85cda4a..1374865fe8 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/SimpleTextureAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/SimpleTextureAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAccessor.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAccessor.java index 9fac2fedcc..e30f722413 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.SpriteContents; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java similarity index 91% rename from src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java index 98e360477b..4da917cc3b 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsAnimatedTextureAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.SpriteContents; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java index 93018e4595..e17563dd5b 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsFrameInfoAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.SpriteContents; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsTickerAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsTickerAccessor.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsTickerAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsTickerAccessor.java index 863e3b063e..4162d8ccf3 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/SpriteContentsTickerAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/SpriteContentsTickerAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.SpriteContents.AnimatedTexture; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/TextureAtlasAccessor.java b/src/main/java/net/irisshaders/iris/mixin/texture/TextureAtlasAccessor.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/texture/TextureAtlasAccessor.java rename to src/main/java/net/irisshaders/iris/mixin/texture/TextureAtlasAccessor.java index edab693c02..da268ff2ac 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/TextureAtlasAccessor.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/TextureAtlasAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.texture; +package net.irisshaders.iris.mixin.texture; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinDirectoryLister.java b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinDirectoryLister.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinDirectoryLister.java rename to src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinDirectoryLister.java index 31af51028d..2f17bfdb0a 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinDirectoryLister.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinDirectoryLister.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin.texture.pbr; +package net.irisshaders.iris.mixin.texture.pbr; -import net.coderbot.iris.texture.pbr.PBRType; +import net.irisshaders.iris.texture.pbr.PBRType; import net.minecraft.client.renderer.texture.atlas.SpriteSource; import net.minecraft.client.renderer.texture.atlas.sources.DirectoryLister; import net.minecraft.resources.FileToIdConverter; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinSpriteContents.java b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinSpriteContents.java similarity index 83% rename from src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinSpriteContents.java rename to src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinSpriteContents.java index 03e7a489ec..a9758d7067 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinSpriteContents.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinSpriteContents.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.texture.pbr; +package net.irisshaders.iris.mixin.texture.pbr; -import net.coderbot.iris.texture.pbr.PBRSpriteHolder; -import net.coderbot.iris.texture.pbr.SpriteContentsExtension; +import net.irisshaders.iris.texture.pbr.PBRSpriteHolder; +import net.irisshaders.iris.texture.pbr.SpriteContentsExtension; import net.minecraft.client.renderer.texture.SpriteContents; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; diff --git a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinTextureAtlas.java b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinTextureAtlas.java similarity index 87% rename from src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinTextureAtlas.java rename to src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinTextureAtlas.java index 218e0c998a..58b9925c00 100644 --- a/src/main/java/net/coderbot/iris/mixin/texture/pbr/MixinTextureAtlas.java +++ b/src/main/java/net/irisshaders/iris/mixin/texture/pbr/MixinTextureAtlas.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.mixin.texture.pbr; +package net.irisshaders.iris.mixin.texture.pbr; -import net.coderbot.iris.texture.pbr.PBRAtlasHolder; -import net.coderbot.iris.texture.pbr.TextureAtlasExtension; +import net.irisshaders.iris.texture.pbr.PBRAtlasHolder; +import net.irisshaders.iris.texture.pbr.TextureAtlasExtension; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/net/coderbot/iris/mixin/texunits/MixinGlStateManager.java b/src/main/java/net/irisshaders/iris/mixin/texunits/MixinGlStateManager.java similarity index 100% rename from src/main/java/net/coderbot/iris/mixin/texunits/MixinGlStateManager.java rename to src/main/java/net/irisshaders/iris/mixin/texunits/MixinGlStateManager.java diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/MixinBufferBuilder.java b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java similarity index 67% rename from src/main/java/net/coderbot/iris/mixin/vertices/MixinBufferBuilder.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java index 5b8ae15471..eb6606f5a9 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/MixinBufferBuilder.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinBufferBuilder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.vertices; +package net.irisshaders.iris.mixin.vertices; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferVertexConsumer; @@ -7,24 +7,25 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import org.joml.Vector3f; -import net.coderbot.iris.vertices.NormI8; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.BufferBuilderPolygonView; +import net.irisshaders.iris.vertices.ExtendedDataHelper; +import net.irisshaders.iris.vertices.ExtendingBufferBuilder; +import net.irisshaders.iris.vertices.IrisExtendedBufferBuilder; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormI8; +import net.irisshaders.iris.vertices.NormalHelper; import org.jetbrains.annotations.NotNull; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.BlockSensitiveBufferBuilder; -import net.coderbot.iris.vertices.BufferBuilderPolygonView; -import net.coderbot.iris.vertices.ExtendedDataHelper; -import net.coderbot.iris.vertices.ExtendingBufferBuilder; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormalHelper; import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.nio.ByteBuffer; @@ -33,49 +34,31 @@ * Dynamically and transparently extends the vanilla vertex formats with additional data */ @Mixin(BufferBuilder.class) -public abstract class MixinBufferBuilder extends DefaultedVertexConsumer implements BufferVertexConsumer, BlockSensitiveBufferBuilder, ExtendingBufferBuilder { +public abstract class MixinBufferBuilder extends DefaultedVertexConsumer implements BufferVertexConsumer, BlockSensitiveBufferBuilder, ExtendingBufferBuilder, IrisExtendedBufferBuilder { @Unique - private boolean extending; - - @Unique - private boolean iris$shouldNotExtend = false; - + private final BufferBuilderPolygonView polygon = new BufferBuilderPolygonView(); @Unique - private boolean iris$isTerrain = false; - + private final Vector3f normal = new Vector3f(); @Unique - private int vertexCount; - + private boolean iris$shouldNotExtend; @Unique - private final BufferBuilderPolygonView polygon = new BufferBuilderPolygonView(); - + private boolean extending; @Unique - private final Vector3f normal = new Vector3f(); - + private boolean iris$isTerrain; @Unique private boolean injectNormalAndUV1; - @Unique - private short currentBlock; - + private int vertexCount; @Unique - private short currentRenderType; - + private short currentBlock = -1; + @Unique + private short currentRenderType = -1; @Unique private int currentLocalPosX; - @Unique private int currentLocalPosY; - @Unique private int currentLocalPosZ; - - @Shadow - private boolean fastFormat; - - @Shadow - private boolean fullFormat; - @Shadow private ByteBuffer buffer; @@ -97,9 +80,6 @@ public abstract class MixinBufferBuilder extends DefaultedVertexConsumer impleme @Shadow public abstract void putShort(int i, short s); - @Shadow - protected abstract void switchFormat(VertexFormat arg); - @Shadow public abstract void nextElement(); @@ -110,75 +90,44 @@ public abstract class MixinBufferBuilder extends DefaultedVertexConsumer impleme iris$shouldNotExtend = false; } - @Inject(method = "begin", at = @At("HEAD")) - private void iris$onBegin(VertexFormat.Mode drawMode, VertexFormat format, CallbackInfo ci) { - boolean shouldExtend = (!iris$shouldNotExtend) && BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat(); - extending = shouldExtend && (format == DefaultVertexFormat.BLOCK || format == DefaultVertexFormat.NEW_ENTITY - || format == DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP); - vertexCount = 0; - - if (extending) { - injectNormalAndUV1 = format == DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP; - } - } - - @Inject(method = "begin", at = @At("RETURN")) - private void iris$afterBegin(VertexFormat.Mode drawMode, VertexFormat format, CallbackInfo ci) { - if (extending) { - if (format == DefaultVertexFormat.BLOCK) { - this.switchFormat(IrisVertexFormats.TERRAIN); - this.iris$isTerrain = true; - } else if (format == DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP) { - this.switchFormat(IrisVertexFormats.GLYPH); - this.iris$isTerrain = false; - } else { - this.switchFormat(IrisVertexFormats.ENTITY); - this.iris$isTerrain = false; - } - this.currentElement = this.format.getElements().get(0); - } - } - @Override public @NotNull VertexConsumer uv2(int pBufferVertexConsumer0, int pInt1) { - return BufferVertexConsumer.super.uv2(pBufferVertexConsumer0, pInt1); } - @ModifyArg(method = "begin", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/vertex/BufferBuilder;switchFormat(Lcom/mojang/blaze3d/vertex/VertexFormat;)V")) - private VertexFormat iris$afterBeginSwitchFormat(VertexFormat arg) { - if (extending) { - if (format == DefaultVertexFormat.BLOCK) { - this.switchFormat(IrisVertexFormats.TERRAIN); - this.iris$isTerrain = true; - } else if (format == DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP) { - this.switchFormat(IrisVertexFormats.GLYPH); - this.iris$isTerrain = false; - } else { - this.switchFormat(IrisVertexFormats.ENTITY); - this.iris$isTerrain = false; - } - } - return arg; - } - - - - @Inject(method = "discard()V", at = @At("HEAD")) - private void iris$onDiscard(CallbackInfo ci) { + @ModifyVariable(method = "begin", at = @At("HEAD"), argsOnly = true) + private VertexFormat iris$extendFormat(VertexFormat format) { extending = false; + iris$isTerrain = false; injectNormalAndUV1 = false; - vertexCount = 0; - } - @Inject(method = "switchFormat", at = @At("RETURN")) - private void iris$preventHardcodedVertexWriting(VertexFormat format, CallbackInfo ci) { - if (!extending) { - return; + if (iris$shouldNotExtend || !WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) { + return format; + } + + if (format == DefaultVertexFormat.BLOCK) { + extending = true; + iris$isTerrain = true; + injectNormalAndUV1 = false; + return IrisVertexFormats.TERRAIN; + } else if (format == DefaultVertexFormat.NEW_ENTITY) { + extending = true; + iris$isTerrain = false; + injectNormalAndUV1 = false; + return IrisVertexFormats.ENTITY; + } else if (format == DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP) { + extending = true; + iris$isTerrain = false; + injectNormalAndUV1 = true; + return IrisVertexFormats.GLYPH; } - fastFormat = false; - fullFormat = false; + return format; + } + + @Inject(method = "reset()V", at = @At("HEAD")) + private void iris$onReset(CallbackInfo ci) { + vertexCount = 0; } @Inject(method = "endVertex", at = @At("HEAD")) @@ -197,7 +146,7 @@ public abstract class MixinBufferBuilder extends DefaultedVertexConsumer impleme this.putShort(0, currentBlock); this.putShort(2, currentRenderType); } else { - // ENTITY_ELEMENT + // ENTITY_ID_ELEMENT this.putShort(0, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()); this.putShort(2, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); this.putShort(4, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); @@ -290,6 +239,11 @@ private void fillExtendedData(int vertexAmount) { } } + @Unique + private void putInt(int i, int value) { + this.buffer.putInt(this.nextElementByte + i, value); + } + @Override public void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ) { this.currentBlock = block; @@ -308,8 +262,68 @@ public void endBlock() { this.currentLocalPosZ = 0; } - @Unique - private void putInt(int i, int value) { - this.buffer.putInt(this.nextElementByte + i, value); + @Override + public VertexFormat iris$format() { + return format; + } + + @Override + public VertexFormat.Mode iris$mode() { + return mode; + } + + @Override + public boolean iris$extending() { + return extending; + } + + @Override + public boolean iris$isTerrain() { + return iris$isTerrain; + } + + @Override + public boolean iris$injectNormalAndUV1() { + return injectNormalAndUV1; + } + + @Override + public int iris$vertexCount() { + return vertexCount; + } + + @Override + public void iris$incrementVertexCount() { + vertexCount++; + } + + @Override + public void iris$resetVertexCount() { + vertexCount = 0; + } + + @Override + public short iris$currentBlock() { + return currentBlock; + } + + @Override + public short iris$currentRenderType() { + return currentRenderType; + } + + @Override + public int iris$currentLocalPosX() { + return currentLocalPosX; + } + + @Override + public int iris$currentLocalPosY() { + return currentLocalPosY; + } + + @Override + public int iris$currentLocalPosZ() { + return currentLocalPosZ; } -} +} \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormat.java b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormat.java similarity index 82% rename from src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormat.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormat.java index ce59b40cea..ce89f333ba 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormat.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormat.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.mixin.vertices; +package net.irisshaders.iris.mixin.vertices; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.vertices.ImmediateState; -import net.coderbot.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.vertices.ImmediateState; +import net.irisshaders.iris.vertices.IrisVertexFormats; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -17,7 +17,7 @@ public class MixinVertexFormat { @Inject(method = "setupBufferState", at = @At("HEAD"), cancellable = true) private void iris$onSetupBufferState(CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() && ImmediateState.renderWithExtendedVertexFormat) { + if (WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() && ImmediateState.renderWithExtendedVertexFormat) { if ((Object) this == DefaultVertexFormat.BLOCK) { IrisVertexFormats.TERRAIN.setupBufferState(); @@ -36,7 +36,7 @@ public class MixinVertexFormat { @Inject(method = "clearBufferState", at = @At("HEAD"), cancellable = true) private void iris$onClearBufferState(CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() && ImmediateState.renderWithExtendedVertexFormat) { + if (WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() && ImmediateState.renderWithExtendedVertexFormat) { if ((Object) this == DefaultVertexFormat.BLOCK) { IrisVertexFormats.TERRAIN.clearBufferState(); diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormatElement.java b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormatElement.java similarity index 94% rename from src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormatElement.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormatElement.java index 677667d1ef..ced52c687c 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/MixinVertexFormatElement.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/MixinVertexFormatElement.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.mixin.vertices; +package net.irisshaders.iris.mixin.vertices; import com.mojang.blaze3d.vertex.VertexFormatElement; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java index e8ced92f40..0bbe6e215c 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinBufferBuilder_SeparateAo.java @@ -1,12 +1,11 @@ -package net.coderbot.iris.mixin.vertices.block_rendering; +package net.irisshaders.iris.mixin.vertices.block_rendering; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.DefaultedVertexConsumer; import com.mojang.blaze3d.vertex.PoseStack; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.client.renderer.block.model.BakedQuad; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable; @@ -14,11 +13,11 @@ /** * Allows directional shading and ambient occlusion data to be stored separately in the vertex format. - * + *

    * By default, directional shading and ambient occlusion lighting coefficients are pre-multiplied into the vertex color * RGB. However, this causes issues with shader packs which would like to operate on this data separately from the * actual vertex color, which is generally Minecraft's built-in block tinting such as water color and foliage color. - * + *

    * Since the alpha field of the vertex color is unused for blocks (always set to 1.0), it is possible to use the alpha * field to store the directional shading / ambient occlusion coefficient for each vertex. This mixin implements that * behavior, though conditionally controlled by the current shader pack of course. @@ -31,8 +30,8 @@ public abstract class MixinBufferBuilder_SeparateAo extends DefaultedVertexConsu @Override public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brightnesses, float red, float green, - float blue, int[] lights, int overlay, boolean useQuadColorData) { - if (BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { + float blue, int[] lights, int overlay, boolean useQuadColorData) { + if (WorldRenderingSettings.INSTANCE.shouldUseSeparateAo()) { this.brightnesses = brightnesses; this.brightnessIndex = 0; @@ -45,7 +44,7 @@ public void putBulkData(PoseStack.Pose matrixEntry, BakedQuad quad, float[] brig @ModifyVariable(method = "vertex", at = @At("HEAD"), index = 7, argsOnly = true) public float vertex(float alpha) { - if (brightnesses != null && BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { + if (brightnesses != null && WorldRenderingSettings.INSTANCE.shouldUseSeparateAo()) { if (brightnessIndex < brightnesses.length) { alpha = brightnesses[brightnessIndex++]; } else { diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java similarity index 88% rename from src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java index fa1298f416..9609f7bccb 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinChunkRebuildTask.java @@ -1,12 +1,11 @@ -package net.coderbot.iris.mixin.vertices.block_rendering; +package net.irisshaders.iris.mixin.vertices.block_rendering; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.ReferenceArraySet; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.vertices.BlockSensitiveBufferBuilder; -import net.coderbot.iris.vertices.ExtendedDataHelper; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.ExtendedDataHelper; import net.minecraft.client.renderer.ChunkBufferBuilderPack; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.BlockRenderDispatcher; @@ -16,7 +15,6 @@ import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.FluidState; import net.minecraftforge.client.model.data.ModelData; @@ -28,28 +26,26 @@ import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Iterator; -import java.util.Random; import java.util.Set; /** * Captures and tracks the current block being rendered. - * + *

    * Uses a priority of 999 so that we apply before Indigo's mixins. */ @Mixin(targets = "net.minecraft.client.renderer.chunk.ChunkRenderDispatcher$RenderChunk$RebuildTask", priority = 999) public class MixinChunkRebuildTask { - private static final String RENDER = "Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask;compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;"; - @Unique - private BlockSensitiveBufferBuilder lastBufferBuilder; - + private static final String RENDER = "Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask;compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;"; // Resolve the ID map on the main thread to avoid thread safety issues @Unique private final Object2IntMap blockStateIds = getBlockStateIds(); + @Unique + private BlockSensitiveBufferBuilder lastBufferBuilder; @Unique private Object2IntMap getBlockStateIds() { - return BlockRenderingSettings.INSTANCE.getBlockStateIds(); + return WorldRenderingSettings.INSTANCE.getBlockStateIds(); } @Unique @@ -62,7 +58,7 @@ private short resolveBlockId(BlockState state) { } @Inject(method = RENDER, at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/block/BlockRenderDispatcher;renderLiquid(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/BlockAndTintGetter;Lcom/mojang/blaze3d/vertex/VertexConsumer;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/material/FluidState;)V"), locals = LocalCapture.CAPTURE_FAILHARD) - private void iris$onRenderLiquid(float cameraX, float cameraY, float cameraZ, ChunkBufferBuilderPack buffers, CallbackInfoReturnable cir, ChunkRenderDispatcher.RenderChunk.RebuildTask.CompileResults results,int i, BlockPos blockPos, BlockPos blockPos2, VisGraph chunkOcclusionDataBuilder,RenderChunkRegion chunkRendererRegion, PoseStack poseStack, Set set2, RandomSource random, BlockRenderDispatcher blockRenderManager, Iterator var15, BlockPos blockPos3, BlockState blockState, BlockState state2, FluidState fluidState, RenderType renderType, BufferBuilder bufferBuilder2) { + private void iris$onRenderLiquid(float cameraX, float cameraY, float cameraZ, ChunkBufferBuilderPack buffers, CallbackInfoReturnable cir, ChunkRenderDispatcher.RenderChunk.RebuildTask.CompileResults results, int i, BlockPos blockPos, BlockPos blockPos2, VisGraph chunkOcclusionDataBuilder, RenderChunkRegion chunkRendererRegion, PoseStack poseStack, Set set2, RandomSource random, BlockRenderDispatcher blockRenderManager, Iterator var15, BlockPos blockPos3, BlockState blockState, BlockState blockState2, FluidState fluidState, RenderType renderType, BufferBuilder bufferBuilder2) { if (bufferBuilder2 instanceof BlockSensitiveBufferBuilder) { lastBufferBuilder = ((BlockSensitiveBufferBuilder) bufferBuilder2); // All fluids have a ShadersMod render type of 1, to match behavior of Minecraft 1.7 and earlier. diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinClientLevel.java b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinClientLevel.java similarity index 84% rename from src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinClientLevel.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinClientLevel.java index ce0b4628fa..e69409f7b4 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/block_rendering/MixinClientLevel.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/block_rendering/MixinClientLevel.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.mixin.vertices.block_rendering; +package net.irisshaders.iris.mixin.vertices.block_rendering; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.client.multiplayer.ClientLevel; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -14,7 +14,7 @@ public class MixinClientLevel { @ModifyVariable(method = "getShade(Lnet/minecraft/core/Direction;Z)F", at = @At("HEAD"), argsOnly = true) private boolean iris$maybeDisableDirectionalShading(boolean shaded) { - if (BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { + if (WorldRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { return false; } else { return shaded; diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinBufferSource.java b/src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinBufferSource.java similarity index 93% rename from src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinBufferSource.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinBufferSource.java index 803fc45b55..0d86591192 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinBufferSource.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinBufferSource.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.mixin.vertices.immediate; +package net.irisshaders.iris.mixin.vertices.immediate; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.vertices.ExtendingBufferBuilder; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.vertices.ExtendingBufferBuilder; +import net.irisshaders.iris.vertices.ImmediateState; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinLevelRenderer.java b/src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinLevelRenderer.java similarity index 92% rename from src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinLevelRenderer.java rename to src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinLevelRenderer.java index 5b90825e3d..c6dc76bd6b 100644 --- a/src/main/java/net/coderbot/iris/mixin/vertices/immediate/MixinLevelRenderer.java +++ b/src/main/java/net/irisshaders/iris/mixin/vertices/immediate/MixinLevelRenderer.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.mixin.vertices.immediate; +package net.irisshaders.iris.mixin.vertices.immediate; import com.mojang.blaze3d.vertex.PoseStack; -import org.joml.Matrix4f; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.vertices.ImmediateState; import net.minecraft.client.Camera; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.LightTexture; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/main/java/net/coderbot/iris/parsing/BiomeCategories.java b/src/main/java/net/irisshaders/iris/parsing/BiomeCategories.java similarity index 87% rename from src/main/java/net/coderbot/iris/parsing/BiomeCategories.java rename to src/main/java/net/irisshaders/iris/parsing/BiomeCategories.java index 22fe371816..bcf28aafb7 100644 --- a/src/main/java/net/coderbot/iris/parsing/BiomeCategories.java +++ b/src/main/java/net/irisshaders/iris/parsing/BiomeCategories.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; public enum BiomeCategories { NONE, diff --git a/src/main/java/net/coderbot/iris/parsing/BooleanVectorizedFunction.java b/src/main/java/net/irisshaders/iris/parsing/BooleanVectorizedFunction.java similarity index 96% rename from src/main/java/net/coderbot/iris/parsing/BooleanVectorizedFunction.java rename to src/main/java/net/irisshaders/iris/parsing/BooleanVectorizedFunction.java index 85e1badf7d..7f9b7b2c6f 100644 --- a/src/main/java/net/coderbot/iris/parsing/BooleanVectorizedFunction.java +++ b/src/main/java/net/irisshaders/iris/parsing/BooleanVectorizedFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.expression.VariableExpression; @@ -52,7 +52,7 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet for (int i = 0; i < this.size; i++) { this.index = i; this.inner.evaluateTo(this.vectorAccessors, context, functionReturn); - if(!functionReturn.booleanReturn) + if (!functionReturn.booleanReturn) return; // if false -> return false } diff --git a/src/main/java/net/coderbot/iris/parsing/ExtendedBiome.java b/src/main/java/net/irisshaders/iris/parsing/ExtendedBiome.java similarity index 63% rename from src/main/java/net/coderbot/iris/parsing/ExtendedBiome.java rename to src/main/java/net/irisshaders/iris/parsing/ExtendedBiome.java index d0557e4c3f..c441b93aa9 100644 --- a/src/main/java/net/coderbot/iris/parsing/ExtendedBiome.java +++ b/src/main/java/net/irisshaders/iris/parsing/ExtendedBiome.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; public interface ExtendedBiome { - void setBiomeCategory(int biomeCategory); - int getBiomeCategory(); - float getDownfall(); + void setBiomeCategory(int biomeCategory); + + float getDownfall(); } diff --git a/src/main/java/net/coderbot/iris/parsing/IrisFunctions.java b/src/main/java/net/irisshaders/iris/parsing/IrisFunctions.java similarity index 84% rename from src/main/java/net/coderbot/iris/parsing/IrisFunctions.java rename to src/main/java/net/irisshaders/iris/parsing/IrisFunctions.java index a7f7ac7641..380ab557c5 100644 --- a/src/main/java/net/coderbot/iris/parsing/IrisFunctions.java +++ b/src/main/java/net/irisshaders/iris/parsing/IrisFunctions.java @@ -1,11 +1,36 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.expression.Expression; -import kroppeb.stareval.function.*; +import kroppeb.stareval.function.AbstractTypedFunction; +import kroppeb.stareval.function.B2BFunction; +import kroppeb.stareval.function.BB2BFunction; +import kroppeb.stareval.function.F2FFunction; +import kroppeb.stareval.function.F2IFunction; +import kroppeb.stareval.function.FF2BFunction; +import kroppeb.stareval.function.FF2FFunction; +import kroppeb.stareval.function.FFF2BFunction; +import kroppeb.stareval.function.FFF2FFunction; +import kroppeb.stareval.function.FunctionContext; +import kroppeb.stareval.function.FunctionResolver; +import kroppeb.stareval.function.FunctionReturn; +import kroppeb.stareval.function.I2IFunction; +import kroppeb.stareval.function.II2BFunction; +import kroppeb.stareval.function.II2IFunction; +import kroppeb.stareval.function.III2BFunction; +import kroppeb.stareval.function.III2IFunction; +import kroppeb.stareval.function.Type; +import kroppeb.stareval.function.TypedFunction; import kroppeb.stareval.function.TypedFunction.Parameter; -import org.joml.*; +import kroppeb.stareval.function.V2FFunction; +import kroppeb.stareval.function.V2IFunction; +import org.joml.Matrix4f; +import org.joml.Vector2f; +import org.joml.Vector2i; +import org.joml.Vector3f; +import org.joml.Vector3i; +import org.joml.Vector4f; +import org.joml.Vector4i; -import java.lang.Math; import java.util.Arrays; import java.util.Random; import java.util.function.BiConsumer; @@ -40,15 +65,15 @@ * # smooth([id], val, [fadeInTime, [fadeOutTime]]) Smooths a variable with custom fade-in time. * # The "id" must be unique, if not specified it is generated automatically * # Default fade time is 1 sec. - * + *

    * # Boolean functions * # between(x, min, max) Check if a value is between min and max values * # equals(x, y, epsilon) Compare two float values with error margin * # in(x, val1, val2, ...) Check if a value equals one of several values */ public class IrisFunctions { - static final FunctionResolver.Builder builder = new FunctionResolver.Builder(); public static final FunctionResolver functions; + static final FunctionResolver.Builder builder = new FunctionResolver.Builder(); static { { @@ -193,7 +218,7 @@ public class IrisFunctions { // TODO the base may be static so doing `log(2, x)` would be slower than `log(x)/log(2)` IrisFunctions.add("log", - (base, value) -> (float) (Math.log(value) / Math.log(base))); + (base, value) -> (float) (Math.log(value) / Math.log(base))); // cause I want consistency IrisFunctions.add("exp10", (a) -> (float) Math.pow(10, a)); @@ -347,19 +372,19 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // if max < min => undefined behaviour // TODO: glsl has vecn mix(vecn x, float min, float max) IrisFunctions.addVectorizable("clamp", - (val, min, max) -> Math.max(min, Math.min(max, val))); + (val, min, max) -> Math.max(min, Math.min(max, val))); IrisFunctions.add("clamp", - (val, min, max) -> Math.max(min, Math.min(max, val))); + (val, min, max) -> Math.max(min, Math.min(max, val))); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC2, (val, min, max, dest) -> { - val.min(max,dest); + val.min(max, dest); dest.max(min); }); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC3, (val, min, max, dest) -> { - val.min(max,dest); + val.min(max, dest); dest.max(min); }); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC4, (val, min, max, dest) -> { - val.min(max,dest); + val.min(max, dest); dest.max(min); }); @@ -407,7 +432,7 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // random, random(float min, float max) IrisFunctions.add("random", random::nextFloat); IrisFunctions.add("random", (min, max) -> - min + random.nextFloat() * (max - min)); + min + random.nextFloat() * (max - min)); } { // IF @@ -422,8 +447,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet params[0].evaluateTo(context, functionReturn); params[ - functionReturn.booleanReturn ? 1 : 2 - ].evaluateTo(context, functionReturn); + functionReturn.booleanReturn ? 1 : 2 + ].evaluateTo(context, functionReturn); } }); @@ -436,8 +461,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet params[0].evaluateTo(context, functionReturn); params[ - functionReturn.booleanReturn ? 1 : 2 - ].evaluateTo(context, functionReturn); + functionReturn.booleanReturn ? 1 : 2 + ].evaluateTo(context, functionReturn); } }); @@ -476,8 +501,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet params[0].evaluateTo(context, functionReturn); params[ - functionReturn.booleanReturn ? 1 : 2 - ].evaluateTo(context, functionReturn); + functionReturn.booleanReturn ? 1 : 2 + ].evaluateTo(context, functionReturn); } }); @@ -490,27 +515,27 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // smooth(target) builder.addDynamicFunction("smooth", Type.Float, () -> - new AbstractTypedFunction( - Type.Float, - new Parameter[]{ - new Parameter(Type.Float, false), // target - }, - 0, - false - ) { - private final SmoothFloat smoothFloat = new SmoothFloat(); + new AbstractTypedFunction( + Type.Float, + new Parameter[]{ + new Parameter(Type.Float, false), // target + }, + 0, + false + ) { + private final SmoothFloat smoothFloat = new SmoothFloat(); - @Override - public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context, functionReturn); - float target = functionReturn.floatReturn; - functionReturn.floatReturn = smoothFloat.updateAndGet( - target, - 1, - 1 - ); - } - }); + @Override + public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { + params[0].evaluateTo(context, functionReturn); + float target = functionReturn.floatReturn; + functionReturn.floatReturn = smoothFloat.updateAndGet( + target, + 1, + 1 + ); + } + }); // smooth(id, target) builder.addDynamicFunction("smooth", Type.Float, () -> @@ -539,32 +564,32 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // smooth(target, fadeTime) builder.addDynamicFunction("smooth", Type.Float, () -> - new AbstractTypedFunction( - Type.Float, - new Parameter[]{ - new Parameter(Type.Float, false), // target - new Parameter(Type.Float, false), // fadeTime - }, - 0, - false - ) { - private final SmoothFloat smoothFloat = new SmoothFloat(); + new AbstractTypedFunction( + Type.Float, + new Parameter[]{ + new Parameter(Type.Float, false), // target + new Parameter(Type.Float, false), // fadeTime + }, + 0, + false + ) { + private final SmoothFloat smoothFloat = new SmoothFloat(); - @Override - public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context, functionReturn); - float target = functionReturn.floatReturn; + @Override + public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { + params[0].evaluateTo(context, functionReturn); + float target = functionReturn.floatReturn; - params[1].evaluateTo(context, functionReturn); - float fadeTime = functionReturn.floatReturn; + params[1].evaluateTo(context, functionReturn); + float fadeTime = functionReturn.floatReturn; - functionReturn.floatReturn = smoothFloat.updateAndGet( - target, - fadeTime, - fadeTime - ); - } - }); + functionReturn.floatReturn = smoothFloat.updateAndGet( + target, + fadeTime, + fadeTime + ); + } + }); // smooth(id, target, fadeTime) builder.addDynamicFunction("smooth", Type.Float, () -> @@ -598,35 +623,35 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // smooth(target, fadeUpTime, fadeDownTime) builder.addDynamicFunction("smooth", Type.Float, () -> - new AbstractTypedFunction( - Type.Float, - new Parameter[]{ - new Parameter(Type.Float, false), // target - new Parameter(Type.Float, false), // fadeUpTime - new Parameter(Type.Float, false), // fadeDownTime - }, - 0, - false - ) { - private final SmoothFloat smoothFloat = new SmoothFloat(); + new AbstractTypedFunction( + Type.Float, + new Parameter[]{ + new Parameter(Type.Float, false), // target + new Parameter(Type.Float, false), // fadeUpTime + new Parameter(Type.Float, false), // fadeDownTime + }, + 0, + false + ) { + private final SmoothFloat smoothFloat = new SmoothFloat(); - @Override - public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context, functionReturn); - float target = functionReturn.floatReturn; - - params[1].evaluateTo(context, functionReturn); - float fadeUpTime = functionReturn.floatReturn; - params[2].evaluateTo(context, functionReturn); - float fadeDownTime = functionReturn.floatReturn; - - functionReturn.floatReturn = smoothFloat.updateAndGet( - target, - fadeUpTime, - fadeDownTime - ); - } - }); + @Override + public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { + params[0].evaluateTo(context, functionReturn); + float target = functionReturn.floatReturn; + + params[1].evaluateTo(context, functionReturn); + float fadeUpTime = functionReturn.floatReturn; + params[2].evaluateTo(context, functionReturn); + float fadeDownTime = functionReturn.floatReturn; + + functionReturn.floatReturn = smoothFloat.updateAndGet( + target, + fadeUpTime, + fadeDownTime + ); + } + }); // smooth(id, target, fadeUpTime, fadeDownTime) builder.addDynamicFunction("smooth", Type.Float, () -> @@ -691,16 +716,16 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet Arrays.fill(params, Type.Float); int finalLength = length; IrisFunctions.add("in", new AbstractTypedFunction( - Type.Boolean, - params + Type.Boolean, + params ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context,functionReturn); + params[0].evaluateTo(context, functionReturn); float value = functionReturn.floatReturn; - for(int i = 1; i < finalLength; i++){ - params[i].evaluateTo(context,functionReturn); - if(functionReturn.floatReturn == value){ + for (int i = 1; i < finalLength; i++) { + params[i].evaluateTo(context, functionReturn); + if (functionReturn.floatReturn == value) { functionReturn.booleanReturn = true; return; } @@ -719,69 +744,69 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet TypedFunction function = new VectorConstructor(type, size); // TODO make it possible to do `vec3(vec2(0),0)` add( - Character.toLowerCase( - type.getClass().getSimpleName().charAt(0) - ) + "vec" + size, function); + Character.toLowerCase( + type.getClass().getSimpleName().charAt(0) + ) + "vec" + size, function); } } add("vec2", new AbstractTypedFunction( - VectorType.VEC2, - new Type[]{Type.Float, Type.Float} + VectorType.VEC2, + new Type[]{Type.Float, Type.Float} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context,functionReturn); + params[0].evaluateTo(context, functionReturn); float x = functionReturn.floatReturn; - params[1].evaluateTo(context,functionReturn); + params[1].evaluateTo(context, functionReturn); float y = functionReturn.floatReturn; // TODO: this can't be cached atm. If we swap this to a function provider we could - functionReturn.objectReturn = new Vector2f(x,y); + functionReturn.objectReturn = new Vector2f(x, y); } }); add("vec3", new AbstractTypedFunction( - VectorType.VEC3, - new Type[]{Type.Float, Type.Float, Type.Float} + VectorType.VEC3, + new Type[]{Type.Float, Type.Float, Type.Float} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context,functionReturn); + params[0].evaluateTo(context, functionReturn); float x = functionReturn.floatReturn; - params[1].evaluateTo(context,functionReturn); + params[1].evaluateTo(context, functionReturn); float y = functionReturn.floatReturn; - params[2].evaluateTo(context,functionReturn); + params[2].evaluateTo(context, functionReturn); float z = functionReturn.floatReturn; // TODO: this can't be cached atm. If we swap this to a function provider we could - functionReturn.objectReturn = new Vector3f(x,y,z); + functionReturn.objectReturn = new Vector3f(x, y, z); } }); add("vec4", new AbstractTypedFunction( - VectorType.VEC4, - new Type[]{Type.Float, Type.Float,Type.Float, Type.Float} + VectorType.VEC4, + new Type[]{Type.Float, Type.Float, Type.Float, Type.Float} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { - params[0].evaluateTo(context,functionReturn); + params[0].evaluateTo(context, functionReturn); float x = functionReturn.floatReturn; - params[1].evaluateTo(context,functionReturn); + params[1].evaluateTo(context, functionReturn); float y = functionReturn.floatReturn; - params[2].evaluateTo(context,functionReturn); + params[2].evaluateTo(context, functionReturn); float z = functionReturn.floatReturn; - params[3].evaluateTo(context,functionReturn); + params[3].evaluateTo(context, functionReturn); float w = functionReturn.floatReturn; // TODO: this can't be cached atm. If we swap this to a function provider we could - functionReturn.objectReturn = new Vector4f(x,y,z,w); + functionReturn.objectReturn = new Vector4f(x, y, z, w); } }); } @@ -790,18 +815,18 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet { // is this the best way to do these? String[][] accessNames = new String[][]{ - new String[]{"0", "r", "x", "s"}, - new String[]{"1", "g", "y", "t"}, - new String[]{"2", "b", "z", "p"}, - new String[]{"3", "a", "w", "q"} + new String[]{"0", "r", "x", "s"}, + new String[]{"1", "g", "y", "t"}, + new String[]{"2", "b", "z", "p"}, + new String[]{"3", "a", "w", "q"} }; { // access$0 for (String access : accessNames[0]) { IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC2} + Type.Float, + new Type[]{VectorType.VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -811,8 +836,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC2} + Type.Int, + new Type[]{VectorType.I_VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -822,8 +847,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC3} + Type.Float, + new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -833,8 +858,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC3} + Type.Int, + new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -844,8 +869,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC4} + Type.Float, + new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -855,8 +880,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC4} + Type.Int, + new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -871,8 +896,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // access$1 for (String access : accessNames[1]) { IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC2} + Type.Float, + new Type[]{VectorType.VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -882,8 +907,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC2} + Type.Int, + new Type[]{VectorType.I_VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -893,8 +918,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC3} + Type.Float, + new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -904,8 +929,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC3} + Type.Int, + new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -915,8 +940,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC4} + Type.Float, + new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -926,8 +951,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC4} + Type.Int, + new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -942,8 +967,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // access$2 for (String access : accessNames[2]) { IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC3} + Type.Float, + new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -953,8 +978,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC3} + Type.Int, + new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -964,8 +989,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC4} + Type.Float, + new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -975,8 +1000,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC4} + Type.Int, + new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -991,8 +1016,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet // access$3 for (String access : accessNames[3]) { IrisFunctions.add("", new AbstractTypedFunction( - Type.Float, - new Type[]{VectorType.VEC4} + Type.Float, + new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -1002,8 +1027,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); IrisFunctions.add("", new AbstractTypedFunction( - Type.Int, - new Type[]{VectorType.I_VEC4} + Type.Int, + new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -1016,12 +1041,12 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet { // matrix access - for(int i = 0; i<4; i++) { + for (int i = 0; i < 4; i++) { for (String access : accessNames[i]) { int finalI = i; IrisFunctions.add("", new AbstractTypedFunction( - VectorType.VEC4, - new Type[]{MatrixType.MAT4} + VectorType.VEC4, + new Type[]{MatrixType.MAT4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { @@ -1064,22 +1089,10 @@ static void addBooleanVectorizable(String name, T func } } - interface ObjectObject2BooleanFunction { - boolean apply(T t, U u); - } - - interface TriConsumer { - void accept(T t, U u, V v); - } - - interface QuadConsumer { - void accept(T t, U u, V v, W w); - } - static void addUnaryOpJOML(String name, VectorType.JOMLVector type, BiConsumer function) { builder.add(name, new AbstractTypedFunction( - type, - new Type[]{type} + type, + new Type[]{type} ) { final private T vector = type.create(); @@ -1097,8 +1110,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet static void addBinaryOpJOML(String name, VectorType.JOMLVector type, TriConsumer function) { builder.add(name, new AbstractTypedFunction( - type, - new Type[]{type, type} + type, + new Type[]{type, type} ) { final private T vector = type.create(); @@ -1119,8 +1132,8 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet static void addTernaryOpJOML(String name, VectorType.JOMLVector type, QuadConsumer function) { builder.add(name, new AbstractTypedFunction( - type, - new Type[]{type, type, type} + type, + new Type[]{type, type, type} ) { final private T vector = type.create(); @@ -1142,15 +1155,14 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); } - static void addBinaryToBooleanOpJOML( - String name, - VectorType.JOMLVector type, - boolean inverted, - ObjectObject2BooleanFunction function) { + String name, + VectorType.JOMLVector type, + boolean inverted, + ObjectObject2BooleanFunction function) { builder.add(name, new AbstractTypedFunction( - type, - new Type[]{type, type} + type, + new Type[]{type, type} ) { @SuppressWarnings("unchecked") @Override @@ -1166,7 +1178,6 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet }); } - static void add(String name, T function) { builder.add(name, function); } @@ -1203,5 +1214,17 @@ static void addExplicitCast(final Type from, final Type to, final Consumer { + boolean apply(T t, U u); + } + + interface TriConsumer { + void accept(T t, U u, V v); + } + + interface QuadConsumer { + void accept(T t, U u, V v, W w); + } } diff --git a/src/main/java/net/coderbot/iris/parsing/IrisOptions.java b/src/main/java/net/irisshaders/iris/parsing/IrisOptions.java similarity index 65% rename from src/main/java/net/coderbot/iris/parsing/IrisOptions.java rename to src/main/java/net/irisshaders/iris/parsing/IrisOptions.java index e58ceb9bfe..05e5f76db3 100644 --- a/src/main/java/net/coderbot/iris/parsing/IrisOptions.java +++ b/src/main/java/net/irisshaders/iris/parsing/IrisOptions.java @@ -1,10 +1,11 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.parser.BinaryOp; import kroppeb.stareval.parser.ParserOptions; import kroppeb.stareval.parser.UnaryOp; public class IrisOptions { + public static final ParserOptions options; static final BinaryOp Multiply = new BinaryOp("multiply", 0); static final BinaryOp Divide = new BinaryOp("divide", 0); static final BinaryOp Remainder = new BinaryOp("remainder", 0); @@ -18,38 +19,35 @@ public class IrisOptions { static final BinaryOp MoreThanOrEquals = new BinaryOp("moreThanOrEquals", 2); static final BinaryOp And = new BinaryOp("and", 3); static final BinaryOp Or = new BinaryOp("or", 3); - static final UnaryOp Not = new UnaryOp("not"); static final UnaryOp Negate = new UnaryOp("negate"); - - public static final ParserOptions options; - + static { final ParserOptions.Builder builder = new ParserOptions.Builder(); - builder.addBinaryOp("*",Multiply); - builder.addBinaryOp("/",Divide); - builder.addBinaryOp("%",Remainder); - - builder.addBinaryOp("+",Add); - builder.addBinaryOp("-",Subtract); - - builder.addBinaryOp("==",Equals); - builder.addBinaryOp("!=",NotEquals); - builder.addBinaryOp("<",LessThan); - builder.addBinaryOp(">",MoreThan); - builder.addBinaryOp("<=",LessThanOrEquals); - builder.addBinaryOp(">=",MoreThanOrEquals); - - builder.addBinaryOp("≠",NotEquals); - builder.addBinaryOp("≤",LessThanOrEquals); - builder.addBinaryOp("≥",MoreThanOrEquals); - - builder.addBinaryOp("&&",And); - builder.addBinaryOp("||",Or); - + builder.addBinaryOp("*", Multiply); + builder.addBinaryOp("/", Divide); + builder.addBinaryOp("%", Remainder); + + builder.addBinaryOp("+", Add); + builder.addBinaryOp("-", Subtract); + + builder.addBinaryOp("==", Equals); + builder.addBinaryOp("!=", NotEquals); + builder.addBinaryOp("<", LessThan); + builder.addBinaryOp(">", MoreThan); + builder.addBinaryOp("<=", LessThanOrEquals); + builder.addBinaryOp(">=", MoreThanOrEquals); + + builder.addBinaryOp("≠", NotEquals); + builder.addBinaryOp("≤", LessThanOrEquals); + builder.addBinaryOp("≥", MoreThanOrEquals); + + builder.addBinaryOp("&&", And); + builder.addBinaryOp("||", Or); + builder.addUnaryOp("!", Not); builder.addUnaryOp("-", Negate); - + options = builder.build(); } } diff --git a/src/main/java/net/coderbot/iris/parsing/MatrixType.java b/src/main/java/net/irisshaders/iris/parsing/MatrixType.java similarity index 94% rename from src/main/java/net/coderbot/iris/parsing/MatrixType.java rename to src/main/java/net/irisshaders/iris/parsing/MatrixType.java index 39932394a2..24f19a5fc0 100644 --- a/src/main/java/net/coderbot/iris/parsing/MatrixType.java +++ b/src/main/java/net/irisshaders/iris/parsing/MatrixType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.function.Type; import org.joml.Matrix2f; @@ -8,6 +8,9 @@ import java.util.function.Supplier; public class MatrixType extends Type.ObjectType { + public static MatrixType MAT2 = new MatrixType<>("mat2", Matrix2f::new); + public static MatrixType MAT3 = new MatrixType<>("mat3", Matrix3f::new); + public static MatrixType MAT4 = new MatrixType<>("mat4", Matrix4f::new); final String name; private final Supplier supplier; @@ -20,8 +23,4 @@ public MatrixType(String name, Supplier supplier) { public String toString() { return name; } - - public static MatrixType MAT2 = new MatrixType<>("mat2", Matrix2f::new); - public static MatrixType MAT3 = new MatrixType<>("mat3", Matrix3f::new); - public static MatrixType MAT4 = new MatrixType<>("mat4", Matrix4f::new); } diff --git a/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java b/src/main/java/net/irisshaders/iris/parsing/SmoothFloat.java similarity index 97% rename from src/main/java/net/coderbot/iris/parsing/SmoothFloat.java rename to src/main/java/net/irisshaders/iris/parsing/SmoothFloat.java index 48e6351fb4..e1f276ef8d 100644 --- a/src/main/java/net/coderbot/iris/parsing/SmoothFloat.java +++ b/src/main/java/net/irisshaders/iris/parsing/SmoothFloat.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; /** * An implementation of basic exponential smoothing that converts a sequence of unsmoothed values into a sequence of @@ -30,6 +30,30 @@ public class SmoothFloat { private float cachedHalfLifeDown; private float cachedDecayDown; + /** + * Computes an exponential decay factor based on the given decay constant and time value + * + * @param k the decay constant, derived from the half life + * @param t the time that has passed since the decay started + */ + private static float exponentialDecayFactor(float k, float t) { + // https://en.wikipedia.org/wiki/Exponential_decay + // e^(-kt) + return (float) Math.exp(-k * t); + } + + /** + * Computes a linearly interpolated value between v0 and v1 + * + * @param v0 the starting value (t = 0) + * @param v1 the ending value (t = 1) + * @param t the time/progress value - should be in the range of 0.0 to 1.0 + */ + private static float lerp(float v0, float v1, float t) { + // https://en.wikipedia.org/wiki/Linear_interpolation + return (1 - t) * v0 + t * v1; + } + /** * Takes one value from the unsmoothed value sequence, and smooths it into our accumulator */ @@ -94,28 +118,4 @@ private float computeDecay(float halfLife) { // k = 1 / τ return (float) (1.0f / (halfLife / LN_OF_2)); } - - /** - * Computes an exponential decay factor based on the given decay constant and time value - * - * @param k the decay constant, derived from the half life - * @param t the time that has passed since the decay started - */ - private static float exponentialDecayFactor(float k, float t) { - // https://en.wikipedia.org/wiki/Exponential_decay - // e^(-kt) - return (float) Math.exp(-k * t); - } - - /** - * Computes a linearly interpolated value between v0 and v1 - * - * @param v0 the starting value (t = 0) - * @param v1 the ending value (t = 1) - * @param t the time/progress value - should be in the range of 0.0 to 1.0 - */ - private static float lerp(float v0, float v1, float t) { - // https://en.wikipedia.org/wiki/Linear_interpolation - return (1 - t) * v0 + t * v1; - } } diff --git a/src/main/java/net/coderbot/iris/parsing/VectorConstructor.java b/src/main/java/net/irisshaders/iris/parsing/VectorConstructor.java similarity index 82% rename from src/main/java/net/coderbot/iris/parsing/VectorConstructor.java rename to src/main/java/net/irisshaders/iris/parsing/VectorConstructor.java index 5e9c71d559..2a8582756e 100644 --- a/src/main/java/net/coderbot/iris/parsing/VectorConstructor.java +++ b/src/main/java/net/irisshaders/iris/parsing/VectorConstructor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.Util; import kroppeb.stareval.expression.Expression; @@ -10,22 +10,22 @@ import java.util.Arrays; public class VectorConstructor extends AbstractTypedFunction { - + public VectorConstructor(Type inner, int size) { super( - new VectorType.ArrayVector(inner, size), - Util.make(new Type[size], params -> Arrays.fill(params, inner)) + new VectorType.ArrayVector(inner, size), + Util.make(new Type[size], params -> Arrays.fill(params, inner)) ); } - + @Override public VectorType.ArrayVector getReturnType() { return (VectorType.ArrayVector) super.getReturnType(); } - + @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn - functionReturn) { + functionReturn) { VectorType.ArrayVector vectorType = this.getReturnType(); vectorType.map(params, context, functionReturn, (i, p, ctx, fr) -> p[i].evaluateTo(ctx, fr)); } diff --git a/src/main/java/net/coderbot/iris/parsing/VectorType.java b/src/main/java/net/irisshaders/iris/parsing/VectorType.java similarity index 80% rename from src/main/java/net/coderbot/iris/parsing/VectorType.java rename to src/main/java/net/irisshaders/iris/parsing/VectorType.java index 40f3f4aa95..3bde908240 100644 --- a/src/main/java/net/coderbot/iris/parsing/VectorType.java +++ b/src/main/java/net/irisshaders/iris/parsing/VectorType.java @@ -1,8 +1,13 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import org.joml.*; +import org.joml.Vector2f; +import org.joml.Vector2i; +import org.joml.Vector3f; +import org.joml.Vector3i; +import org.joml.Vector4f; +import org.joml.Vector4i; import java.util.Arrays; import java.util.Objects; @@ -11,6 +16,41 @@ import java.util.stream.Stream; abstract public class VectorType extends Type.ObjectType { + public static final JOMLVector VEC2 = new JOMLVector<>("vec2", Vector2f::new); + public static final JOMLVector VEC3 = new JOMLVector<>("vec3", Vector3f::new); + public static final JOMLVector VEC4 = new JOMLVector<>("vec4", Vector4f::new); + public static final JOMLVector I_VEC2 = new JOMLVector<>("ivec2", Vector2i::new); + public static final JOMLVector I_VEC3 = new JOMLVector<>("ivec3", Vector3i::new); + public static final JOMLVector I_VEC4 = new JOMLVector<>("ivec4", Vector4i::new); + public static final VectorType B_VEC2 = new ArrayVector(Type.Boolean, 2); + public static final VectorType B_VEC3 = new ArrayVector(Type.Boolean, 3); + public static final VectorType B_VEC4 = new ArrayVector(Type.Boolean, 4); + public static final ArrayVector[] AllArrayVectorTypes = Stream.of(Type.Int, Type.Boolean) + .flatMap(type -> + IntStream + .rangeClosed(2, 4) + .mapToObj(i -> new ArrayVector(type, i)) + ).toArray(ArrayVector[]::new); + public static final VectorType[] AllVectorTypes = Arrays.stream(Type.AllPrimitives) + .flatMap(type -> + IntStream + .rangeClosed(2, 4) + .mapToObj(i -> VectorType.of(type, i)) + ).toArray(VectorType[]::new); + + public static VectorType of(Type.Primitive primitive, int size) { + if (primitive.equals(Type.Float)) { + return switch (size) { + case 2 -> VEC2; + case 3 -> VEC3; + case 4 -> VEC4; + default -> throw new IllegalArgumentException("not a valid vector"); + }; + } else { + return new ArrayVector(primitive, size); + } + } + public static class ArrayVector extends VectorType { private final Type inner; private final int size; @@ -44,8 +84,7 @@ public void map(T1 item1, T2 item2, FunctionReturn functionReturn, IntO @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof ArrayVector)) return false; - ArrayVector that = (ArrayVector) o; + if (!(o instanceof ArrayVector that)) return false; return size == that.size && inner.equals(that.inner); } @@ -54,15 +93,15 @@ public int hashCode() { return Objects.hash(inner, size); } - public interface IntObjectObjectObjectConsumer { - void accept(int a, TB b, TC c, TD d); - } - @Override public String toString() { String base = this.inner.equals(Type.Float) ? "" : this.inner.toString().substring(0, 1); return "__" + base + "vec" + this.size; } + + public interface IntObjectObjectObjectConsumer { + void accept(int a, TB b, TC c, TD d); + } } public static class JOMLVector extends VectorType { @@ -79,47 +118,8 @@ public String toString() { return this.name; } - public T create(){ + public T create() { return this.supplier.get(); } } - - public static final JOMLVector VEC2 = new JOMLVector<>("vec2", Vector2f::new); - public static final JOMLVector VEC3 = new JOMLVector<>("vec3", Vector3f::new); - public static final JOMLVector VEC4 = new JOMLVector<>("vec4", Vector4f::new); - - public static final JOMLVector I_VEC2 = new JOMLVector<>("ivec2", Vector2i::new); - public static final JOMLVector I_VEC3 = new JOMLVector<>("ivec3", Vector3i::new); - public static final JOMLVector I_VEC4 = new JOMLVector<>("ivec4", Vector4i::new); - - public static final VectorType B_VEC2 = new ArrayVector(Type.Boolean, 2); - public static final VectorType B_VEC3 = new ArrayVector(Type.Boolean, 3); - public static final VectorType B_VEC4 = new ArrayVector(Type.Boolean, 4); - - public static final ArrayVector[] AllArrayVectorTypes = Stream.of(Type.Int, Type.Boolean) - .flatMap(type -> - IntStream - .rangeClosed(2, 4) - .mapToObj(i -> new ArrayVector(type, i)) - ).toArray(ArrayVector[]::new); - - public static final VectorType[] AllVectorTypes = Arrays.stream(Type.AllPrimitives) - .flatMap(type -> - IntStream - .rangeClosed(2, 4) - .mapToObj(i -> VectorType.of(type, i)) - ).toArray(VectorType[]::new); - - public static VectorType of(Type.Primitive primitive, int size){ - if(primitive.equals(Type.Float)){ - switch (size){ - case 2:return VEC2; - case 3:return VEC3; - case 4:return VEC4; - default: throw new IllegalArgumentException("not a valid vector"); - } - }else{ - return new ArrayVector(primitive, size); - } - } } diff --git a/src/main/java/net/coderbot/iris/parsing/VectorizedFunction.java b/src/main/java/net/irisshaders/iris/parsing/VectorizedFunction.java similarity index 92% rename from src/main/java/net/coderbot/iris/parsing/VectorizedFunction.java rename to src/main/java/net/irisshaders/iris/parsing/VectorizedFunction.java index 987f1b5191..e3f5b508b5 100644 --- a/src/main/java/net/coderbot/iris/parsing/VectorizedFunction.java +++ b/src/main/java/net/irisshaders/iris/parsing/VectorizedFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.parsing; +package net.irisshaders.iris.parsing; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.expression.VariableExpression; @@ -6,7 +6,6 @@ import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; import kroppeb.stareval.function.TypedFunction; -import org.lwjgl.system.CallbackI; import java.util.Collection; @@ -18,6 +17,11 @@ public class VectorizedFunction implements TypedFunction { private final ElementAccessExpression[] vectorAccessors; private int index; + private final VectorType.ArrayVector.IntObjectObjectObjectConsumer mapper = + (i, self, ctx, fr) -> { + self.index = i; + self.inner.evaluateTo(self.vectorAccessors, ctx, fr); + }; public VectorizedFunction(TypedFunction inner, int size) { this.inner = inner; @@ -56,12 +60,6 @@ public void evaluateTo(Expression[] params, FunctionContext context, FunctionRet returnType.map(this, context, functionReturn, this.mapper); } - private final VectorType.ArrayVector.IntObjectObjectObjectConsumer mapper = - (i, self, ctx, fr) -> { - self.index = i; - self.inner.evaluateTo(self.vectorAccessors, ctx, fr); - }; - class ElementAccessExpression implements Expression { final Type parameterType; Object vector; diff --git a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java b/src/main/java/net/irisshaders/iris/pathways/CenterDepthSampler.java similarity index 85% rename from src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java rename to src/main/java/net/irisshaders/iris/pathways/CenterDepthSampler.java index 288ec0510e..2f4b8f46f9 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CenterDepthSampler.java +++ b/src/main/java/net/irisshaders/iris/pathways/CenterDepthSampler.java @@ -1,20 +1,19 @@ -package net.coderbot.iris.postprocess; +package net.irisshaders.iris.pathways; import com.google.common.collect.ImmutableSet; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.program.Program; -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.texture.DepthCopyStrategy; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelType; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.program.Program; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.texture.DepthCopyStrategy; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.PixelType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import org.apache.commons.io.IOUtils; import org.joml.Matrix4f; diff --git a/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java b/src/main/java/net/irisshaders/iris/pathways/FullScreenQuadRenderer.java similarity index 82% rename from src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java rename to src/main/java/net/irisshaders/iris/pathways/FullScreenQuadRenderer.java index 0a72570989..78bbbf6445 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FullScreenQuadRenderer.java +++ b/src/main/java/net/irisshaders/iris/pathways/FullScreenQuadRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.postprocess; +package net.irisshaders.iris.pathways; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; @@ -6,11 +6,8 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexBuffer; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.fantastic.VertexBufferHelper; -import net.coderbot.iris.gl.IrisRenderSystem; -import org.lwjgl.opengl.GL11; - -import org.lwjgl.opengl.GL20C; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.helpers.VertexBufferHelper; /** * Renders a full-screen textured quad to the screen. Used in composite / deferred rendering. @@ -18,12 +15,10 @@ public class FullScreenQuadRenderer { public static final FullScreenQuadRenderer INSTANCE = new FullScreenQuadRenderer(); - private VertexBuffer quad; + private final VertexBuffer quad; private FullScreenQuadRenderer() { - // 1 quad * vertex size in bytes * 6 vertices per quad (2 triangles) = initial allocation - // TODO: We don't do a full initial allocation? - BufferBuilder bufferBuilder = new BufferBuilder(DefaultVertexFormat.POSITION_TEX.getVertexSize()); + BufferBuilder bufferBuilder = new BufferBuilder(DefaultVertexFormat.POSITION_TEX.getVertexSize() * 4); bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferBuilder.vertex(0.0F, 0.0F, 0.0F).uv(0.0F, 0.0F).endVertex(); bufferBuilder.vertex(1.0F, 0.0F, 0.0F).uv(1.0F, 0.0F).endVertex(); @@ -50,7 +45,6 @@ public void begin() { RenderSystem.disableDepthTest(); BufferUploader.reset(); quad.bind(); - } public void renderQuad() { diff --git a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java b/src/main/java/net/irisshaders/iris/pathways/HandRenderer.java similarity index 85% rename from src/main/java/net/coderbot/iris/pipeline/HandRenderer.java rename to src/main/java/net/irisshaders/iris/pathways/HandRenderer.java index 7f801aad9f..52788721f7 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HandRenderer.java +++ b/src/main/java/net/irisshaders/iris/pathways/HandRenderer.java @@ -1,14 +1,16 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pathways; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; import org.joml.Matrix4f; -import net.coderbot.batchedentityrendering.impl.FullyBufferedMultiBufferSource; -import net.coderbot.iris.mixin.GameRendererAccessor; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.batchedentityrendering.impl.FullyBufferedMultiBufferSource; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.mixin.GameRendererAccessor; +import net.irisshaders.iris.pipeline.WorldRenderingPhase; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GameRenderer; @@ -21,18 +23,17 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.GameType; +import org.joml.Matrix4f; public class HandRenderer { public static final HandRenderer INSTANCE = new HandRenderer(); - + public static final float DEPTH = 0.125F; + private final FullyBufferedMultiBufferSource bufferSource = new FullyBufferedMultiBufferSource(); private boolean ACTIVE; private boolean renderingSolid; - private final FullyBufferedMultiBufferSource bufferSource = new FullyBufferedMultiBufferSource(); - - public static final float DEPTH = 0.125F; private void setupGlState(GameRenderer gameRenderer, Camera camera, PoseStack poseStack, float tickDelta) { - final PoseStack.Pose pose = poseStack.last(); + final PoseStack.Pose pose = poseStack.last(); // We need to scale the matrix by 0.125 so the hand doesn't clip through blocks. Matrix4f scaleMatrix = new Matrix4f().scale(1F, 1F, DEPTH); @@ -40,7 +41,7 @@ private void setupGlState(GameRenderer gameRenderer, Camera camera, PoseStack po gameRenderer.resetProjectionMatrix(scaleMatrix); pose.pose().identity(); - pose.normal().identity(); + pose.normal().identity(); ((GameRendererAccessor) gameRenderer).invokeBobHurt(poseStack, tickDelta); @@ -51,12 +52,12 @@ private void setupGlState(GameRenderer gameRenderer, Camera camera, PoseStack po private boolean canRender(Camera camera, GameRenderer gameRenderer) { return !(!((GameRendererAccessor) gameRenderer).getRenderHand() - || camera.isDetached() - || !(camera.getEntity() instanceof Player) - || ((GameRendererAccessor)gameRenderer).getPanoramicMode() - || Minecraft.getInstance().options.hideGui - || (camera.getEntity() instanceof LivingEntity && ((LivingEntity)camera.getEntity()).isSleeping()) - || Minecraft.getInstance().gameMode.getPlayerMode() == GameType.SPECTATOR); + || camera.isDetached() + || !(camera.getEntity() instanceof Player) + || ((GameRendererAccessor) gameRenderer).getPanoramicMode() + || Minecraft.getInstance().options.hideGui + || (camera.getEntity() instanceof LivingEntity && ((LivingEntity) camera.getEntity()).isSleeping()) + || Minecraft.getInstance().gameMode.getPlayerMode() == GameType.SPECTATOR); } public boolean isHandTranslucent(InteractionHand hand) { diff --git a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java b/src/main/java/net/irisshaders/iris/pathways/HorizonRenderer.java similarity index 98% rename from src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java rename to src/main/java/net/irisshaders/iris/pathways/HorizonRenderer.java index 71ceb31afb..1f2ac811fc 100644 --- a/src/main/java/net/coderbot/iris/pipeline/HorizonRenderer.java +++ b/src/main/java/net/irisshaders/iris/pathways/HorizonRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pathways; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.DefaultVertexFormat; @@ -7,10 +7,8 @@ import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; import org.joml.Matrix4f; -import org.lwjgl.opengl.GL11; /** * Renders the sky horizon. Vanilla Minecraft simply uses the "clear color" for its horizon, and then draws a plane diff --git a/src/main/java/net/irisshaders/iris/pathways/LightningHandler.java b/src/main/java/net/irisshaders/iris/pathways/LightningHandler.java new file mode 100644 index 0000000000..c55a1de12e --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pathways/LightningHandler.java @@ -0,0 +1,28 @@ +package net.irisshaders.iris.pathways; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.irisshaders.iris.layer.InnerWrappedRenderType; +import net.irisshaders.iris.layer.LightningRenderStateShard; +import net.minecraft.client.renderer.RenderType; + +public class LightningHandler extends RenderType { + public static final RenderType IRIS_LIGHTNING = new InnerWrappedRenderType("iris_lightning2", RenderType.create( + "iris_lightning", + DefaultVertexFormat.POSITION_COLOR, + VertexFormat.Mode.QUADS, + 256, + false, + true, + RenderType.CompositeState.builder() + .setShaderState(RENDERTYPE_LIGHTNING_SHADER) + .setWriteMaskState(COLOR_DEPTH_WRITE) + .setTransparencyState(LIGHTNING_TRANSPARENCY) + .setOutputState(WEATHER_TARGET) + .createCompositeState(false) + ), new LightningRenderStateShard()); + + public LightningHandler(String pRenderType0, VertexFormat pVertexFormat1, VertexFormat.Mode pVertexFormat$Mode2, int pInt3, boolean pBoolean4, boolean pBoolean5, Runnable pRunnable6, Runnable pRunnable7) { + super(pRenderType0, pVertexFormat1, pVertexFormat$Mode2, pInt3, pBoolean4, pBoolean5, pRunnable6, pRunnable7); + } +} diff --git a/src/main/java/net/coderbot/iris/colorspace/ColorSpace.java b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpace.java similarity index 60% rename from src/main/java/net/coderbot/iris/colorspace/ColorSpace.java rename to src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpace.java index 6a94b4bf2b..c8f5f6bd59 100644 --- a/src/main/java/net/coderbot/iris/colorspace/ColorSpace.java +++ b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpace.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.colorspace; +package net.irisshaders.iris.pathways.colorspace; public enum ColorSpace { SRGB, diff --git a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceComputeConverter.java b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceComputeConverter.java similarity index 82% rename from src/main/java/net/coderbot/iris/colorspace/ColorSpaceComputeConverter.java rename to src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceComputeConverter.java index 54a0c4462c..a454aecc63 100644 --- a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceComputeConverter.java +++ b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceComputeConverter.java @@ -1,14 +1,12 @@ -package net.coderbot.iris.colorspace; +package net.irisshaders.iris.pathways.colorspace; import com.google.common.collect.ImmutableSet; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -import net.coderbot.iris.gl.program.ProgramBuilder; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.shaderpack.StringPair; -import net.coderbot.iris.shaderpack.preprocessor.JcppProcessor; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.program.ComputeProgram; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor; import org.apache.commons.io.IOUtils; import org.lwjgl.opengl.GL43C; @@ -25,6 +23,7 @@ public class ColorSpaceComputeConverter implements ColorSpaceConverter { private ComputeProgram program; private int target; + public ColorSpaceComputeConverter(int width, int height, ColorSpace colorSpace) { rebuildProgram(width, height, colorSpace); } diff --git a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceConverter.java b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceConverter.java similarity index 72% rename from src/main/java/net/coderbot/iris/colorspace/ColorSpaceConverter.java rename to src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceConverter.java index 07a1d86263..b224cd12a2 100644 --- a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceConverter.java +++ b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceConverter.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.colorspace; +package net.irisshaders.iris.pathways.colorspace; public interface ColorSpaceConverter { void rebuildProgram(int width, int height, ColorSpace colorSpace); + void process(int target); } diff --git a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceFragmentConverter.java b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceFragmentConverter.java similarity index 82% rename from src/main/java/net/coderbot/iris/colorspace/ColorSpaceFragmentConverter.java rename to src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceFragmentConverter.java index 75a1b6a4ea..ba83a717bb 100644 --- a/src/main/java/net/coderbot/iris/colorspace/ColorSpaceFragmentConverter.java +++ b/src/main/java/net/irisshaders/iris/pathways/colorspace/ColorSpaceFragmentConverter.java @@ -1,22 +1,19 @@ -package net.coderbot.iris.colorspace; +package net.irisshaders.iris.pathways.colorspace; import com.google.common.collect.ImmutableSet; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -import net.coderbot.iris.gl.program.ProgramBuilder; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.postprocess.FullScreenQuadRenderer; -import net.coderbot.iris.shaderpack.StringPair; -import net.coderbot.iris.shaderpack.preprocessor.JcppProcessor; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.program.Program; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.pathways.FullScreenQuadRenderer; +import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor; import org.apache.commons.io.IOUtils; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL30C; -import org.lwjgl.opengl.GL43C; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -33,6 +30,7 @@ public class ColorSpaceFragmentConverter implements ColorSpaceConverter { private int swapTexture; private int target; + public ColorSpaceFragmentConverter(int width, int height, ColorSpace colorSpace) { rebuildProgram(width, height, colorSpace); } diff --git a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java b/src/main/java/net/irisshaders/iris/pipeline/CompositeRenderer.java similarity index 82% rename from src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java rename to src/main/java/net/irisshaders/iris/pipeline/CompositeRenderer.java index 63e116473c..0ed212a216 100644 --- a/src/main/java/net/coderbot/iris/postprocess/CompositeRenderer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/CompositeRenderer.java @@ -1,11 +1,4 @@ -package net.coderbot.iris.postprocess; - -import java.util.Arrays; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.IntSupplier; -import java.util.function.Supplier; +package net.irisshaders.iris.pipeline; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -13,50 +6,54 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.framebuffer.ViewportData; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -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.shader.ShaderCompileException; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.pipeline.ShaderPrinter; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.samplers.IrisImages; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; -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.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.buffer.ShaderStorageBufferHolder; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.framebuffer.ViewportData; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.program.ComputeProgram; +import net.irisshaders.iris.gl.program.Program; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.pathways.CenterDepthSampler; +import net.irisshaders.iris.pathways.FullScreenQuadRenderer; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.samplers.IrisImages; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.shaderpack.FilledIndirectPointer; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.targets.BufferFlipper; +import net.irisshaders.iris.targets.RenderTarget; +import net.irisshaders.iris.targets.RenderTargets; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL15C; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL43C; +import java.util.Arrays; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.function.Supplier; public class CompositeRenderer { @@ -71,10 +68,10 @@ public class CompositeRenderer { private final CustomUniforms customUniforms; private final Object2ObjectMap irisCustomTextures; private final Set customImages; - private TextureStage textureStage; - private WorldRenderingPipeline pipeline; + private final TextureStage textureStage; + private final WorldRenderingPipeline pipeline; - public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, RenderTargets renderTargets, + public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, RenderTargets renderTargets, ShaderStorageBufferHolder holder, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier, CenterDepthSampler centerDepthSampler, BufferFlipper bufferFlipper, Supplier shadowTargetsSupplier, TextureStage textureStage, @@ -93,7 +90,7 @@ public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDir final PackRenderTargetDirectives renderTargetDirectives = packDirectives.getRenderTargetDirectives(); final Map renderTargetSettings = - renderTargetDirectives.getRenderTargetSettings(); + renderTargetDirectives.getRenderTargetSettings(); final ImmutableList.Builder passes = ImmutableList.builder(); final ImmutableSet.Builder flippedAtLeastOnce = new ImmutableSet.Builder<>(); @@ -114,7 +111,7 @@ public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDir if (source == null || !source.isValid()) { if (computes[i] != null) { ComputeOnlyPass pass = new ComputeOnlyPass(); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier, holder); passes.add(pass); } continue; @@ -125,7 +122,7 @@ public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDir pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); pass.blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(null); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, shadowTargetsSupplier, holder); int[] drawBuffers = directives.getDrawBuffers(); @@ -138,7 +135,7 @@ public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDir for (int buffer : drawBuffers) { RenderTarget target = renderTargets.get(buffer); if ((passWidth > 0 && passWidth != target.getWidth()) || (passHeight > 0 && passHeight != target.getHeight())) { - throw new IllegalStateException("Pass sizes must match for drawbuffers " + Arrays.toString(drawBuffers) + "\nOriginal width: " + passWidth + " New width: " + target.getWidth()+ " Original height: " + passHeight + " New height: " + target.getHeight()) ; + throw new IllegalStateException("Pass sizes must match for drawbuffers " + Arrays.toString(drawBuffers) + "\nOriginal width: " + passWidth + " New width: " + target.getWidth() + " Original height: " + passHeight + " New height: " + target.getHeight()); } passWidth = target.getWidth(); passHeight = target.getHeight(); @@ -177,11 +174,36 @@ public CompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDir GlStateManager._glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, 0); } + private static void setupMipmapping(net.irisshaders.iris.targets.RenderTarget target, boolean readFromAlt) { + if (target == null) return; + + int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); + + // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer + // (since the last mipmap was generated) + // + // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the + // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a + // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the + // sampling mode is always reset between frames, so this only persists after the first program to use + // mipmapping on this buffer. + // + // Also note that this only applies to one of the two buffers in a render target buffer pair - making it + // unlikely that this issue occurs in practice with most shader packs. + IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); + + int filter = GL20C.GL_LINEAR_MIPMAP_LINEAR; + if (target.getInternalFormat().getPixelFormat().isInteger()) { + filter = GL20C.GL_NEAREST_MIPMAP_NEAREST; + } + + IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); + } + public ImmutableSet getFlippedAtLeastOnceFinal() { return this.flippedAtLeastOnceFinal; } - public void recalculateSizes() { for (Pass pass : passes) { if (pass instanceof ComputeOnlyPass) { @@ -203,40 +225,6 @@ public void recalculateSizes() { } } - private static class Pass { - int[] drawBuffers; - int viewWidth; - int viewHeight; - Program program; - BlendModeOverride blendModeOverride; - ComputeProgram[] computes; - GlFramebuffer framebuffer; - ImmutableSet flippedAtLeastOnce; - ImmutableSet stageReadsFromAlt; - ImmutableSet mipmappedBuffers; - ViewportData viewportScale; - - protected void destroy() { - this.program.destroy(); - for (ComputeProgram compute : this.computes) { - if (compute != null) { - compute.destroy(); - } - } - } - } - - private class ComputeOnlyPass extends Pass { - @Override - protected void destroy() { - for (ComputeProgram compute : this.computes) { - if (compute != null) { - compute.destroy(); - } - } - } - } - public void renderAll() { RenderSystem.disableBlend(); @@ -316,35 +304,9 @@ public void renderAll() { RenderSystem.activeTexture(GL15C.GL_TEXTURE0); } - private static void setupMipmapping(net.coderbot.iris.rendertarget.RenderTarget target, boolean readFromAlt) { - if (target == null) return; - - int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); - - // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer - // (since the last mipmap was generated) - // - // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the - // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a - // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the - // sampling mode is always reset between frames, so this only persists after the first program to use - // mipmapping on this buffer. - // - // Also note that this only applies to one of the two buffers in a render target buffer pair - making it - // unlikely that this issue occurs in practice with most shader packs. - IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); - - int filter = GL20C.GL_LINEAR_MIPMAP_LINEAR; - if (target.getInternalFormat().getPixelFormat().isInteger()) { - filter = GL20C.GL_NEAREST_MIPMAP_NEAREST; - } - - IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - } - // TODO: Don't just copy this from DeferredWorldRenderingPipeline private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, - Supplier shadowTargetsSupplier) { + Supplier shadowTargetsSupplier) { // TODO: Properly handle empty shaders Map transformed = TransformPatcher.patchComposite( source.getName(), @@ -362,7 +324,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe try { builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment, - IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); + IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (ShaderCompileException e) { throw e; } catch (RuntimeException e) { @@ -376,7 +338,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); IrisSamplers.addCustomTextures(builder, irisCustomTextures); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -403,7 +365,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe return build; } - private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier) { + private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier, ShaderStorageBufferHolder holder) { ComputeProgram[] programs = new ComputeProgram[compute.length]; for (int i = 0; i < programs.length; i++) { ComputeSource source = compute[i]; @@ -415,7 +377,7 @@ private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, renderTargets, true); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); IrisSamplers.addCustomTextures(builder, irisCustomTextures); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -455,7 +417,7 @@ private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flippedAtLeastOnce; + ImmutableSet stageReadsFromAlt; + ImmutableSet mipmappedBuffers; + ViewportData viewportScale; + + protected void destroy() { + this.program.destroy(); + for (ComputeProgram compute : this.computes) { + if (compute != null) { + compute.destroy(); + } + } + } + } + + private static class ComputeOnlyPass extends Pass { + @Override + protected void destroy() { + for (ComputeProgram compute : this.computes) { + if (compute != null) { + compute.destroy(); + } + } + } + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java b/src/main/java/net/irisshaders/iris/pipeline/CustomTextureManager.java similarity index 81% rename from src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java rename to src/main/java/net/irisshaders/iris/pipeline/CustomTextureManager.java index 46b4a0695c..71cfe4109f 100644 --- a/src/main/java/net/coderbot/iris/pipeline/CustomTextureManager.java +++ b/src/main/java/net/irisshaders/iris/pipeline/CustomTextureManager.java @@ -1,27 +1,26 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.gl.texture.GlTexture; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.gl.texture.TextureWrapper; -import net.coderbot.iris.mixin.LightTextureAccessor; -import net.coderbot.iris.rendertarget.NativeImageBackedCustomTexture; -import net.coderbot.iris.rendertarget.NativeImageBackedNoiseTexture; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.texture.CustomTextureData; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.texture.format.TextureFormat; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.coderbot.iris.texture.pbr.PBRTextureHolder; -import net.coderbot.iris.texture.pbr.PBRTextureManager; -import net.coderbot.iris.texture.pbr.PBRType; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.texture.GlTexture; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.texture.TextureWrapper; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.LightTextureAccessor; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.texture.CustomTextureData; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.targets.backed.NativeImageBackedCustomTexture; +import net.irisshaders.iris.targets.backed.NativeImageBackedNoiseTexture; +import net.irisshaders.iris.texture.format.TextureFormat; +import net.irisshaders.iris.texture.format.TextureFormatLoader; +import net.irisshaders.iris.texture.pbr.PBRTextureHolder; +import net.irisshaders.iris.texture.pbr.PBRTextureManager; +import net.irisshaders.iris.texture.pbr.PBRType; import net.minecraft.ResourceLocationException; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.AbstractTexture; @@ -60,7 +59,7 @@ public CustomTextureManager(PackDirectives packDirectives, customTextureIds.put(samplerName, createCustomTexture(textureData)); } catch (IOException | ResourceLocationException e) { Iris.logger.error("Unable to parse the image data for the custom texture on stage " - + textureStage + ", sampler " + samplerName, e); + + textureStage + ", sampler " + samplerName, e); } }); @@ -104,8 +103,7 @@ private TextureAccess createCustomTexture(CustomTextureData textureData) throws // possible that a mod will create a different light texture, so this code path is robust to that. return new TextureWrapper(((LightTextureAccessor) Minecraft.getInstance().gameRenderer.lightTexture()) .getLightTexture()::getId, TextureType.TEXTURE_2D); - } else if (textureData instanceof CustomTextureData.RawData1D) { - CustomTextureData.RawData1D rawData1D = (CustomTextureData.RawData1D) textureData; + } else if (textureData instanceof CustomTextureData.RawData1D rawData1D) { GlTexture texture = new GlTexture(TextureType.TEXTURE_1D, rawData1D.getSizeX(), 0, 0, rawData1D.getInternalFormat().getGlFormat(), rawData1D.getPixelFormat().getGlFormat(), rawData1D.getPixelType().getGlFormat(), rawData1D.getContent(), rawData1D.getFilteringData()); ownedRawTextures.add(texture); @@ -115,20 +113,17 @@ private TextureAccess createCustomTexture(CustomTextureData textureData) throws ownedRawTextures.add(texture); return texture; - } else if (textureData instanceof CustomTextureData.RawData2D) { - CustomTextureData.RawData2D rawData2D = (CustomTextureData.RawData2D) textureData; + } else if (textureData instanceof CustomTextureData.RawData2D rawData2D) { GlTexture texture = new GlTexture(TextureType.TEXTURE_2D, rawData2D.getSizeX(), rawData2D.getSizeY(), 0, rawData2D.getInternalFormat().getGlFormat(), rawData2D.getPixelFormat().getGlFormat(), rawData2D.getPixelType().getGlFormat(), rawData2D.getContent(), rawData2D.getFilteringData()); ownedRawTextures.add(texture); return texture; - } else if (textureData instanceof CustomTextureData.RawData3D) { - CustomTextureData.RawData3D rawData3D = (CustomTextureData.RawData3D) textureData; + } else if (textureData instanceof CustomTextureData.RawData3D rawData3D) { GlTexture texture = new GlTexture(TextureType.TEXTURE_3D, rawData3D.getSizeX(), rawData3D.getSizeY(), rawData3D.getSizeZ(), rawData3D.getInternalFormat().getGlFormat(), rawData3D.getPixelFormat().getGlFormat(), rawData3D.getPixelType().getGlFormat(), rawData3D.getContent(), rawData3D.getFilteringData()); ownedRawTextures.add(texture); return texture; - } else if (textureData instanceof CustomTextureData.ResourceData) { - CustomTextureData.ResourceData resourceData = (CustomTextureData.ResourceData) textureData; + } else if (textureData instanceof CustomTextureData.ResourceData resourceData) { String namespace = resourceData.getNamespace(); String location = resourceData.getLocation(); @@ -165,17 +160,11 @@ private TextureAccess createCustomTexture(CustomTextureData textureData) throws if (texture != null) { int id = texture.getId(); PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); - AbstractTexture pbrTexture; - switch (pbrType) { - case NORMAL: - pbrTexture = pbrHolder.getNormalTexture(); - break; - case SPECULAR: - pbrTexture = pbrHolder.getSpecularTexture(); - break; - default: - throw new Error("Unknown PBRType '" + pbrType + "'"); - } + AbstractTexture pbrTexture = switch (pbrType) { + case NORMAL -> pbrHolder.normalTexture(); + case SPECULAR -> pbrHolder.specularTexture(); + default -> throw new IllegalArgumentException("Unknown PBRType '" + pbrType + "'"); + }; TextureFormat textureFormat = TextureFormatLoader.getFormat(); if (textureFormat != null) { diff --git a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java b/src/main/java/net/irisshaders/iris/pipeline/FinalPassRenderer.java similarity index 86% rename from src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java rename to src/main/java/net/irisshaders/iris/pipeline/FinalPassRenderer.java index c9e8261c9a..b902497f88 100644 --- a/src/main/java/net/coderbot/iris/postprocess/FinalPassRenderer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/FinalPassRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.postprocess; +package net.irisshaders.iris.pipeline; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -6,41 +6,42 @@ import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -import net.coderbot.iris.gl.program.ProgramBuilder; -import net.coderbot.iris.gl.program.ProgramSamplers; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.gl.program.ProgramUniforms; -import net.coderbot.iris.gl.sampler.SamplerLimits; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.pipeline.DeferredWorldRenderingPipeline; -import net.coderbot.iris.pipeline.ShaderPrinter; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.rendertarget.Blaze3dRenderTargetExt; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.samplers.IrisImages; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; -import net.coderbot.iris.shaderpack.ProgramDirectives; -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.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.buffer.ShaderStorageBufferHolder; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.program.ComputeProgram; +import net.irisshaders.iris.gl.program.Program; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.pathways.CenterDepthSampler; +import net.irisshaders.iris.pathways.FullScreenQuadRenderer; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.samplers.IrisImages; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.shaderpack.FilledIndirectPointer; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.targets.Blaze3dRenderTargetExt; +import net.irisshaders.iris.targets.RenderTarget; +import net.irisshaders.iris.targets.RenderTargets; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11C; @@ -64,23 +65,23 @@ public class FinalPassRenderer { private final GlFramebuffer colorHolder; private final Object2ObjectMap irisCustomTextures; private final Set customImages; - private int lastColorTextureId; - private int lastColorTextureVersion; private final TextureAccess noiseTexture; private final FrameUpdateNotifier updateNotifier; private final CenterDepthSampler centerDepthSampler; private final Object2ObjectMap customTextureIds; - private WorldRenderingPipeline pipeline; private final CustomUniforms customUniforms; + private final WorldRenderingPipeline pipeline; + private int lastColorTextureId; + private int lastColorTextureVersion; // TODO: The length of this argument list is getting a bit ridiculous - public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, RenderTargets renderTargets, TextureAccess noiseTexture, + public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, RenderTargets renderTargets, TextureAccess noiseTexture, ShaderStorageBufferHolder holder, FrameUpdateNotifier updateNotifier, ImmutableSet flippedBuffers, CenterDepthSampler centerDepthSampler, Supplier shadowTargetsSupplier, Object2ObjectMap customTextureIds, Object2ObjectMap irisCustomTextures, Set customImages, ImmutableSet flippedAtLeastOnce - , CustomUniforms customUniforms) { + , CustomUniforms customUniforms) { this.pipeline = pipeline; this.updateNotifier = updateNotifier; this.centerDepthSampler = centerDepthSampler; @@ -90,7 +91,7 @@ public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, Rende final PackRenderTargetDirectives renderTargetDirectives = pack.getPackDirectives().getRenderTargetDirectives(); final Map renderTargetSettings = - renderTargetDirectives.getRenderTargetSettings(); + renderTargetDirectives.getRenderTargetSettings(); this.noiseTexture = noiseTexture; this.renderTargets = renderTargets; @@ -100,7 +101,7 @@ public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, Rende ProgramDirectives directives = source.getDirectives(); pass.program = createProgram(source, flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier); - pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier); + pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, shadowTargetsSupplier, holder); pass.stageReadsFromAlt = flippedBuffers; pass.mipmappedBuffers = directives.getMipmappedBuffers(); @@ -113,7 +114,7 @@ public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, Rende // up with whatever was written last (since we're reading from these framebuffers) instead of trying to create // a framebuffer with color attachments different from what was written last (as we do with normal composite // passes that write to framebuffers). - this.baseline = renderTargets.createGbufferFramebuffer(flippedBuffers, new int[] {0}); + this.baseline = renderTargets.createGbufferFramebuffer(flippedBuffers, new int[]{0}); this.colorHolder = new GlFramebuffer(); this.lastColorTextureId = Minecraft.getInstance().getMainRenderTarget().getColorTextureId(); this.lastColorTextureVersion = ((Blaze3dRenderTargetExt) Minecraft.getInstance().getMainRenderTarget()).iris$getColorBufferVersion(); @@ -136,7 +137,7 @@ public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, Rende swap.target = target; swap.width = target1.getWidth(); swap.height = target1.getHeight(); - swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target}); + swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[]{target}); // NB: This is handled in RenderTargets now. //swap.from.readBuffer(target); swap.targetTexture = renderTargets.get(target).getMainTexture(); @@ -149,23 +150,45 @@ public FinalPassRenderer(WorldRenderingPipeline pipeline, ProgramSet pack, Rende GlStateManager._glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, 0); } - private static final class Pass { - Program program; - ComputeProgram[] computes; - ImmutableSet stageReadsFromAlt; - ImmutableSet mipmappedBuffers; + private static void setupMipmapping(RenderTarget target, boolean readFromAlt) { + if (target == null) return; - private void destroy() { - this.program.destroy(); + int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); + + // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer + // (since the last mipmap was generated) + // + // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the + // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a + // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the + // sampling mode is always reset between frames, so this only persists after the first program to use + // mipmapping on this buffer. + // + // Also note that this only applies to one of the two buffers in a render target buffer pair - making it + // unlikely that this issue occurs in practice with most shader packs. + IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); + + int filter = GL20C.GL_LINEAR_MIPMAP_LINEAR; + if (target.getInternalFormat().getPixelFormat().isInteger()) { + filter = GL20C.GL_NEAREST_MIPMAP_NEAREST; } + + IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); } - private static final class SwapPass { - public int target; - public int width; - public int height; - GlFramebuffer from; - int targetTexture; + private static void resetRenderTarget(RenderTarget target) { + if (target == null) return; + // Resets the sampling mode of the given render target and then unbinds it to prevent accidental sampling of it + // elsewhere. + int filter = GL20C.GL_LINEAR; + if (target.getInternalFormat().getPixelFormat().isInteger()) { + filter = GL20C.GL_NEAREST; + } + + IrisRenderSystem.texParameteri(target.getMainTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); + IrisRenderSystem.texParameteri(target.getAltTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); + + RenderSystem.bindTexture(0); } public void renderFinalPass() { @@ -290,54 +313,13 @@ public void recalculateSwapPassSize() { for (SwapPass swapPass : swapPasses) { RenderTarget target = renderTargets.get(swapPass.target); renderTargets.destroyFramebuffer(swapPass.from); - swapPass.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {swapPass.target}); + swapPass.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[]{swapPass.target}); swapPass.width = target.getWidth(); swapPass.height = target.getHeight(); swapPass.targetTexture = target.getMainTexture(); } } - private static void setupMipmapping(RenderTarget target, boolean readFromAlt) { - if (target == null) return; - - int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); - - // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer - // (since the last mipmap was generated) - // - // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the - // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a - // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the - // sampling mode is always reset between frames, so this only persists after the first program to use - // mipmapping on this buffer. - // - // Also note that this only applies to one of the two buffers in a render target buffer pair - making it - // unlikely that this issue occurs in practice with most shader packs. - IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); - - int filter = GL20C.GL_LINEAR_MIPMAP_LINEAR; - if (target.getInternalFormat().getPixelFormat().isInteger()) { - filter = GL20C.GL_NEAREST_MIPMAP_NEAREST; - } - - IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - } - - private static void resetRenderTarget(RenderTarget target) { - if (target == null) return; - // Resets the sampling mode of the given render target and then unbinds it to prevent accidental sampling of it - // elsewhere. - int filter = GL20C.GL_LINEAR; - if (target.getInternalFormat().getPixelFormat().isInteger()) { - filter = GL20C.GL_NEAREST; - } - - IrisRenderSystem.texParameteri(target.getMainTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - IrisRenderSystem.texParameteri(target.getAltTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - - RenderSystem.bindTexture(0); - } - // TODO: Don't just copy this from DeferredWorldRenderingPipeline private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier) { @@ -359,7 +341,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe try { builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment, - IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); + IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (ShaderCompileException e) { throw e; } catch (RuntimeException e) { @@ -372,7 +354,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); IrisImages.addCustomImages(builder, customImages); @@ -398,7 +380,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe return build; } - private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier) { + private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, Supplier shadowTargetsSupplier, ShaderStorageBufferHolder holder) { ComputeProgram[] programs = new ComputeProgram[compute.length]; for (int i = 0; i < programs.length; i++) { ComputeSource source = compute[i]; @@ -410,7 +392,7 @@ private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet flipped, renderTargets, true); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true, pipeline); IrisSamplers.addCustomTextures(builder, irisCustomTextures); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -449,7 +431,7 @@ private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet stageReadsFromAlt; + ImmutableSet mipmappedBuffers; + + private void destroy() { + this.program.destroy(); + } + } + + private static final class SwapPass { + public int target; + public int width; + public int height; + GlFramebuffer from; + int targetTexture; + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/NewWorldRenderingPipeline.java b/src/main/java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java similarity index 76% rename from src/main/java/net/coderbot/iris/pipeline/newshader/NewWorldRenderingPipeline.java rename to src/main/java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java index 8f1a9e8b2a..ab442a8395 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/NewWorldRenderingPipeline.java +++ b/src/main/java/net/irisshaders/iris/pipeline/IrisRenderingPipeline.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.pipeline; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -8,83 +8,83 @@ import com.mojang.blaze3d.vertex.VertexFormat; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; -import net.coderbot.iris.block_rendering.BlockMaterialMapping; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.colorspace.ColorSpace; -import net.coderbot.iris.colorspace.ColorSpaceConverter; -import net.coderbot.iris.colorspace.ColorSpaceFragmentConverter; -import net.coderbot.iris.compat.dh.DHCompat; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.gl.buffer.ShaderStorageBufferHolder; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.gl.image.ImageHolder; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.ProgramBuilder; -import net.coderbot.iris.gl.program.ProgramImages; -import net.coderbot.iris.gl.program.ProgramSamplers; -import net.coderbot.iris.gl.sampler.SamplerHolder; -import net.coderbot.iris.gl.shader.ShaderCompileException; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.gl.sampler.SamplerLimits; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.mixin.LevelRendererAccessor; -import net.coderbot.iris.pipeline.ClearPass; -import net.coderbot.iris.pipeline.ClearPassCreator; -import net.coderbot.iris.pipeline.CustomTextureManager; -import net.coderbot.iris.pipeline.HorizonRenderer; -import net.coderbot.iris.pipeline.ShaderPrinter; -import net.coderbot.iris.pipeline.ShadowRenderer; -import net.coderbot.iris.pipeline.SodiumTerrainPipeline; -import net.coderbot.iris.pipeline.WorldRenderingPhase; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.fallback.FallbackShader; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.postprocess.BufferFlipper; -import net.coderbot.iris.postprocess.CenterDepthSampler; -import net.coderbot.iris.postprocess.CompositeRenderer; -import net.coderbot.iris.postprocess.FinalPassRenderer; -import net.coderbot.iris.rendertarget.Blaze3dRenderTargetExt; -import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.samplers.IrisImages; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.shaderpack.CloudSetting; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.ImageInformation; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shaderpack.ParticleRenderingSettings; -import net.coderbot.iris.shaderpack.ProgramFallbackResolver; -import net.coderbot.iris.shaderpack.ProgramSet; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.ShaderPack; -import net.coderbot.iris.shaderpack.loading.ProgramId; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.shadows.ShadowCompositeRenderer; -import net.coderbot.iris.shadows.ShadowRenderTargets; -import net.coderbot.iris.texture.TextureInfoCache; -import net.coderbot.iris.texture.format.TextureFormat; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.coderbot.iris.texture.pbr.PBRTextureHolder; -import net.coderbot.iris.texture.pbr.PBRTextureManager; -import net.coderbot.iris.texture.pbr.PBRType; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.buffer.ShaderStorageBufferHolder; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.image.ImageHolder; +import net.irisshaders.iris.gl.program.ComputeProgram; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.sampler.SamplerHolder; +import net.irisshaders.iris.gl.sampler.SamplerLimits; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.helpers.FakeChainedJsonException; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.LevelRendererAccessor; +import net.irisshaders.iris.pathways.CenterDepthSampler; +import net.irisshaders.iris.pathways.HorizonRenderer; +import net.irisshaders.iris.pathways.colorspace.ColorSpace; +import net.irisshaders.iris.pathways.colorspace.ColorSpaceConverter; +import net.irisshaders.iris.pathways.colorspace.ColorSpaceFragmentConverter; +import net.irisshaders.iris.pipeline.programs.ExtendedShader; +import net.irisshaders.iris.pipeline.programs.FallbackShader; +import net.irisshaders.iris.pipeline.programs.ShaderCreator; +import net.irisshaders.iris.pipeline.programs.ShaderKey; +import net.irisshaders.iris.pipeline.programs.ShaderMap; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.samplers.IrisImages; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.shaderpack.FilledIndirectPointer; +import net.irisshaders.iris.shaderpack.ImageInformation; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.materialmap.BlockMaterialMapping; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramFallbackResolver; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.CloudSetting; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.shadows.ShadowCompositeRenderer; +import net.irisshaders.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.shadows.ShadowRenderer; +import net.irisshaders.iris.targets.Blaze3dRenderTargetExt; +import net.irisshaders.iris.targets.BufferFlipper; +import net.irisshaders.iris.targets.ClearPass; +import net.irisshaders.iris.targets.ClearPassCreator; +import net.irisshaders.iris.targets.RenderTargetStateListener; +import net.irisshaders.iris.targets.RenderTargets; +import net.irisshaders.iris.targets.backed.NativeImageBackedSingleColorTexture; +import net.irisshaders.iris.texture.TextureInfoCache; +import net.irisshaders.iris.texture.format.TextureFormat; +import net.irisshaders.iris.texture.format.TextureFormatLoader; +import net.irisshaders.iris.texture.pbr.PBRTextureHolder; +import net.irisshaders.iris.texture.pbr.PBRTextureManager; +import net.irisshaders.iris.texture.pbr.PBRType; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.DimensionSpecialEffects; @@ -92,6 +92,7 @@ import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.DynamicTexture; +import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.joml.Vector3d; import org.joml.Vector4f; @@ -105,6 +106,7 @@ import java.io.IOException; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.OptionalInt; @@ -112,7 +114,7 @@ import java.util.function.IntFunction; import java.util.function.Supplier; -public class NewWorldRenderingPipeline implements WorldRenderingPipeline, CoreWorldRenderingPipeline, RenderTargetStateListener { +public class IrisRenderingPipeline implements WorldRenderingPipeline, ShaderRenderingPipeline, RenderTargetStateListener { private final RenderTargets renderTargets; private final ShaderMap shaderMap; private final CustomUniforms customUniforms; @@ -120,76 +122,67 @@ public class NewWorldRenderingPipeline implements WorldRenderingPipeline, CoreWo private final Object2ObjectMap, String> customTextureMap; private final ComputeProgram[] setup; private final boolean separateHardwareSamplers; - private ShaderStorageBufferHolder shaderStorageBufferHolder; private final ProgramFallbackResolver resolver; - - private ShadowRenderTargets shadowRenderTargets; private final Supplier shadowTargetsSupplier; - - private WorldRenderingPhase overridePhase = null; - private WorldRenderingPhase phase = WorldRenderingPhase.NONE; - private final Set loadedShaders; - private ImmutableList clearPassesFull; - private ImmutableList clearPasses; - private ImmutableList shadowClearPasses; - private ImmutableList shadowClearPassesFull; - private final GlFramebuffer baseline; - private final CompositeRenderer beginRenderer; private final CompositeRenderer prepareRenderer; private final CompositeRenderer deferredRenderer; private final CompositeRenderer compositeRenderer; private final FinalPassRenderer finalPassRenderer; - private final CustomTextureManager customTextureManager; private final DynamicTexture whitePixel; private final FrameUpdateNotifier updateNotifier; private final CenterDepthSampler centerDepthSampler; private final SodiumTerrainPipeline sodiumTerrainPipeline; private final ColorSpaceConverter colorSpaceConverter; - private final ImmutableSet flippedBeforeShadow; private final ImmutableSet flippedAfterPrepare; private final ImmutableSet flippedAfterTranslucent; - - public boolean isBeforeTranslucent; - private final HorizonRenderer horizonRenderer = new HorizonRenderer(); @Nullable - private ComputeProgram[] shadowComputes; - + private final ComputeProgram[] shadowComputes; private final float sunPathRotation; private final boolean shouldRenderUnderwaterOverlay; private final boolean shouldRenderVignette; private final boolean shouldWriteRainAndSnowToDepthBuffer; private final boolean oldLighting; private final OptionalInt forcedShadowRenderDistanceChunks; - private boolean destroyed = false; - private boolean isRenderingWorld; - private boolean isMainBound; - private boolean frustumCulling; + private final boolean frustumCulling; + private final boolean occlusionCulling; private final CloudSetting cloudSetting; private final boolean shouldRenderSun; private final boolean shouldRenderMoon; private final boolean allowConcurrentCompute; - @Nullable private final ShadowRenderer shadowRenderer; private final int shadowMapResolution; + private final ParticleRenderingSettings particleRenderingSettings; + private final PackDirectives packDirectives; + private final Set customImages; + private final GlImage[] clearImages; + private final ShaderPack pack; + private final PackShadowDirectives shadowDirectives; + private final DHCompat dhCompat; + private final int stackSize = 0; + public boolean isBeforeTranslucent; + private ShaderStorageBufferHolder shaderStorageBufferHolder; + private ShadowRenderTargets shadowRenderTargets; + private WorldRenderingPhase overridePhase = null; + private WorldRenderingPhase phase = WorldRenderingPhase.NONE; + private ImmutableList clearPassesFull; + private ImmutableList clearPasses; + private ImmutableList shadowClearPasses; + private ImmutableList shadowClearPassesFull; + private boolean destroyed = false; + private boolean isRenderingWorld; + private boolean isMainBound; private boolean shouldBindPBR; private int currentNormalTexture; private int currentSpecularTexture; - private ParticleRenderingSettings particleRenderingSettings; - private PackDirectives packDirectives; - private Set customImages; - private GlImage[] clearImages; - private final ShaderPack pack; - private PackShadowDirectives shadowDirectives; private ColorSpace currentColorSpace; - private DHCompat dhCompat; - public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { + public IrisRenderingPipeline(ProgramSet programSet) { ShaderPrinter.resetPrintState(); this.shouldRenderUnderwaterOverlay = programSet.getPackDirectives().underwaterOverlay(); @@ -206,8 +199,7 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { this.shouldRenderMoon = programSet.getPackDirectives().shouldRenderMoon(); this.allowConcurrentCompute = programSet.getPackDirectives().getConcurrentCompute(); this.frustumCulling = programSet.getPackDirectives().shouldUseFrustumCulling(); - this.dhCompat = new DHCompat(); - + this.occlusionCulling = programSet.getPackDirectives().shouldUseOcclusionCulling(); this.resolver = new ProgramFallbackResolver(programSet); this.pack = programSet.getPack(); @@ -216,6 +208,20 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat(); DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); + if (!programSet.getPackDirectives().getBufferObjects().isEmpty()) { + if (IrisRenderSystem.supportsSSBO()) { + this.shaderStorageBufferHolder = new ShaderStorageBufferHolder(programSet.getPackDirectives().getBufferObjects(), main.width, main.height); + + this.shaderStorageBufferHolder.setupBuffers(); + } else { + throw new IllegalStateException("Shader storage buffers/immutable buffer storage is not supported on this graphics card, however the shaderpack requested them? This shouldn't be possible."); + } + } else { + for (int i = 0; i < Math.min(16, SamplerLimits.get().getMaxShaderStorageUnits()); i++) { + IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, i, 0); + } + } + this.customImages = new HashSet<>(); for (ImageInformation information : programSet.getPack().getIrisCustomImages()) { if (information.isRelative()) { @@ -244,7 +250,7 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { if (shadowDirectives.getDistanceRenderMul() >= 0.0) { // add 15 and then divide by 16 to ensure we're rounding up forcedShadowRenderDistanceChunks = - OptionalInt.of(((int) (shadowDirectives.getDistance() * shadowDirectives.getDistanceRenderMul()) + 15) / 16); + OptionalInt.of(((int) (shadowDirectives.getDistance() * shadowDirectives.getDistanceRenderMul()) + 15) / 16); } else { forcedShadowRenderDistanceChunks = OptionalInt.of(-1); } @@ -266,7 +272,6 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { BufferFlipper flipper = new BufferFlipper(); - this.centerDepthSampler = new CenterDepthSampler(() -> renderTargets.getDepthTexture(), programSet.getPackDirectives().getCenterDepthHalfLife()); this.shadowMapResolution = programSet.getPackDirectives().getShadowDirectives().getResolution(); @@ -280,51 +285,37 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { return shadowRenderTargets; }; - if (!programSet.getPackDirectives().getBufferObjects().isEmpty()) { - if (IrisRenderSystem.supportsSSBO()) { - this.shaderStorageBufferHolder = new ShaderStorageBufferHolder(programSet.getPackDirectives().getBufferObjects(), main.width, main.height); - - this.shaderStorageBufferHolder.setupBuffers(); - } else { - throw new IllegalStateException("Shader storage buffers/immutable buffer storage is not supported on this graphics card, however the shaderpack requested them? This shouldn't be possible."); - } - } else { - for (int i = 0; i < Math.min(16, SamplerLimits.get().getMaxShaderStorageUnits()); i++) { - IrisRenderSystem.bindBufferBase(GL43C.GL_SHADER_STORAGE_BUFFER, i, 0); - } - } - this.shadowComputes = createShadowComputes(programSet.getShadowCompute(), programSet); - this.beginRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getBegin(), programSet.getBeginCompute(), renderTargets, + this.beginRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getBegin(), programSet.getBeginCompute(), renderTargets, shaderStorageBufferHolder, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.BEGIN, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.BEGIN, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, programSet.getPackDirectives().getExplicitFlips("begin_pre"), customUniforms); flippedBeforeShadow = flipper.snapshot(); - this.prepareRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getPrepare(), programSet.getPrepareCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.PREPARE, - customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.PREPARE, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, - programSet.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms); + this.prepareRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getPrepare(), programSet.getPrepareCompute(), renderTargets, shaderStorageBufferHolder, + customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.PREPARE, + customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.PREPARE, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, + programSet.getPackDirectives().getExplicitFlips("prepare_pre"), customUniforms); flippedAfterPrepare = flipper.snapshot(); - this.deferredRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getDeferred(), programSet.getDeferredCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.DEFERRED, - customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.DEFERRED, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, - programSet.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms); + this.deferredRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getDeferred(), programSet.getDeferredCompute(), renderTargets, shaderStorageBufferHolder, + customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.DEFERRED, + customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.DEFERRED, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, + programSet.getPackDirectives().getExplicitFlips("deferred_pre"), customUniforms); flippedAfterTranslucent = flipper.snapshot(); - this.compositeRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getComposite(), programSet.getCompositeCompute(), renderTargets, - customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.COMPOSITE_AND_FINAL, - customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.COMPOSITE_AND_FINAL, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, - programSet.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms); - this.finalPassRenderer = new FinalPassRenderer(this, programSet, renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, flipper.snapshot(), - centerDepthSampler, shadowTargetsSupplier, - customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.COMPOSITE_AND_FINAL, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, - this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms); + this.compositeRenderer = new CompositeRenderer(this, programSet.getPackDirectives(), programSet.getComposite(), programSet.getCompositeCompute(), renderTargets, shaderStorageBufferHolder, + customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, flipper, shadowTargetsSupplier, TextureStage.COMPOSITE_AND_FINAL, + customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.COMPOSITE_AND_FINAL, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, + programSet.getPackDirectives().getExplicitFlips("composite_pre"), customUniforms); + this.finalPassRenderer = new FinalPassRenderer(this, programSet, renderTargets, customTextureManager.getNoiseTexture(), shaderStorageBufferHolder, updateNotifier, flipper.snapshot(), + centerDepthSampler, shadowTargetsSupplier, + customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.COMPOSITE_AND_FINAL, Object2ObjectMaps.emptyMap()), customTextureManager.getIrisCustomTextures(), customImages, + this.compositeRenderer.getFlippedAtLeastOnceFinal(), customUniforms); Supplier> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; @@ -334,14 +325,14 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap())); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); if (!shouldBindPBR) { shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor); } - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, true, true, false); IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -370,19 +361,21 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { return builder.build(); }; + this.dhCompat = new DHCompat(this, shadowDirectives.isDhShadowEnabled().orElse(true)); + IntFunction createShadowTerrainSamplers = (programId) -> { ProgramSamplers.Builder builder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap().getOrDefault(TextureStage.GBUFFERS_AND_SHADOW, Object2ObjectMaps.emptyMap())); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flippedBeforeShadow, renderTargets, false); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flippedBeforeShadow, renderTargets, false, this); IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); if (!shouldBindPBR) { shouldBindPBR = IrisSamplers.hasPBRSamplers(customTextureSamplerInterceptor); } - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, true, true, false); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -414,7 +407,6 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { return builder.build(); }; - this.baseline = renderTargets.createFramebufferWritingToMain(new int[] {0}); this.loadedShaders = new HashSet<>(); @@ -441,18 +433,18 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { } }); - BlockRenderingSettings.INSTANCE.setBlockStateIds( - BlockMaterialMapping.createBlockStateIdMap(programSet.getPack().getIdMap().getBlockProperties())); - BlockRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programSet.getPack().getIdMap().getBlockRenderTypeMap())); + WorldRenderingSettings.INSTANCE.setBlockStateIds( + BlockMaterialMapping.createBlockStateIdMap(programSet.getPack().getIdMap().getBlockProperties())); + WorldRenderingSettings.INSTANCE.setBlockTypeIds(BlockMaterialMapping.createBlockTypeMap(programSet.getPack().getIdMap().getBlockRenderTypeMap())); - BlockRenderingSettings.INSTANCE.setEntityIds(programSet.getPack().getIdMap().getEntityIdMap()); - BlockRenderingSettings.INSTANCE.setItemIds(programSet.getPack().getIdMap().getItemIdMap()); - BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programSet.getPackDirectives().getAmbientOcclusionLevel()); - BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); - BlockRenderingSettings.INSTANCE.setUseSeparateAo(programSet.getPackDirectives().shouldUseSeparateAo()); - BlockRenderingSettings.INSTANCE.setVoxelizeLightBlocks(programSet.getPackDirectives().shouldVoxelizeLightBlocks()); - BlockRenderingSettings.INSTANCE.setSeparateEntityDraws(programSet.getPackDirectives().shouldUseSeparateEntityDraws()); - BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(true); + WorldRenderingSettings.INSTANCE.setEntityIds(programSet.getPack().getIdMap().getEntityIdMap()); + WorldRenderingSettings.INSTANCE.setItemIds(programSet.getPack().getIdMap().getItemIdMap()); + WorldRenderingSettings.INSTANCE.setAmbientOcclusionLevel(programSet.getPackDirectives().getAmbientOcclusionLevel()); + WorldRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); + WorldRenderingSettings.INSTANCE.setUseSeparateAo(programSet.getPackDirectives().shouldUseSeparateAo()); + WorldRenderingSettings.INSTANCE.setVoxelizeLightBlocks(programSet.getPackDirectives().shouldVoxelizeLightBlocks()); + WorldRenderingSettings.INSTANCE.setSeparateEntityDraws(programSet.getPackDirectives().shouldUseSeparateEntityDraws()); + WorldRenderingSettings.INSTANCE.setUseExtendedVertexFormat(true); if (shadowRenderTargets == null && shadowDirectives.isShadowEnabled() == OptionalBoolean.TRUE) { shadowRenderTargets = new ShadowRenderTargets(this, shadowMapResolution, shadowDirectives); @@ -462,14 +454,13 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { ShaderInstance shader = shaderMap.getShader(ShaderKey.SHADOW_TERRAIN_CUTOUT); boolean shadowUsesImages = false; - if (shader instanceof ExtendedShader) { - ExtendedShader shader2 = (ExtendedShader) shader; + if (shader instanceof ExtendedShader shader2) { shadowUsesImages = shader2.hasActiveImages(); } this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives); this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives); - this.shadowCompositeRenderer = new ShadowCompositeRenderer(this, programSet.getPackDirectives(), programSet.getShadowComposite(), programSet.getShadowCompCompute(), this.shadowRenderTargets, customTextureManager.getNoiseTexture(), updateNotifier, + this.shadowCompositeRenderer = new ShadowCompositeRenderer(this, programSet.getPackDirectives(), programSet.getShadowComposite(), programSet.getShadowCompCompute(), this.shadowRenderTargets, this.shaderStorageBufferHolder, customTextureManager.getNoiseTexture(), updateNotifier, customTextureManager.getCustomTextureIdMap(TextureStage.SHADOWCOMP), customImages, programSet.getPackDirectives().getExplicitFlips("shadowcomp_pre"), customTextureManager.getIrisCustomTextures(), customUniforms); if (programSet.getPackDirectives().getShadowDirectives().isShadowEnabled().orElse(true)) { @@ -486,7 +477,6 @@ public NewWorldRenderingPipeline(ProgramSet programSet) throws IOException { this.shadowRenderer = null; } - dhCompat.setFramebuffer(renderTargets.createGbufferFramebuffer(ImmutableSet.of(), new int[] { 0 })); // TODO: Create fallback Sodium shaders if the pack doesn't provide terrain shaders // Currently we use Sodium's shaders but they don't support EXP2 fog underwater. this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programSet, createTerrainSamplers, @@ -544,7 +534,7 @@ public void process(int target) { //if (IrisRenderSystem.supportsCompute()) { // colorSpaceConverter = new ColorSpaceComputeConverter(main.width, main.height, IrisVideoSettings.colorSpace); //} else { - colorSpaceConverter = new ColorSpaceFragmentConverter(main.width, main.height, IrisVideoSettings.colorSpace); + colorSpaceConverter = new ColorSpaceFragmentConverter(main.width, main.height, IrisVideoSettings.colorSpace); //} } @@ -586,13 +576,13 @@ private ComputeProgram[] createShadowComputes(ComputeSource[] compute, ProgramSe ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage)); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false, this); IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); IrisImages.addRenderTargetImages(builder, flipped, renderTargets); IrisImages.addCustomImages(builder, customImages); - IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true, false)); + IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, true, true, false); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); @@ -607,7 +597,7 @@ private ComputeProgram[] createShadowComputes(ComputeSource[] compute, ProgramSe this.customUniforms.mapholderToPass(builder, programs[i]); - programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups()); + programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups(), FilledIndirectPointer.basedOff(shaderStorageBufferHolder, source.getIndirectPointer())); } } @@ -649,7 +639,7 @@ private ComputeProgram[] createSetupComputes(ComputeSource[] compute, ProgramSet ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage)); - IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, true); + IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, true, this); IrisSamplers.addCustomTextures(builder, customTextureManager.getIrisCustomTextures()); IrisSamplers.addCompositeSamplers(builder, renderTargets); IrisSamplers.addCustomImages(customTextureSamplerInterceptor, customImages); @@ -670,7 +660,7 @@ private ComputeProgram[] createSetupComputes(ComputeSource[] compute, ProgramSet this.customUniforms.mapholderToPass(builder, programs[i]); - programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups()); + programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups(), FilledIndirectPointer.basedOff(shaderStorageBufferHolder, source.getIndirectPointer())); } } @@ -684,7 +674,7 @@ private ShaderInstance createShader(String name, Optional source, } return createShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(), key.getFogMode(), - key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText()); + key.isIntensity(), key.shouldIgnoreLightmap(), key.isGlint(), key.isText()); } @Override @@ -706,8 +696,8 @@ private ShaderInstance createShader(String name, ProgramSource source, ProgramId () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; - ExtendedShader extendedShader = NewShaderTests.create(this, name, source, programId, beforeTranslucent, afterTranslucent, - baseline, fallbackAlpha, vertexFormat, inputs, updateNotifier, this, flipped, fogMode, isIntensity, isFullbright, false, isLines, customUniforms); + ExtendedShader extendedShader = ShaderCreator.create(this, name, source, programId, beforeTranslucent, afterTranslucent, + fallbackAlpha, vertexFormat, inputs, updateNotifier, this, flipped, fogMode, isIntensity, isFullbright, false, isLines, customUniforms); loadedShaders.add(extendedShader); @@ -715,12 +705,12 @@ private ShaderInstance createShader(String name, ProgramSource source, ProgramId } private ShaderInstance createFallbackShader(String name, ShaderKey key) throws IOException { - GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); - GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, new int[] {0}); + GlFramebuffer beforeTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, new int[]{0}); + GlFramebuffer afterTranslucent = renderTargets.createGbufferFramebuffer(flippedAfterTranslucent, new int[]{0}); - FallbackShader shader = NewShaderTests.createFallback(name, beforeTranslucent, afterTranslucent, - key.getAlphaTest(), key.getVertexFormat(), null, this, key.getFogMode(), - key == ShaderKey.GLINT, key.isText(), key.hasDiffuseLighting(), key.isIntensity(), key.shouldIgnoreLightmap()); + FallbackShader shader = ShaderCreator.createFallback(name, beforeTranslucent, afterTranslucent, + key.getAlphaTest(), key.getVertexFormat(), null, this, key.getFogMode(), + key == ShaderKey.GLINT, key.isText(), key.hasDiffuseLighting(), key.isIntensity(), key.shouldIgnoreLightmap()); loadedShaders.add(shader); @@ -733,15 +723,15 @@ private ShaderInstance createShadowShader(String name, Optional s } return createShadowShader(name, source.get(), key.getProgram(), key.getAlphaTest(), key.getVertexFormat(), - key.isIntensity(), key.shouldIgnoreLightmap(), key.isText()); + key.isIntensity(), key.shouldIgnoreLightmap(), key.isText()); } private ShaderInstance createFallbackShadowShader(String name, ShaderKey key) throws IOException { - GlFramebuffer framebuffer = shadowRenderTargets.createShadowFramebuffer(ImmutableSet.of(), new int[] { 0 }); + GlFramebuffer framebuffer = shadowRenderTargets.createShadowFramebuffer(ImmutableSet.of(), new int[]{0}); - FallbackShader shader = NewShaderTests.createFallback(name, framebuffer, framebuffer, - key.getAlphaTest(), key.getVertexFormat(), BlendModeOverride.OFF, this, key.getFogMode(), - key == ShaderKey.GLINT, key.isText(), key.hasDiffuseLighting(), key.isIntensity(), key.shouldIgnoreLightmap()); + FallbackShader shader = ShaderCreator.createFallback(name, framebuffer, framebuffer, + key.getAlphaTest(), key.getVertexFormat(), BlendModeOverride.OFF, this, key.getFogMode(), + key == ShaderKey.GLINT, key.isText(), key.hasDiffuseLighting(), key.isIntensity(), key.shouldIgnoreLightmap()); loadedShaders.add(shader); @@ -757,8 +747,8 @@ private ShaderInstance createShadowShader(String name, ProgramSource source, Pro Supplier> flipped = () -> flippedBeforeShadow; - ExtendedShader extendedShader = NewShaderTests.create(this, name, source, programId, framebuffer, framebuffer, baseline, - fallbackAlpha, vertexFormat, inputs, updateNotifier, this, flipped, FogMode.PER_VERTEX, isIntensity, isFullbright, true, isLines, customUniforms); + ExtendedShader extendedShader = ShaderCreator.create(this, name, source, programId, framebuffer, framebuffer, + fallbackAlpha, vertexFormat, inputs, updateNotifier, this, flipped, FogMode.PER_VERTEX, isIntensity, isFullbright, true, isLines, customUniforms); loadedShaders.add(extendedShader); @@ -766,14 +756,14 @@ private ShaderInstance createShadowShader(String name, ProgramSource source, Pro } public void addGbufferOrShadowSamplers(SamplerHolder samplers, ImageHolder images, Supplier> flipped, - boolean isShadowPass, InputAvailability availability) { + boolean isShadowPass, boolean hasTexture, boolean hasLightmap, boolean hasOverlay) { TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; ProgramSamplers.CustomTextureSamplerInterceptor samplerHolder = - ProgramSamplers.customTextureSamplerInterceptor(samplers, - customTextureManager.getCustomTextureIdMap().getOrDefault(textureStage, Object2ObjectMaps.emptyMap())); + ProgramSamplers.customTextureSamplerInterceptor(samplers, + customTextureManager.getCustomTextureIdMap().getOrDefault(textureStage, Object2ObjectMaps.emptyMap())); - IrisSamplers.addRenderTargetSamplers(samplerHolder, flipped, renderTargets, false); + IrisSamplers.addRenderTargetSamplers(samplerHolder, flipped, renderTargets, false, this); IrisSamplers.addCustomTextures(samplerHolder, customTextureManager.getIrisCustomTextures()); IrisImages.addRenderTargetImages(images, flipped, renderTargets); IrisImages.addCustomImages(images, customImages); @@ -782,23 +772,17 @@ public void addGbufferOrShadowSamplers(SamplerHolder samplers, ImageHolder image shouldBindPBR = IrisSamplers.hasPBRSamplers(samplerHolder); } - IrisSamplers.addLevelSamplers(samplers, this, whitePixel, availability); + IrisSamplers.addLevelSamplers(samplers, this, whitePixel, hasTexture, hasLightmap, hasOverlay); IrisSamplers.addWorldDepthSamplers(samplerHolder, this.renderTargets); IrisSamplers.addNoiseSampler(samplerHolder, this.customTextureManager.getNoiseTexture()); IrisSamplers.addCustomImages(samplerHolder, customImages); - if (isShadowPass || IrisSamplers.hasShadowSamplers(samplerHolder)) { - if (!isShadowPass) { - shadowTargetsSupplier.get(); - } - - IrisSamplers.addShadowSamplers(samplerHolder, Objects.requireNonNull(shadowRenderTargets), null, separateHardwareSamplers); + if (IrisSamplers.hasShadowSamplers(samplerHolder)) { + IrisSamplers.addShadowSamplers(samplerHolder, shadowTargetsSupplier.get(), null, separateHardwareSamplers); } if (isShadowPass || IrisImages.hasShadowImages(images)) { - // Note: hasShadowSamplers currently queries for shadow images too, so the shadow render targets will be - // created by this point... that's sorta ugly, though. - IrisImages.addShadowColorImages(images, Objects.requireNonNull(shadowRenderTargets), null); + IrisImages.addShadowColorImages(images, shadowTargetsSupplier.get(), null); } } @@ -811,29 +795,17 @@ public WorldRenderingPhase getPhase() { return phase; } - @Override - public void beginSodiumTerrainRendering() { - // no-op - } - - @Override - public void endSodiumTerrainRendering() { - // no-op - } - - @Override - public void setOverridePhase(WorldRenderingPhase phase) { - this.overridePhase = phase; - } - @Override public void setPhase(WorldRenderingPhase phase) { + GLDebug.popGroup(); + if (phase != WorldRenderingPhase.NONE) + GLDebug.pushGroup(phase.ordinal(), StringUtils.capitalize(phase.name().toLowerCase(Locale.ROOT).replace("_", " "))); this.phase = phase; } @Override - public void setSpecialCondition(SpecialCondition special) { - // no-op + public void setOverridePhase(WorldRenderingPhase phase) { + this.overridePhase = phase; } @Override @@ -855,14 +827,14 @@ public int getCurrentSpecularTexture() { public void onSetShaderTexture(int id) { if (shouldBindPBR && isRenderingWorld) { PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); - currentNormalTexture = pbrHolder.getNormalTexture().getId(); - currentSpecularTexture = pbrHolder.getSpecularTexture().getId(); + currentNormalTexture = pbrHolder.normalTexture().getId(); + currentSpecularTexture = pbrHolder.specularTexture().getId(); TextureFormat textureFormat = TextureFormatLoader.getFormat(); if (textureFormat != null) { int previousBinding = GlStateManagerAccessor.getTEXTURES()[GlStateManagerAccessor.getActiveTexture()].binding; - textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); - textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); + textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.normalTexture()); + textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.specularTexture()); GlStateManager._bindTexture(previousBinding); } @@ -870,12 +842,6 @@ public void onSetShaderTexture(int id) { } } - @Override - public void onShadowBufferChange() { - this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives); - this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives); - } - @Override public void beginLevelRendering() { isRenderingWorld = true; @@ -884,6 +850,7 @@ public void beginLevelRendering() { RenderSystem.activeTexture(GL15C.GL_TEXTURE0); Vector4f emptyClearColor = new Vector4f(1.0F); + for (GlImage image : clearImages) { ARBClearTexture.glClearTexImage(image.getId(), 0, image.getFormat().getGlFormat(), image.getPixelType().getGlFormat(), (int[]) null); } @@ -891,6 +858,8 @@ public void beginLevelRendering() { if (shadowRenderTargets != null) { if (packDirectives.getShadowDirectives().isShadowEnabled() == OptionalBoolean.FALSE) { if (shadowRenderTargets.isFullClearRequired()) { + this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives); + this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives); shadowRenderTargets.onFullClear(); for (ClearPass clearPass : shadowClearPassesFull) { clearPass.execute(emptyClearColor); @@ -903,15 +872,17 @@ public void beginLevelRendering() { ImmutableList passes; - for (ComputeProgram computeProgram : shadowComputes) { - if (computeProgram != null) { - computeProgram.use(); - customUniforms.push(computeProgram); - computeProgram.dispatch(shadowMapResolution, shadowMapResolution); + for (ComputeProgram computeProgram : shadowComputes) { + if (computeProgram != null) { + computeProgram.use(); + customUniforms.push(computeProgram); + computeProgram.dispatch(shadowMapResolution, shadowMapResolution); + } } - } if (shadowRenderTargets.isFullClearRequired()) { + this.shadowClearPasses = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, false, shadowDirectives); + this.shadowClearPassesFull = ClearPassCreator.createShadowClearPasses(shadowRenderTargets, true, shadowDirectives); passes = shadowClearPassesFull; shadowRenderTargets.onFullClear(); } else { @@ -1164,6 +1135,11 @@ public boolean shouldDisableFrustumCulling() { return !frustumCulling; } + @Override + public boolean shouldDisableOcclusionCulling() { + return !occlusionCulling; + } + @Override public CloudSetting getCloudSetting() { return cloudSetting; @@ -1232,6 +1208,7 @@ public void destroy() { Minecraft.getInstance().getMainRenderTarget().bindWrite(false); renderTargets.destroy(); + dhCompat.clearPipeline(); customImages.forEach(GlImage::destroy); @@ -1274,17 +1251,49 @@ protected AbstractTexture getWhitePixel() { } @Override - public void beginPostChain() { + public void setIsMainBound(boolean bound) { + isMainBound = bound; + } + public Optional getDHTerrainShader() { + return resolver.resolve(ProgramId.DhTerrain); } - @Override - public void endPostChain() { + public Optional getDHWaterShader() { + return resolver.resolve(ProgramId.DhWater); + } + public Optional getDHShadowShader() { + return resolver.resolve(ProgramId.DhShadow); } - @Override - public void setIsMainBound(boolean bound) { - isMainBound = bound; + public CustomUniforms getCustomUniforms() { + return customUniforms; + } + + public GlFramebuffer createDHFramebuffer(ProgramSource sources, boolean trans) { + return renderTargets.createDHFramebuffer(trans ? flippedAfterTranslucent : flippedAfterPrepare, + sources.getDirectives().getDrawBuffers()); + } + + public ImmutableSet getFlippedBeforeShadow() { + return flippedBeforeShadow; + } + + public ImmutableSet getFlippedAfterPrepare() { + return flippedAfterPrepare; + } + + public ImmutableSet getFlippedAfterTranslucent() { + return flippedAfterTranslucent; + } + + public GlFramebuffer createDHFramebufferShadow(ProgramSource sources) { + + return shadowRenderTargets.createDHFramebuffer(ImmutableSet.of(), new int[]{0, 1}); + } + + public boolean hasShadowRenderTargets() { + return shadowRenderTargets != null; } } diff --git a/src/main/java/net/coderbot/iris/pipeline/PipelineManager.java b/src/main/java/net/irisshaders/iris/pipeline/PipelineManager.java similarity index 87% rename from src/main/java/net/coderbot/iris/pipeline/PipelineManager.java rename to src/main/java/net/irisshaders/iris/pipeline/PipelineManager.java index 5deec8b654..6409014b89 100644 --- a/src/main/java/net/coderbot/iris/pipeline/PipelineManager.java +++ b/src/main/java/net/irisshaders/iris/pipeline/PipelineManager.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.Iris; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.shaderpack.DimensionId; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL20C; @@ -16,10 +15,9 @@ import java.util.function.Function; public class PipelineManager { - private static PipelineManager instance; private final Function pipelineFactory; private final Map pipelinesPerDimension = new HashMap<>(); - private WorldRenderingPipeline pipeline = new FixedFunctionWorldRenderingPipeline(); + private WorldRenderingPipeline pipeline = new VanillaRenderingPipeline(); private int versionCounterForSodiumShaderReload = 0; public PipelineManager(Function pipelineFactory) { @@ -35,12 +33,12 @@ public WorldRenderingPipeline preparePipeline(NamespacedId currentDimension) { pipeline = pipelineFactory.apply(currentDimension); pipelinesPerDimension.put(currentDimension, pipeline); - if (BlockRenderingSettings.INSTANCE.isReloadRequired()) { + if (WorldRenderingSettings.INSTANCE.isReloadRequired()) { if (Minecraft.getInstance().levelRenderer != null) { Minecraft.getInstance().levelRenderer.allChanged(); } - BlockRenderingSettings.INSTANCE.clearReloadRequired(); + WorldRenderingSettings.INSTANCE.clearReloadRequired(); } } else { pipeline = pipelinesPerDimension.get(currentDimension); diff --git a/src/main/java/net/irisshaders/iris/pipeline/ShaderRenderingPipeline.java b/src/main/java/net/irisshaders/iris/pipeline/ShaderRenderingPipeline.java new file mode 100644 index 0000000000..8ece5d0425 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/ShaderRenderingPipeline.java @@ -0,0 +1,12 @@ +package net.irisshaders.iris.pipeline; + +import net.irisshaders.iris.pipeline.programs.ShaderMap; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; + +public interface ShaderRenderingPipeline extends WorldRenderingPipeline { + ShaderMap getShaderMap(); + + FrameUpdateNotifier getFrameUpdateNotifier(); + + boolean shouldOverrideShaders(); +} diff --git a/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java b/src/main/java/net/irisshaders/iris/pipeline/SodiumTerrainPipeline.java similarity index 86% rename from src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java rename to src/main/java/net/irisshaders/iris/pipeline/SodiumTerrainPipeline.java index c8e445f593..4dfd6daf54 100644 --- a/src/main/java/net/coderbot/iris/pipeline/SodiumTerrainPipeline.java +++ b/src/main/java/net/irisshaders/iris/pipeline/SodiumTerrainPipeline.java @@ -1,27 +1,28 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import com.google.common.collect.ImmutableSet; import com.google.common.primitives.Ints; -import me.jellysquid.mods.sodium.client.gl.shader.ShaderLoader; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.gl.blending.AlphaTest; -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.gl.program.ProgramImages; -import net.coderbot.iris.gl.program.ProgramSamplers; -import net.coderbot.iris.gl.program.ProgramUniforms; -import net.coderbot.iris.pipeline.newshader.AlphaTests; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.pipeline.newshader.ShaderAttributeInputs; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.shaderpack.ProgramSet; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.loading.ProgramId; -import net.coderbot.iris.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.AlphaTests; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.targets.RenderTargets; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.resources.ResourceLocation; import java.util.ArrayList; @@ -34,50 +35,12 @@ import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.coderbot.iris.uniforms.custom.CustomUniforms; public class SodiumTerrainPipeline { - Optional terrainSolidVertex; - Optional terrainSolidGeometry; - Optional terrainSolidTessControl; - Optional terrainSolidTessEval; - Optional terrainSolidFragment; - GlFramebuffer terrainSolidFramebuffer; - BlendModeOverride terrainSolidBlendOverride; - List terrainSolidBufferOverrides; - - Optional terrainCutoutVertex; - Optional terrainCutoutGeometry; - Optional terrainCutoutTessControl; - Optional terrainCutoutTessEval; - Optional terrainCutoutFragment; - GlFramebuffer terrainCutoutFramebuffer; - BlendModeOverride terrainCutoutBlendOverride; - List terrainCutoutBufferOverrides; - Optional terrainCutoutAlpha; - - Optional translucentVertex; - Optional translucentGeometry; - Optional translucentTessControl; - Optional translucentTessEval; - Optional translucentFragment; - GlFramebuffer translucentFramebuffer; - BlendModeOverride translucentBlendOverride; - List translucentBufferOverrides; - Optional translucentAlpha; - - Optional shadowVertex; - Optional shadowGeometry; - Optional shadowTessControl; - Optional shadowTessEval; - Optional shadowFragment; - Optional shadowCutoutFragment; - GlFramebuffer shadowFramebuffer; - BlendModeOverride shadowBlendOverride = BlendModeOverride.OFF; - List shadowBufferOverrides; - Optional shadowAlpha; - - private static String defaultVertex = """ + private static final Supplier> terrainCutoutDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA); + private static final Supplier> translucentDefault = () -> Optional.of(AlphaTest.ALWAYS); + private static final Supplier> shadowDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA); + private static final String defaultVertex = """ #version 330 core in ivec2 a_LightCoord; @@ -139,49 +102,48 @@ void _vert_init() { """ + "_vert_tex_diffuse_coord = (a_TexCoord * " + (1.0f / 32768.0f) + ");" + """ - _vert_tex_light_coord = a_LightCoord; - _vert_color = a_Color; - _draw_id = (a_PosId.w >> 8u) & 0xffu; - _material_params = (a_PosId.w >> 0u) & 0xFFu; - } - uvec3 _get_relative_chunk_coord(uint pos) { - return uvec3(pos) >> uvec3(5u, 0u, 2u) & uvec3(7u, 3u, 7u); - } - vec3 _get_draw_translation(uint pos) { - return _get_relative_chunk_coord(pos) * vec3(16.0f); - } - vec4 getVertexPosition() { - return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0f); - } - - uniform sampler2D lightmap; // The light map texture + _vert_tex_light_coord = a_LightCoord; + _vert_color = a_Color; + _draw_id = (a_PosId.w >> 8u) & 0xffu; + _material_params = (a_PosId.w >> 0u) & 0xFFu; + } + uvec3 _get_relative_chunk_coord(uint pos) { + return uvec3(pos) >> uvec3(5u, 0u, 2u) & uvec3(7u, 3u, 7u); + } + vec3 _get_draw_translation(uint pos) { + return _get_relative_chunk_coord(pos) * vec3(16.0f); + } + vec4 getVertexPosition() { + return vec4(_vert_position + u_RegionOffset + _get_draw_translation(_draw_id), 1.0f); + } - vec3 _sample_lightmap(ivec2 uv) { - return texture(lightmap, clamp(uv / 256.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0))).rgb; - } + uniform sampler2D lightmap; // The light map texture + vec3 _sample_lightmap(ivec2 uv) { + return texture(lightmap, clamp(uv / 256.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0))).rgb; + } - void main() { - _vert_init(); - // Transform the chunk-local vertex position into world model space - vec3 translation = u_RegionOffset + _get_draw_translation(_draw_id); - vec3 position = _vert_position + translation; + void main() { + _vert_init(); - v_FragDistance = getFragDistance(fogShape, position); + // Transform the chunk-local vertex position into world model space + vec3 translation = u_RegionOffset + _get_draw_translation(_draw_id); + vec3 position = _vert_position + translation; - // Transform the vertex position into model-view-projection space - gl_Position = iris_ProjectionMatrix * iris_ModelViewMatrix * vec4(position, 1.0); + v_FragDistance = getFragDistance(fogShape, position); - v_ColorModulator = vec4((_vert_color.rgb * _vert_color.a), 1) * vec4(_sample_lightmap(_vert_tex_light_coord), 1.0); - v_TexCoord = _vert_tex_diffuse_coord; + // Transform the vertex position into model-view-projection space + gl_Position = iris_ProjectionMatrix * iris_ModelViewMatrix * vec4(position, 1.0); - v_MaterialMipBias = _material_mip_bias(_material_params); - v_MaterialAlphaCutoff = _material_alpha_cutoff(_material_params); - } - """; + v_ColorModulator = vec4((_vert_color.rgb * _vert_color.a), 1) * vec4(_sample_lightmap(_vert_tex_light_coord), 1.0); + v_TexCoord = _vert_tex_diffuse_coord; - private static String defaultFragment = """ + v_MaterialMipBias = _material_mip_bias(_material_params); + v_MaterialAlphaCutoff = _material_alpha_cutoff(_material_params); + } + """; + private static final String defaultFragment = """ #version 330 core const int FOG_SHAPE_SPHERICAL = 0; @@ -223,17 +185,49 @@ void main() { out_FragColor = _linearFog(diffuseColor, v_FragDistance, iris_FogColor, iris_FogStart, iris_FogEnd); } """; - - ProgramSet programSet; - private final WorldRenderingPipeline parent; private final CustomUniforms customUniforms; - private final IntFunction createTerrainSamplers; private final IntFunction createShadowSamplers; - private final IntFunction createTerrainImages; private final IntFunction createShadowImages; + Optional terrainSolidVertex; + Optional terrainSolidGeometry; + Optional terrainSolidTessControl; + Optional terrainSolidTessEval; + Optional terrainSolidFragment; + GlFramebuffer terrainSolidFramebuffer; + BlendModeOverride terrainSolidBlendOverride; + List terrainSolidBufferOverrides; + Optional terrainCutoutVertex; + Optional terrainCutoutGeometry; + Optional terrainCutoutTessControl; + Optional terrainCutoutTessEval; + Optional terrainCutoutFragment; + GlFramebuffer terrainCutoutFramebuffer; + BlendModeOverride terrainCutoutBlendOverride; + List terrainCutoutBufferOverrides; + Optional terrainCutoutAlpha; + Optional translucentVertex; + Optional translucentGeometry; + Optional translucentTessControl; + Optional translucentTessEval; + Optional translucentFragment; + GlFramebuffer translucentFramebuffer; + BlendModeOverride translucentBlendOverride; + List translucentBufferOverrides; + Optional translucentAlpha; + Optional shadowVertex; + Optional shadowGeometry; + Optional shadowTessControl; + Optional shadowTessEval; + Optional shadowFragment; + Optional shadowCutoutFragment; + GlFramebuffer shadowFramebuffer; + BlendModeOverride shadowBlendOverride = BlendModeOverride.OFF; + List shadowBufferOverrides; + Optional shadowAlpha; + ProgramSet programSet; public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSet, IntFunction createTerrainSamplers, IntFunction createShadowSamplers, IntFunction createTerrainImages, IntFunction createShadowImages, @@ -251,24 +245,24 @@ public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSe this.shadowFramebuffer = shadowFramebuffer; terrainSolidSource.ifPresent(sources -> terrainSolidFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, - sources.getDirectives().getDrawBuffers())); + sources.getDirectives().getDrawBuffers())); terrainCutoutSource.ifPresent(sources -> terrainCutoutFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, - sources.getDirectives().getDrawBuffers())); + sources.getDirectives().getDrawBuffers())); translucentSource.ifPresent(sources -> translucentFramebuffer = targets.createGbufferFramebuffer(flippedAfterTranslucent, - sources.getDirectives().getDrawBuffers())); + sources.getDirectives().getDrawBuffers())); if (terrainSolidFramebuffer == null) { - terrainSolidFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); + terrainSolidFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[]{0}); } if (terrainCutoutFramebuffer == null) { - terrainCutoutFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); + terrainCutoutFramebuffer = targets.createGbufferFramebuffer(flippedAfterPrepare, new int[]{0}); } if (translucentFramebuffer == null) { - translucentFramebuffer = targets.createGbufferFramebuffer(flippedAfterTranslucent, new int[] {0}); + translucentFramebuffer = targets.createGbufferFramebuffer(flippedAfterTranslucent, new int[]{0}); } this.createTerrainSamplers = createTerrainSamplers; @@ -277,9 +271,31 @@ public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSe this.createShadowImages = createShadowImages; } - private static final Supplier> terrainCutoutDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA); - private static final Supplier> translucentDefault = () -> Optional.of(AlphaTest.ALWAYS); - private static final Supplier> shadowDefault = () -> Optional.of(AlphaTests.ONE_TENTH_ALPHA); + @SafeVarargs + private static Optional first(Optional... candidates) { + for (Optional candidate : candidates) { + if (candidate.isPresent()) { + return candidate; + } + } + + return Optional.empty(); + } + + public static String parseSodiumImport(String shader) { + Pattern IMPORT_PATTERN = Pattern.compile("#import <(?.*):(?.*)>"); + Matcher matcher = IMPORT_PATTERN.matcher(shader); + + if (!matcher.matches()) { + throw new IllegalArgumentException("Malformed import statement (expected format: " + IMPORT_PATTERN + ")"); + } + + String namespace = matcher.group("namespace"); + String path = matcher.group("path"); + + ResourceLocation identifier = new ResourceLocation(namespace, path); + return ""; + } public void patchShaders(ChunkVertexType vertexType) { ShaderAttributeInputs inputs = new ShaderAttributeInputs(true, true, false, true, true); @@ -293,9 +309,9 @@ public void patchShaders(ChunkVertexType vertexType) { terrainSolidBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Terrain.getBlendModeOverride()); terrainSolidBufferOverrides = new ArrayList<>(); sources.getDirectives().getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.getIndex()); + int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index()); if (index > -1) { - terrainSolidBufferOverrides.add(new BufferBlendOverride(index, information.getBlendMode())); + terrainSolidBufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); } }); @@ -328,9 +344,9 @@ public void patchShaders(ChunkVertexType vertexType) { terrainCutoutBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Terrain.getBlendModeOverride()); terrainCutoutBufferOverrides = new ArrayList<>(); sources.getDirectives().getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.getIndex()); + int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index()); if (index > -1) { - terrainCutoutBufferOverrides.add(new BufferBlendOverride(index, information.getBlendMode())); + terrainCutoutBufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); } }); terrainCutoutAlpha = sources.getDirectives().getAlphaTestOverride().or(terrainCutoutDefault); @@ -366,9 +382,9 @@ public void patchShaders(ChunkVertexType vertexType) { translucentBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Water.getBlendModeOverride()); translucentBufferOverrides = new ArrayList<>(); sources.getDirectives().getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.getIndex()); + int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index()); if (index > -1) { - translucentBufferOverrides.add(new BufferBlendOverride(index, information.getBlendMode())); + translucentBufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); } }); translucentAlpha = sources.getDirectives().getAlphaTestOverride().or(translucentDefault); @@ -403,9 +419,9 @@ public void patchShaders(ChunkVertexType vertexType) { shadowBlendOverride = sources.getDirectives().getBlendModeOverride().orElse(ProgramId.Shadow.getBlendModeOverride()); shadowBufferOverrides = new ArrayList<>(); sources.getDirectives().getBufferBlendOverrides().forEach(information -> { - int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.getIndex()); + int index = Ints.indexOf(sources.getDirectives().getDrawBuffers(), information.index()); if (index > -1) { - shadowBufferOverrides.add(new BufferBlendOverride(index, information.getBlendMode())); + shadowBufferOverrides.add(new BufferBlendOverride(index, information.blendMode())); } }); shadowAlpha = sources.getDirectives().getAlphaTestOverride().or(shadowDefault); @@ -494,6 +510,7 @@ public Optional getTerrainCutoutFragmentShaderSource() { public GlFramebuffer getTerrainSolidFramebuffer() { return terrainSolidFramebuffer; } + public GlFramebuffer getTerrainCutoutFramebuffer() { return terrainCutoutFramebuffer; } @@ -628,38 +645,4 @@ public ProgramImages initShadowImages(int programId) { public CustomUniforms getCustomUniforms() { return customUniforms; } - - /*public void bindFramebuffer() { - this.framebuffer.bind(); - } - - public void unbindFramebuffer() { - GlStateManager.bindFramebuffer(GL30C.GL_FRAMEBUFFER, 0); - }*/ - - @SafeVarargs - private static Optional first(Optional... candidates) { - for (Optional candidate : candidates) { - if (candidate.isPresent()) { - return candidate; - } - } - - return Optional.empty(); - } - - public static String parseSodiumImport(String shader) { - Pattern IMPORT_PATTERN = Pattern.compile("#import <(?.*):(?.*)>"); - Matcher matcher = IMPORT_PATTERN.matcher(shader); - - if (!matcher.matches()) { - throw new IllegalArgumentException("Malformed import statement (expected format: " + IMPORT_PATTERN + ")"); - } - - String namespace = matcher.group("namespace"); - String path = matcher.group("path"); - - ResourceLocation identifier = new ResourceLocation(namespace, path); - return ""; - } } diff --git a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java b/src/main/java/net/irisshaders/iris/pipeline/VanillaRenderingPipeline.java similarity index 65% rename from src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java rename to src/main/java/net/irisshaders/iris/pipeline/VanillaRenderingPipeline.java index e4346a5ce4..7c150da469 100644 --- a/src/main/java/net/coderbot/iris/pipeline/FixedFunctionWorldRenderingPipeline.java +++ b/src/main/java/net/irisshaders/iris/pipeline/VanillaRenderingPipeline.java @@ -1,41 +1,34 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.dh.DHCompat; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.mixin.LevelRendererAccessor; -import net.coderbot.iris.shaderpack.CloudSetting; -import net.coderbot.iris.shaderpack.ParticleRenderingSettings; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.mixin.LevelRendererAccessor; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.shaderpack.properties.CloudSetting; +import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.targets.RenderTargetStateListener; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import java.util.List; import java.util.OptionalInt; -public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeline { - public FixedFunctionWorldRenderingPipeline() { - BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); - BlockRenderingSettings.INSTANCE.setUseSeparateAo(false); - BlockRenderingSettings.INSTANCE.setSeparateEntityDraws(false); - BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f); - BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false); - BlockRenderingSettings.INSTANCE.setVoxelizeLightBlocks(false); - BlockRenderingSettings.INSTANCE.setBlockTypeIds(null); - } - - @Override - public void onShadowBufferChange() { - +public class VanillaRenderingPipeline implements WorldRenderingPipeline { + public VanillaRenderingPipeline() { + WorldRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); + WorldRenderingSettings.INSTANCE.setUseSeparateAo(false); + WorldRenderingSettings.INSTANCE.setSeparateEntityDraws(false); + WorldRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f); + WorldRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false); + WorldRenderingSettings.INSTANCE.setVoxelizeLightBlocks(false); + WorldRenderingSettings.INSTANCE.setBlockTypeIds(null); } @Override @@ -70,38 +63,13 @@ public WorldRenderingPhase getPhase() { return WorldRenderingPhase.NONE; } - @Override - public void beginSodiumTerrainRendering() { - - } - - @Override - public void endSodiumTerrainRendering() { - - } - - @Override - public void setOverridePhase(WorldRenderingPhase phase) { - - } - @Override public void setPhase(WorldRenderingPhase phase) { } - //@Override - public void setInputs(InputAvailability availability) { - - } - @Override - public void setSpecialCondition(SpecialCondition special) { - - } - - //@Override - public void syncProgram() { + public void setOverridePhase(WorldRenderingPhase phase) { } @@ -127,7 +95,7 @@ public void onSetShaderTexture(int id) { @Override public void beginHand() { - // stub: nothing to do here + // stub: nothing to do here } @Override @@ -177,6 +145,11 @@ public boolean shouldDisableFrustumCulling() { return false; } + @Override + public boolean shouldDisableOcclusionCulling() { + return false; + } + @Override public CloudSetting getCloudSetting() { return CloudSetting.DEFAULT; diff --git a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPhase.java b/src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPhase.java similarity index 96% rename from src/main/java/net/coderbot/iris/pipeline/WorldRenderingPhase.java rename to src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPhase.java index c274992c7b..81eb4a3227 100644 --- a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPhase.java +++ b/src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPhase.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import net.minecraft.client.renderer.RenderType; diff --git a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java b/src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPipeline.java similarity index 58% rename from src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java rename to src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPipeline.java index 3bec5584b0..f47c6753d0 100644 --- a/src/main/java/net/coderbot/iris/pipeline/WorldRenderingPipeline.java +++ b/src/main/java/net/irisshaders/iris/pipeline/WorldRenderingPipeline.java @@ -1,42 +1,42 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.compat.dh.DHCompat; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gbuffer_overrides.matching.SpecialCondition; -import net.coderbot.iris.gbuffer_overrides.state.RenderTargetStateListener; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.mixin.LevelRendererAccessor; -import net.coderbot.iris.shaderpack.CloudSetting; -import net.coderbot.iris.shaderpack.ParticleRenderingSettings; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.mixin.LevelRendererAccessor; +import net.irisshaders.iris.shaderpack.properties.CloudSetting; +import net.irisshaders.iris.shaderpack.properties.ParticleRenderingSettings; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.targets.RenderTargetStateListener; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import net.minecraft.client.Camera; import java.util.List; import java.util.OptionalInt; public interface WorldRenderingPipeline { - void onShadowBufferChange(); + void beginLevelRendering(); - void beginLevelRendering(); void renderShadows(LevelRendererAccessor worldRenderer, Camera camera); + void addDebugText(List messages); + OptionalInt getForcedShadowRenderDistanceChunksForDisplay(); - Object2ObjectMap, String> getTextureMap(); + Object2ObjectMap, String> getTextureMap(); - WorldRenderingPhase getPhase(); + WorldRenderingPhase getPhase(); - void beginSodiumTerrainRendering(); - void endSodiumTerrainRendering(); - void setOverridePhase(WorldRenderingPhase phase); void setPhase(WorldRenderingPhase phase); - void setSpecialCondition(SpecialCondition special); + + void setOverridePhase(WorldRenderingPhase phase); + RenderTargetStateListener getRenderTargetStateListener(); int getCurrentNormalTexture(); + int getCurrentSpecularTexture(); void onSetShaderTexture(int id); @@ -44,27 +44,44 @@ public interface WorldRenderingPipeline { void beginHand(); void beginTranslucents(); + void finalizeLevelRendering(); + void finalizeGameRendering(); + void destroy(); SodiumTerrainPipeline getSodiumTerrainPipeline(); + FrameUpdateNotifier getFrameUpdateNotifier(); boolean shouldDisableVanillaEntityShadows(); + boolean shouldDisableDirectionalShading(); + boolean shouldDisableFrustumCulling(); + + boolean shouldDisableOcclusionCulling(); + CloudSetting getCloudSetting(); + boolean shouldRenderUnderwaterOverlay(); + boolean shouldRenderVignette(); + boolean shouldRenderSun(); + boolean shouldRenderMoon(); + boolean shouldWriteRainAndSnowToDepthBuffer(); + ParticleRenderingSettings getParticleRenderingSettings(); + boolean allowConcurrentCompute(); + boolean hasFeature(FeatureFlags flags); float getSunPathRotation(); - DHCompat getDHCompat(); + DHCompat getDHCompat(); } diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/fallback/ShaderSynthesizer.java b/src/main/java/net/irisshaders/iris/pipeline/fallback/ShaderSynthesizer.java similarity index 78% rename from src/main/java/net/coderbot/iris/pipeline/newshader/fallback/ShaderSynthesizer.java rename to src/main/java/net/irisshaders/iris/pipeline/fallback/ShaderSynthesizer.java index f350653fb8..3b4c37c806 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/fallback/ShaderSynthesizer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/fallback/ShaderSynthesizer.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.pipeline.newshader.fallback; +package net.irisshaders.iris.pipeline.fallback; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.pipeline.newshader.AlphaTests; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.pipeline.newshader.ShaderAttributeInputs; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.AlphaTests; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; public class ShaderSynthesizer { public static String vsh(boolean hasChunkOffset, ShaderAttributeInputs inputs, FogMode fogMode, @@ -29,34 +29,34 @@ public static String vsh(boolean hasChunkOffset, ShaderAttributeInputs inputs, F if (inputs.isNewLines()) { shader.append("const float VIEW_SHRINK = 1.0 - (1.0 / 256.0);\n" + - "const mat4 VIEW_SCALE = mat4(\n" + - " VIEW_SHRINK, 0.0, 0.0, 0.0,\n" + - " 0.0, VIEW_SHRINK, 0.0, 0.0,\n" + - " 0.0, 0.0, VIEW_SHRINK, 0.0,\n" + - " 0.0, 0.0, 0.0, 1.0\n" + - ");\n"); + "const mat4 VIEW_SCALE = mat4(\n" + + " VIEW_SHRINK, 0.0, 0.0, 0.0,\n" + + " 0.0, VIEW_SHRINK, 0.0, 0.0,\n" + + " 0.0, 0.0, VIEW_SHRINK, 0.0,\n" + + " 0.0, 0.0, 0.0, 1.0\n" + + ");\n"); shader.append("uniform float LineWidth;\n" + - "uniform vec2 ScreenSize;\n"); + "uniform vec2 ScreenSize;\n"); main.append("vec4 linePosStart = ProjMat * VIEW_SCALE * ModelViewMat * vec4(" + position + ", 1.0);\n" + - " vec4 linePosEnd = ProjMat * VIEW_SCALE * ModelViewMat * vec4(" + position + " + Normal, 1.0);\n" + - "\n" + - " vec3 ndc1 = linePosStart.xyz / linePosStart.w;\n" + - " vec3 ndc2 = linePosEnd.xyz / linePosEnd.w;\n" + - "\n" + - " vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * ScreenSize);\n" + - " vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * LineWidth / ScreenSize;\n" + - "\n" + - " if (lineOffset.x < 0.0) {\n" + - " lineOffset *= -1.0;\n" + - " }\n" + - "\n" + - " if (gl_VertexID % 2 == 0) {\n" + - " gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);\n" + - " } else {\n" + - " gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);\n" + - " }\n"); + " vec4 linePosEnd = ProjMat * VIEW_SCALE * ModelViewMat * vec4(" + position + " + Normal, 1.0);\n" + + "\n" + + " vec3 ndc1 = linePosStart.xyz / linePosStart.w;\n" + + " vec3 ndc2 = linePosEnd.xyz / linePosEnd.w;\n" + + "\n" + + " vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * ScreenSize);\n" + + " vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * LineWidth / ScreenSize;\n" + + "\n" + + " if (lineOffset.x < 0.0) {\n" + + " lineOffset *= -1.0;\n" + + " }\n" + + "\n" + + " if (gl_VertexID % 2 == 0) {\n" + + " gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);\n" + + " } else {\n" + + " gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);\n" + + " }\n"); } else { main.append(" gl_Position = ProjMat * ModelViewMat * vec4("); main.append(position); @@ -82,13 +82,13 @@ public static String vsh(boolean hasChunkOffset, ShaderAttributeInputs inputs, F // Copied from Mojang code. shader.append("vec4 minecraft_mix_light(vec3 lightDir0, vec3 lightDir1, vec3 normal, vec4 color) {\n" + - " lightDir0 = normalize(lightDir0);\n" + - " lightDir1 = normalize(lightDir1);\n" + - " float light0 = max(0.0, dot(lightDir0, normal));\n" + - " float light1 = max(0.0, dot(lightDir1, normal));\n" + - " float lightAccum = min(1.0, (light0 + light1) * 0.6 + 0.4);\n" + - " return vec4(color.rgb * lightAccum, color.a);\n" + - "}\n"); + " lightDir0 = normalize(lightDir0);\n" + + " lightDir1 = normalize(lightDir1);\n" + + " float light0 = max(0.0, dot(lightDir0, normal));\n" + + " float light1 = max(0.0, dot(lightDir1, normal));\n" + + " float lightAccum = min(1.0, (light0 + light1) * 0.6 + 0.4);\n" + + " return vec4(color.rgb * lightAccum, color.a);\n" + + "}\n"); shader.append("in vec3 Normal;\n"); @@ -143,7 +143,6 @@ public static String vsh(boolean hasChunkOffset, ShaderAttributeInputs inputs, F } - // void main shader.append("void main() {\n"); shader.append(main); diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/ExtendedShader.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ExtendedShader.java similarity index 62% rename from src/main/java/net/coderbot/iris/pipeline/newshader/ExtendedShader.java rename to src/main/java/net/irisshaders/iris/pipeline/programs/ExtendedShader.java index 79f6b0faae..c18dbcfd5a 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/ExtendedShader.java +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ExtendedShader.java @@ -1,60 +1,56 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.pipeline.programs; -import com.ibm.icu.impl.ICUNotifier; -import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.preprocessor.GlslPreprocessor; import com.mojang.blaze3d.shaders.Program; import com.mojang.blaze3d.shaders.ProgramManager; import com.mojang.blaze3d.shaders.Uniform; import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.blending.BlendMode; -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.gl.image.ImageHolder; -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.gl.sampler.SamplerHolder; -import net.coderbot.iris.gl.state.ValueUpdateNotifier; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder; -import net.coderbot.iris.gl.uniform.DynamicUniformHolder; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.custom.CustomUniforms; -import org.joml.Vector3f; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.image.ImageHolder; +import net.irisshaders.iris.gl.program.IrisProgramTypes; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.sampler.SamplerHolder; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.uniform.DynamicLocationalUniformHolder; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.vertices.ImmediateState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; -import org.apache.logging.log4j.util.TriConsumer; import org.jetbrains.annotations.Nullable; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.lwjgl.opengl.ARBTextureSwizzle; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; -import org.lwjgl.opengl.GL32C; +import org.lwjgl.opengl.KHRDebug; import java.io.IOException; -import java.util.HashMap; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; -import java.util.function.IntSupplier; -import java.util.function.Supplier; public class ExtendedShader extends ShaderInstance implements ShaderInstanceInterface { + private static final Matrix4f identity; + private static ExtendedShader lastApplied; + + static { + identity = new Matrix4f(); + identity.identity(); + } + private final boolean intensitySwizzle; private final List bufferBlendOverrides; private final boolean hasOverrides; @@ -62,31 +58,35 @@ public class ExtendedShader extends ShaderInstance implements ShaderInstanceInte private final Uniform projectionInverse; private final Uniform normalMatrix; private final CustomUniforms customUniforms; - NewWorldRenderingPipeline parent; - ProgramUniforms uniforms; - ProgramSamplers samplers; - ProgramImages images; - GlFramebuffer writingToBeforeTranslucent; - GlFramebuffer writingToAfterTranslucent; - GlFramebuffer baseline; - BlendModeOverride blendModeOverride; + private final IrisRenderingPipeline parent; + private final ProgramUniforms uniforms; + private final ProgramSamplers samplers; + private final ProgramImages images; + private final GlFramebuffer writingToBeforeTranslucent; + private final GlFramebuffer writingToAfterTranslucent; + private final BlendModeOverride blendModeOverride; float alphaTest; boolean usesTessellation; + Matrix4f tempMatrix4f = new Matrix4f(); + Matrix3f tempMatrix3f = new Matrix3f(); + float[] tempFloats = new float[16]; + float[] tempFloats2 = new float[9]; private Program geometry, tessControl, tessEval; - private final ShaderAttributeInputs inputs; - - private static ExtendedShader lastApplied; - private final Vector3f chunkOffset = new Vector3f(); public ExtendedShader(ResourceProvider resourceFactory, String string, VertexFormat vertexFormat, boolean usesTessellation, GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent, - GlFramebuffer baseline, BlendModeOverride blendModeOverride, AlphaTest alphaTest, + BlendModeOverride blendModeOverride, AlphaTest alphaTest, Consumer uniformCreator, BiConsumer samplerCreator, boolean isIntensity, - NewWorldRenderingPipeline parent, ShaderAttributeInputs inputs, @Nullable List bufferBlendOverrides, CustomUniforms customUniforms) throws IOException { + IrisRenderingPipeline parent, @Nullable List bufferBlendOverrides, CustomUniforms customUniforms) throws IOException { super(resourceFactory, string, vertexFormat); + GLDebug.nameObject(KHRDebug.GL_SHADER, this.getVertexProgram().getId(), string + "_vertex.vsh"); + GLDebug.nameObject(KHRDebug.GL_SHADER, this.getFragmentProgram().getId(), string + "_fragment.fsh"); + int programId = this.getId(); + GLDebug.nameObject(KHRDebug.GL_PROGRAM, programId, string); + ProgramUniforms.Builder uniformBuilder = ProgramUniforms.builder(string, programId); ProgramSamplers.Builder samplerBuilder = ProgramSamplers.builder(programId, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); uniformCreator.accept(uniformBuilder); @@ -101,13 +101,11 @@ public ExtendedShader(ResourceProvider resourceFactory, String string, VertexFor images = builder.build(); this.writingToBeforeTranslucent = writingToBeforeTranslucent; this.writingToAfterTranslucent = writingToAfterTranslucent; - this.baseline = baseline; this.blendModeOverride = blendModeOverride; this.bufferBlendOverrides = bufferBlendOverrides; this.hasOverrides = bufferBlendOverrides != null && !bufferBlendOverrides.isEmpty(); - this.alphaTest = alphaTest.getReference(); + this.alphaTest = alphaTest.reference(); this.parent = parent; - this.inputs = inputs; this.modelViewInverse = this.getUniform("ModelViewMatInverse"); this.projectionInverse = this.getUniform("ProjMatInverse"); @@ -133,18 +131,6 @@ public void clear() { Minecraft.getInstance().getMainRenderTarget().bindWrite(false); } - Matrix4f tempMatrix4f = new Matrix4f(); - Matrix3f tempMatrix3f = new Matrix3f(); - private static final Matrix4f identity; - - static { - identity = new Matrix4f(); - identity.identity(); - } - - float[] tempFloats = new float[16]; - float[] tempFloats2 = new float[9]; - @Override public void apply() { CapturedRenderingState.INSTANCE.setCurrentAlphaTest(alphaTest); @@ -156,7 +142,7 @@ public void apply() { if (intensitySwizzle) { IrisRenderSystem.texParameteriv(RenderSystem.getShaderTexture(0), TextureType.TEXTURE_2D.getGlType(), ARBTextureSwizzle.GL_TEXTURE_SWIZZLE_RGBA, - new int[] { GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED }); + new int[]{GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED}); } IrisRenderSystem.bindTextureToUnit(TextureType.TEXTURE_2D.getGlType(), IrisSamplers.ALBEDO_TEXTURE_UNIT, RenderSystem.getShaderTexture(0)); @@ -183,7 +169,6 @@ public void apply() { if (normalMatrix != null) { normalMatrix.set(tempMatrix3f.set(tempMatrix4f.set(MODEL_VIEW_MATRIX.getFloatBuffer())).invert().transpose().get(tempFloats2)); } - } else { } uploadIfNotNull(projectionInverse); @@ -231,11 +216,6 @@ private void uploadIfNotNull(Uniform uniform) { } } - @Override - public void close() { - super.close(); - } - @Override public void attachToProgram() { super.attachToProgram(); @@ -251,46 +231,49 @@ public void attachToProgram() { } @Override - public void iris$createExtraShaders(ResourceProvider factory, ResourceLocation name) throws IOException { - factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_geometry.gsh")).ifPresent(geometry -> { - try { - this.geometry = Program.compileShader(IrisProgramTypes.GEOMETRY, name.getPath(), geometry.open(), geometry.sourcePackId(), new GlslPreprocessor() { - @Nullable - @Override - public String applyImport(boolean bl, String string) { - return null; - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - }); - factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_tessControl.tcs")).ifPresent(tessControl -> { - try { - this.tessControl = Program.compileShader(IrisProgramTypes.TESS_CONTROL, name.getPath(), tessControl.open(), tessControl.sourcePackId(), new GlslPreprocessor() { - @Nullable - @Override - public String applyImport(boolean bl, String string) { - return null; - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - }); - factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_tessEval.tes")).ifPresent(tessEval -> { - try { - this.tessEval = Program.compileShader(IrisProgramTypes.TESS_EVAL, name.getPath(), tessEval.open(), tessEval.sourcePackId(), new GlslPreprocessor() { - @Nullable - @Override - public String applyImport(boolean bl, String string) { - return null; - } - }); - } catch (IOException e) { - e.printStackTrace(); - } - }); + public void iris$createExtraShaders(ResourceProvider factory, ResourceLocation name) { + factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_geometry.gsh")).ifPresent(geometry -> { + try { + this.geometry = Program.compileShader(IrisProgramTypes.GEOMETRY, name.getPath(), geometry.open(), geometry.sourcePackId(), new GlslPreprocessor() { + @Nullable + @Override + public String applyImport(boolean bl, String string) { + return null; + } + }); + GLDebug.nameObject(KHRDebug.GL_SHADER, this.geometry.getId(), name.getPath() + "_geometry.gsh"); + } catch (IOException e) { + Iris.logger.error("Failed to create shader program", e); + } + }); + factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_tessControl.tcs")).ifPresent(tessControl -> { + try { + this.tessControl = Program.compileShader(IrisProgramTypes.TESS_CONTROL, name.getPath(), tessControl.open(), tessControl.sourcePackId(), new GlslPreprocessor() { + @Nullable + @Override + public String applyImport(boolean bl, String string) { + return null; + } + }); + GLDebug.nameObject(KHRDebug.GL_SHADER, this.tessControl.getId(), name.getPath() + "_tessControl.tcs"); + } catch (IOException e) { + Iris.logger.error("Failed to create shader program", e); + } + }); + factory.getResource(new ResourceLocation(name.getNamespace(), name.getPath() + "_tessEval.tes")).ifPresent(tessEval -> { + try { + this.tessEval = Program.compileShader(IrisProgramTypes.TESS_EVAL, name.getPath(), tessEval.open(), tessEval.sourcePackId(), new GlslPreprocessor() { + @Nullable + @Override + public String applyImport(boolean bl, String string) { + return null; + } + }); + GLDebug.nameObject(KHRDebug.GL_SHADER, this.tessEval.getId(), name.getPath() + "_tessEval.tes"); + } catch (IOException e) { + Iris.logger.error("Failed to create shader program", e); + } + }); } public Program getGeometry() { diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/fallback/FallbackShader.java b/src/main/java/net/irisshaders/iris/pipeline/programs/FallbackShader.java similarity index 84% rename from src/main/java/net/coderbot/iris/pipeline/newshader/fallback/FallbackShader.java rename to src/main/java/net/irisshaders/iris/pipeline/programs/FallbackShader.java index 04a88cd806..497f235971 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/fallback/FallbackShader.java +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/FallbackShader.java @@ -1,17 +1,17 @@ -package net.coderbot.iris.pipeline.newshader.fallback; +package net.irisshaders.iris.pipeline.programs; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.shaders.ProgramManager; import com.mojang.blaze3d.shaders.Uniform; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.pipeline.newshader.NewWorldRenderingPipeline; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.uniforms.CapturedRenderingState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ShaderInstance; import net.minecraft.server.packs.resources.ResourceProvider; @@ -21,7 +21,7 @@ import java.util.List; public class FallbackShader extends ShaderInstance { - private final NewWorldRenderingPipeline parent; + private final IrisRenderingPipeline parent; private final BlendModeOverride blendModeOverride; private final GlFramebuffer writingToBeforeTranslucent; private final GlFramebuffer writingToAfterTranslucent; @@ -37,7 +37,7 @@ public class FallbackShader extends ShaderInstance { public FallbackShader(ResourceProvider resourceFactory, String string, VertexFormat vertexFormat, GlFramebuffer writingToBeforeTranslucent, GlFramebuffer writingToAfterTranslucent, - BlendModeOverride blendModeOverride, float alphaValue, NewWorldRenderingPipeline parent) throws IOException { + BlendModeOverride blendModeOverride, float alphaValue, IrisRenderingPipeline parent) throws IOException { super(resourceFactory, string, vertexFormat); this.parent = parent; diff --git a/src/main/java/net/coderbot/iris/pipeline/ShaderAccess.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderAccess.java similarity index 50% rename from src/main/java/net/coderbot/iris/pipeline/ShaderAccess.java rename to src/main/java/net/irisshaders/iris/pipeline/programs/ShaderAccess.java index eb9993ebe0..0675fe7169 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShaderAccess.java +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderAccess.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline.programs; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.newshader.CoreWorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.ShaderKey; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.pipeline.ShaderRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.ShaderInstance; @@ -10,8 +10,8 @@ public class ShaderAccess { public static ShaderInstance getParticleTranslucentShader() { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); - if (pipeline instanceof CoreWorldRenderingPipeline) { - ShaderInstance override = ((CoreWorldRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.PARTICLES_TRANS); + if (pipeline instanceof ShaderRenderingPipeline) { + ShaderInstance override = ((ShaderRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.PARTICLES_TRANS); if (override != null) { return override; diff --git a/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderCreator.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderCreator.java new file mode 100644 index 0000000000..f61a5394a1 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderCreator.java @@ -0,0 +1,229 @@ +package net.irisshaders.iris.pipeline.programs; + +import com.google.common.collect.ImmutableSet; +import com.google.common.primitives.Ints; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; +import net.irisshaders.iris.pipeline.IrisRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.pipeline.fallback.ShaderSynthesizer; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.VanillaUniforms; +import net.irisshaders.iris.uniforms.builtin.BuiltinReplacementUniforms; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.PathPackResources; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceProvider; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; + +public class ShaderCreator { + public static ExtendedShader create(WorldRenderingPipeline pipeline, String name, ProgramSource source, ProgramId programId, GlFramebuffer writingToBeforeTranslucent, + GlFramebuffer writingToAfterTranslucent, AlphaTest fallbackAlpha, + VertexFormat vertexFormat, ShaderAttributeInputs inputs, FrameUpdateNotifier updateNotifier, + IrisRenderingPipeline parent, Supplier> flipped, FogMode fogMode, boolean isIntensity, + boolean isFullbright, boolean isShadowPass, boolean isLines, CustomUniforms customUniforms) throws IOException { + AlphaTest alpha = source.getDirectives().getAlphaTestOverride().orElse(fallbackAlpha); + BlendModeOverride blendModeOverride = source.getDirectives().getBlendModeOverride().orElse(programId.getBlendModeOverride()); + + Map transformed = TransformPatcher.patchVanilla( + name, + source.getVertexSource().orElseThrow(RuntimeException::new), + source.getGeometrySource().orElse(null), + source.getTessControlSource().orElse(null), + source.getTessEvalSource().orElse(null), + source.getFragmentSource().orElseThrow(RuntimeException::new), + alpha, isLines, true, inputs, pipeline.getTextureMap()); + String vertex = transformed.get(PatchShaderType.VERTEX); + String geometry = transformed.get(PatchShaderType.GEOMETRY); + String tessControl = transformed.get(PatchShaderType.TESS_CONTROL); + String tessEval = transformed.get(PatchShaderType.TESS_EVAL); + String fragment = transformed.get(PatchShaderType.FRAGMENT); + + String shaderJsonString = String.format(""" + { + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "%s", + "fragment": "%s", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "uniforms": [ + { "name": "iris_TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "iris_ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "iris_ModelViewMatInverse", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "iris_ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "iris_ProjMatInverse", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "iris_NormalMat", "type": "matrix3x3", "count": 9, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 ] }, + { "name": "iris_ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "iris_ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "iris_GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "iris_FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "iris_FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "iris_FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } + ] + }""", name, name); + + ShaderPrinter.printProgram(name).addSources(transformed).addJson(shaderJsonString).print(); + + ResourceProvider shaderResourceFactory = new IrisProgramResourceFactory(shaderJsonString, vertex, geometry, tessControl, tessEval, fragment); + + List overrides = new ArrayList<>(); + source.getDirectives().getBufferBlendOverrides().forEach(information -> { + int index = Ints.indexOf(source.getDirectives().getDrawBuffers(), information.index()); + if (index > -1) { + overrides.add(new BufferBlendOverride(index, information.blendMode())); + } + }); + + return new ExtendedShader(shaderResourceFactory, name, vertexFormat, tessControl != null || tessEval != null, writingToBeforeTranslucent, writingToAfterTranslucent, blendModeOverride, alpha, uniforms -> { + CommonUniforms.addDynamicUniforms(uniforms, FogMode.PER_VERTEX); + customUniforms.assignTo(uniforms); + BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms); + VanillaUniforms.addVanillaUniforms(uniforms); + }, (samplerHolder, imageHolder) -> { + parent.addGbufferOrShadowSamplers(samplerHolder, imageHolder, flipped, isShadowPass, inputs.hasTex(), inputs.hasLight(), inputs.hasOverlay()); + }, isIntensity, parent, overrides, customUniforms); + } + + public static FallbackShader createFallback(String name, GlFramebuffer writingToBeforeTranslucent, + GlFramebuffer writingToAfterTranslucent, AlphaTest alpha, + VertexFormat vertexFormat, BlendModeOverride blendModeOverride, + IrisRenderingPipeline parent, FogMode fogMode, boolean entityLighting, + boolean isGlint, boolean isText, boolean intensityTex, boolean isFullbright) throws IOException { + ShaderAttributeInputs inputs = new ShaderAttributeInputs(vertexFormat, isFullbright, false, isGlint, isText); + + // TODO: Is this check sound in newer versions? + boolean isLeash = vertexFormat == DefaultVertexFormat.POSITION_COLOR_LIGHTMAP; + String vertex = ShaderSynthesizer.vsh(true, inputs, fogMode, entityLighting, isLeash); + String fragment = ShaderSynthesizer.fsh(inputs, fogMode, alpha, intensityTex, isLeash); + + + String shaderJsonString = String.format(""" + { + "blend": { + "func": "add", + "srcrgb": "srcalpha", + "dstrgb": "1-srcalpha" + }, + "vertex": "%s", + "fragment": "%s", + "attributes": [ + "Position", + "Color", + "UV0", + "UV1", + "UV2", + "Normal" + ], + "uniforms": [ + { "name": "TextureMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ModelViewMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ProjMat", "type": "matrix4x4", "count": 16, "values": [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ] }, + { "name": "ChunkOffset", "type": "float", "count": 3, "values": [ 0.0, 0.0, 0.0 ] }, + { "name": "ColorModulator", "type": "float", "count": 4, "values": [ 1.0, 1.0, 1.0, 1.0 ] }, + { "name": "GlintAlpha", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "Light0_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "Light1_Direction", "type": "float", "count": 3, "values": [0.0, 0.0, 0.0] }, + { "name": "FogStart", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "FogEnd", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogDensity", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "FogIsExp2", "type": "int", "count": 1, "values": [ 0 ] }, + { "name": "AlphaTestValue", "type": "float", "count": 1, "values": [ 0.0 ] }, + { "name": "LineWidth", "type": "float", "count": 1, "values": [ 1.0 ] }, + { "name": "ScreenSize", "type": "float", "count": 2, "values": [ 1.0, 1.0 ] }, + { "name": "FogColor", "type": "float", "count": 4, "values": [ 0.0, 0.0, 0.0, 0.0 ] } + ] + }""", name, name); + ShaderPrinter.printProgram(name) + .addSource(PatchShaderType.VERTEX, vertex) + .addSource(PatchShaderType.FRAGMENT, fragment) + .addJson(shaderJsonString) + .print(); + + ResourceProvider shaderResourceFactory = new IrisProgramResourceFactory(shaderJsonString, vertex, null, null, null, fragment); + + return new FallbackShader(shaderResourceFactory, name, vertexFormat, writingToBeforeTranslucent, + writingToAfterTranslucent, blendModeOverride, alpha.reference(), parent); + } + + private record IrisProgramResourceFactory(String json, String vertex, String geometry, String tessControl, + String tessEval, String fragment) implements ResourceProvider { + + @Override + public Optional getResource(ResourceLocation id) { + final String path = id.getPath(); + + if (path.endsWith("json")) { + return Optional.of(new StringResource(id, json)); + } else if (path.endsWith("vsh")) { + return Optional.of(new StringResource(id, vertex)); + } else if (path.endsWith("gsh")) { + if (geometry == null) { + return Optional.empty(); + } + return Optional.of(new StringResource(id, geometry)); + } else if (path.endsWith("tcs")) { + if (tessControl == null) { + return Optional.empty(); + } + return Optional.of(new StringResource(id, tessControl)); + } else if (path.endsWith("tes")) { + if (tessEval == null) { + return Optional.empty(); + } + return Optional.of(new StringResource(id, tessEval)); + } else if (path.endsWith("fsh")) { + return Optional.of(new StringResource(id, fragment)); + } + + return Optional.empty(); + } + } + + private static class StringResource extends Resource { + private final String content; + + private StringResource(ResourceLocation id, String content) { + super(new PathPackResources("", FabricLoader.getInstance().getConfigDir(), true), () -> new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))); + this.content = content; + } + + @Override + public InputStream open() { + return IOUtils.toInputStream(content, StandardCharsets.UTF_8); + } + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderInstanceInterface.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderInstanceInterface.java similarity index 85% rename from src/main/java/net/coderbot/iris/pipeline/newshader/ShaderInstanceInterface.java rename to src/main/java/net/irisshaders/iris/pipeline/programs/ShaderInstanceInterface.java index a5d53bf3ee..d374cf1a8c 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderInstanceInterface.java +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderInstanceInterface.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.pipeline.programs; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceProvider; diff --git a/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderKey.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderKey.java new file mode 100644 index 0000000000..8b05c9912f --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderKey.java @@ -0,0 +1,147 @@ +package net.irisshaders.iris.pipeline.programs; + +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.AlphaTests; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.vertices.IrisVertexFormats; + +import java.util.Locale; + +public enum ShaderKey { + // if you auto-format this and destroy all the manual indentation, I'll steal your kneecaps + + BASIC(ProgramId.Basic, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + BASIC_COLOR(ProgramId.Basic, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + TEXTURED(ProgramId.Textured, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP), + TEXTURED_COLOR(ProgramId.Textured, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + SKY_BASIC(ProgramId.SkyBasic, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + SKY_BASIC_COLOR(ProgramId.SkyBasic, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + SKY_TEXTURED(ProgramId.SkyTextured, AlphaTests.OFF, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP), + SKY_TEXTURED_COLOR(ProgramId.SkyTextured, AlphaTests.OFF, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + CLOUDS(ProgramId.Clouds, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR_NORMAL, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + CLOUDS_SODIUM(ProgramId.Clouds, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.CLOUDS, FogMode.PER_FRAGMENT, LightingModel.LIGHTMAP), + TERRAIN_SOLID(ProgramId.TerrainSolid, AlphaTests.OFF, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TERRAIN_CUTOUT(ProgramId.TerrainCutout, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TERRAIN_TRANSLUCENT(ProgramId.Water, AlphaTests.OFF, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + MOVING_BLOCK(ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + ENTITIES_ALPHA(ProgramId.Entities, AlphaTests.VERTEX_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + ENTITIES_SOLID(ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + ENTITIES_SOLID_DIFFUSE(ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + ENTITIES_SOLID_BRIGHT(ProgramId.Entities, AlphaTests.OFF, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + ENTITIES_CUTOUT(ProgramId.Entities, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + ENTITIES_CUTOUT_DIFFUSE(ProgramId.Entities, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + ENTITIES_TRANSLUCENT(ProgramId.EntitiesTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + ENTITIES_EYES(ProgramId.SpiderEyes, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + ENTITIES_EYES_TRANS(ProgramId.SpiderEyes, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + HAND_CUTOUT(ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + HAND_CUTOUT_BRIGHT(ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + HAND_CUTOUT_DIFFUSE(ProgramId.Hand, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + HAND_TEXT(ProgramId.Hand, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + HAND_TEXT_INTENSITY(ProgramId.Hand, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + HAND_TRANSLUCENT(ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + HAND_WATER_BRIGHT(ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + HAND_WATER_DIFFUSE(ProgramId.HandWater, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + LIGHTNING(ProgramId.Entities, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + LEASH(ProgramId.Basic, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TEXT_BG(ProgramId.EntitiesTrans, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + PARTICLES(ProgramId.Particles, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + PARTICLES_TRANS(ProgramId.ParticlesTrans, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + WEATHER(ProgramId.Weather, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + CRUMBLING(ProgramId.DamagedBlock, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.OFF, LightingModel.FULLBRIGHT), + TEXT(ProgramId.EntitiesTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TEXT_INTENSITY(ProgramId.EntitiesTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TEXT_BE(ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + TEXT_INTENSITY_BE(ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.GLYPH, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + BLOCK_ENTITY(ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + BLOCK_ENTITY_BRIGHT(ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.FULLBRIGHT), + BLOCK_ENTITY_DIFFUSE(ProgramId.Block, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + BE_TRANSLUCENT(ProgramId.BlockTrans, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.PER_VERTEX, LightingModel.DIFFUSE_LM), + BEACON(ProgramId.BeaconBeam, AlphaTests.OFF, DefaultVertexFormat.BLOCK, FogMode.PER_FRAGMENT, LightingModel.FULLBRIGHT), + GLINT(ProgramId.ArmorGlint, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + LINES(ProgramId.Line, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_NORMAL, FogMode.PER_VERTEX, LightingModel.LIGHTMAP), + + // Note: These must be at the very end (NewWorldRenderingPipeline implementation details) + SHADOW_TERRAIN_CUTOUT(ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.TERRAIN, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_ENTITIES_CUTOUT(ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, IrisVertexFormats.ENTITY, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_BEACON_BEAM(ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.BLOCK, FogMode.OFF, LightingModel.FULLBRIGHT), + SHADOW_BASIC(ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_BASIC_COLOR(ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_TEX(ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_TEX, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_TEX_COLOR(ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_CLOUDS(ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.POSITION_TEX_COLOR_NORMAL, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_LINES(ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_NORMAL, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_LEASH(ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_LIGHTNING(ProgramId.Shadow, AlphaTests.OFF, DefaultVertexFormat.POSITION_COLOR, FogMode.OFF, LightingModel.FULLBRIGHT), + SHADOW_PARTICLES(ProgramId.Shadow, AlphaTests.ONE_TENTH_ALPHA, DefaultVertexFormat.PARTICLE, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_TEXT(ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_TEXT_BG(ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, FogMode.OFF, LightingModel.LIGHTMAP), + SHADOW_TEXT_INTENSITY(ProgramId.Shadow, AlphaTests.NON_ZERO_ALPHA, IrisVertexFormats.GLYPH, FogMode.OFF, LightingModel.LIGHTMAP); + + private final ProgramId program; + private final AlphaTest alphaTest; + private final VertexFormat vertexFormat; + private final FogMode fogMode; + private final LightingModel lightingModel; + + ShaderKey(ProgramId program, AlphaTest alphaTest, VertexFormat vertexFormat, FogMode fogMode, LightingModel lightingModel) { + this.program = program; + this.alphaTest = alphaTest; + this.vertexFormat = vertexFormat; + this.fogMode = fogMode; + this.lightingModel = lightingModel; + } + + public ProgramId getProgram() { + return program; + } + + public AlphaTest getAlphaTest() { + return alphaTest; + } + + public VertexFormat getVertexFormat() { + return vertexFormat; + } + + public FogMode getFogMode() { + return fogMode; + } + + public boolean isIntensity() { + return this == TEXT_INTENSITY || this == TEXT_INTENSITY_BE || this == SHADOW_TEXT_INTENSITY; + } + + public String getName() { + return toString().toLowerCase(Locale.ROOT); + } + + public boolean isShadow() { + return this.getProgram() == ProgramId.Shadow; + } + + public boolean hasDiffuseLighting() { + return lightingModel == LightingModel.DIFFUSE || lightingModel == LightingModel.DIFFUSE_LM; + } + + public boolean shouldIgnoreLightmap() { + return lightingModel == LightingModel.FULLBRIGHT || lightingModel == LightingModel.DIFFUSE; + } + + public boolean isGlint() { + return this == GLINT; + } + + public boolean isText() { + return this.name().contains("TEXT"); + } + + enum LightingModel { + FULLBRIGHT, + LIGHTMAP, + DIFFUSE, + DIFFUSE_LM + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderMap.java b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderMap.java similarity index 93% rename from src/main/java/net/coderbot/iris/pipeline/newshader/ShaderMap.java rename to src/main/java/net/irisshaders/iris/pipeline/programs/ShaderMap.java index c61e0d7e30..da4036ae74 100644 --- a/src/main/java/net/coderbot/iris/pipeline/newshader/ShaderMap.java +++ b/src/main/java/net/irisshaders/iris/pipeline/programs/ShaderMap.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.newshader; +package net.irisshaders.iris.pipeline.programs; import net.minecraft.client.renderer.ShaderInstance; diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java b/src/main/java/net/irisshaders/iris/pipeline/transform/Patch.java similarity index 51% rename from src/main/java/net/coderbot/iris/pipeline/transform/Patch.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/Patch.java index bc60081e74..174ed952ea 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/Patch.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/Patch.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.pipeline.transform; +package net.irisshaders.iris.pipeline.transform; public enum Patch { - ATTRIBUTES, VANILLA, + DH, SODIUM, COMPOSITE, COMPUTE diff --git a/src/main/java/net/irisshaders/iris/pipeline/transform/PatchShaderType.java b/src/main/java/net/irisshaders/iris/pipeline/transform/PatchShaderType.java new file mode 100644 index 0000000000..bc9bcc9b5c --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/PatchShaderType.java @@ -0,0 +1,32 @@ +package net.irisshaders.iris.pipeline.transform; + +import net.irisshaders.iris.gl.shader.ShaderType; + +public enum PatchShaderType { + VERTEX(ShaderType.VERTEX, ".vsh"), + GEOMETRY(ShaderType.GEOMETRY, ".gsh"), + TESS_CONTROL(ShaderType.TESSELATION_CONTROL, ".tcs"), + TESS_EVAL(ShaderType.TESSELATION_EVAL, ".tes"), + FRAGMENT(ShaderType.FRAGMENT, ".fsh"), + COMPUTE(ShaderType.COMPUTE, ".csh"); + + public final ShaderType glShaderType; + public final String extension; + + PatchShaderType(ShaderType glShaderType, String extension) { + this.glShaderType = glShaderType; + this.extension = extension; + } + + public static PatchShaderType[] fromGlShaderType(ShaderType glShaderType) { + return switch (glShaderType) { + case VERTEX -> new PatchShaderType[]{VERTEX}; + case GEOMETRY -> new PatchShaderType[]{GEOMETRY}; + case TESSELATION_CONTROL -> new PatchShaderType[]{TESS_CONTROL}; + case TESSELATION_EVAL -> new PatchShaderType[]{TESS_EVAL}; + case COMPUTE -> new PatchShaderType[]{COMPUTE}; + case FRAGMENT -> new PatchShaderType[]{FRAGMENT}; + default -> throw new IllegalArgumentException("Unknown shader type: " + glShaderType); + }; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/ShaderPrinter.java b/src/main/java/net/irisshaders/iris/pipeline/transform/ShaderPrinter.java similarity index 77% rename from src/main/java/net/coderbot/iris/pipeline/ShaderPrinter.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/ShaderPrinter.java index da426bdb90..5882e7ef22 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShaderPrinter.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/ShaderPrinter.java @@ -1,7 +1,9 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.pipeline.transform; + +import net.irisshaders.iris.Iris; +import org.apache.commons.io.FilenameUtils; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -9,23 +11,44 @@ import java.util.Map; import java.util.stream.Stream; -import net.coderbot.iris.Iris; -import net.coderbot.iris.pipeline.transform.PatchShaderType; import net.minecraftforge.fml.loading.FMLPaths; /** * Static class that deals with printing the patched_shader folder. */ public class ShaderPrinter { + private static final Path debugOutDir = FMLPaths.GAMEDIR.get().resolve("patched_shaders"); private static boolean outputLocationCleared = false; private static int programCounter = 0; - private static final Path debugOutDir = FMLPaths.GAMEDIR.get().resolve("patched_shaders"); public static void resetPrintState() { outputLocationCleared = false; programCounter = 0; } + public static void deleteIfClearing() { + if (!outputLocationCleared) { + try { + if (Files.exists(debugOutDir)) { + try (Stream stream = Files.list(debugOutDir)) { + stream.forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + } + + Files.createDirectories(debugOutDir); + } catch (IOException e) { + Iris.logger.warn("Failed to initialize debug patched shader source location", e); + } + outputLocationCleared = true; + } + } + public static ProgramPrintBuilder printProgram(String name) { return new ProgramPrintBuilder(name); } @@ -96,7 +119,9 @@ public void print() { if (!outputLocationCleared) { try { if (Files.exists(debugOutDir)) { - try (Stream stream = Files.list(debugOutDir)) { + try (Stream stream = Files.list(debugOutDir).filter(s -> { + return !FilenameUtils.getExtension(s.toString()).contains("properties"); + })) { stream.forEach(path -> { try { Files.delete(path); @@ -116,7 +141,7 @@ public void print() { try { for (int i = 0; i < sources.size(); i += 2) { - Files.write(debugOutDir.resolve(sources.get(i)), sources.get(i + 1).getBytes(StandardCharsets.UTF_8)); + Files.writeString(debugOutDir.resolve(sources.get(i)), sources.get(i + 1)); } } catch (IOException e) { Iris.logger.warn("Failed to write debug patched shader source", e); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/irisshaders/iris/pipeline/transform/TransformPatcher.java similarity index 71% rename from src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/TransformPatcher.java index 6017ca5b20..d86f34e25a 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/TransformPatcher.java @@ -1,16 +1,4 @@ -package net.coderbot.iris.pipeline.transform; - -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.coderbot.iris.gl.shader.ShaderCompileException; -import oculus.org.antlr.v4.runtime.Token; -import oculus.org.antlr.v4.runtime.misc.ParseCancellationException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +package net.irisshaders.iris.pipeline.transform; import io.github.douira.glsl_transformer.ast.node.Profile; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; @@ -27,147 +15,65 @@ import io.github.douira.glsl_transformer.token_filter.TokenFilter; import io.github.douira.glsl_transformer.util.LRUCache; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.ShaderPrinter; -import net.coderbot.iris.pipeline.newshader.ShaderAttributeInputs; -import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; -import net.coderbot.iris.pipeline.transform.parameter.ComputeParameters; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; -import net.coderbot.iris.pipeline.transform.parameter.SodiumParameters; -import net.coderbot.iris.pipeline.transform.parameter.TextureStageParameters; -import net.coderbot.iris.pipeline.transform.parameter.VanillaParameters; -import net.coderbot.iris.pipeline.transform.transformer.AttributeTransformer; -import net.coderbot.iris.pipeline.transform.transformer.CommonTransformer; -import net.coderbot.iris.pipeline.transform.transformer.CompatibilityTransformer; -import net.coderbot.iris.pipeline.transform.transformer.CompositeCoreTransformer; -import net.coderbot.iris.pipeline.transform.transformer.CompositeTransformer; -import net.coderbot.iris.pipeline.transform.transformer.SodiumCoreTransformer; -import net.coderbot.iris.pipeline.transform.transformer.SodiumTransformer; -import net.coderbot.iris.pipeline.transform.transformer.TextureTransformer; -import net.coderbot.iris.pipeline.transform.transformer.VanillaCoreTransformer; -import net.coderbot.iris.pipeline.transform.transformer.VanillaTransformer; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.shader.ShaderCompileException; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.parameter.ComputeParameters; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; +import net.irisshaders.iris.pipeline.transform.parameter.TextureStageParameters; +import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; +import net.irisshaders.iris.pipeline.transform.transformer.CommonTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.CompatibilityTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.CompositeCoreTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.CompositeTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.DHTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.SodiumCoreTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.SodiumTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.TextureTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.VanillaCoreTransformer; +import net.irisshaders.iris.pipeline.transform.transformer.VanillaTransformer; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import oculus.org.antlr.v4.runtime.Token; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 tessControl; - final String tessEval; - final String fragment; - final String compute; - - public CacheKey(Parameters parameters, String vertex, String geometry, String tessControl, String tessEval, String fragment) { - this.parameters = parameters; - this.vertex = vertex; - this.geometry = geometry; - this.tessControl = tessControl; - this.tessEval = tessEval; - this.fragment = fragment; - this.compute = null; - } - - public CacheKey(Parameters parameters, String compute) { - this.parameters = parameters; - this.vertex = null; - this.geometry = null; - this.tessControl = null; - this.tessEval = null; - this.fragment = null; - this.compute = compute; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); - result = prime * result + ((vertex == null) ? 0 : vertex.hashCode()); - result = prime * result + ((geometry == null) ? 0 : geometry.hashCode()); - result = prime * result + ((tessControl == null) ? 0 : tessControl.hashCode()); - result = prime * result + ((tessEval == null) ? 0 : tessEval.hashCode()); - result = prime * result + ((fragment == null) ? 0 : fragment.hashCode()); - result = prime * result + ((compute == null) ? 0 : compute.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; - CacheKey other = (CacheKey) obj; - 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; - if (geometry == null) { - if (other.geometry != null) - return false; - } else if (!geometry.equals(other.geometry)) - return false; - if (tessControl == null) { - if (other.tessControl != null) - return false; - } else if (!tessControl.equals(other.tessControl)) - return false; - if (tessEval == null) { - if (other.tessEval != null) - return false; - } else if (!tessEval.equals(other.tessEval)) - return false; - if (fragment == null) { - if (other.fragment != null) - return false; - } else if (!fragment.equals(other.fragment)) - return false; - if (compute == null) { - if (other.compute != null) - return false; - } else if (!compute.equals(other.compute)) - return false; - return true; - } - } - + private static final List internalPrefixes = List.of("iris_", "irisMain", "moj_import"); + private static final Pattern versionPattern = Pattern.compile("^.*#version\\s+(\\d+)", Pattern.DOTALL); + private static final EnumASTTransformer transformer; + static Logger LOGGER = LogManager.getLogger(TransformPatcher.class); // TODO: Only do the NewLines patches if the source code isn't from // gbuffers_lines (what does this mean?) - static TokenFilter parseTokenFilter = new ChannelFilter(TokenChannel.PREPROCESSOR) { + static TokenFilter parseTokenFilter = new ChannelFilter<>(TokenChannel.PREPROCESSOR) { @Override public boolean isTokenAllowed(Token token) { if (!super.isTokenAllowed(token)) { @@ -178,10 +84,8 @@ public boolean isTokenAllowed(Token token) { } }; - private static final List internalPrefixes = List.of("iris_", "irisMain", "moj_import"); - static { - transformer = new EnumASTTransformer(PatchShaderType.class) { + transformer = new EnumASTTransformer<>(PatchShaderType.class) { { setRootSupplier(RootSupplier.PREFIX_UNORDERED_ED_EXACT); } @@ -195,7 +99,7 @@ public TranslationUnit parseTranslationUnit(Root rootInstance, String input) { throw new IllegalArgumentException( "No #version directive found in source code! See debugging.md for more information."); } - transformer.getLexer().version = Version.fromNumber(Integer.parseInt(matcher.group(1))); + transformer.getLexer().version = Version.fromNumber(Integer.parseInt(matcher.group(1))); return super.parseTranslationUnit(rootInstance, input); } @@ -228,65 +132,61 @@ public TranslationUnit parseTranslationUnit(Root rootInstance, String input) { } Profile profile = versionStatement.profile; Version version = versionStatement.version; - switch (parameters.patch) { - case ATTRIBUTES: - AttributeTransformer.transform(transformer, tree, root, (AttributeParameters) parameters); - break; - case COMPUTE: - // we can assume the version is at least 400 because it's a compute shader + if (Objects.requireNonNull(parameters.patch) == Patch.COMPUTE) {// we can assume the version is at least 400 because it's a compute shader + versionStatement.profile = Profile.CORE; + CommonTransformer.transform(transformer, tree, root, parameters, true); + } else {// handling of Optifine's special core profile mode + boolean isLine = (parameters.patch == Patch.VANILLA && ((VanillaParameters) parameters).isLines()); + + if (profile == Profile.CORE || version.number >= 150 && profile == null || isLine) { + // patch the version number to at least 330 + if (version.number < 330) { + versionStatement.version = Version.GLSL33; + } + + switch (parameters.patch) { + case COMPOSITE: + CompositeCoreTransformer.transform(transformer, tree, root, parameters); + break; + case SODIUM: + SodiumParameters sodiumParameters = (SodiumParameters) parameters; + SodiumCoreTransformer.transform(transformer, tree, root, sodiumParameters); + break; + case VANILLA: + VanillaCoreTransformer.transform(transformer, tree, root, (VanillaParameters) parameters); + break; + default: + throw new UnsupportedOperationException("Unknown patch type: " + parameters.patch); + } + + if (parameters.type == PatchShaderType.FRAGMENT) { + CompatibilityTransformer.transformFragmentCore(transformer, tree, root, parameters); + } + } else { + // patch the version number to at least 330 + if (version.number < 330) { + versionStatement.version = Version.GLSL33; + } versionStatement.profile = Profile.CORE; - CommonTransformer.transform(transformer, tree, root, parameters, true); - break; - default: - // handling of Optifine's special core profile mode - boolean isLine = (parameters.patch == Patch.VANILLA && ((VanillaParameters) parameters).isLines()); - - if (profile == Profile.CORE || version.number >= 150 && profile == null || isLine) { - // patch the version number to at least 330 - if (version.number < 330) { - versionStatement.version = Version.GLSL33; - } - - switch (parameters.patch) { - case COMPOSITE: - CompositeCoreTransformer.transform(transformer, tree, root, parameters); - break; - case SODIUM: - SodiumParameters sodiumParameters = (SodiumParameters) parameters; - SodiumCoreTransformer.transform(transformer, tree, root, sodiumParameters); - break; - case VANILLA: - VanillaCoreTransformer.transform(transformer, tree, root, (VanillaParameters) parameters); - break; - default: - throw new UnsupportedOperationException("Unknown patch type: " + parameters.patch); - } - - if (parameters.type == PatchShaderType.FRAGMENT) { - CompatibilityTransformer.transformFragmentCore(transformer, tree, root, parameters); - } - } else { - // patch the version number to at least 330 - if (version.number < 330) { - versionStatement.version = Version.GLSL33; - } - versionStatement.profile = Profile.CORE; - - switch (parameters.patch) { - case COMPOSITE: - CompositeTransformer.transform(transformer, tree, root, parameters); - break; - case SODIUM: - SodiumParameters sodiumParameters = (SodiumParameters) parameters; - SodiumTransformer.transform(transformer, tree, root, sodiumParameters); - break; - case VANILLA: - VanillaTransformer.transform(transformer, tree, root, (VanillaParameters) parameters); - break; - default: - throw new UnsupportedOperationException("Unknown patch type: " + parameters.patch); - } + + switch (parameters.patch) { + case COMPOSITE: + CompositeTransformer.transform(transformer, tree, root, parameters); + break; + case SODIUM: + SodiumParameters sodiumParameters = (SodiumParameters) parameters; + SodiumTransformer.transform(transformer, tree, root, sodiumParameters); + break; + case VANILLA: + VanillaTransformer.transform(transformer, tree, root, (VanillaParameters) parameters); + break; + case DH: + DHTransformer.transform(transformer, tree, root, parameters); + break; + default: + throw new UnsupportedOperationException("Unknown patch type: " + parameters.patch); } + } } TextureTransformer.transform(transformer, tree, root, parameters.getTextureStage(), parameters.getTextureMap()); @@ -300,8 +200,6 @@ public TranslationUnit parseTranslationUnit(Root rootInstance, String input) { transformer.setTokenFilter(parseTokenFilter); } - private static final Pattern versionPattern = Pattern.compile("^.*#version\\s+(\\d+)", Pattern.DOTALL); - private static Map transformInternal( String name, Map inputs, @@ -316,7 +214,7 @@ private static Map transformInternal( } private static Map transform(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, - Parameters parameters) { + Parameters parameters) { // stop if all are null if (vertex == null && geometry == null && tessControl == null && tessEval == null && fragment == null) { return null; @@ -390,9 +288,22 @@ public static Map patchVanilla( new VanillaParameters(Patch.VANILLA, textureMap, alpha, isLines, hasChunkOffset, inputs, geometry != null, tessControl != null || tessEval != null)); } - public static Map patchSodium(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, - AlphaTest alpha, ShaderAttributeInputs inputs, + + public static Map patchDH( + String name, String vertex, String tessControl, String tessEval, String geometry, String fragment, Object2ObjectMap, String> textureMap) { + return transform(name, vertex, geometry, tessControl, tessEval, fragment, + new Parameters(Patch.DH, textureMap) { + @Override + public TextureStage getTextureStage() { + return TextureStage.GBUFFERS_AND_SHADOW; + } + }); + } + + public static Map patchSodium(String name, String vertex, String geometry, String tessControl, String tessEval, String fragment, + AlphaTest alpha, ShaderAttributeInputs inputs, + Object2ObjectMap, String> textureMap) { return transform(name, vertex, geometry, tessControl, tessEval, fragment, new SodiumParameters(Patch.SODIUM, textureMap, alpha, inputs)); } @@ -411,4 +322,92 @@ public static String patchCompute( return transformCompute(name, compute, new ComputeParameters(Patch.COMPUTE, stage, textureMap)) .getOrDefault(PatchShaderType.COMPUTE, null); } + + private static class CacheKey { + final Parameters parameters; + final String vertex; + final String geometry; + final String tessControl; + final String tessEval; + final String fragment; + final String compute; + + public CacheKey(Parameters parameters, String vertex, String geometry, String tessControl, String tessEval, String fragment) { + this.parameters = parameters; + this.vertex = vertex; + this.geometry = geometry; + this.tessControl = tessControl; + this.tessEval = tessEval; + this.fragment = fragment; + this.compute = null; + } + + public CacheKey(Parameters parameters, String compute) { + this.parameters = parameters; + this.vertex = null; + this.geometry = null; + this.tessControl = null; + this.tessEval = null; + this.fragment = null; + this.compute = compute; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((parameters == null) ? 0 : parameters.hashCode()); + result = prime * result + ((vertex == null) ? 0 : vertex.hashCode()); + result = prime * result + ((geometry == null) ? 0 : geometry.hashCode()); + result = prime * result + ((tessControl == null) ? 0 : tessControl.hashCode()); + result = prime * result + ((tessEval == null) ? 0 : tessEval.hashCode()); + result = prime * result + ((fragment == null) ? 0 : fragment.hashCode()); + result = prime * result + ((compute == null) ? 0 : compute.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; + CacheKey other = (CacheKey) obj; + 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; + if (geometry == null) { + if (other.geometry != null) + return false; + } else if (!geometry.equals(other.geometry)) + return false; + if (tessControl == null) { + if (other.tessControl != null) + return false; + } else if (!tessControl.equals(other.tessControl)) + return false; + if (tessEval == null) { + if (other.tessEval != null) + return false; + } else if (!tessEval.equals(other.tessEval)) + return false; + if (fragment == null) { + if (other.fragment != null) + return false; + } else if (!fragment.equals(other.fragment)) + return false; + if (compute == null) { + return other.compute == null; + } else return compute.equals(other.compute); + } + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/ComputeParameters.java similarity index 54% rename from src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/parameter/ComputeParameters.java index 327438d45d..a8c3d0bcab 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/ComputeParameters.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/ComputeParameters.java @@ -1,17 +1,17 @@ -package net.coderbot.iris.pipeline.transform.parameter; +package net.irisshaders.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.shaderpack.texture.TextureStage; public class ComputeParameters extends TextureStageParameters { // WARNING: adding new fields requires updating hashCode and equals methods! public ComputeParameters(Patch patch, TextureStage stage, - Object2ObjectMap, String> textureMap) { + Object2ObjectMap, String> textureMap) { super(patch, stage, textureMap); } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/GeometryInfoParameters.java b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/GeometryInfoParameters.java similarity index 65% rename from src/main/java/net/coderbot/iris/pipeline/transform/parameter/GeometryInfoParameters.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/parameter/GeometryInfoParameters.java index dcfec4f283..68306d36cd 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/GeometryInfoParameters.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/GeometryInfoParameters.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.pipeline.transform.parameter; +package net.irisshaders.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.shaderpack.texture.TextureStage; public abstract class GeometryInfoParameters extends Parameters { public final boolean hasGeometry; @@ -12,7 +12,7 @@ public abstract class GeometryInfoParameters extends Parameters { // WARNING: adding new fields requires updating hashCode and equals methods! public GeometryInfoParameters(Patch patch, - Object2ObjectMap, String> textureMap, boolean hasGeometry, boolean hasTesselation) { + Object2ObjectMap, String> textureMap, boolean hasGeometry, boolean hasTesselation) { super(patch, textureMap); this.hasGeometry = hasGeometry; this.hasTesselation = hasTesselation; @@ -35,8 +35,6 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; GeometryInfoParameters other = (GeometryInfoParameters) obj; - if (hasGeometry != other.hasGeometry) - return false; - return true; + return hasGeometry == other.hasGeometry; } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/Parameters.java similarity index 74% rename from src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/parameter/Parameters.java index dc63746f87..16e1117506 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/Parameters.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/Parameters.java @@ -1,18 +1,18 @@ -package net.coderbot.iris.pipeline.transform.parameter; +package net.irisshaders.iris.pipeline.transform.parameter; import io.github.douira.glsl_transformer.ast.transform.JobParameters; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.shaderpack.texture.TextureStage; public abstract class Parameters implements JobParameters { public final Patch patch; - public PatchShaderType type; // may only be set by TransformPatcher private final Object2ObjectMap, String> textureMap; + public PatchShaderType type; // may only be set by TransformPatcher // WARNING: adding new fields requires updating hashCode and equals methods! public Parameters(Patch patch, Object2ObjectMap, String> textureMap) { @@ -21,7 +21,7 @@ public Parameters(Patch patch, Object2ObjectMap, String> textureMap, - AlphaTest alpha, - ShaderAttributeInputs inputs) { + Object2ObjectMap, String> textureMap, + AlphaTest alpha, + ShaderAttributeInputs inputs) { super(patch, textureMap); this.inputs = inputs; this.alpha = alpha; } + @Override public AlphaTest getAlphaTest() { return alpha; @@ -59,10 +60,7 @@ public boolean equals(Object obj) { } else if (!inputs.equals(other.inputs)) return false; if (alpha == null) { - if (other.alpha != null) - return false; - } else if (!alpha.equals(other.alpha)) - return false; - return true; + return other.alpha == null; + } else return alpha.equals(other.alpha); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/TextureStageParameters.java similarity index 67% rename from src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/parameter/TextureStageParameters.java index b2516ddb76..433b7f8bff 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/TextureStageParameters.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/TextureStageParameters.java @@ -1,18 +1,18 @@ -package net.coderbot.iris.pipeline.transform.parameter; +package net.irisshaders.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.shaderpack.texture.TextureStage; public class TextureStageParameters extends Parameters { private final TextureStage stage; // WARNING: adding new fields requires updating hashCode and equals methods! public TextureStageParameters(Patch patch, TextureStage stage, - Object2ObjectMap, String> textureMap) { + Object2ObjectMap, String> textureMap) { super(patch, textureMap); this.stage = stage; } @@ -39,9 +39,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; TextureStageParameters other = (TextureStageParameters) obj; - if (stage != other.stage) - return false; - return true; + return stage == other.stage; } @Override diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/VanillaParameters.java b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/VanillaParameters.java similarity index 71% rename from src/main/java/net/coderbot/iris/pipeline/transform/parameter/VanillaParameters.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/parameter/VanillaParameters.java index 08f6309aad..6dccd62f76 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/parameter/VanillaParameters.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/parameter/VanillaParameters.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.pipeline.transform.parameter; +package net.irisshaders.iris.pipeline.transform.parameter; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.pipeline.newshader.ShaderAttributeInputs; -import net.coderbot.iris.pipeline.transform.Patch; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.state.ShaderAttributeInputs; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.pipeline.transform.Patch; +import net.irisshaders.iris.shaderpack.texture.TextureStage; public class VanillaParameters extends GeometryInfoParameters { public final AlphaTest alpha; @@ -16,10 +16,10 @@ public class VanillaParameters extends GeometryInfoParameters { // WARNING: adding new fields requires updating hashCode and equals methods! public VanillaParameters( - Patch patch, - Object2ObjectMap, String> textureMap, - AlphaTest alpha, boolean isLines, boolean hasChunkOffset, - ShaderAttributeInputs inputs, boolean hasGeometry, boolean hasTesselation) { + Patch patch, + Object2ObjectMap, String> textureMap, + AlphaTest alpha, boolean isLines, boolean hasChunkOffset, + ShaderAttributeInputs inputs, boolean hasGeometry, boolean hasTesselation) { super(patch, textureMap, hasGeometry, hasTesselation); this.alpha = alpha; this.isLines = isLines; @@ -73,8 +73,6 @@ public boolean equals(Object obj) { return false; if (hasChunkOffset != other.hasChunkOffset) return false; - if (isLines != other.isLines) - return false; - return true; + return isLines == other.isLines; } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CommonTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CommonTransformer.java similarity index 75% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/CommonTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CommonTransformer.java index a90eeec580..e9e294f358 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CommonTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CommonTransformer.java @@ -1,10 +1,4 @@ -package net.coderbot.iris.pipeline.transform.transformer; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Stream; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.Identifier; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; @@ -31,90 +25,127 @@ import io.github.douira.glsl_transformer.ast.transform.Template; import io.github.douira.glsl_transformer.parser.ParseShape; import io.github.douira.glsl_transformer.util.Type; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Stream; public class CommonTransformer { public static final AutoHintedMatcher glTextureMatrix0 = new AutoHintedMatcher<>( - "gl_TextureMatrix[0]", ParseShape.EXPRESSION); + "gl_TextureMatrix[0]", ParseShape.EXPRESSION); public static final AutoHintedMatcher glTextureMatrix1 = new AutoHintedMatcher<>( - "gl_TextureMatrix[1]", ParseShape.EXPRESSION); + "gl_TextureMatrix[1]", ParseShape.EXPRESSION); public static final AutoHintedMatcher glTextureMatrix2 = new AutoHintedMatcher<>( - "gl_TextureMatrix[2]", ParseShape.EXPRESSION); + "gl_TextureMatrix[2]", ParseShape.EXPRESSION); public static final Matcher sampler = new Matcher<>( - "uniform Type name;", ParseShape.EXTERNAL_DECLARATION) { + "uniform Type name;", ParseShape.EXTERNAL_DECLARATION) { { markClassedPredicateWildcard("type", - pattern.getRoot().identifierIndex.getUnique("Type").getAncestor(TypeSpecifier.class), - BuiltinFixedTypeSpecifier.class, - specifier -> specifier.type.kind == TypeKind.SAMPLER); + pattern.getRoot().identifierIndex.getUnique("Type").getAncestor(TypeSpecifier.class), + BuiltinFixedTypeSpecifier.class, + specifier -> specifier.type.kind == TypeKind.SAMPLER); markClassWildcard("name*", - pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); + pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); } }; private static final AutoHintedMatcher glFragDataI = new AutoHintedMatcher<>( - "gl_FragData[index]", ParseShape.EXPRESSION) { + "gl_FragData[index]", ParseShape.EXPRESSION) { { markClassedPredicateWildcard("index", - pattern.getRoot().identifierIndex.getUnique("index").getAncestor(ReferenceExpression.class), - LiteralExpression.class, - literalExpression -> literalExpression.isInteger() && literalExpression.getInteger() >= 0); + pattern.getRoot().identifierIndex.getUnique("index").getAncestor(ReferenceExpression.class), + LiteralExpression.class, + literalExpression -> literalExpression.isInteger() && literalExpression.getInteger() >= 0); } }; private static final Template fragDataDeclaration = Template - .withExternalDeclaration("layout (location = __index) out vec4 __name;"); + .withExternalDeclaration("layout (location = __index) out vec4 __name;"); + private static final List replaceExpressions = new ArrayList<>(); + private static final List replaceIndexes = new ArrayList<>(); + private static final Template inputDeclarationTemplate = Template.withExternalDeclaration( + "uniform int __name;"); + static { fragDataDeclaration.markLocalReplacement("__index", ReferenceExpression.class); fragDataDeclaration.markIdentifierReplacement("__name"); } - private static final List replaceExpressions = new ArrayList<>(); - private static final List replaceIndexes = new ArrayList<>(); + static { + inputDeclarationTemplate.markLocalReplacement( + inputDeclarationTemplate.getSourceRoot().nodeIndex.getOne(StorageQualifier.class)); + inputDeclarationTemplate.markLocalReplacement( + inputDeclarationTemplate.getSourceRoot().nodeIndex.getOne(BuiltinNumericTypeSpecifier.class)); + inputDeclarationTemplate.markIdentifierReplacement("__name"); + } static void renameFunctionCall(Root root, String oldName, String newName) { root.process(root.identifierIndex.getStream(oldName) .filter(id -> id.getParent() instanceof FunctionCallExpression), - id -> id.setName(newName)); + id -> id.setName(newName)); } static void renameAndWrapShadow(ASTParser t, Root root, String oldName, String innerName) { root.process(root.identifierIndex.getStream(oldName) .filter(id -> id.getParent() instanceof FunctionCallExpression), - id -> { - FunctionCallExpression functionCall = (FunctionCallExpression) id.getParent(); - functionCall.getFunctionName().setName(innerName); - FunctionCallExpression wrapper = (FunctionCallExpression) t.parseExpression(root, "vec4()"); - functionCall.replaceBy(wrapper); - wrapper.getParameters().add(functionCall); - }); + id -> { + FunctionCallExpression functionCall = (FunctionCallExpression) id.getParent(); + functionCall.getFunctionName().setName(innerName); + FunctionCallExpression wrapper = (FunctionCallExpression) t.parseExpression(root, "vec4()"); + functionCall.replaceBy(wrapper); + wrapper.getParameters().add(functionCall); + }); + } + + public static void patchMultiTexCoord3( + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters) { + if (parameters.type.glShaderType == ShaderType.VERTEX + && root.identifierIndex.has("gl_MultiTexCoord3") + && !root.identifierIndex.has("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 + // an existing declaration robustly. But basically the proper way to do this is + // 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_DECLARATIONS, + "attribute vec4 mc_midTexCoord;"); + } } public static void upgradeStorageQualifiers( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters) { for (StorageQualifier qualifier : root.nodeIndex.get(StorageQualifier.class)) { if (qualifier.storageType == StorageType.ATTRIBUTE) { qualifier.storageType = StorageType.IN; } else if (qualifier.storageType == StorageType.VARYING) { qualifier.storageType = parameters.type.glShaderType == ShaderType.VERTEX - ? StorageType.OUT - : StorageType.IN; + ? StorageType.OUT + : StorageType.IN; } } } public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters, - boolean core) { + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters, + boolean core) { // TODO: What if the shader does gl_PerVertex.gl_FogFragCoord ? root.rename("gl_FogFragCoord", "iris_FogFragCoord"); @@ -122,11 +153,11 @@ public static void transform( // TODO: This doesn't handle geometry shaders... How do we do that? if (parameters.type.glShaderType == ShaderType.VERTEX) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "out float iris_FogFragCoord;"); + "out float iris_FogFragCoord;"); tree.prependMainFunctionBody(t, "iris_FogFragCoord = 0.0f;"); } else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in float iris_FogFragCoord;"); + "in float iris_FogFragCoord;"); } if (parameters.type.glShaderType == ShaderType.VERTEX) { @@ -135,7 +166,7 @@ public static void transform( // even though they write to it. tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "vec4 iris_FrontColor;"); + "vec4 iris_FrontColor;"); root.rename("gl_FrontColor", "iris_FrontColor"); } @@ -144,7 +175,7 @@ public static void transform( // which implements this if (root.identifierIndex.has("gl_FragColor")) { Iris.logger.warn( - "[Patcher] gl_FragColor is not supported yet, please use gl_FragData! Assuming that the shaderpack author intended to use gl_FragData[0]..."); + "[Patcher] gl_FragColor is not supported yet, please use gl_FragData! Assuming that the shaderpack author intended to use gl_FragData[0]..."); root.replaceReferenceExpressions(t, "gl_FragColor", "gl_FragData[0]"); } @@ -174,13 +205,13 @@ public static void transform( } for (int i = 0; i < replaceExpressions.size(); i++) { replaceExpressions.get(i).replaceByAndDelete( - new ReferenceExpression(new Identifier("iris_FragData" + replaceIndexes.get(i)))); + new ReferenceExpression(new Identifier("iris_FragData" + replaceIndexes.get(i)))); } for (long index : replaceIndexesSet) { tree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, - fragDataDeclaration.getInstanceFor(root, - new LiteralExpression(Type.INT32, index), - new Identifier("iris_FragData" + index))); + fragDataDeclaration.getInstanceFor(root, + new LiteralExpression(Type.INT32, index), + new Identifier("iris_FragData" + index))); } replaceExpressions.clear(); replaceIndexes.clear(); @@ -189,7 +220,7 @@ public static void transform( if ((parameters.getAlphaTest() != AlphaTest.ALWAYS && !core) && replaceIndexesSet.contains(0L)) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "uniform float iris_currentAlphaTest;"); tree.appendMainFunctionBody(t, - parameters.getAlphaTest().toExpression("iris_FragData0.a", "iris_currentAlphaTest", " ")); + parameters.getAlphaTest().toExpression("iris_FragData0.a", "iris_currentAlphaTest", " ")); } } @@ -227,25 +258,25 @@ public static void transform( samplerDeclarationMember.getName().setName("gtexture"); } root.process(targets.filter(id -> !(id.getParent() instanceof FunctionCallExpression)), - id -> id.setName("gtexture")); + id -> id.setName("gtexture")); // This must be defined and valid in all shader passes, including composite // passes. A shader that relies on this behavior is SEUS v11 - it reads // gl_Fog.color and breaks if it is not properly defined. root.rename("gl_Fog", "iris_Fog"); tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform float iris_FogDensity;", - "uniform float iris_FogStart;", - "uniform float iris_FogEnd;", - "uniform vec4 iris_FogColor;", - "struct iris_FogParameters {" + - "vec4 color;" + - "float density;" + - "float start;" + - "float end;" + - "float scale;" + - "};", - "iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, iris_FogStart, iris_FogEnd, 1.0 / (iris_FogEnd - iris_FogStart));"); + "uniform float iris_FogDensity;", + "uniform float iris_FogStart;", + "uniform float iris_FogEnd;", + "uniform vec4 iris_FogColor;", + "struct iris_FogParameters {" + + "vec4 color;" + + "float density;" + + "float start;" + + "float end;" + + "float scale;" + + "};", + "iris_FogParameters iris_Fog = iris_FogParameters(iris_FogColor, iris_FogDensity, iris_FogStart, iris_FogEnd, 1.0 / (iris_FogEnd - iris_FogStart));"); // TODO: Add similar functions for all legacy texture sampling functions renameFunctionCall(root, "texture2D", "texture"); @@ -263,19 +294,6 @@ public static void transform( renameAndWrapShadow(t, root, "shadow2DLod", "textureLod"); } - private static class RenameTargetResult { - public final DeclarationExternalDeclaration samplerDeclaration; - public final DeclarationMember samplerDeclarationMember; - public final Stream targets; - - public RenameTargetResult(DeclarationExternalDeclaration samplerDeclaration, - DeclarationMember samplerDeclarationMember, Stream targets) { - this.samplerDeclaration = samplerDeclaration; - this.samplerDeclarationMember = samplerDeclarationMember; - this.targets = targets; - } - } - private static RenameTargetResult getGtextureRenameTargets(String name, Root root) { List gtextureTargets = new ArrayList<>(); DeclarationExternalDeclaration samplerDeclaration = null; @@ -288,7 +306,7 @@ private static RenameTargetResult getGtextureRenameTargets(String name, Root roo continue; } DeclarationExternalDeclaration externalDeclaration = (DeclarationExternalDeclaration) id.getAncestor( - 3, 0, DeclarationExternalDeclaration.class::isInstance); + 3, 0, DeclarationExternalDeclaration.class::isInstance); if (externalDeclaration == null) { continue; } @@ -296,8 +314,8 @@ private static RenameTargetResult getGtextureRenameTargets(String name, Root roo // check that any of the members match the name boolean foundNameMatch = false; for (DeclarationMember member : sampler - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class).getMembers()) { + .getNodeMatch("name*", DeclarationMember.class) + .getAncestor(TypeAndInitDeclaration.class).getMembers()) { if (member.getName().getName().equals(name)) { foundNameMatch = true; } @@ -349,32 +367,21 @@ public static void applyIntelHd4000Workaround(Root root) { } public static void replaceGlMultiTexCoordBounded( - ASTParser t, - Root root, - int minimum, - int maximum) { + ASTParser t, + Root root, + int minimum, + int maximum) { root.replaceReferenceExpressions(t, - root.getPrefixIdentifierIndex().prefixQueryFlat("gl_MultiTexCoord") - .filter(id -> { - int index = Integer.parseInt(id.getName().substring("gl_MultiTexCoord".length())); - return index >= minimum && index <= maximum; - }), - "vec4(0.0, 0.0, 0.0, 1.0)"); - } - - private static final Template inputDeclarationTemplate = Template.withExternalDeclaration( - "uniform int __name;"); - - static { - inputDeclarationTemplate.markLocalReplacement( - inputDeclarationTemplate.getSourceRoot().nodeIndex.getOne(StorageQualifier.class)); - inputDeclarationTemplate.markLocalReplacement( - inputDeclarationTemplate.getSourceRoot().nodeIndex.getOne(BuiltinNumericTypeSpecifier.class)); - inputDeclarationTemplate.markIdentifierReplacement("__name"); + root.getPrefixIdentifierIndex().prefixQueryFlat("gl_MultiTexCoord") + .filter(id -> { + int index = Integer.parseInt(id.getName().substring("gl_MultiTexCoord".length())); + return index >= minimum && index <= maximum; + }), + "vec4(0.0, 0.0, 0.0, 1.0)"); } public static void addIfNotExists(Root root, ASTParser t, TranslationUnit tree, String name, Type type, - StorageType storageType) { + StorageType storageType) { if (root.externalDeclarationIndex.getStream(name) .noneMatch((entry) -> entry.declaration() instanceof DeclarationExternalDeclaration)) { tree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, inputDeclarationTemplate.getInstanceFor(root, @@ -383,4 +390,8 @@ public static void addIfNotExists(Root root, ASTParser t, TranslationUnit tree, new Identifier(name))); } } + + private record RenameTargetResult(DeclarationExternalDeclaration samplerDeclaration, + DeclarationMember samplerDeclarationMember, Stream targets) { + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompatibilityTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompatibilityTransformer.java similarity index 73% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompatibilityTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompatibilityTransformer.java index 334e7f7842..86d8f4a23e 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompatibilityTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompatibilityTransformer.java @@ -1,20 +1,4 @@ -package net.coderbot.iris.pipeline.transform.transformer; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Comparator; -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.Collectors; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.Identifier; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; @@ -52,24 +36,116 @@ import io.github.douira.glsl_transformer.ast.transform.TransformationException; import io.github.douira.glsl_transformer.parser.ParseShape; 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.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.ArrayDeque; +import java.util.ArrayList; +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.Collectors; +import java.util.stream.Stream; public class CompatibilityTransformer { - static Logger LOGGER = LogManager.getLogger(CompatibilityTransformer.class); + private static final Logger LOGGER = LogManager.getLogger(CompatibilityTransformer.class); private static final AutoHintedMatcher sildursWaterFract = new AutoHintedMatcher<>( - "fract(worldpos.y + 0.001)", ParseShape.EXPRESSION); + "fract(worldpos.y + 0.001)", ParseShape.EXPRESSION); + private static final ShaderType[] pipeline = {ShaderType.VERTEX, ShaderType.TESSELATION_CONTROL, ShaderType.TESSELATION_EVAL, ShaderType.GEOMETRY, ShaderType.FRAGMENT}; + private static final Matcher outDeclarationMatcher = new DeclarationMatcher( + StorageType.OUT); + private static final Matcher 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));"); + private static final Matcher nonLayoutOutDeclarationMatcher = new Matcher<>( + "out float name;", + ParseShape.EXTERNAL_DECLARATION) { + { + markClassWildcard("qualifier", pattern.getRoot().nodeIndex.getUnique(TypeQualifier.class)); + markClassWildcard("type", pattern.getRoot().nodeIndex.getUnique(BuiltinNumericTypeSpecifier.class)); + markClassWildcard("name*", + pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); + } + + @Override + public boolean matchesExtract(ExternalDeclaration tree) { + boolean result = super.matchesExtract(tree); + if (!result) { + return false; + } + + // look for an out qualifier but no layout qualifier + TypeQualifier qualifier = getNodeMatch("qualifier", TypeQualifier.class); + var hasOutQualifier = false; + for (TypeQualifierPart part : qualifier.getParts()) { + if (part instanceof StorageQualifier storageQualifier) { + if (storageQualifier.storageType == StorageType.OUT) { + hasOutQualifier = true; + } + } else if (part instanceof LayoutQualifier) { + return false; + } + } + return hasOutQualifier; + } + }; + private static final Template layoutedOutDeclarationTemplate = Template + .withExternalDeclaration("out __type __name;"); + private static final String attachTargetPrefix = "outColor"; + private static final List reservedWords = List.of("texture"); + + static { + declarationTemplate + .markLocalReplacement(declarationTemplate.getSourceRoot().nodeIndex.getUnique(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()); + } + + static { + layoutedOutDeclarationTemplate.markLocalReplacement( + layoutedOutDeclarationTemplate.getSourceRoot().nodeIndex.getOne(TypeQualifier.class)); + layoutedOutDeclarationTemplate.markLocalReplacement("__type", TypeSpecifier.class); + layoutedOutDeclarationTemplate.markLocalReplacement("__name", DeclarationMember.class); + } 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 (constQualifier instanceof StorageQualifier storageQualifier) { if (storageQualifier.storageType == StorageQualifier.StorageType.CONST) { return storageQualifier; } @@ -78,24 +154,22 @@ private static StorageQualifier getConstQualifier(TypeQualifier qualifier) { return null; } - private static List reservedWords = List.of("texture"); - 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"); + "waving water disconnecting from other water blocks; See https://github.com/IrisShaders/Iris/issues/509"); } } - /** - * 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 + /* + 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<>(); @@ -112,15 +186,15 @@ public static void transformEach(ASTParser t, TranslationUnit tree, Root root, P // TODO: integrate into debug mode (allow user to disable this behavior for // debugging purposes) unusedFunctions.add(definition); - /* - * 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." - * ); - * } - */ + /* + * 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; } @@ -212,16 +286,16 @@ public static void transformEach(ASTParser t, TranslationUnit tree, Root root, P if (constDeclarationHit) { LOGGER.warn( - "Removed the const keyword from declarations that use const parameters. See debugging.md for more information."); + "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); + root.nodeIndex.getStream(EmptyDeclaration.class), + ASTNode::detachAndDelete); if (emptyDeclarationHit) { LOGGER.warn( - "Removed empty external declarations (\";\")."); + "Removed empty external declarations (\";\")."); } // rename reserved words within files @@ -229,8 +303,8 @@ public static void transformEach(ASTParser t, TranslationUnit tree, Root root, P String newName = "iris_renamed_" + reservedWord; if (root.process(root.identifierIndex.getStream(reservedWord).filter( id -> !(id.getParent() instanceof FunctionCallExpression) - && !(id.getParent() instanceof FunctionPrototype)), - id -> id.setName(newName))) { + && !(id.getParent() instanceof FunctionPrototype)), + id -> id.setName(newName))) { LOGGER.warn("Renamed reserved word \"" + reservedWord + "\" to \"" + newName + "\"."); } } @@ -267,99 +341,26 @@ public static void transformEach(ASTParser t, TranslationUnit tree, Root root, P } LOGGER.warn( - "Moved unsized array specifier (of the form []) from the type to each of the the declaration member(s) " - + structMember.getDeclarators().stream().map(StructDeclarator::getName).map(Identifier::getName) - .collect(Collectors.joining(", ")) - + ". See debugging.md for more information."); + "Moved unsized array specifier (of the form []) from the type to each of the the declaration member(s) " + + structMember.getDeclarators().stream().map(StructDeclarator::getName).map(Identifier::getName) + .collect(Collectors.joining(", ")) + + ". See debugging.md for more information."); } } - private static class DeclarationMatcher extends Matcher { - private final StorageType storageType; - - public DeclarationMatcher(StorageType storageType) { - super("out float name;", ParseShape.EXTERNAL_DECLARATION); - this.storageType = storageType; - } - - { - markClassWildcard("qualifier", pattern.getRoot().nodeIndex.getUnique(TypeQualifier.class)); - markClassWildcard("type", pattern.getRoot().nodeIndex.getUnique(BuiltinNumericTypeSpecifier.class)); - markClassWildcard("name*", - pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); - } - - @Override - public boolean matchesExtract(ExternalDeclaration tree) { - 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; - if (storageQualifier.storageType == storageType) { - return true; - } - } - } - return false; - } - } - - private static final ShaderType[] pipeline = { ShaderType.VERTEX, ShaderType.TESSELATION_CONTROL, ShaderType.TESSELATION_EVAL, ShaderType.GEOMETRY, ShaderType.FRAGMENT }; - private static final Matcher outDeclarationMatcher = new DeclarationMatcher( - StorageType.OUT); - private static final Matcher 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.getUnique(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(() -> new FunctionCallExpression( - new Identifier(type.getMostCompactName()), - Stream.of(LiteralExpression.getDefaultValue(type))))); + new Identifier(name), + type.isScalar() + ? LiteralExpression.getDefaultValue(type) + : root.indexNodes(() -> 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 (qualifierPart instanceof StorageQualifier storageQualifier) { if (((StorageQualifier) qualifierPart).storageType == StorageType.IN) { storageQualifier.storageType = StorageType.OUT; } @@ -370,27 +371,26 @@ private static TypeQualifier makeQualifierOut(TypeQualifier typeQualifier) { // does transformations that require cross-shader type data public static void transformGrouped( - ASTParser t, - 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 - * these attributes are added and initialized. - * - * It doesn't bother with array specifiers because they are only legal in - * geometry shaders, but then also only as an in declaration. The out - * declaration in the vertex shader is still just a single value. Missing out - * declarations in the geometry shader are also just normal. - * - * TODO: - * - fix issues where Iris' own declarations are detected and patched like - * iris_FogFragCoord if there are geometry shaders present - * - improved geometry shader support? They use funky declarations + ASTParser t, + 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 + these attributes are added and initialized. + + It doesn't bother with array specifiers because they are only legal in + geometry shaders, but then also only as an in declaration. The out + declaration in the vertex shader is still just a single value. Missing out + declarations in the geometry shader are also just normal. + + TODO: + - fix issues where Iris' own declarations are detected and patched like + 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]; + for (ShaderType type : pipeline) { PatchShaderType[] patchTypes = PatchShaderType.fromGlShaderType(type); // check if the patch types have sources and continue if not @@ -426,11 +426,11 @@ public static void transformGrouped( for (DeclarationExternalDeclaration declaration : prevRoot.nodeIndex.get(DeclarationExternalDeclaration.class)) { if (outDeclarationMatcher.matchesExtract(declaration)) { BuiltinNumericTypeSpecifier extractedType = outDeclarationMatcher.getNodeMatch("type", - BuiltinNumericTypeSpecifier.class); + BuiltinNumericTypeSpecifier.class); for (DeclarationMember member : outDeclarationMatcher - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class) - .getMembers()) { + .getNodeMatch("name*", DeclarationMember.class) + .getAncestor(TypeAndInitDeclaration.class) + .getMembers()) { String name = member.getName().getName(); if (!name.startsWith("gl_")) { outDeclarations.put(name, extractedType); @@ -453,11 +453,11 @@ public static void transformGrouped( } BuiltinNumericTypeSpecifier inTypeSpecifier = inDeclarationMatcher.getNodeMatch("type", - BuiltinNumericTypeSpecifier.class); + BuiltinNumericTypeSpecifier.class); for (DeclarationMember inDeclarationMember : inDeclarationMatcher - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class) - .getMembers()) { + .getNodeMatch("name*", DeclarationMember.class) + .getAncestor(TypeAndInitDeclaration.class) + .getMembers()) { String name = inDeclarationMember.getName().getName(); if (name.startsWith("gl_")) { continue; @@ -472,10 +472,10 @@ public static void transformGrouped( 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."); + "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; @@ -483,12 +483,12 @@ public static void transformGrouped( // 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); + .getNodeMatch("qualifier").cloneInto(prevRoot); makeQualifierOut(outQualifier); prevTree.injectNode(ASTInjectionPoint.BEFORE_DECLARATIONS, declarationTemplate.getInstanceFor(prevRoot, - outQualifier, - inTypeSpecifier.cloneInto(prevRoot), - new Identifier(name))); + outQualifier, + inTypeSpecifier.cloneInto(prevRoot), + new Identifier(name))); // add the initializer to the main function prevTree.prependMainFunctionBody(getInitializer(prevRoot, name, inType)); @@ -497,10 +497,10 @@ public static void transformGrouped( 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."); + "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 @@ -523,10 +523,10 @@ public static void transformGrouped( // declaration is not if (outTypeSpecifier.getArraySpecifier() != null) { LOGGER.warn( - "The out declaration '" + name + "' in the " + prevPatchTypes.glShaderType.name() - + " shader that has a missing corresponding in declaration in the next stage " - + type.name() - + " has an array type and could not be compatibility-patched. See debugging.md for more information."); + "The out declaration '" + name + "' in the " + prevPatchTypes.glShaderType.name() + + " shader that has a missing corresponding in declaration in the next stage " + + type.name() + + " has an array type and could not be compatibility-patched. See debugging.md for more information."); continue; } @@ -543,20 +543,20 @@ public static void transformGrouped( outDeclarations.put(name, null); LOGGER.warn( - "The in declaration '" + name + "' in the " + currentType.glShaderType.name() - + " shader that is never assigned to in the previous stage " - + prevType.name() - + " has been compatibility-patched by adding an initialization for it. See debugging.md for more information."); + "The in declaration '" + name + "' in the " + currentType.glShaderType.name() + + " shader that is never assigned to in the previous stage " + + prevType.name() + + " has been compatibility-patched by adding an initialization for it. See debugging.md for more information."); 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."); + "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; } @@ -590,27 +590,27 @@ public static void transformGrouped( outMember.detach(); outTypeSpecifier = outTypeSpecifier.cloneInto(prevRoot); DeclarationExternalDeclaration singleOutDeclaration = (DeclarationExternalDeclaration) declarationTemplate - .getInstanceFor(prevRoot, - makeQualifierOut(outDeclaration.getType().getTypeQualifier().cloneInto(prevRoot)), - outTypeSpecifier, - new Identifier(name)); + .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))); + 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.appendMainFunctionBody( - (isVector && outType.getDimensions()[0] < inType.getDimensions()[0] ? statementTemplateVector - : statementTemplate).getInstanceFor(prevRoot, - new Identifier(name), - new Identifier(newName), - inTypeSpecifier.cloneInto(prevRoot))); + (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)); @@ -619,11 +619,11 @@ public static void transformGrouped( 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."); + "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."); } } } @@ -633,62 +633,13 @@ public static void transformGrouped( } } - private static final Matcher nonLayoutOutDeclarationMatcher = new Matcher( - "out float name;", - ParseShape.EXTERNAL_DECLARATION) { - { - markClassWildcard("qualifier", pattern.getRoot().nodeIndex.getUnique(TypeQualifier.class)); - markClassWildcard("type", pattern.getRoot().nodeIndex.getUnique(BuiltinNumericTypeSpecifier.class)); - markClassWildcard("name*", - pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); - } - - @Override - public boolean matchesExtract(ExternalDeclaration tree) { - boolean result = super.matchesExtract(tree); - if (!result) { - return false; - } - - // look for an out qualifier but no layout qualifier - TypeQualifier qualifier = getNodeMatch("qualifier", TypeQualifier.class); - var hasOutQualifier = false; - for (TypeQualifierPart part : qualifier.getParts()) { - if (part instanceof StorageQualifier) { - StorageQualifier storageQualifier = (StorageQualifier) part; - if (storageQualifier.storageType == StorageType.OUT) { - hasOutQualifier = true; - } - } else if (part instanceof LayoutQualifier) { - return false; - } - } - return hasOutQualifier; - } - }; - - private static final Template layoutedOutDeclarationTemplate = Template - .withExternalDeclaration("out __type __name;"); - - static { - layoutedOutDeclarationTemplate.markLocalReplacement( - layoutedOutDeclarationTemplate.getSourceRoot().nodeIndex.getOne(TypeQualifier.class)); - layoutedOutDeclarationTemplate.markLocalReplacement("__type", TypeSpecifier.class); - layoutedOutDeclarationTemplate.markLocalReplacement("__name", DeclarationMember.class); - } - - record NewDeclarationData(TypeQualifier qualifier, TypeSpecifier type, DeclarationMember member, int number) { - } - - private static final String attachTargetPrefix = "outColor"; - public static void transformFragmentCore(ASTParser t, TranslationUnit tree, Root root, Parameters parameters) { // do layout attachment (attaches a location(layout = 4) to the out declaration // outColor4 for example) // iterate the declarations - ArrayList newDeclarationData = new ArrayList(); - ArrayList declarationsToRemove = new ArrayList(); + ArrayList newDeclarationData = new ArrayList<>(); + ArrayList declarationsToRemove = new ArrayList<>(); for (DeclarationExternalDeclaration declaration : root.nodeIndex.get(DeclarationExternalDeclaration.class)) { if (!nonLayoutOutDeclarationMatcher.matchesExtract(declaration)) { continue; @@ -696,12 +647,12 @@ public static void transformFragmentCore(ASTParser t, TranslationUnit tree, Root // find the matching outColor members List members = nonLayoutOutDeclarationMatcher - .getNodeMatch("name*", DeclarationMember.class) - .getAncestor(TypeAndInitDeclaration.class) - .getMembers(); + .getNodeMatch("name*", DeclarationMember.class) + .getAncestor(TypeAndInitDeclaration.class) + .getMembers(); TypeQualifier typeQualifier = nonLayoutOutDeclarationMatcher.getNodeMatch("qualifier", TypeQualifier.class); BuiltinNumericTypeSpecifier typeSpecifier = nonLayoutOutDeclarationMatcher.getNodeMatch("type", - BuiltinNumericTypeSpecifier.class); + BuiltinNumericTypeSpecifier.class); int addedDeclarations = 0; for (DeclarationMember member : members) { String name = member.getName().getName(); @@ -741,7 +692,7 @@ public static void transformFragmentCore(ASTParser t, TranslationUnit tree, Root } // generate new declarations with layout qualifiers for each outColor member - ArrayList newDeclarations = new ArrayList(); + ArrayList newDeclarations = new ArrayList<>(); // Note: since everything is wrapped in a big Root.indexBuildSession, we don't // need to do it manually here @@ -750,15 +701,51 @@ public static void transformFragmentCore(ASTParser t, TranslationUnit tree, Root member.detach(); TypeQualifier newQualifier = data.qualifier.cloneInto(root); newQualifier.getChildren() - .add(new LayoutQualifier(Stream.of(new NamedLayoutQualifierPart( - new Identifier("location"), - new LiteralExpression(Type.INT32, data.number))))); + .add(new LayoutQualifier(Stream.of(new NamedLayoutQualifierPart( + new Identifier("location"), + new LiteralExpression(Type.INT32, data.number))))); ExternalDeclaration newDeclaration = layoutedOutDeclarationTemplate.getInstanceFor(root, - newQualifier, - data.type.cloneInto(root), - member); + newQualifier, + data.type.cloneInto(root), + member); newDeclarations.add(newDeclaration); } tree.injectNodes(ASTInjectionPoint.BEFORE_DECLARATIONS, newDeclarations); } + + private static class DeclarationMatcher extends Matcher { + private final StorageType storageType; + + { + markClassWildcard("qualifier", pattern.getRoot().nodeIndex.getUnique(TypeQualifier.class)); + markClassWildcard("type", pattern.getRoot().nodeIndex.getUnique(BuiltinNumericTypeSpecifier.class)); + markClassWildcard("name*", + pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); + } + + public DeclarationMatcher(StorageType storageType) { + super("out float name;", ParseShape.EXTERNAL_DECLARATION); + this.storageType = storageType; + } + + @Override + public boolean matchesExtract(ExternalDeclaration tree) { + 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) { + if (storageQualifier.storageType == storageType) { + return true; + } + } + } + return false; + } + } + + record NewDeclarationData(TypeQualifier qualifier, TypeSpecifier type, DeclarationMember member, int number) { + } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeCoreTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeCoreTransformer.java similarity index 64% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeCoreTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeCoreTransformer.java index 08af1e7be5..f7428bd301 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeCoreTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeCoreTransformer.java @@ -1,17 +1,17 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; import io.github.douira.glsl_transformer.ast.query.Root; import io.github.douira.glsl_transformer.ast.transform.ASTParser; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; public class CompositeCoreTransformer { public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters) { CompositeDepthTransformer.transform(t, tree, root); if (parameters.type == PatchShaderType.VERTEX) { @@ -20,10 +20,10 @@ public static void transform( root.replaceReferenceExpressions(t, "modelViewMatrix", "mat4(1.0)"); // This is used to scale the quad projection matrix from (0, 1) to (-1, 1). root.replaceReferenceExpressions(t, "projectionMatrix", - "mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0))"); + "mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0))"); root.replaceReferenceExpressions(t, "modelViewMatrixInverse", "mat4(1.0)"); root.replaceReferenceExpressions(t, "projectionMatrixInverse", - "inverse(mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0)))"); + "inverse(mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0)))"); root.replaceReferenceExpressions(t, "textureMatrix", "mat4(1.0)"); } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeDepthTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeDepthTransformer.java similarity index 81% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeDepthTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeDepthTransformer.java index 44415a6b74..40ea3b1f69 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeDepthTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeDepthTransformer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; import io.github.douira.glsl_transformer.ast.node.declaration.DeclarationMember; @@ -13,21 +13,21 @@ class CompositeDepthTransformer { private static final HintedMatcher uniformFloatCenterDepthSmooth = new HintedMatcher<>( - "uniform float name;", ParseShape.EXTERNAL_DECLARATION, "centerDepthSmooth") { + "uniform float name;", ParseShape.EXTERNAL_DECLARATION, "centerDepthSmooth") { { markClassWildcard("name*", - pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); + pattern.getRoot().identifierIndex.getUnique("name").getAncestor(DeclarationMember.class)); } }; public static void transform( - ASTParser t, - TranslationUnit tree, - Root root) { + ASTParser t, + TranslationUnit tree, + Root root) { // replace original declaration if (root.processMatches(t, uniformFloatCenterDepthSmooth, (match) -> { TypeAndInitDeclaration declaration = ((TypeAndInitDeclaration) ((DeclarationExternalDeclaration) match) - .getDeclaration()); + .getDeclaration()); DeclarationMember memberToDelete = null; for (DeclarationMember member : declaration.getMembers()) { if (member.getName().getName().equals("centerDepthSmooth")) { @@ -44,11 +44,11 @@ public static void transform( } })) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform sampler2D iris_centerDepthSmooth;"); + "uniform sampler2D iris_centerDepthSmooth;"); // if centerDepthSmooth is not declared as a uniform, we don't make it available root.replaceReferenceExpressions(t, "centerDepthSmooth", - "texture(iris_centerDepthSmooth, vec2(0.5)).r"); + "texture(iris_centerDepthSmooth, vec2(0.5)).r"); } } } diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeTransformer.java similarity index 74% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeTransformer.java index d077f20378..7469c0e46c 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/CompositeTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/CompositeTransformer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; import io.github.douira.glsl_transformer.ast.node.expression.Expression; @@ -9,31 +9,31 @@ import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; import io.github.douira.glsl_transformer.ast.transform.ASTParser; import io.github.douira.glsl_transformer.parser.ParseShape; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; public class CompositeTransformer { - private static final AutoHintedMatcher glTextureMatrix0To7 = new AutoHintedMatcher( - "gl_TextureMatrix[index]", ParseShape.EXPRESSION) { + private static final AutoHintedMatcher glTextureMatrix0To7 = new AutoHintedMatcher<>( + "gl_TextureMatrix[index]", ParseShape.EXPRESSION) { { markClassedPredicateWildcard("index", - pattern.getRoot().identifierIndex.getOne("index").getAncestor(ReferenceExpression.class), - LiteralExpression.class, - literalExpression -> { - if (!literalExpression.isInteger()) { - return false; - } - long index = literalExpression.getInteger(); - return index >= 0 && index < 8; - }); + pattern.getRoot().identifierIndex.getOne("index").getAncestor(ReferenceExpression.class), + LiteralExpression.class, + literalExpression -> { + if (!literalExpression.isInteger()) { + return false; + } + long index = literalExpression.getInteger(); + return index >= 0 && index < 8; + }); } }; public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters) { CommonTransformer.transform(t, tree, root, parameters, true); CompositeDepthTransformer.transform(t, tree, root); @@ -46,7 +46,7 @@ public static void transform( if (parameters.type.glShaderType == ShaderType.VERTEX) { root.replaceReferenceExpressions(t, "gl_MultiTexCoord0", - "vec4(UV0, 0.0, 1.0)"); + "vec4(UV0, 0.0, 1.0)"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "in vec2 UV0;"); CommonTransformer.replaceGlMultiTexCoordBounded(t, root, 1, 7); } @@ -66,7 +66,7 @@ public static void transform( tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "in vec3 Position;"); if (root.identifierIndex.has("ftransform")) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); + "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); } root.replaceReferenceExpressions(t, "gl_Vertex", "vec4(Position, 1.0)"); } @@ -74,12 +74,12 @@ public static void transform( // TODO: All of the transformed variants of the input matrices, preferably // computed on the CPU side... root.replaceReferenceExpressions(t, "gl_ModelViewProjectionMatrix", - "(gl_ProjectionMatrix * gl_ModelViewMatrix)"); + "(gl_ProjectionMatrix * gl_ModelViewMatrix)"); root.replaceReferenceExpressions(t, "gl_ModelViewMatrix", "mat4(1.0)"); // This is used to scale the quad projection matrix from (0, 1) to (-1, 1). root.replaceReferenceExpressions(t, "gl_ProjectionMatrix", - "mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0))"); + "mat4(vec4(2.0, 0.0, 0.0, 0.0), vec4(0.0, 2.0, 0.0, 0.0), vec4(0.0), vec4(-1.0, -1.0, 0.0, 1.0))"); CommonTransformer.applyIntelHd4000Workaround(root); } diff --git a/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/DHTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/DHTransformer.java new file mode 100644 index 0000000000..6413ce5132 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/DHTransformer.java @@ -0,0 +1,142 @@ +package net.irisshaders.iris.pipeline.transform.transformer; + +import io.github.douira.glsl_transformer.ast.node.TranslationUnit; +import io.github.douira.glsl_transformer.ast.node.type.qualifier.StorageQualifier; +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 io.github.douira.glsl_transformer.util.Type; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.Parameters; + +import static net.irisshaders.iris.pipeline.transform.transformer.CommonTransformer.addIfNotExists; + +public class DHTransformer { + public static void transform( + ASTParser t, + TranslationUnit tree, + Root root, Parameters parameters) { + CommonTransformer.transform(t, tree, root, parameters, false); + + + root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix0, "mat4(1.0)"); + root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix1, "mat4(1.0)"); + root.rename("gl_ProjectionMatrix", "iris_ProjectionMatrix"); + + if (parameters.type.glShaderType == ShaderType.VERTEX) { + // Alias of gl_MultiTexCoord1 on 1.15+ for OptiFine + // See https://github.com/IrisShaders/Iris/issues/1149 + root.rename("gl_MultiTexCoord2", "gl_MultiTexCoord1"); + + root.replaceReferenceExpressions(t, "gl_MultiTexCoord0", + "vec4(0.0, 0.0, 0.0, 1.0)"); + + root.replaceReferenceExpressions(t, "gl_MultiTexCoord1", + "vec4(_vert_tex_light_coord, 0.0, 1.0)"); + + + // gl_MultiTexCoord0 and gl_MultiTexCoord1 are the only valid inputs (with + // gl_MultiTexCoord2 and gl_MultiTexCoord3 as aliases), other texture + // coordinates are not valid inputs. + CommonTransformer.replaceGlMultiTexCoordBounded(t, root, 4, 7); + } + + root.rename("gl_Color", "_vert_color"); + + if (parameters.type.glShaderType == ShaderType.VERTEX) { + root.replaceReferenceExpressions(t, "gl_Normal", "_vert_normal"); + + } + + // TODO: Should probably add the normal matrix as a proper uniform that's + // computed on the CPU-side of things + root.replaceReferenceExpressions(t, "gl_NormalMatrix", + "iris_NormalMatrix"); + tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, + "uniform mat3 iris_NormalMatrix;"); + + tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, + "uniform mat4 iris_ModelViewMatrixInverse;"); + + tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, + "uniform mat4 iris_ProjectionMatrixInverse;"); + + Iris.logger.warn("Type is " + parameters.type); + + // TODO: All of the transformed variants of the input matrices, preferably + // computed on the CPU side... + root.rename("gl_ModelViewMatrix", "iris_ModelViewMatrix"); + root.rename("gl_ModelViewMatrixInverse", "iris_ModelViewMatrixInverse"); + root.rename("gl_ProjectionMatrixInverse", "iris_ProjectionMatrixInverse"); + + if (parameters.type.glShaderType == ShaderType.VERTEX) { + // TODO: Vaporwave-Shaderpack expects that vertex positions will be aligned to + // chunks. + if (root.identifierIndex.has("ftransform")) { + tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, + "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); + } + tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, + "uniform mat4 iris_ProjectionMatrix;", + "uniform mat4 iris_ModelViewMatrix;", + // _draw_translation replaced with Chunks[_draw_id].offset.xyz + "vec4 getVertexPosition() { return vec4(modelOffset + _vert_position, 1.0); }"); + root.replaceReferenceExpressions(t, "gl_Vertex", "getVertexPosition()"); + + // inject here so that _vert_position is available to the above. (injections + // inject in reverse order if performed piece-wise but in correct order if + // performed as an array of injections) + injectVertInit(t, tree, root, parameters); + } else { + tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, + "uniform mat4 iris_ModelViewMatrix;", + "uniform mat4 iris_ProjectionMatrix;"); + } + + root.replaceReferenceExpressions(t, "gl_ModelViewProjectionMatrix", + "(iris_ProjectionMatrix * iris_ModelViewMatrix)"); + + CommonTransformer.applyIntelHd4000Workaround(root); + } + + public static void injectVertInit( + ASTParser t, + TranslationUnit tree, + Root root, + Parameters parameters) { + tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, + // translated from sodium's chunk_vertex.glsl + "vec3 _vert_position;", + "vec2 _vert_tex_light_coord;", + "int dhMaterialId;", + "vec4 _vert_color;", + "vec3 _vert_normal;", + "uniform float mircoOffset;", + "uniform vec3 modelOffset;", + "const vec3 irisNormals[6] = vec3[](vec3(0,-1,0),vec3(0,1,0),vec3(0,0,-1),vec3(0,0,1),vec3(-1,0,0),vec3(1,0,0));", + "void _vert_init() {" + + " uint meta = vPosition.a;\n" + + "uint mirco = (meta & 0xFF00u) >> 8u; // mirco offset which is a xyz 2bit value\n" + + " // 0b00 = no offset\n" + + " // 0b01 = positive offset\n" + + " // 0b11 = negative offset\n" + + " // format is: 0b00zzyyxx\n" + + " float mx = (mirco & 1u)!=0u ? mircoOffset : 0.0;\n" + + " mx = (mirco & 2u)!=0u ? -mx : mx;\n" + + " float my = (mirco & 4u)!=0u ? mircoOffset : 0.0;\n" + + " my = (mirco & 8u)!=0u ? -my : my;\n" + + " float mz = (mirco & 16u)!=0u ? mircoOffset : 0.0;\n" + + " mz = (mirco & 32u)!=0u ? -mz : mz;\n" + + " uint lights = meta & 0xFFu;\n" + + "_vert_position = (vPosition.xyz + vec3(mx, 0, mz));" + + "_vert_normal = irisNormals[irisExtra.y];" + + "dhMaterialId = int(irisExtra.x);" + + "_vert_tex_light_coord = vec2((float(lights/16u)+0.5) / 16.0, (mod(float(lights), 16.0)+0.5) / 16.0);" + + "_vert_color = iris_color; }"); + addIfNotExists(root, t, tree, "iris_color", Type.F32VEC4, StorageQualifier.StorageType.IN); + addIfNotExists(root, t, tree, "vPosition", Type.U32VEC4, StorageQualifier.StorageType.IN); + addIfNotExists(root, t, tree, "irisExtra", Type.U32VEC4, StorageQualifier.StorageType.IN); + tree.prependMainFunctionBody(t, "_vert_init();"); + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/AttributeTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/EntityPatcher.java similarity index 51% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/AttributeTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/EntityPatcher.java index baa53ad1d8..879ee8cf06 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/AttributeTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/EntityPatcher.java @@ -1,8 +1,5 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; -import java.util.stream.Stream; - -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.abstract_node.ASTNode; import io.github.douira.glsl_transformer.ast.node.external_declaration.ExternalDeclaration; @@ -10,138 +7,30 @@ import io.github.douira.glsl_transformer.ast.query.match.AutoHintedMatcher; 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.TransformationException; import io.github.douira.glsl_transformer.parser.ParseShape; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.AttributeParameters; -import net.coderbot.iris.pipeline.transform.parameter.GeometryInfoParameters; -import net.coderbot.iris.pipeline.transform.parameter.Parameters; -import net.coderbot.iris.pipeline.transform.parameter.VanillaParameters; - -/** - * Implements AttributeShaderTransformer - */ -public class AttributeTransformer { - public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - AttributeParameters parameters) { - if (tree.getVersionStatement().getNormalizedProfile().isCore()) { - if (parameters.type == PatchShaderType.VERTEX) { - throw new TransformationException("Vertex shaders must be in the compatibility profile to run properly!"); - } - 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) { - root.rename("gl_MultiTexCoord1", "gl_MultiTexCoord2"); - } - - 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)"); - } - - patchTextureMatrices(t, tree, root, parameters.inputs.lightmap); - - if (parameters.inputs.overlay) { - patchOverlayColor(t, tree, root, parameters); - } - - patchMultiTexCoord3(t, tree, root, parameters); - } - - public static void patchMultiTexCoord3( - ASTParser t, - TranslationUnit tree, - Root root, - Parameters parameters) { - if (parameters.type.glShaderType == ShaderType.VERTEX - && root.identifierIndex.has("gl_MultiTexCoord3") - && !root.identifierIndex.has("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 - // an existing declaration robustly. But basically the proper way to do this is - // 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_DECLARATIONS, - "attribute vec4 mc_midTexCoord;"); - } - } - - private static void patchTextureMatrices( - ASTParser t, - TranslationUnit tree, - Root root, - boolean hasLightmap) { - root.rename("gl_TextureMatrix", "iris_TextureMatrix"); - - tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "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_DECLARATIONS, - "mat4 iris_LightmapTextureMatrix = gl_TextureMatrix[2];"); - } else { - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "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 - tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "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)" + - ");"); - } +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.GeometryInfoParameters; +import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; +public class EntityPatcher { private static final AutoHintedMatcher uniformVec4EntityColor = new AutoHintedMatcher<>( - "uniform vec4 entityColor;", ParseShape.EXTERNAL_DECLARATION); + "uniform vec4 entityColor;", ParseShape.EXTERNAL_DECLARATION); private static final AutoHintedMatcher uniformIntEntityId = new AutoHintedMatcher<>( - "uniform int entityId;", ParseShape.EXTERNAL_DECLARATION); + "uniform int entityId;", ParseShape.EXTERNAL_DECLARATION); private static final AutoHintedMatcher uniformIntBlockEntityId = new AutoHintedMatcher<>( - "uniform int blockEntityId;", ParseShape.EXTERNAL_DECLARATION); + "uniform int blockEntityId;", ParseShape.EXTERNAL_DECLARATION); private static final AutoHintedMatcher uniformIntCurrentRenderedItemId = new AutoHintedMatcher<>( - "uniform int currentRenderedItemId;", ParseShape.EXTERNAL_DECLARATION); + "uniform int currentRenderedItemId;", ParseShape.EXTERNAL_DECLARATION); // Add entity color -> overlay color attribute support. public static void patchOverlayColor( - ASTParser t, - TranslationUnit tree, - Root root, - GeometryInfoParameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + GeometryInfoParameters parameters) { // delete original declaration root.processMatches(t, uniformVec4EntityColor, ASTNode::detachAndDelete); @@ -150,23 +39,23 @@ public static void patchOverlayColor( // TODO: We're exposing entityColor to this stage even if it isn't declared in // this stage. But this is needed for the pass-through behavior. tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform sampler2D iris_overlay;", - "out vec4 entityColor;", - "out vec4 iris_vertexColor;", - "in ivec2 iris_UV1;"); + "uniform sampler2D iris_overlay;", + "out vec4 entityColor;", + "out vec4 iris_vertexColor;", + "in ivec2 iris_UV1;"); // Create our own main function to wrap the existing main function, so that we // can pass through the overlay color at the end to the geometry or fragment // stage. tree.prependMainFunctionBody(t, - "vec4 overlayColor = texelFetch(iris_overlay, iris_UV1, 0);", - "entityColor = vec4(overlayColor.rgb, 1.0 - overlayColor.a);", - "iris_vertexColor = iris_Color;", - // Workaround for a shader pack bug: - // https://github.com/IrisShaders/Iris/issues/1549 - // Some shader packs incorrectly ignore the alpha value, and assume that rgb - // will be zero if there is no hit flash, we try to emulate that here - "entityColor.rgb *= float(entityColor.a != 0.0);"); + "vec4 overlayColor = texelFetch(iris_overlay, iris_UV1, 0);", + "entityColor = vec4(overlayColor.rgb, 1.0 - overlayColor.a);", + "iris_vertexColor = iris_Color;", + // Workaround for a shader pack bug: + // https://github.com/IrisShaders/Iris/issues/1549 + // Some shader packs incorrectly ignore the alpha value, and assume that rgb + // will be zero if there is no hit flash, we try to emulate that here + "entityColor.rgb *= float(entityColor.a != 0.0);"); } else if (parameters.type.glShaderType == ShaderType.TESSELATION_CONTROL) { // replace read references to grab the color from the first vertex. root.replaceReferenceExpressions(t, "entityColor", "entityColor[gl_InvocationID]"); @@ -199,13 +88,13 @@ public static void patchOverlayColor( // TODO: this is passthrough behavior tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "out vec4 entityColorGS;", - "in vec4 entityColor[];", - "out vec4 iris_vertexColorGS;", - "in vec4 iris_vertexColor[];"); + "out vec4 entityColorGS;", + "in vec4 entityColor[];", + "out vec4 iris_vertexColorGS;", + "in vec4 iris_vertexColor[];"); tree.prependMainFunctionBody(t, - "entityColorGS = entityColor[0];", - "iris_vertexColorGS = iris_vertexColor[0];"); + "entityColorGS = entityColor[0];", + "iris_vertexColorGS = iris_vertexColor[0];"); if (parameters.hasTesselation) { root.rename("iris_vertexColor", "iris_vertexColorTES"); @@ -213,7 +102,7 @@ public static void patchOverlayColor( } } else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in vec4 entityColor;", "in vec4 iris_vertexColor;"); + "in vec4 entityColor;", "in vec4 iris_vertexColor;"); tree.prependMainFunctionBody(t, "float iris_vertexColorAlpha = iris_vertexColor.a;"); @@ -229,10 +118,10 @@ public static void patchOverlayColor( } public static void patchEntityId( - ASTParser t, - TranslationUnit tree, - Root root, - VanillaParameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + VanillaParameters parameters) { // delete original declaration root.processMatches(t, uniformIntEntityId, ASTNode::detachAndDelete); root.processMatches(t, uniformIntBlockEntityId, ASTNode::detachAndDelete); @@ -264,43 +153,43 @@ public static void patchEntityId( // TODO: We're exposing entityColor to this stage even if it isn't declared in // this stage. But this is needed for the pass-through behavior. tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "flat out ivec3 iris_entityInfo;", - "in ivec3 iris_Entity;"); + "flat out ivec3 iris_entityInfo;", + "in ivec3 iris_Entity;"); // Create our own main function to wrap the existing main function, so that we // can pass through the overlay color at the end to the geometry or fragment // stage. tree.prependMainFunctionBody(t, - "iris_entityInfo = iris_Entity;"); + "iris_entityInfo = iris_Entity;"); } else if (parameters.type.glShaderType == ShaderType.TESSELATION_CONTROL) { // TODO: this is passthrough behavior tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "flat out ivec3 iris_entityInfoTCS[];", - "flat in ivec3 iris_entityInfo[];"); + "flat out ivec3 iris_entityInfoTCS[];", + "flat in ivec3 iris_entityInfo[];"); root.replaceReferenceExpressions(t, "iris_entityInfo", "iris_EntityInfo[gl_InvocationID]"); tree.prependMainFunctionBody(t, - "iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];"); + "iris_entityInfoTCS[gl_InvocationID] = iris_entityInfo[gl_InvocationID];"); } else if (parameters.type.glShaderType == ShaderType.TESSELATION_EVAL) { // TODO: this is passthrough behavior tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "flat out ivec3 iris_entityInfoTES;", - "flat in ivec3 iris_entityInfoTCS[];"); + "flat out ivec3 iris_entityInfoTES;", + "flat in ivec3 iris_entityInfoTCS[];"); tree.prependMainFunctionBody(t, - "iris_entityInfoTES = iris_entityInfoTCS[0];"); + "iris_entityInfoTES = iris_entityInfoTCS[0];"); root.replaceReferenceExpressions(t, "iris_entityInfo", "iris_EntityInfoTCS[0]"); } else if (parameters.type.glShaderType == ShaderType.GEOMETRY) { // TODO: this is passthrough behavior tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "flat out ivec3 iris_entityInfoGS;", - "flat in ivec3 iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[];"); + "flat out ivec3 iris_entityInfoGS;", + "flat in ivec3 iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[];"); tree.prependMainFunctionBody(t, - "iris_entityInfoGS = iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[0];"); + "iris_entityInfoGS = iris_entityInfo" + (parameters.hasTesselation ? "TES" : "") + "[0];"); } else if (parameters.type.glShaderType == ShaderType.FRAGMENT) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "flat in ivec3 iris_entityInfo;"); + "flat in ivec3 iris_entityInfo;"); // Different output name to avoid a name collision in the geometry shader. if (parameters.hasGeometry) { diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumCoreTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumCoreTransformer.java similarity index 82% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumCoreTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumCoreTransformer.java index d72db6c10d..5c4502aadc 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumCoreTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumCoreTransformer.java @@ -1,17 +1,17 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; import io.github.douira.glsl_transformer.ast.query.Root; import io.github.douira.glsl_transformer.ast.transform.ASTParser; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.SodiumParameters; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; public class SodiumCoreTransformer { public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - SodiumParameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + SodiumParameters parameters) { root.rename("alphaTestRef", "iris_currentAlphaTest"); root.rename("modelViewMatrix", "iris_ModelViewMatrix"); root.rename("modelViewMatrixInverse", "iris_ModelViewMatrixInverse"); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumTransformer.java similarity index 93% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumTransformer.java index f0cd0f0511..775d499657 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/SodiumTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/SodiumTransformer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.Identifier; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; @@ -10,15 +10,11 @@ import io.github.douira.glsl_transformer.ast.transform.ASTInjectionPoint; import io.github.douira.glsl_transformer.ast.transform.ASTParser; import io.github.douira.glsl_transformer.util.Type; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.gl.blending.AlphaTest; -import net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.newshader.AlphaTests; -import net.coderbot.iris.pipeline.transform.parameter.SodiumParameters; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.SodiumParameters; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; -import java.util.Set; - -import static net.coderbot.iris.pipeline.transform.transformer.CommonTransformer.addIfNotExists; +import static net.irisshaders.iris.pipeline.transform.transformer.CommonTransformer.addIfNotExists; public class SodiumTransformer { public static void transform( @@ -56,7 +52,7 @@ public static void transform( "vec4(240.0, 240.0, 0.0, 1.0)"); } - AttributeTransformer.patchMultiTexCoord3(t, tree, root, parameters); + CommonTransformer.patchMultiTexCoord3(t, tree, root, parameters); // gl_MultiTexCoord0 and gl_MultiTexCoord1 are the only valid inputs (with // gl_MultiTexCoord2 and gl_MultiTexCoord3 as aliases), other texture @@ -135,7 +131,7 @@ public static void injectVertInit( TranslationUnit tree, Root root, SodiumParameters parameters) { - String separateAo = BlockRenderingSettings.INSTANCE.shouldUseSeparateAo() ? "a_Color" : "vec4(a_Color.rgb * a_Color.a, 1.0)"; + String separateAo = WorldRenderingSettings.INSTANCE.shouldUseSeparateAo() ? "a_Color" : "vec4(a_Color.rgb * a_Color.a, 1.0)"; tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, // translated from sodium's chunk_vertex.glsl "vec3 _vert_position;", diff --git a/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/TextureTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/TextureTransformer.java new file mode 100644 index 0000000000..56cf48d4df --- /dev/null +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/TextureTransformer.java @@ -0,0 +1,66 @@ +package net.irisshaders.iris.pipeline.transform.transformer; + +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.declaration.TypeAndInitDeclaration; +import io.github.douira.glsl_transformer.ast.node.external_declaration.DeclarationExternalDeclaration; +import io.github.douira.glsl_transformer.ast.node.type.specifier.BuiltinFixedTypeSpecifier; +import io.github.douira.glsl_transformer.ast.query.Root; +import io.github.douira.glsl_transformer.ast.transform.ASTParser; +import it.unimi.dsi.fastutil.objects.Object2ObjectMap; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.shaderpack.texture.TextureStage; + +public class TextureTransformer { + public static void transform( + ASTParser t, + TranslationUnit tree, + Root root, + TextureStage stage, Object2ObjectMap, String> textureMap) { + textureMap.forEach((stringTextureTypeTextureStageTri, s) -> { + if (stringTextureTypeTextureStageTri.third() == stage) { + String name = stringTextureTypeTextureStageTri.first(); + + // check if the declaration has the right type and rename if one is found + // iterates all hits of the identifier and checks the ancestors + for (Identifier id : root.identifierIndex.get(name)) { + TypeAndInitDeclaration initDeclaration = (TypeAndInitDeclaration) id.getAncestor( + 2, 0, TypeAndInitDeclaration.class::isInstance); + if (initDeclaration == null) { + continue; + } + DeclarationExternalDeclaration declaration = (DeclarationExternalDeclaration) initDeclaration.getAncestor( + 1, 0, DeclarationExternalDeclaration.class::isInstance); + if (declaration == null) { + continue; + } + if (initDeclaration.getType().getTypeSpecifier() instanceof BuiltinFixedTypeSpecifier fixed + && isTypeValid(stringTextureTypeTextureStageTri.second(), fixed.type)) { + root.rename(stringTextureTypeTextureStageTri.first(), s); + break; + } + } + } + }); + } + + private static boolean isTypeValid(TextureType expectedType, BuiltinFixedTypeSpecifier.BuiltinType extractedType) { + // not TransformationException because this should never happen + return switch (expectedType) { + case TEXTURE_1D -> extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER1D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER1D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER1D; + case TEXTURE_RECTANGLE -> extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER2DRECT || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER2DRECT || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER2DRECT; + case TEXTURE_2D -> extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER2D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER2D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER2D; + case TEXTURE_3D -> extractedType == BuiltinFixedTypeSpecifier.BuiltinType.SAMPLER3D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.ISAMPLER3D || + extractedType == BuiltinFixedTypeSpecifier.BuiltinType.USAMPLER3D; + default -> throw new IllegalStateException("Unexpected enum! " + expectedType); + }; + } +} diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaCoreTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaCoreTransformer.java similarity index 83% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaCoreTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaCoreTransformer.java index 4b838304bf..ea86d4fa95 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaCoreTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaCoreTransformer.java @@ -1,27 +1,27 @@ -package net.coderbot.iris.pipeline.transform.transformer; - -import static net.coderbot.iris.pipeline.transform.transformer.CommonTransformer.addIfNotExists; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; import io.github.douira.glsl_transformer.ast.node.type.qualifier.StorageQualifier.StorageType; import io.github.douira.glsl_transformer.ast.query.Root; import io.github.douira.glsl_transformer.ast.transform.ASTParser; import io.github.douira.glsl_transformer.util.Type; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.VanillaParameters; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; + +import static net.irisshaders.iris.pipeline.transform.transformer.CommonTransformer.addIfNotExists; public class VanillaCoreTransformer { public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - VanillaParameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + VanillaParameters parameters) { if (parameters.inputs.hasOverlay()) { if (!parameters.inputs.isText()) { - AttributeTransformer.patchOverlayColor(t, tree, root, parameters); + EntityPatcher.patchOverlayColor(t, tree, root, parameters); } - AttributeTransformer.patchEntityId(t, tree, root, parameters); + EntityPatcher.patchEntityId(t, tree, root, parameters); } CommonTransformer.transform(t, tree, root, parameters, true); @@ -38,9 +38,9 @@ public static void transform( root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix0, "iris_TextureMat"); root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix1, - "mat4(vec4(0.00390625, 0.0, 0.0, 0.0), vec4(0.0, 0.00390625, 0.0, 0.0), vec4(0.0, 0.0, 0.00390625, 0.0), vec4(0.03125, 0.03125, 0.03125, 1.0))"); + "mat4(vec4(0.00390625, 0.0, 0.0, 0.0), vec4(0.0, 0.00390625, 0.0, 0.0), vec4(0.0, 0.0, 0.00390625, 0.0), vec4(0.03125, 0.03125, 0.03125, 1.0))"); root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix2, - "mat4(vec4(0.00390625, 0.0, 0.0, 0.0), vec4(0.0, 0.00390625, 0.0, 0.0), vec4(0.0, 0.0, 0.00390625, 0.0), vec4(0.03125, 0.03125, 0.03125, 1.0))"); + "mat4(vec4(0.00390625, 0.0, 0.0, 0.0), vec4(0.0, 0.00390625, 0.0, 0.0), vec4(0.0, 0.0, 0.00390625, 0.0), vec4(0.03125, 0.03125, 0.03125, 1.0))"); addIfNotExists(root, t, tree, "iris_TextureMat", Type.F32MAT4X4, StorageType.UNIFORM); addIfNotExists(root, t, tree, "iris_ProjMat", Type.F32MAT4X4, StorageType.UNIFORM); addIfNotExists(root, t, tree, "iris_ProjMatInverse", Type.F32MAT4X4, StorageType.UNIFORM); diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaTransformer.java b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaTransformer.java similarity index 61% rename from src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaTransformer.java rename to src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaTransformer.java index 460ab8c680..cc88c05d1d 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/transformer/VanillaTransformer.java +++ b/src/main/java/net/irisshaders/iris/pipeline/transform/transformer/VanillaTransformer.java @@ -1,27 +1,27 @@ -package net.coderbot.iris.pipeline.transform.transformer; +package net.irisshaders.iris.pipeline.transform.transformer; import io.github.douira.glsl_transformer.ast.node.TranslationUnit; 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 net.coderbot.iris.gl.shader.ShaderType; -import net.coderbot.iris.pipeline.newshader.AlphaTests; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.parameter.VanillaParameters; +import net.irisshaders.iris.gl.blending.AlphaTests; +import net.irisshaders.iris.gl.shader.ShaderType; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.parameter.VanillaParameters; public class VanillaTransformer { public static void transform( - ASTParser t, - TranslationUnit tree, - Root root, - VanillaParameters parameters) { + ASTParser t, + TranslationUnit tree, + Root root, + VanillaParameters parameters) { // this happens before common to make sure the renaming of attributes is done on // attribute inserted by this if (parameters.inputs.hasOverlay()) { - AttributeTransformer.patchOverlayColor(t, tree, root, parameters); - AttributeTransformer.patchEntityId(t, tree, root, parameters); + EntityPatcher.patchOverlayColor(t, tree, root, parameters); + EntityPatcher.patchEntityId(t, tree, root, parameters); } else if (parameters.inputs.isText()) { - AttributeTransformer.patchEntityId(t, tree, root, parameters); + EntityPatcher.patchEntityId(t, tree, root, parameters); } CommonTransformer.transform(t, tree, root, parameters, false); @@ -33,25 +33,25 @@ public static void transform( if (parameters.inputs.hasTex()) { root.replaceReferenceExpressions(t, "gl_MultiTexCoord0", - "vec4(iris_UV0, 0.0, 1.0)"); + "vec4(iris_UV0, 0.0, 1.0)"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in vec2 iris_UV0;"); + "in vec2 iris_UV0;"); } else { root.replaceReferenceExpressions(t, "gl_MultiTexCoord0", - "vec4(0.5, 0.5, 0.0, 1.0)"); + "vec4(0.5, 0.5, 0.0, 1.0)"); } if (parameters.inputs.hasLight()) { root.replaceReferenceExpressions(t, "gl_MultiTexCoord1", - "vec4(iris_UV2, 0.0, 1.0)"); + "vec4(iris_UV2, 0.0, 1.0)"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in ivec2 iris_UV2;"); + "in ivec2 iris_UV2;"); } else { root.replaceReferenceExpressions(t, "gl_MultiTexCoord1", - "vec4(240.0, 240.0, 0.0, 1.0)"); + "vec4(240.0, 240.0, 0.0, 1.0)"); } - AttributeTransformer.patchMultiTexCoord3(t, tree, root, parameters); + CommonTransformer.patchMultiTexCoord3(t, tree, root, parameters); // gl_MultiTexCoord0 and gl_MultiTexCoord1 are the only valid inputs (with // gl_MultiTexCoord2 and gl_MultiTexCoord3 as aliases), other texture @@ -60,21 +60,21 @@ public static void transform( } tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform vec4 iris_ColorModulator;"); + "uniform vec4 iris_ColorModulator;"); if (parameters.inputs.hasColor() && parameters.type == PatchShaderType.VERTEX) { // TODO: Handle the fragment / geometry shader here if (parameters.alpha == AlphaTests.VERTEX_ALPHA) { root.replaceReferenceExpressions(t, "gl_Color", - "vec4((iris_Color * iris_ColorModulator).rgb, iris_ColorModulator.a)"); + "vec4((iris_Color * iris_ColorModulator).rgb, iris_ColorModulator.a)"); } else { root.replaceReferenceExpressions(t, "gl_Color", - "(iris_Color * iris_ColorModulator)"); + "(iris_Color * iris_ColorModulator)"); } if (parameters.type.glShaderType == ShaderType.VERTEX) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in vec4 iris_Color;"); + "in vec4 iris_Color;"); } } else if (parameters.inputs.isGlint()) { tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, @@ -92,21 +92,21 @@ public static void transform( root.rename("gl_Normal", "iris_Normal"); } else { root.replaceReferenceExpressions(t, "gl_Normal", - "vec3(0.0, 0.0, 1.0)"); + "vec3(0.0, 0.0, 1.0)"); } tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in vec3 iris_Normal;"); + "in vec3 iris_Normal;"); } else { root.replaceReferenceExpressions(t, "gl_Normal", - "vec3(0.0, 0.0, 1.0)"); + "vec3(0.0, 0.0, 1.0)"); } } tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform mat4 iris_LightmapTextureMatrix;", - "uniform mat4 iris_TextureMat;", - "uniform mat4 iris_ModelViewMat;"); + "uniform mat4 iris_LightmapTextureMatrix;", + "uniform mat4 iris_TextureMat;", + "uniform mat4 iris_ModelViewMat;"); // TODO: More solid way to handle texture matrices root.replaceExpressionMatches(t, CommonTransformer.glTextureMatrix0, "iris_TextureMat"); @@ -115,28 +115,28 @@ public static void transform( // TODO: Should probably add the normal matrix as a proper uniform that's // computed on the CPU-side of things root.replaceReferenceExpressions(t, "gl_NormalMatrix", - "iris_NormalMat"); + "iris_NormalMat"); root.replaceReferenceExpressions(t, "gl_ModelViewMatrixInverse", - "iris_ModelViewMatInverse"); + "iris_ModelViewMatInverse"); root.replaceReferenceExpressions(t, "gl_ProjectionMatrixInverse", - "iris_ProjMatInverse"); + "iris_ProjMatInverse"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "uniform mat3 iris_NormalMat;"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "uniform mat4 iris_ProjMatInverse;"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, "uniform mat4 iris_ModelViewMatInverse;"); if (parameters.type.glShaderType == ShaderType.VERTEX) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "in vec3 iris_Position;"); + "in vec3 iris_Position;"); if (root.identifierIndex.has("ftransform")) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); + "vec4 ftransform() { return gl_ModelViewProjectionMatrix * gl_Vertex; }"); } if (parameters.inputs.isNewLines()) { root.replaceReferenceExpressions(t, "gl_Vertex", - "vec4(iris_Position + iris_vertex_offset, 1.0)"); + "vec4(iris_Position + iris_vertex_offset, 1.0)"); // Create our own main function to wrap the existing main function, so that we // can do our line shenanigans. @@ -144,33 +144,33 @@ public static void transform( // in the vertex shader root.rename("main", "irisMain"); tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "vec3 iris_vertex_offset = vec3(0.0);"); + "vec3 iris_vertex_offset = vec3(0.0);"); tree.parseAndInjectNodes(t, ASTInjectionPoint.END, - "uniform vec2 iris_ScreenSize;", - "uniform float iris_LineWidth;", - "void iris_widen_lines(vec4 linePosStart, vec4 linePosEnd) {" + - "vec3 ndc1 = linePosStart.xyz / linePosStart.w;" + - "vec3 ndc2 = linePosEnd.xyz / linePosEnd.w;" + - "vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * iris_ScreenSize);" + - "vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * iris_LineWidth / iris_ScreenSize;" - + - "if (lineOffset.x < 0.0) {" + - " lineOffset *= -1.0;" + - "}" + - "if (gl_VertexID % 2 == 0) {" + - " gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + - "} else {" + - " gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + - "}}", - "void main() {" + - "iris_vertex_offset = iris_Normal;" + - "irisMain();" + - "vec4 linePosEnd = gl_Position;" + - "gl_Position = vec4(0.0);" + - "iris_vertex_offset = vec3(0.0);" + - "irisMain();" + - "vec4 linePosStart = gl_Position;" + - "iris_widen_lines(linePosStart, linePosEnd);}"); + "uniform vec2 iris_ScreenSize;", + "uniform float iris_LineWidth;", + "void iris_widen_lines(vec4 linePosStart, vec4 linePosEnd) {" + + "vec3 ndc1 = linePosStart.xyz / linePosStart.w;" + + "vec3 ndc2 = linePosEnd.xyz / linePosEnd.w;" + + "vec2 lineScreenDirection = normalize((ndc2.xy - ndc1.xy) * iris_ScreenSize);" + + "vec2 lineOffset = vec2(-lineScreenDirection.y, lineScreenDirection.x) * iris_LineWidth / iris_ScreenSize;" + + + "if (lineOffset.x < 0.0) {" + + " lineOffset *= -1.0;" + + "}" + + "if (gl_VertexID % 2 == 0) {" + + " gl_Position = vec4((ndc1 + vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + + "} else {" + + " gl_Position = vec4((ndc1 - vec3(lineOffset, 0.0)) * linePosStart.w, linePosStart.w);" + + "}}", + "void main() {" + + "iris_vertex_offset = iris_Normal;" + + "irisMain();" + + "vec4 linePosEnd = gl_Position;" + + "gl_Position = vec4(0.0);" + + "iris_vertex_offset = vec3(0.0);" + + "irisMain();" + + "vec4 linePosStart = gl_Position;" + + "iris_widen_lines(linePosStart, linePosEnd);}"); } else { root.replaceReferenceExpressions(t, "gl_Vertex", "vec4(iris_Position, 1.0)"); } @@ -179,36 +179,36 @@ public static void transform( // TODO: All of the transformed variants of the input matrices, preferably // computed on the CPU side... root.replaceReferenceExpressions(t, "gl_ModelViewProjectionMatrix", - "(gl_ProjectionMatrix * gl_ModelViewMatrix)"); + "(gl_ProjectionMatrix * gl_ModelViewMatrix)"); if (parameters.hasChunkOffset) { boolean doInjection = root.replaceReferenceExpressionsReport(t, "gl_ModelViewMatrix", - "(iris_ModelViewMat * _iris_internal_translate(iris_ChunkOffset))"); + "(iris_ModelViewMat * _iris_internal_translate(iris_ChunkOffset))"); if (doInjection) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_FUNCTIONS, - "uniform vec3 iris_ChunkOffset;", - "mat4 _iris_internal_translate(vec3 offset) {" + - "return mat4(1.0, 0.0, 0.0, 0.0," + - "0.0, 1.0, 0.0, 0.0," + - "0.0, 0.0, 1.0, 0.0," + - "offset.x, offset.y, offset.z, 1.0); }"); + "uniform vec3 iris_ChunkOffset;", + "mat4 _iris_internal_translate(vec3 offset) {" + + "return mat4(1.0, 0.0, 0.0, 0.0," + + "0.0, 1.0, 0.0, 0.0," + + "0.0, 0.0, 1.0, 0.0," + + "offset.x, offset.y, offset.z, 1.0); }"); } } else if (parameters.inputs.isNewLines()) { tree.parseAndInjectNodes(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "const float iris_VIEW_SHRINK = 1.0 - (1.0 / 256.0);", - "const mat4 iris_VIEW_SCALE = mat4(" + - "iris_VIEW_SHRINK, 0.0, 0.0, 0.0," + - "0.0, iris_VIEW_SHRINK, 0.0, 0.0," + - "0.0, 0.0, iris_VIEW_SHRINK, 0.0," + - "0.0, 0.0, 0.0, 1.0);"); + "const float iris_VIEW_SHRINK = 1.0 - (1.0 / 256.0);", + "const mat4 iris_VIEW_SCALE = mat4(" + + "iris_VIEW_SHRINK, 0.0, 0.0, 0.0," + + "0.0, iris_VIEW_SHRINK, 0.0, 0.0," + + "0.0, 0.0, iris_VIEW_SHRINK, 0.0," + + "0.0, 0.0, 0.0, 1.0);"); root.replaceReferenceExpressions(t, "gl_ModelViewMatrix", - "(iris_VIEW_SCALE * iris_ModelViewMat)"); + "(iris_VIEW_SCALE * iris_ModelViewMat)"); } else { root.rename("gl_ModelViewMatrix", "iris_ModelViewMat"); } root.rename("gl_ProjectionMatrix", "iris_ProjMat"); tree.parseAndInjectNode(t, ASTInjectionPoint.BEFORE_DECLARATIONS, - "uniform mat4 iris_ProjMat;"); + "uniform mat4 iris_ProjMat;"); } } diff --git a/src/main/java/net/coderbot/iris/samplers/IrisImages.java b/src/main/java/net/irisshaders/iris/samplers/IrisImages.java similarity index 86% rename from src/main/java/net/coderbot/iris/samplers/IrisImages.java rename to src/main/java/net/irisshaders/iris/samplers/IrisImages.java index d5a39e1d95..0979ba8f84 100644 --- a/src/main/java/net/coderbot/iris/samplers/IrisImages.java +++ b/src/main/java/net/irisshaders/iris/samplers/IrisImages.java @@ -1,13 +1,12 @@ -package net.coderbot.iris.samplers; +package net.irisshaders.iris.samplers; import com.google.common.collect.ImmutableSet; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.gl.image.ImageHolder; -import net.coderbot.iris.gl.program.ProgramImages; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.image.ImageHolder; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.targets.RenderTarget; +import net.irisshaders.iris.targets.RenderTargets; import java.util.Set; import java.util.function.IntSupplier; diff --git a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java b/src/main/java/net/irisshaders/iris/samplers/IrisSamplers.java similarity index 85% rename from src/main/java/net/coderbot/iris/samplers/IrisSamplers.java rename to src/main/java/net/irisshaders/iris/samplers/IrisSamplers.java index f9f9aa55b5..eae5847506 100644 --- a/src/main/java/net/coderbot/iris/samplers/IrisSamplers.java +++ b/src/main/java/net/irisshaders/iris/samplers/IrisSamplers.java @@ -1,25 +1,21 @@ -package net.coderbot.iris.samplers; +package net.irisshaders.iris.samplers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.gl.sampler.GlSampler; -import net.coderbot.iris.gl.sampler.SamplerHolder; -import net.coderbot.iris.gl.sampler.SamplerLimits; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.sampler.GlSampler; +import net.irisshaders.iris.gl.sampler.SamplerHolder; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.targets.RenderTarget; +import net.irisshaders.iris.targets.RenderTargets; import net.minecraft.client.renderer.texture.AbstractTexture; -import org.lwjgl.opengl.GL33C; import java.util.Set; import java.util.function.IntSupplier; @@ -52,7 +48,7 @@ public static void initRenderer() { } public static void addRenderTargetSamplers(SamplerHolder samplers, Supplier> flipped, - RenderTargets renderTargets, boolean isFullscreenPass) { + RenderTargets renderTargets, boolean isFullscreenPass, WorldRenderingPipeline pipeline) { // colortex0,1,2,3 are only able to be sampled from fullscreen passes. // Iris could lift this restriction, though I'm not sure if it could cause issues. int startIndex = isFullscreenPass ? 0 : 4; @@ -96,6 +92,10 @@ public static void addRenderTargetSamplers(SamplerHolder samplers, Supplier pipeline.getDHCompat().getDepthTex(), null, "dhDepthTex", "dhDepthTex0"); + samplers.addDynamicSampler(TextureType.TEXTURE_2D, () -> pipeline.getDHCompat().getDepthTexNoTranslucent(), null, "dhDepthTex1"); } public static void addNoiseSampler(SamplerHolder samplers, TextureAccess sampler) { @@ -106,8 +106,8 @@ public static boolean hasShadowSamplers(SamplerHolder samplers) { // TODO: Keep this up to date with the actual definitions. // TODO: Don't query image presence using the sampler interface even though the current underlying implementation // is the same. - ImmutableList.Builder shadowSamplers = ImmutableList.builder().add("shadowtex0", "shadowtex0HW", "shadowtex1", "shadowtex1HW", "shadow", "watershadow", - "shadowcolor"); + ImmutableList.Builder shadowSamplers = ImmutableList.builder().add("shadowtex0", "shadowtex0DH", "shadowtex0HW", "shadowtex1", "shadowtex1HW", "shadowtex1DH", "shadow", "watershadow", + "shadowcolor"); for (int i = 0; i < PackShadowDirectives.MAX_SHADOW_COLOR_BUFFERS_IRIS; i++) { shadowSamplers.add("shadowcolor" + i); @@ -134,7 +134,7 @@ public static boolean addShadowSamplers(SamplerHolder samplers, ShadowRenderTarg usesShadows = true; samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(0) ? shadowRenderTargets.isLinearFiltered(0) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST : null), "shadowtex0", "watershadow"); samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(1) ? shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST : null), - "shadowtex1", "shadow"); + "shadowtex1", "shadow"); } else { usesShadows = samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTexture()::getTextureId, separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(0) ? shadowRenderTargets.isLinearFiltered(0) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST : null), "shadowtex0", "shadow"); usesShadows |= samplers.addDynamicSampler(TextureType.TEXTURE_2D, shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, separateHardwareSamplers ? null : (shadowRenderTargets.isHardwareFiltered(1) ? shadowRenderTargets.isLinearFiltered(1) ? SHADOW_SAMPLER_LINEAR : SHADOW_SAMPLER_NEAREST : null), "shadowtex1"); @@ -178,22 +178,22 @@ public static boolean hasPBRSamplers(SamplerHolder samplers) { return samplers.hasSampler("normals") || samplers.hasSampler("specular"); } - public static void addLevelSamplers(SamplerHolder samplers, WorldRenderingPipeline pipeline, AbstractTexture whitePixel, InputAvailability availability) { - if (availability.texture) { + public static void addLevelSamplers(SamplerHolder samplers, WorldRenderingPipeline pipeline, AbstractTexture whitePixel, boolean hasTexture, boolean hasLightmap, boolean hasOverlay) { + if (hasTexture) { samplers.addExternalSampler(ALBEDO_TEXTURE_UNIT, "tex", "texture", "gtexture"); } else { // TODO: Rebind unbound sampler IDs instead of hardcoding a list... samplers.addDynamicSampler(whitePixel::getId, "tex", "texture", "gtexture", - "gcolor", "colortex0"); + "gcolor", "colortex0"); } - if (availability.lightmap) { + if (hasLightmap) { samplers.addExternalSampler(LIGHTMAP_TEXTURE_UNIT, "lightmap"); } else { samplers.addDynamicSampler(whitePixel::getId, "lightmap"); } - if (availability.overlay) { + if (hasOverlay) { samplers.addExternalSampler(OVERLAY_TEXTURE_UNIT, "iris_overlay"); } else { samplers.addDynamicSampler(whitePixel::getId, "iris_overlay"); @@ -211,11 +211,11 @@ public static void addWorldDepthSamplers(SamplerHolder samplers, RenderTargets r public static void addCompositeSamplers(SamplerHolder samplers, RenderTargets renderTargets) { samplers.addDynamicSampler(renderTargets::getDepthTexture, - "gdepthtex", "depthtex0"); + "gdepthtex", "depthtex0"); samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, - "depthtex1"); + "depthtex1"); samplers.addDynamicSampler(renderTargets.getDepthTextureNoHand()::getTextureId, - "depthtex2"); + "depthtex2"); } public static void addCustomTextures(SamplerHolder samplers, Object2ObjectMap irisCustomTextures) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/DimensionId.java b/src/main/java/net/irisshaders/iris/shaderpack/DimensionId.java similarity index 72% rename from src/main/java/net/coderbot/iris/shaderpack/DimensionId.java rename to src/main/java/net/irisshaders/iris/shaderpack/DimensionId.java index fe17145777..7c66bac5b8 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/DimensionId.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/DimensionId.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; public class DimensionId { public static NamespacedId OVERWORLD = new NamespacedId("minecraft", "overworld"); diff --git a/src/main/java/net/irisshaders/iris/shaderpack/FilledIndirectPointer.java b/src/main/java/net/irisshaders/iris/shaderpack/FilledIndirectPointer.java new file mode 100644 index 0000000000..88d455f0e8 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/FilledIndirectPointer.java @@ -0,0 +1,12 @@ +package net.irisshaders.iris.shaderpack; + +import net.irisshaders.iris.gl.buffer.ShaderStorageBufferHolder; +import net.irisshaders.iris.shaderpack.properties.IndirectPointer; + +public record FilledIndirectPointer(int buffer, long offset) { + public static FilledIndirectPointer basedOff(ShaderStorageBufferHolder holder, IndirectPointer pointer) { + if (pointer == null || holder == null) return null; + + return new FilledIndirectPointer(holder.getBufferIndex(pointer.buffer()), pointer.offset()); + } +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java b/src/main/java/net/irisshaders/iris/shaderpack/IdMap.java similarity index 85% rename from src/main/java/net/coderbot/iris/shaderpack/IdMap.java rename to src/main/java/net/irisshaders/iris/shaderpack/IdMap.java index f84347057f..f410a00f54 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/IdMap.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/IdMap.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; @@ -8,14 +8,21 @@ import it.unimi.dsi.fastutil.objects.Object2IntMaps; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.materialmap.BlockEntry; -import net.coderbot.iris.shaderpack.materialmap.BlockRenderType; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; -import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor; +import net.fabricmc.loader.api.FabricLoader; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.shaderpack.materialmap.BlockEntry; +import net.irisshaders.iris.shaderpack.materialmap.BlockRenderType; +import net.irisshaders.iris.shaderpack.materialmap.LegacyIdMap; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.option.OrderBackedProperties; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor; import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -89,7 +96,8 @@ private static Optional loadProperties(Path shaderPath, String name, return Optional.empty(); } - String processed = PropertiesPreprocessor.preprocessSource(fileContents, shaderPackOptions, environmentDefines); + // TODO: This is the worst code I have ever made. Do not do this. + String processed = PropertiesPreprocessor.preprocessSource(fileContents, shaderPackOptions, environmentDefines).replaceAll("\\\\\\n\\s*\\n", " ").replaceAll("\\S\s*block\\.", "\nblock."); StringReader propertiesReader = new StringReader(processed); @@ -105,13 +113,22 @@ private static Optional loadProperties(Path shaderPath, String name, return Optional.empty(); } + if (Iris.getIrisConfig().areDebugOptionsEnabled()) { + ShaderPrinter.deleteIfClearing(); + try (OutputStream os = Files.newOutputStream(FabricLoader.getInstance().getGameDir().resolve("patched_shaders").resolve(name))) { + properties.store(new OutputStreamWriter(os, StandardCharsets.UTF_8), "Patched version of properties"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + return Optional.of(properties); } private static String readProperties(Path shaderPath, String name) { try { // ID maps should be encoded in ISO_8859_1. - return new String(Files.readAllBytes(shaderPath.resolve(name)), StandardCharsets.ISO_8859_1); + return Files.readString(shaderPath.resolve(name), StandardCharsets.ISO_8859_1); } catch (NoSuchFileException e) { Iris.logger.debug("An " + name + " file was not found in the current shaderpack"); @@ -219,7 +236,7 @@ private static Int2ObjectMap> parseBlockMap(Properties properti /** * Parses a render layer map. - * + *

    * This feature is used by Chocapic v9 and Wisdom Shaders. Otherwise, it is a rarely-used feature. */ private static Map parseRenderTypeMap(Properties properties, String keyPrefix, String fileName) { @@ -306,9 +323,9 @@ public boolean equals(Object o) { IdMap idMap = (IdMap) o; return Objects.equals(itemIdMap, idMap.itemIdMap) - && Objects.equals(entityIdMap, idMap.entityIdMap) - && Objects.equals(blockPropertiesMap, idMap.blockPropertiesMap) - && Objects.equals(blockRenderTypeMap, idMap.blockRenderTypeMap); + && Objects.equals(entityIdMap, idMap.entityIdMap) + && Objects.equals(blockPropertiesMap, idMap.blockPropertiesMap) + && Objects.equals(blockRenderTypeMap, idMap.blockRenderTypeMap); } @Override diff --git a/src/main/java/net/irisshaders/iris/shaderpack/ImageInformation.java b/src/main/java/net/irisshaders/iris/shaderpack/ImageInformation.java new file mode 100644 index 0000000000..3bb6bf96f9 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/ImageInformation.java @@ -0,0 +1,12 @@ +package net.irisshaders.iris.shaderpack; + +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.PixelFormat; +import net.irisshaders.iris.gl.texture.PixelType; +import net.irisshaders.iris.gl.texture.TextureType; + +public record ImageInformation(String name, String samplerName, TextureType target, PixelFormat format, + InternalTextureFormat internalTextureFormat, + PixelType type, int width, int height, int depth, boolean clear, boolean isRelative, + float relativeWidth, float relativeHeight) { +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/IrisDefines.java b/src/main/java/net/irisshaders/iris/shaderpack/IrisDefines.java similarity index 57% rename from src/main/java/net/coderbot/iris/shaderpack/IrisDefines.java rename to src/main/java/net/irisshaders/iris/shaderpack/IrisDefines.java index f6b9230587..83fc306ee3 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/IrisDefines.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/IrisDefines.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack; import com.google.common.collect.ImmutableList; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.shader.StandardMacros; -import net.coderbot.iris.parsing.BiomeCategories; -import net.coderbot.iris.uniforms.BiomeParameters; -import net.minecraft.world.level.biome.Biome; +import net.irisshaders.iris.gl.shader.StandardMacros; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.parsing.BiomeCategories; +import net.irisshaders.iris.uniforms.BiomeUniforms; import java.util.ArrayList; import java.util.List; @@ -25,16 +24,12 @@ private static void define(List defines, String key, String value) { public static ImmutableList createIrisReplacements() { ArrayList s = new ArrayList<>(StandardMacros.createStandardEnvironmentDefines()); - define(s, "PPT_NONE", "0"); - define(s, "PPT_RAIN", "1"); - define(s, "PPT_SNOW", "2"); - define(s, "BIOME_SWAMP_HILLS", "-1"); - BiomeParameters.getBiomeMap().forEach((biome, id) -> define(s, "BIOME_" + biome.location().getPath().toUpperCase(Locale.ROOT), String.valueOf(id))); + BiomeUniforms.getBiomeMap().forEach((biome, id) -> define(s, "BIOME_" + biome.location().getPath().toUpperCase(Locale.ROOT), String.valueOf(id))); BiomeCategories[] categories = BiomeCategories.values(); for (int i = 0; i < categories.length; i++) { - define(s, "CAT_" + categories[i].name().toUpperCase(Locale.ROOT), String.valueOf(i)); + define(s, "CAT_" + categories[i].name().toUpperCase(Locale.ROOT), String.valueOf(i)); } return ImmutableList.copyOf(s); diff --git a/src/main/java/net/coderbot/iris/shaderpack/LanguageMap.java b/src/main/java/net/irisshaders/iris/shaderpack/LanguageMap.java similarity index 91% rename from src/main/java/net/coderbot/iris/shaderpack/LanguageMap.java rename to src/main/java/net/irisshaders/iris/shaderpack/LanguageMap.java index 09797e6b00..2edac525e8 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/LanguageMap.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/LanguageMap.java @@ -1,19 +1,14 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Set; +import java.util.*; import java.util.stream.Stream; public class LanguageMap { diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java b/src/main/java/net/irisshaders/iris/shaderpack/ShaderPack.java similarity index 84% rename from src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java rename to src/main/java/net/irisshaders/iris/shaderpack/ShaderPack.java index 4660fcc4cf..d4104b73da 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShaderPack.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/ShaderPack.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; @@ -8,28 +8,34 @@ import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.colorspace.ColorSpace; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gui.FeatureMissingErrorScreen; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.coderbot.iris.gl.texture.TextureDefinition; -import net.coderbot.iris.shaderpack.include.AbsolutePackPath; -import net.coderbot.iris.shaderpack.include.IncludeGraph; -import net.coderbot.iris.shaderpack.include.IncludeProcessor; -import net.coderbot.iris.shaderpack.include.ShaderPackSourceNames; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; -import net.coderbot.iris.shaderpack.option.ProfileSet; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; -import net.coderbot.iris.shaderpack.option.menu.OptionMenuContainer; -import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; -import net.coderbot.iris.shaderpack.option.values.OptionValues; -import net.coderbot.iris.shaderpack.preprocessor.JcppProcessor; -import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor; -import net.coderbot.iris.shaderpack.texture.CustomTextureData; -import net.coderbot.iris.shaderpack.texture.TextureFilteringData; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.texture.TextureDefinition; +import net.irisshaders.iris.gui.FeatureMissingErrorScreen; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.pathways.colorspace.ColorSpace; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.include.IncludeGraph; +import net.irisshaders.iris.shaderpack.include.IncludeProcessor; +import net.irisshaders.iris.shaderpack.include.ShaderPackSourceNames; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; +import net.irisshaders.iris.shaderpack.option.OrderBackedProperties; +import net.irisshaders.iris.shaderpack.option.ProfileSet; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.option.menu.OptionMenuContainer; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.preprocessor.JcppProcessor; +import net.irisshaders.iris.shaderpack.preprocessor.PropertiesPreprocessor; +import net.irisshaders.iris.shaderpack.programs.ProgramSet; +import net.irisshaders.iris.shaderpack.programs.ProgramSetInterface; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; +import net.irisshaders.iris.shaderpack.texture.CustomTextureData; +import net.irisshaders.iris.shaderpack.texture.TextureFilteringData; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; @@ -37,7 +43,6 @@ import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; -import net.coderbot.iris.uniforms.custom.CustomUniforms; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; @@ -58,14 +63,12 @@ import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; -import java.util.stream.Stream; public class ShaderPack { private static final Gson GSON = new Gson(); - + public final CustomUniforms.Builder customUniforms; private final ProgramSet base; private final Map overrides; - private final IdMap idMap; private final LanguageMap languageMap; private final EnumMap> customTextureDataMap = new EnumMap<>(TextureStage.class); @@ -73,22 +76,19 @@ public class ShaderPack { private final CustomTextureData customNoiseTexture; private final ShaderPackOptions shaderPackOptions; private final OptionMenuContainer menuContainer; - private final ProfileSet.ProfileResult profile; private final String profileInfo; private final List irisCustomImages; private final Set activeFeatures; private final Function sourceProvider; private final ShaderProperties shaderProperties; - private List dimensionIds; + private final List dimensionIds; private Map dimensionMap; public ShaderPack(Path root, ImmutableList environmentDefines) throws IOException, IllegalStateException { this(root, Collections.emptyMap(), environmentDefines); } - public final CustomUniforms.Builder customUniforms; - /** * Reads a shader pack from the disk. * @@ -108,7 +108,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList potentialFileNames = ShaderPackSourceNames.POTENTIAL_STARTS; ShaderPackSourceNames.findPresentSources(starts, root, AbsolutePackPath.fromAbsolutePath("/"), - potentialFileNames); + potentialFileNames); dimensionIds = new ArrayList<>(); @@ -116,7 +116,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList dimensionIdCreator = loadProperties(root, "dimension.properties", environmentDefines).map(dimensionProperties -> { - hasDimensionIds[0] = dimensionProperties.size() > 0; + hasDimensionIds[0] = !dimensionProperties.isEmpty(); dimensionMap = parseDimensionMap(dimensionProperties, "dimension.", "dimension.properties"); return parseDimensionIds(dimensionProperties, "dimension."); }).orElse(new ArrayList<>()); @@ -163,10 +163,15 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList finalEnvironmentDefines = environmentDefines; + List finalEnvironmentDefines = new ArrayList<>(List.copyOf(environmentDefines)); + for (FeatureFlags flag : FeatureFlags.values()) { + if (flag.isUsable()) { + finalEnvironmentDefines.add(new StringPair("IRIS_FEATURE_" + flag.name(), "")); + } + } this.shaderProperties = loadProperties(root, "shaders.properties") - .map(source -> new ShaderProperties(source, shaderPackOptions, finalEnvironmentDefines)) - .orElseGet(ShaderProperties::empty); + .map(source -> new ShaderProperties(source, shaderPackOptions, finalEnvironmentDefines)) + .orElseGet(ShaderProperties::empty); activeFeatures = new HashSet<>(); for (int i = 0; i < shaderProperties.getRequiredFeatureFlags().size(); i++) { @@ -185,7 +190,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList invalidFlagList = shaderProperties.getRequiredFeatureFlags().stream().filter(FeatureFlags::isInvalid).map(FeatureFlags::getValue).collect(Collectors.toList()); - List invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).collect(Collectors.toList()); + List invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).toList(); if (!invalidFeatureFlags.isEmpty()) { if (Minecraft.getInstance().screen instanceof ShaderPackScreen) { @@ -198,8 +203,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList newEnvDefines = new ArrayList<>(); - environmentDefines.forEach(newEnvDefines::add); + List newEnvDefines = new ArrayList<>(environmentDefines); if (shaderProperties.supportsColorCorrection().orElse(false)) { for (ColorSpace space : ColorSpace.values()) { @@ -207,12 +211,11 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList optionalFeatureFlags = shaderProperties.getOptionalFeatureFlags().stream().filter(flag -> !FeatureFlags.isInvalid(flag)).collect(Collectors.toList()); + List optionalFeatureFlags = shaderProperties.getOptionalFeatureFlags().stream().filter(flag -> !FeatureFlags.isInvalid(flag)).toList(); if (!optionalFeatureFlags.isEmpty()) { optionalFeatureFlags.forEach(flag -> Iris.logger.warn("Found flag " + flag)); optionalFeatureFlags.forEach(flag -> newEnvDefines.add(new StringPair("IRIS_FEATURE_" + flag, ""))); - } environmentDefines = ImmutableList.copyOf(newEnvDefines); @@ -237,7 +240,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList p.optionValues).orElse(new HashMap<>())); + this.shaderPackOptions.getOptionSet(), this.profile.current.map(p -> p.optionValues).orElse(new HashMap<>())); int userOptionsChanged = this.shaderPackOptions.getOptionValues().getOptionsChanged() - profileOptions.getOptionsChanged(); @@ -318,7 +321,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList { try { @@ -330,6 +333,7 @@ public ShaderPack(Path root, Map changedConfigs, ImmutableList loadProperties(Path shaderPath, String name, return Optional.of(properties); } - private List parseDimensionIds(Properties dimensionProperties, String keyPrefix) { - List names = new ArrayList<>(); - - dimensionProperties.forEach((keyObject, value) -> { - String key = (String) keyObject; - if (!key.startsWith(keyPrefix)) { - // Not a valid line, ignore it - return; - } - - key = key.substring(keyPrefix.length()); - - names.add(key); - }); - - return names; - } - private static Map parseDimensionMap(Properties properties, String keyPrefix, String fileName) { Map overrides = new Object2ObjectArrayMap<>(); @@ -402,14 +388,6 @@ private static Map parseDimensionMap(Properties properties return overrides; } - private String getCurrentProfileName() { - return profile.current.map(p -> p.name).orElse("Custom"); - } - - public String getProfileInfo() { - return profileInfo; - } - @Nullable private static ProgramSet loadOverrides(boolean has, AbsolutePackPath path, Function sourceProvider, ShaderProperties shaderProperties, ShaderPack pack) { @@ -430,6 +408,47 @@ private static Optional loadProperties(Path shaderPath, String name) { return Optional.of(fileContents); } + private static String readProperties(Path shaderPath, String name) { + try { + // Property files should be encoded in ISO_8859_1. + return Files.readString(shaderPath.resolve(name), StandardCharsets.ISO_8859_1); + } catch (NoSuchFileException e) { + Iris.logger.debug("An " + name + " file was not found in the current shaderpack"); + + return null; + } catch (IOException e) { + Iris.logger.error("An IOException occurred reading " + name + " from the current shaderpack", e); + + return null; + } + } + + private List parseDimensionIds(Properties dimensionProperties, String keyPrefix) { + List names = new ArrayList<>(); + + dimensionProperties.forEach((keyObject, value) -> { + String key = (String) keyObject; + if (!key.startsWith(keyPrefix)) { + // Not a valid line, ignore it + return; + } + + key = key.substring(keyPrefix.length()); + + names.add(key); + }); + + return names; + } + + private String getCurrentProfileName() { + return profile.current.map(p -> p.name).orElse("Custom"); + } + + public String getProfileInfo() { + return profileInfo; + } + // TODO: Implement raw texture data types public CustomTextureData readTexture(Path root, TextureDefinition definition) throws IOException { CustomTextureData customTextureData; @@ -480,24 +499,18 @@ public CustomTextureData readTexture(Path root, TextureDefinition definition) th if (definition instanceof TextureDefinition.PNGDefinition) { customTextureData = new CustomTextureData.PngData(new TextureFilteringData(blur, clamp), content); - } else if (definition instanceof TextureDefinition.RawDefinition) { - TextureDefinition.RawDefinition rawDefinition = (TextureDefinition.RawDefinition) definition; - switch (rawDefinition.getTarget()) { - case TEXTURE_1D: - customTextureData = new CustomTextureData.RawData1D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX()); - break; - case TEXTURE_2D: - customTextureData = new CustomTextureData.RawData2D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY()); - break; - case TEXTURE_3D: - customTextureData = new CustomTextureData.RawData3D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY(), rawDefinition.getSizeZ()); - break; - case TEXTURE_RECTANGLE: - customTextureData = new CustomTextureData.RawDataRect(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY()); - break; - default: - throw new IllegalStateException("Unknown texture type: " + rawDefinition.getTarget()); - } + } else if (definition instanceof TextureDefinition.RawDefinition rawDefinition) { + customTextureData = switch (rawDefinition.getTarget()) { + case TEXTURE_1D -> + new CustomTextureData.RawData1D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX()); + case TEXTURE_2D -> + new CustomTextureData.RawData2D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY()); + case TEXTURE_3D -> + new CustomTextureData.RawData3D(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY(), rawDefinition.getSizeZ()); + case TEXTURE_RECTANGLE -> + new CustomTextureData.RawDataRect(content, new TextureFilteringData(blur, clamp), rawDefinition.getInternalFormat(), rawDefinition.getFormat(), rawDefinition.getPixelType(), rawDefinition.getSizeX(), rawDefinition.getSizeY()); + default -> throw new IllegalStateException("Unknown texture type: " + rawDefinition.getTarget()); + }; } else { customTextureData = null; } @@ -512,21 +525,6 @@ private JsonObject loadMcMeta(Path mcMetaPath) throws IOException, JsonParseExce } } - private static String readProperties(Path shaderPath, String name) { - try { - // Property files should be encoded in ISO_8859_1. - return new String(Files.readAllBytes(shaderPath.resolve(name)), StandardCharsets.ISO_8859_1); - } catch (NoSuchFileException e) { - Iris.logger.debug("An " + name + " file was not found in the current shaderpack"); - - return null; - } catch (IOException e) { - Iris.logger.error("An IOException occurred reading " + name + " from the current shaderpack", e); - - return null; - } - } - public ProgramSet getProgramSet(NamespacedId dimension) { ProgramSetInterface overrides; @@ -591,7 +589,7 @@ public OptionMenuContainer getMenuContainer() { return menuContainer; } - public boolean hasFeature(FeatureFlags feature) { + public boolean hasFeature(FeatureFlags feature) { return activeFeatures.contains(feature); - } + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/discovery/ShaderpackDirectoryManager.java b/src/main/java/net/irisshaders/iris/shaderpack/discovery/ShaderpackDirectoryManager.java similarity index 79% rename from src/main/java/net/coderbot/iris/shaderpack/discovery/ShaderpackDirectoryManager.java rename to src/main/java/net/irisshaders/iris/shaderpack/discovery/ShaderpackDirectoryManager.java index fd427cb3dd..97340231ae 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/discovery/ShaderpackDirectoryManager.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/discovery/ShaderpackDirectoryManager.java @@ -1,12 +1,11 @@ -package net.coderbot.iris.shaderpack.discovery; +package net.irisshaders.iris.shaderpack.discovery; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @@ -19,6 +18,26 @@ public ShaderpackDirectoryManager(Path root) { this.root = root; } + /** + * Straightforward method to use section-sign based chat formatting from a String + */ + private static String removeFormatting(String formatted) { + char[] original = formatted.toCharArray(); + char[] cleaned = new char[original.length]; + int c = 0; + + for (int i = 0; i < original.length; i++) { + // check if it's a section sign + if (original[i] == '§') { + i++; + } else { + cleaned[c++] = original[i]; + } + } + + return new String(cleaned, 0, c); + } + public void copyPackIntoDirectory(String name, Path source) throws IOException { Path target = Iris.getShaderpacksDirectory().resolve(name); @@ -34,7 +53,7 @@ public void copyPackIntoDirectory(String name, Path source) throws IOException { // Copy all sub folders, collected as a list in order to prevent issues with non-ordered sets try (Stream stream = Files.walk(source)) { - for (Path p : stream.filter(Files::isDirectory).collect(Collectors.toList())) { + for (Path p : stream.filter(Files::isDirectory).toList()) { Path folder = source.relativize(p); if (Files.exists(folder)) { @@ -63,41 +82,31 @@ public List enumerate() throws IOException { // // We also ignore chat formatting characters when sorting - some shader packs include chat // formatting in the file name so that they have fancy text when displayed in the shaders list. + // If debug mode is on, show unzipped packs above zipped ones. + + boolean debug = Iris.getIrisConfig().areDebugOptionsEnabled(); + Comparator baseComparator = String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.naturalOrder()); - Comparator comparator = (a, b) -> { - a = removeFormatting(a); - b = removeFormatting(b); + Comparator comparator = (a, b) -> { + if (debug) { + if (Files.isDirectory(a)) { + if (!Files.isDirectory(b)) return -1; + } else if (Files.isDirectory(b)) { + if (!Files.isDirectory(a)) return 1; + } + } - return baseComparator.compare(a, b); + return baseComparator.compare(removeFormatting(a.getFileName().toString()), removeFormatting(b.getFileName().toString())); }; try (Stream list = Files.list(root)) { return list.filter(Iris::isValidToShowPack) + .sorted(comparator) .map(path -> path.getFileName().toString()) - .sorted(comparator).collect(Collectors.toList()); + .collect(Collectors.toList()); } } - /** - * Straightforward method to use section-sign based chat formatting from a String - */ - private static String removeFormatting(String formatted) { - char[] original = formatted.toCharArray(); - char[] cleaned = new char[original.length]; - int c = 0; - - for (int i = 0; i < original.length; i++) { - // check if it's a section sign - if (original[i] == '\u00a7') { - i++; - } else { - cleaned[c++] = original[i]; - } - } - - return new String(cleaned, 0, c); - } - public URI getDirectoryUri() { return root.toUri(); } diff --git a/src/main/java/net/irisshaders/iris/shaderpack/error/RusticError.java b/src/main/java/net/irisshaders/iris/shaderpack/error/RusticError.java new file mode 100644 index 0000000000..2dfc2a48b0 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/error/RusticError.java @@ -0,0 +1,18 @@ +package net.irisshaders.iris.shaderpack.error; + +import org.apache.commons.lang3.StringUtils; + +public record RusticError(String severity, String message, String detailMessage, String file, int lineNumber, + String badLine) { + + + @Override + public String toString() { + return severity + ": " + message + "\n" + + " --> " + file + ":" + lineNumber + "\n" + + " |\n" + + " | " + badLine + "\n" + + " | " + StringUtils.repeat('^', badLine.length()) + " " + detailMessage + "\n" + + " |"; + } +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/include/AbsolutePackPath.java b/src/main/java/net/irisshaders/iris/shaderpack/include/AbsolutePackPath.java similarity index 98% rename from src/main/java/net/coderbot/iris/shaderpack/include/AbsolutePackPath.java rename to src/main/java/net/irisshaders/iris/shaderpack/include/AbsolutePackPath.java index 5ab3183ec8..2ed0533126 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/include/AbsolutePackPath.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/include/AbsolutePackPath.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.include; +package net.irisshaders.iris.shaderpack.include; import java.nio.file.Path; import java.util.ArrayList; @@ -19,40 +19,6 @@ public static AbsolutePackPath fromAbsolutePath(String absolutePath) { return new AbsolutePackPath(normalizeAbsolutePath(absolutePath)); } - public Optional parent() { - if (path.equals("/")) { - return Optional.empty(); - } - - int lastSlash = path.lastIndexOf('/'); - - return Optional.of(new AbsolutePackPath(path.substring(0, lastSlash))); - } - - public AbsolutePackPath resolve(String path) { - if (path.startsWith("/")) { - return fromAbsolutePath(path); - } - - String merged; - - if (!this.path.endsWith("/") & !path.startsWith("/")) { - merged = this.path + "/" + path; - } else { - merged = this.path + path; - } - - return fromAbsolutePath(merged); - } - - public Path resolved(Path root) { - if (path.equals("/")) { - return root; - } - - return root.resolve(path.substring(1)); - } - private static String normalizeAbsolutePath(String path) { if (!path.startsWith("/")) { throw new IllegalArgumentException("Not an absolute path: " + path); @@ -89,6 +55,40 @@ private static String normalizeAbsolutePath(String path) { return normalized.toString(); } + public Optional parent() { + if (path.equals("/")) { + return Optional.empty(); + } + + int lastSlash = path.lastIndexOf('/'); + + return Optional.of(new AbsolutePackPath(path.substring(0, lastSlash))); + } + + public AbsolutePackPath resolve(String path) { + if (path.startsWith("/")) { + return fromAbsolutePath(path); + } + + String merged; + + if (!this.path.endsWith("/") & !path.startsWith("/")) { + merged = this.path + "/" + path; + } else { + merged = this.path + path; + } + + return fromAbsolutePath(merged); + } + + public Path resolved(Path root) { + if (path.equals("/")) { + return root; + } + + return root.resolve(path.substring(1)); + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/src/main/java/net/coderbot/iris/shaderpack/include/FileNode.java b/src/main/java/net/irisshaders/iris/shaderpack/include/FileNode.java similarity index 93% rename from src/main/java/net/coderbot/iris/shaderpack/include/FileNode.java rename to src/main/java/net/irisshaders/iris/shaderpack/include/FileNode.java index 8a87fc0443..aa62d27aef 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/include/FileNode.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/include/FileNode.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.include; +package net.irisshaders.iris.shaderpack.include; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.shaderpack.transform.line.LineTransform; +import net.irisshaders.iris.shaderpack.transform.line.LineTransform; import java.util.Objects; @@ -25,43 +25,11 @@ public FileNode(AbsolutePackPath path, ImmutableList lines) { this.lines = lines; AbsolutePackPath currentDirectory = path.parent().orElseThrow( - () -> new IllegalArgumentException("Not a valid shader file name: " + path)); + () -> new IllegalArgumentException("Not a valid shader file name: " + path)); this.includes = findIncludes(currentDirectory, lines); } - public AbsolutePackPath getPath() { - return path; - } - - public ImmutableList getLines() { - return lines; - } - - public ImmutableMap getIncludes() { - return includes; - } - - public FileNode map(LineTransform transform) { - ImmutableList.Builder newLines = ImmutableList.builder(); - int index = 0; - - for (String line : lines) { - String transformedLine = transform.transform(index, line); - - if (includes.containsKey(index)) { - if (!Objects.equals(line, transformedLine)) { - throw new IllegalStateException("Attempted to modify an #include line in LineTransform."); - } - } - - newLines.add(transformedLine); - index += 1; - } - - return new FileNode(path, newLines.build(), includes); - } - private static ImmutableMap findIncludes(AbsolutePackPath currentDirectory, ImmutableList lines) { ImmutableMap.Builder foundIncludes = ImmutableMap.builder(); @@ -95,4 +63,36 @@ private static ImmutableMap findIncludes(AbsolutePack return foundIncludes.build(); } + + public AbsolutePackPath getPath() { + return path; + } + + public ImmutableList getLines() { + return lines; + } + + public ImmutableMap getIncludes() { + return includes; + } + + public FileNode map(LineTransform transform) { + ImmutableList.Builder newLines = ImmutableList.builder(); + int index = 0; + + for (String line : lines) { + String transformedLine = transform.transform(index, line); + + if (includes.containsKey(index)) { + if (!Objects.equals(line, transformedLine)) { + throw new IllegalStateException("Attempted to modify an #include line in LineTransform."); + } + } + + newLines.add(transformedLine); + index += 1; + } + + return new FileNode(path, newLines.build(), includes); + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/include/IncludeGraph.java b/src/main/java/net/irisshaders/iris/shaderpack/include/IncludeGraph.java similarity index 93% rename from src/main/java/net/coderbot/iris/shaderpack/include/IncludeGraph.java rename to src/main/java/net/irisshaders/iris/shaderpack/include/IncludeGraph.java index e1188115b2..aec33ae3e4 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/include/IncludeGraph.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/include/IncludeGraph.java @@ -1,13 +1,12 @@ -package net.coderbot.iris.shaderpack.include; +package net.irisshaders.iris.shaderpack.include; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.error.RusticError; -import net.coderbot.iris.shaderpack.transform.line.LineTransform; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.error.RusticError; +import net.irisshaders.iris.shaderpack.transform.line.LineTransform; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; @@ -144,6 +143,10 @@ public IncludeGraph(Path root, ImmutableList startingPaths) { detectCycle(); } + private static String readFile(Path path) throws IOException { + return Files.readString(path); + } + private void detectCycle() { List cycle = new ArrayList<>(); Set visited = new HashSet<>(); @@ -186,8 +189,11 @@ private void detectCycle() { } error.append( - "\n = note: #include directives are resolved before any other preprocessor directives, any form of #include guard will not work" + - "\n = note: other cycles may still exist, only the first detected non-trivial cycle will be reported"); + """ + note: #include directives are resolved before any other preprocessor directives, any form of #include guard will not work + + note: other cycles may still exist, only the first detected non-trivial cycle will be reported + """); // TODO: Expose this to the caller (more semantic error handling) Iris.logger.error(error.toString()); @@ -253,8 +259,4 @@ public IncludeGraph map(Function transformProvi public ImmutableMap getFailures() { return failures; } - - private static String readFile(Path path) throws IOException { - return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); - } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/include/IncludeProcessor.java b/src/main/java/net/irisshaders/iris/shaderpack/include/IncludeProcessor.java similarity index 96% rename from src/main/java/net/coderbot/iris/shaderpack/include/IncludeProcessor.java rename to src/main/java/net/irisshaders/iris/shaderpack/include/IncludeProcessor.java index b06db48cb4..7b9afc01d9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/include/IncludeProcessor.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/include/IncludeProcessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.include; +package net.irisshaders.iris.shaderpack.include; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; diff --git a/src/main/java/net/coderbot/iris/shaderpack/include/ShaderPackSourceNames.java b/src/main/java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java similarity index 88% rename from src/main/java/net/coderbot/iris/shaderpack/include/ShaderPackSourceNames.java rename to src/main/java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java index 31556ab7c9..a15e6bb921 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/include/ShaderPackSourceNames.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/include/ShaderPackSourceNames.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.include; +package net.irisshaders.iris.shaderpack.include; import com.google.common.collect.ImmutableList; -import net.coderbot.iris.shaderpack.loading.ProgramArrayId; -import net.coderbot.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.loading.ProgramArrayId; +import net.irisshaders.iris.shaderpack.loading.ProgramId; import java.io.IOException; import java.nio.file.Files; @@ -18,7 +18,7 @@ public class ShaderPackSourceNames { public static final ImmutableList POTENTIAL_STARTS = findPotentialStarts(); public static boolean findPresentSources(ImmutableList.Builder starts, Path packRoot, - AbsolutePackPath directory, ImmutableList candidates) throws IOException { + AbsolutePackPath directory, ImmutableList candidates) throws IOException { Path directoryPath = directory.resolved(packRoot); if (!Files.exists(directoryPath)) { @@ -30,8 +30,8 @@ public static boolean findPresentSources(ImmutableList.Builder Set found; try (Stream stream = Files.list(directoryPath)) { found = stream - .map(path -> path.getFileName().toString()) - .collect(Collectors.toSet()); + .map(path -> path.getFileName().toString()) + .collect(Collectors.toSet()); } for (String candidate : candidates) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramArrayId.java b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramArrayId.java similarity index 92% rename from src/main/java/net/coderbot/iris/shaderpack/loading/ProgramArrayId.java rename to src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramArrayId.java index 975faa3410..de9ac5f4dd 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramArrayId.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramArrayId.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.loading; +package net.irisshaders.iris.shaderpack.loading; public enum ProgramArrayId { Setup(ProgramGroup.Setup, 100), diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramGroup.java b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramGroup.java similarity index 82% rename from src/main/java/net/coderbot/iris/shaderpack/loading/ProgramGroup.java rename to src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramGroup.java index 275f7db650..8292d84cbd 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramGroup.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramGroup.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.loading; +package net.irisshaders.iris.shaderpack.loading; public enum ProgramGroup { Setup("setup"), @@ -9,8 +9,8 @@ public enum ProgramGroup { Gbuffers("gbuffers"), Deferred("deferred"), Composite("composite"), - Final("final") - ; + Final("final"), + Dh("dh"); private final String baseName; diff --git a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramId.java similarity index 85% rename from src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java rename to src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramId.java index c96d31ea4a..71651358f6 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/loading/ProgramId.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/loading/ProgramId.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.loading; +package net.irisshaders.iris.shaderpack.loading; -import net.coderbot.iris.gl.blending.BlendMode; -import net.coderbot.iris.gl.blending.BlendModeFunction; -import net.coderbot.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BlendMode; +import net.irisshaders.iris.gl.blending.BlendModeFunction; +import net.irisshaders.iris.gl.blending.BlendModeOverride; import java.util.Objects; import java.util.Optional; @@ -38,12 +38,15 @@ public enum ProgramId { EntitiesGlowing(ProgramGroup.Gbuffers, "entities_glowing", Entities), ArmorGlint(ProgramGroup.Gbuffers, "armor_glint", Textured), SpiderEyes(ProgramGroup.Gbuffers, "spidereyes", Textured, - new BlendModeOverride(new BlendMode(BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId(), BlendModeFunction.ONE.getGlId()))), + new BlendModeOverride(new BlendMode(BlendModeFunction.SRC_ALPHA.getGlId(), BlendModeFunction.ONE.getGlId(), BlendModeFunction.ZERO.getGlId(), BlendModeFunction.ONE.getGlId()))), Hand(ProgramGroup.Gbuffers, "hand", TexturedLit), Weather(ProgramGroup.Gbuffers, "weather", TexturedLit), Water(ProgramGroup.Gbuffers, "water", Terrain), HandWater(ProgramGroup.Gbuffers, "hand_water", Hand), + DhTerrain(ProgramGroup.Dh, "terrain"), + DhWater(ProgramGroup.Dh, "water", DhTerrain), + DhShadow(ProgramGroup.Dh, "shadow"), Final(ProgramGroup.Final, ""), ; diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockEntry.java similarity index 76% rename from src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockEntry.java index dc02fce407..d2114a0247 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockEntry.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockEntry.java @@ -1,21 +1,13 @@ -package net.coderbot.iris.shaderpack.materialmap; +package net.irisshaders.iris.shaderpack.materialmap; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.Objects; -public class BlockEntry { - private final NamespacedId id; - private final Map propertyPredicates; - - public BlockEntry(NamespacedId id, Map propertyPredicates) { - this.id = id; - this.propertyPredicates = propertyPredicates; - } +public record BlockEntry(NamespacedId id, Map propertyPredicates) { /** * Parses a block ID entry. @@ -78,7 +70,7 @@ public static BlockEntry parse(@NotNull String entry) { if (propertyParts.length != 2) { Iris.logger.warn("Warning: the block ID map entry \"" + entry + "\" could not be fully parsed:"); Iris.logger.warn("- Block state property filters must be of the form \"key=value\", but " - + splitStates[index] + " is not of that form!"); + + splitStates[index] + " is not of that form!"); // Continue and ignore the invalid entry. continue; @@ -90,24 +82,5 @@ public static BlockEntry parse(@NotNull String entry) { return new BlockEntry(id, map); } - public NamespacedId getId() { - return id; - } - - public Map getPropertyPredicates() { - return propertyPredicates; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - BlockEntry that = (BlockEntry) o; - return Objects.equals(id, that.id) && Objects.equals(propertyPredicates, that.propertyPredicates); - } - @Override - public int hashCode() { - return Objects.hash(id, propertyPredicates); - } } diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockMaterialMapping.java similarity index 72% rename from src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockMaterialMapping.java index 4cc7554275..47b8b6c802 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockMaterialMapping.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockMaterialMapping.java @@ -1,16 +1,11 @@ -package net.coderbot.iris.block_rendering; +package net.irisshaders.iris.shaderpack.materialmap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.materialmap.BlockEntry; -import net.coderbot.iris.shaderpack.materialmap.BlockRenderType; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; +import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; +import net.irisshaders.iris.Iris; import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Block; @@ -18,13 +13,10 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.Property; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.registries.ForgeRegistries; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; public class BlockMaterialMapping { public static Object2IntMap createBlockStateIdMap(Int2ObjectMap> blockPropertiesMap) { @@ -39,15 +31,15 @@ public static Object2IntMap createBlockStateIdMap(Int2ObjectMap, ChunkRenderTypeSet> createBlockTypeMap(Map blockPropertiesMap) { - Map, ChunkRenderTypeSet> blockTypeIds = new Object2ObjectOpenHashMap<>(); + public static Map createBlockTypeMap(Map blockPropertiesMap) { + Map blockTypeIds = new Reference2ReferenceOpenHashMap<>(); blockPropertiesMap.forEach((id, blockType) -> { ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); - Holder.Reference block = ForgeRegistries.BLOCKS.getDelegateOrThrow(resourceLocation); + Block block = BuiltInRegistries.BLOCK.get(resourceLocation); - blockTypeIds.put(block, ChunkRenderTypeSet.of(convertBlockToRenderType(blockType))); + blockTypeIds.put(block, convertBlockToRenderType(blockType)); }); return blockTypeIds; @@ -58,33 +50,32 @@ private static RenderType convertBlockToRenderType(BlockRenderType type) { return null; } - switch (type) { - case SOLID: return RenderType.solid(); - case CUTOUT: return RenderType.cutout(); - case CUTOUT_MIPPED: return RenderType.cutoutMipped(); - case TRANSLUCENT: return RenderType.translucent(); - default: return null; - } + return switch (type) { + case SOLID -> RenderType.solid(); + case CUTOUT -> RenderType.cutout(); + case CUTOUT_MIPPED -> RenderType.cutoutMipped(); + case TRANSLUCENT -> RenderType.translucent(); + }; } private static void addBlockStates(BlockEntry entry, Object2IntMap idMap, int intId) { - NamespacedId id = entry.getId(); - ResourceLocation resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); - - Optional> delegateOpt = ForgeRegistries.BLOCKS.getDelegate(resourceLocation); - - // If the block doesn't exist, by default the registry will return AIR. That probably isn't what we want. - if (delegateOpt.isEmpty() || !delegateOpt.get().isBound()) { - return; + NamespacedId id = entry.id(); + ResourceLocation resourceLocation; + try { + resourceLocation = new ResourceLocation(id.getNamespace(), id.getName()); + } catch (Exception exception) { + throw new IllegalStateException("Failed to get entry for " + intId, exception); } - Block block = delegateOpt.get().get(); + Block block = BuiltInRegistries.BLOCK.get(resourceLocation); + // If the block doesn't exist, by default the registry will return AIR. That probably isn't what we want. + // TODO: Assuming that Registry.BLOCK.getDefaultId() == "minecraft:air" here if (block == Blocks.AIR) { return; } - Map propertyPredicates = entry.getPropertyPredicates(); + Map propertyPredicates = entry.propertyPredicates(); if (propertyPredicates.isEmpty()) { // Just add all the states if there aren't any predicates diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockRenderType.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockRenderType.java similarity index 67% rename from src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockRenderType.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockRenderType.java index b2e2525ff1..bb88036e45 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/BlockRenderType.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/BlockRenderType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.materialmap; +package net.irisshaders.iris.shaderpack.materialmap; import java.util.Optional; @@ -6,7 +6,7 @@ * Defines the possible render types for blocks. * * @see - * the corresponding OptiFine documentation. + * the corresponding OptiFine documentation. */ public enum BlockRenderType { /** @@ -30,17 +30,12 @@ public enum BlockRenderType { TRANSLUCENT; public static Optional fromString(String name) { - switch (name) { - case "solid": - return Optional.of(SOLID); - case "cutout": - return Optional.of(CUTOUT); - case "cutout_mipped": - return Optional.of(CUTOUT_MIPPED); - case "translucent": - return Optional.of(TRANSLUCENT); - default: - return Optional.empty(); - } + return switch (name) { + case "solid" -> Optional.of(SOLID); + case "cutout" -> Optional.of(CUTOUT); + case "cutout_mipped" -> Optional.of(CUTOUT_MIPPED); + case "translucent" -> Optional.of(TRANSLUCENT); + default -> Optional.empty(); + }; } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/LegacyIdMap.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/LegacyIdMap.java similarity index 80% rename from src/main/java/net/coderbot/iris/shaderpack/LegacyIdMap.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/LegacyIdMap.java index 73a7d5e4b0..bddc1bca11 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/LegacyIdMap.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/LegacyIdMap.java @@ -1,10 +1,8 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.materialmap; import com.google.common.collect.ImmutableList; import it.unimi.dsi.fastutil.Function; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import net.coderbot.iris.shaderpack.materialmap.BlockEntry; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import java.util.ArrayList; import java.util.Arrays; @@ -13,11 +11,11 @@ public class LegacyIdMap { private static final ImmutableList COLORS = - ImmutableList.of("white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", - "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"); + ImmutableList.of("white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", + "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"); private static final ImmutableList WOOD_TYPES = - ImmutableList.of("oak", "birch", "jungle", "spruce", "acacia", "dark_oak"); + ImmutableList.of("oak", "birch", "jungle", "spruce", "acacia", "dark_oak"); public static void addLegacyValues(Int2ObjectMap> blockIdMap) { add(blockIdMap, 1, block("stone"), block("granite"), block("diorite"), block("andesite")); @@ -60,14 +58,14 @@ public static void addLegacyValues(Int2ObjectMap> blockIdMap) { // Small flowers add(blockIdMap, 37, block("dandelion"), block("poppy"), block("blue_orchid"), - block("allium"), block("azure_bluet"), block("red_tulip"), block("pink_tulip"), - block("white_tulip"), block("orange_tulip"), block("oxeye_daisy"), - block("cornflower"), block("lily_of_the_valley"), block("wither_rose")); + block("allium"), block("azure_bluet"), block("red_tulip"), block("pink_tulip"), + block("white_tulip"), block("orange_tulip"), block("oxeye_daisy"), + block("cornflower"), block("lily_of_the_valley"), block("wither_rose")); // Big tall grass / flowers // Also include seagrass here add(blockIdMap, 175, block("sunflower"), block("lilac"), block("tall_grass"), - block("large_fern"), block("rose_bush"), block("peony"), block("tall_seagrass")); + block("large_fern"), block("rose_bush"), block("peony"), block("tall_seagrass")); // Fire add(blockIdMap, 51, block("fire")); diff --git a/src/main/java/net/coderbot/iris/shaderpack/materialmap/NamespacedId.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/NamespacedId.java similarity index 90% rename from src/main/java/net/coderbot/iris/shaderpack/materialmap/NamespacedId.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/NamespacedId.java index 6a4cb3ce13..2c47e6b234 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/materialmap/NamespacedId.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/NamespacedId.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.materialmap; +package net.irisshaders.iris.shaderpack.materialmap; import java.util.Objects; @@ -58,8 +58,8 @@ public int hashCode() { @Override public String toString() { return "NamespacedId{" + - "namespace='" + namespace + '\'' + - ", name='" + name + '\'' + - '}'; + "namespace='" + namespace + '\'' + + ", name='" + name + '\'' + + '}'; } } diff --git a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java similarity index 85% rename from src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java rename to src/main/java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java index 04bb07014b..351858f0b7 100644 --- a/src/main/java/net/coderbot/iris/block_rendering/BlockRenderingSettings.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/materialmap/WorldRenderingSettings.java @@ -1,23 +1,20 @@ -package net.coderbot.iris.block_rendering; +package net.irisshaders.iris.shaderpack.materialmap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntMap; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Holder; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; import org.jetbrains.annotations.Nullable; import java.util.Map; -public class BlockRenderingSettings { - public static final BlockRenderingSettings INSTANCE = new BlockRenderingSettings(); +public class WorldRenderingSettings { + public static final WorldRenderingSettings INSTANCE = new WorldRenderingSettings(); private boolean reloadRequired; private Object2IntMap blockStateIds; - private Map, ChunkRenderTypeSet> blockTypeIds; + private Map blockTypeIds; private Object2IntFunction entityIds; private Object2IntFunction itemIds; private float ambientOcclusionLevel; @@ -28,7 +25,7 @@ public class BlockRenderingSettings { private boolean separateEntityDraws; private boolean voxelizeLightBlocks; - public BlockRenderingSettings() { + public WorldRenderingSettings() { reloadRequired = false; blockStateIds = null; blockTypeIds = null; @@ -54,22 +51,6 @@ public Object2IntMap getBlockStateIds() { return blockStateIds; } - @Nullable - public Map, ChunkRenderTypeSet> getBlockTypeIds() { - return blockTypeIds; - } - - // TODO (coderbot): This doesn't belong here. But I couldn't think of a nicer place to put it. - @Nullable - public Object2IntFunction getEntityIds() { - return entityIds; - } - - @Nullable - public Object2IntFunction getItemIds() { - return itemIds; - } - public void setBlockStateIds(Object2IntMap blockStateIds) { if (this.blockStateIds != null && this.blockStateIds.equals(blockStateIds)) { return; @@ -79,7 +60,12 @@ public void setBlockStateIds(Object2IntMap blockStateIds) { this.blockStateIds = blockStateIds; } - public void setBlockTypeIds(Map, ChunkRenderTypeSet> blockTypeIds) { + @Nullable + public Map getBlockTypeIds() { + return blockTypeIds; + } + + public void setBlockTypeIds(Map blockTypeIds) { if (this.blockTypeIds != null && this.blockTypeIds.equals(blockTypeIds)) { return; } @@ -88,12 +74,22 @@ public void setBlockTypeIds(Map, ChunkRenderTypeSet> blo this.blockTypeIds = blockTypeIds; } + @Nullable + public Object2IntFunction getEntityIds() { + return entityIds; + } + public void setEntityIds(Object2IntFunction entityIds) { // note: no reload needed, entities are rebuilt every frame. this.entityIds = entityIds; this.hasVillagerConversionId = entityIds.containsKey(new NamespacedId("minecraft", "zombie_villager_converting")); } + @Nullable + public Object2IntFunction getItemIds() { + return itemIds; + } + public void setItemIds(Object2IntFunction itemIds) { // note: no reload needed, entities are rebuilt every frame. this.itemIds = itemIds; @@ -164,9 +160,9 @@ public void setVoxelizeLightBlocks(boolean voxelizeLightBlocks) { this.voxelizeLightBlocks = voxelizeLightBlocks; } - public boolean shouldSeparateEntityDraws() { + public boolean shouldSeparateEntityDraws() { return separateEntityDraws; - } + } public void setSeparateEntityDraws(boolean separateEntityDraws) { this.separateEntityDraws = separateEntityDraws; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/BaseOption.java b/src/main/java/net/irisshaders/iris/shaderpack/option/BaseOption.java similarity index 93% rename from src/main/java/net/coderbot/iris/shaderpack/option/BaseOption.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/BaseOption.java index f1b3615ab0..772a3784a2 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/BaseOption.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/BaseOption.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/BooleanOption.java b/src/main/java/net/irisshaders/iris/shaderpack/option/BooleanOption.java similarity index 72% rename from src/main/java/net/coderbot/iris/shaderpack/option/BooleanOption.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/BooleanOption.java index 089837b833..69fd8afb61 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/BooleanOption.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/BooleanOption.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; public final class BooleanOption extends BaseOption { private final boolean defaultValue; @@ -16,9 +16,9 @@ public boolean getDefaultValue() { @Override public String toString() { return "BooleanDefineOption{" + - "name=" + getName() + - ", comment=" + getComment() + - ", defaultValue=" + defaultValue + - '}'; + "name=" + getName() + + ", comment=" + getComment() + + ", defaultValue=" + defaultValue + + '}'; } } diff --git a/src/main/java/net/irisshaders/iris/shaderpack/option/MergedBooleanOption.java b/src/main/java/net/irisshaders/iris/shaderpack/option/MergedBooleanOption.java new file mode 100644 index 0000000000..5d467f1492 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/MergedBooleanOption.java @@ -0,0 +1,50 @@ +package net.irisshaders.iris.shaderpack.option; + +import com.google.common.collect.ImmutableSet; +import org.jetbrains.annotations.Nullable; + +public class MergedBooleanOption { + private final BooleanOption option; + private final ImmutableSet locations; + + MergedBooleanOption(BooleanOption option, ImmutableSet locations) { + this.option = option; + this.locations = locations; + } + + public MergedBooleanOption(OptionLocation location, BooleanOption option) { + this.option = option; + this.locations = ImmutableSet.of(location); + } + + @Nullable + public MergedBooleanOption merge(MergedBooleanOption other) { + if (this.option.getDefaultValue() != other.option.getDefaultValue()) { + return null; + } + + BooleanOption option; + + // TODO: Collect all known comments + if (this.option.getComment().isPresent()) { + option = this.option; + } else { + option = other.option; + } + + ImmutableSet.Builder mergedLocations = ImmutableSet.builder(); + + mergedLocations.addAll(this.locations); + mergedLocations.addAll(other.locations); + + return new MergedBooleanOption(option, mergedLocations.build()); + } + + public BooleanOption getOption() { + return option; + } + + public ImmutableSet getLocations() { + return locations; + } +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/MergedStringOption.java b/src/main/java/net/irisshaders/iris/shaderpack/option/MergedStringOption.java similarity index 96% rename from src/main/java/net/coderbot/iris/shaderpack/option/MergedStringOption.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/MergedStringOption.java index 9ab1afe6f1..11a8b051cf 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/MergedStringOption.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/MergedStringOption.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableSet; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/OptionAnnotatedSource.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionAnnotatedSource.java similarity index 90% rename from src/main/java/net/coderbot/iris/shaderpack/option/OptionAnnotatedSource.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/OptionAnnotatedSource.java index 6cbabde62e..6438ddb6e3 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/OptionAnnotatedSource.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionAnnotatedSource.java @@ -1,16 +1,16 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shaderpack.include.AbsolutePackPath; -import net.coderbot.iris.shaderpack.option.values.OptionValues; -import net.coderbot.iris.shaderpack.parsing.ParsedString; -import net.coderbot.iris.shaderpack.transform.line.LineTransform; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.parsing.ParsedString; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.shaderpack.transform.line.LineTransform; import java.util.HashMap; import java.util.Map; @@ -52,43 +52,6 @@ * the shader source code fall out of sync with the annotations. */ public final class OptionAnnotatedSource { - /** - * The content of each line within this shader source file. - */ - private final ImmutableList lines; - - private final ImmutableMap booleanOptions; - private final ImmutableMap stringOptions; - - /** - * Optional diagnostic messages for each line. The parser may notice that though a shader pack - * author may have intended for a line to be a valid option, Iris might have ignored it due to - * a syntax error or some other issue. - * - * These diagnostic messages provide reasons for why Iris decided to ignore a plausible option - * line, as well as hints for how an invalid option line can be modified to be a valid one. - */ - private final ImmutableMap diagnostics; - - /** - * Keeps track of references to boolean #define options. Correlates the name of the #define - * option to one of the lines it was referenced on. - * - * References to boolean #define options that happen in plain #if directives are not analyzed - * for the purposes of determining whether a boolean #define option is referenced or not, to - * match OptiFine behavior. Though this might have originally been an oversight, shader packs - * now anticipate this behavior, so it must be replicated here. Since it would be complex to - * fully parse #if directives, this also makes the code simpler. - * - * Note that for the purposes of "confirming" a boolean #define option, it does not matter - * where the reference occurs in a given file - only that it is used at least once in the - * same "logical file" (that is, a file after all #includes have been processed) as it is - * defined. This is because shader config options are parsed as if all #include directives - * have already been substituted for the relevant file. - */ - // TODO: Use an immutable list type - private final ImmutableMap booleanDefineReferences; - private static final ImmutableSet VALID_CONST_OPTION_NAMES; static { @@ -133,6 +96,40 @@ public final class OptionAnnotatedSource { VALID_CONST_OPTION_NAMES = values.build(); } + /** + * The content of each line within this shader source file. + */ + private final ImmutableList lines; + private final ImmutableMap booleanOptions; + private final ImmutableMap stringOptions; + /** + * Optional diagnostic messages for each line. The parser may notice that though a shader pack + * author may have intended for a line to be a valid option, Iris might have ignored it due to + * a syntax error or some other issue. + *

    + * These diagnostic messages provide reasons for why Iris decided to ignore a plausible option + * line, as well as hints for how an invalid option line can be modified to be a valid one. + */ + private final ImmutableMap diagnostics; + /** + * Keeps track of references to boolean #define options. Correlates the name of the #define + * option to one of the lines it was referenced on. + *

    + * References to boolean #define options that happen in plain #if directives are not analyzed + * for the purposes of determining whether a boolean #define option is referenced or not, to + * match OptiFine behavior. Though this might have originally been an oversight, shader packs + * now anticipate this behavior, so it must be replicated here. Since it would be complex to + * fully parse #if directives, this also makes the code simpler. + *

    + * Note that for the purposes of "confirming" a boolean #define option, it does not matter + * where the reference occurs in a given file - only that it is used at least once in the + * same "logical file" (that is, a file after all #includes have been processed) as it is + * defined. This is because shader config options are parsed as if all #include directives + * have already been substituted for the relevant file. + */ + // TODO: Use an immutable list type + private final ImmutableMap booleanDefineReferences; + public OptionAnnotatedSource(final String source) { // Match any valid newline sequence // https://stackoverflow.com/a/31060125 @@ -161,9 +158,9 @@ public OptionAnnotatedSource(final ImmutableList lines) { private static void parseLine(AnnotationsBuilder builder, int index, String lineText) { // Check to see if this line contains anything of interest before we try to parse it. if (!lineText.contains("#define") - && !lineText.contains("const") - && !lineText.contains("#ifdef") - && !lineText.contains("#ifndef")) { + && !lineText.contains("const") + && !lineText.contains("#ifdef") + && !lineText.contains("#ifndef")) { // Nothing of interest. return; } @@ -199,7 +196,7 @@ private static void parseIfdef(AnnotationsBuilder builder, int index, ParsedStri } builder.booleanDefineReferences - .computeIfAbsent(name, n -> new IntArrayList()).add(index); + .computeIfAbsent(name, n -> new IntArrayList()).add(index); } private static void parseConst(AnnotationsBuilder builder, int index, ParsedString line) { @@ -218,8 +215,8 @@ private static void parseConst(AnnotationsBuilder builder, int index, ParsedStri isString = false; } else { builder.diagnostics.put(index, "Unexpected type declaration after const. " + - "Expected int, float, or bool. " + - "Vector const declarations cannot be configured using shader options."); + "Expected int, float, or bool. " + + "Vector const declarations cannot be configured using shader options."); return; } @@ -232,7 +229,7 @@ private static void parseConst(AnnotationsBuilder builder, int index, ParsedStri if (name == null) { builder.diagnostics.put(index, "Expected name of option after type declaration, " + - "but an unexpected character was detected first."); + "but an unexpected character was detected first."); return; } @@ -281,13 +278,13 @@ private static void parseConst(AnnotationsBuilder builder, int index, ParsedStri booleanValue = false; } else { builder.diagnostics.put(index, "Expected true or false as the value of a boolean const option, but got " - + value + "."); + + value + "."); return; } if (!VALID_CONST_OPTION_NAMES.contains(name)) { builder.diagnostics.put(index, "This was a valid const boolean option declaration, but " + name + - " was not recognized as being a name of one of the configurable const options."); + " was not recognized as being a name of one of the configurable const options."); return; } @@ -297,7 +294,7 @@ private static void parseConst(AnnotationsBuilder builder, int index, ParsedStri if (!VALID_CONST_OPTION_NAMES.contains(name)) { builder.diagnostics.put(index, "This was a valid const option declaration, but " + name + - " was not recognized as being a name of one of the configurable const options."); + " was not recognized as being a name of one of the configurable const options."); return; } @@ -307,7 +304,7 @@ private static void parseConst(AnnotationsBuilder builder, int index, ParsedStri builder.stringOptions.put(index, option); } else { builder.diagnostics.put(index, "Ignoring this const option because it is missing an allowed values list" + - "in a comment, but is not a boolean const option."); + "in a comment, but is not a boolean const option."); } } @@ -320,15 +317,15 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par if (!line.takeLiteral("#define")) { builder.diagnostics.put(index, - "This line contains an occurrence of \"#define\" " + - "but it wasn't in a place we expected, ignoring it."); + "This line contains an occurrence of \"#define\" " + + "but it wasn't in a place we expected, ignoring it."); return; } if (!line.takeSomeWhitespace()) { builder.diagnostics.put(index, - "This line properly starts with a #define statement but doesn't have " + - "any whitespace characters after the #define."); + "This line properly starts with a #define statement but doesn't have " + + "any whitespace characters after the #define."); return; } @@ -336,8 +333,8 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par if (name == null) { builder.diagnostics.put(index, - "Invalid syntax after #define directive. " + - "No alphanumeric or underscore characters detected."); + "Invalid syntax after #define directive. " + + "No alphanumeric or underscore characters detected."); return; } @@ -361,16 +358,16 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par } else if (!tookWhitespace) { // Invalid syntax. builder.diagnostics.put(index, - "Invalid syntax after #define directive. Only alphanumeric or underscore " + - "characters are allowed in option names."); + "Invalid syntax after #define directive. Only alphanumeric or underscore " + + "characters are allowed in option names."); return; } if (hasLeadingComment) { builder.diagnostics.put(index, - "Ignoring potential non-boolean #define option since it has a leading comment. " + - "Leading comments (//) are only allowed on boolean #define options."); + "Ignoring potential non-boolean #define option since it has a leading comment. " + + "Leading comments (//) are only allowed on boolean #define options."); return; } @@ -378,7 +375,7 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par if (value == null) { builder.diagnostics.put(index, "Ignoring this #define directive because it doesn't appear to be a boolean #define, " + - "and its potential value wasn't a valid number or a valid word."); + "and its potential value wasn't a valid number or a valid word."); return; } @@ -386,7 +383,7 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par if (line.isEnd()) { builder.diagnostics.put(index, "Ignoring this #define because it doesn't have a comment containing" + - " a list of allowed values afterwards, but it has a value so is therefore not a boolean."); + " a list of allowed values afterwards, but it has a value so is therefore not a boolean."); return; } else if (!tookWhitespace) { if (!line.takeComments()) { @@ -397,8 +394,8 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par } } else if (!line.takeComments()) { builder.diagnostics.put(index, - "Invalid syntax after value #define directive. " + - "Only comments may come after the value."); + "Invalid syntax after value #define directive. " + + "Only comments may come after the value."); return; } @@ -408,7 +405,7 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par if (option == null) { builder.diagnostics.put(index, "Ignoring this #define because it is missing an allowed values list" + - "in a comment, but is not a boolean define."); + "in a comment, but is not a boolean define."); return; } @@ -428,6 +425,29 @@ private static void parseDefineOption(AnnotationsBuilder builder, int index, Par */ } + private static boolean hasLeadingComment(String line) { + return line.trim().startsWith("//"); + } + + private static String removeLeadingComment(String line) { + ParsedString parsed = new ParsedString(line); + + parsed.takeSomeWhitespace(); + parsed.takeComments(); + + return parsed.takeRest(); + } + + private static String setBooleanDefineValue(String line, OptionalBoolean newValue, boolean defaultValue) { + if (hasLeadingComment(line) && newValue.orElse(defaultValue)) { + return removeLeadingComment(line); + } else if (!newValue.orElse(defaultValue)) { + return "//" + line; + } else { + return line; + } + } + public ImmutableMap getBooleanOptions() { return booleanOptions; } @@ -530,29 +550,6 @@ private String editConst(String line, String currentValue, String newValue) { return firstPart + secondPart; } - private static boolean hasLeadingComment(String line) { - return line.trim().startsWith("//"); - } - - private static String removeLeadingComment(String line) { - ParsedString parsed = new ParsedString(line); - - parsed.takeSomeWhitespace(); - parsed.takeComments(); - - return parsed.takeRest(); - } - - private static String setBooleanDefineValue(String line, OptionalBoolean newValue, boolean defaultValue) { - if (hasLeadingComment(line) && newValue.orElse(defaultValue)) { - return removeLeadingComment(line); - } else if (!newValue.orElse(defaultValue)) { - return "//" + line; - } else { - return line; - } - } - private static class AnnotationsBuilder { private final ImmutableMap.Builder booleanOptions; private final ImmutableMap.Builder stringOptions; diff --git a/src/main/java/net/irisshaders/iris/shaderpack/option/OptionLocation.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionLocation.java new file mode 100644 index 0000000000..76c80db960 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionLocation.java @@ -0,0 +1,20 @@ +package net.irisshaders.iris.shaderpack.option; + +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; + +/** + * Encapsulates a single location of an option. + */ +public record OptionLocation(AbsolutePackPath filePath, int lineIndex) { + + + /** + * Gets the index of the line this option is on. + * Note that this is the index - so the first line is + * 0, the second is 1, etc. + */ + @Override + public int lineIndex() { + return lineIndex; + } +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/OptionSet.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionSet.java similarity index 97% rename from src/main/java/net/coderbot/iris/shaderpack/option/OptionSet.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/OptionSet.java index 27db1825cf..8c6efa7a5c 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/OptionSet.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionSet.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import java.util.HashMap; import java.util.Map; @@ -15,6 +15,10 @@ private OptionSet(Builder builder) { this.stringOptions = ImmutableMap.copyOf(builder.stringOptions); } + public static Builder builder() { + return new Builder(); + } + public ImmutableMap getBooleanOptions() { return this.booleanOptions; } @@ -27,10 +31,6 @@ public boolean isBooleanOption(String name) { return booleanOptions.containsKey(name); } - public static Builder builder() { - return new Builder(); - } - public static class Builder { private final Map booleanOptions; private final Map stringOptions; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/OptionTests.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionTests.java similarity index 70% rename from src/main/java/net/coderbot/iris/shaderpack/option/OptionTests.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/OptionTests.java index 395969cd41..4262301a0f 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/OptionTests.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionTests.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; @@ -9,7 +9,7 @@ import java.util.List; public class OptionTests { - public static void main(String[] args) throws IOException { + public static void main(String[] args) throws IOException { List lines = Files.readAllLines(Paths.get("run/shaderpacks/Sildurs Vibrant Shaders v1.29 Medium/shaders/shaders.settings")); OptionAnnotatedSource source = new OptionAnnotatedSource(ImmutableList.copyOf(lines)); @@ -27,10 +27,10 @@ public static void main(String[] args) throws IOException { String type = option.getType() == OptionType.CONST ? " Const" : "Define"; System.out.println( - "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] " + type + " | " + - StringUtils.rightPad(option.getName(), 32, ' ') + " | " + - StringUtils.leftPad(Boolean.toString(option.getDefaultValue()), 5, ' ') + - " | " + option.getComment().orElse("")); + "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] " + type + " | " + + StringUtils.rightPad(option.getName(), 32, ' ') + " | " + + StringUtils.leftPad(Boolean.toString(option.getDefaultValue()), 5, ' ') + + " | " + option.getComment().orElse("")); }); @@ -47,17 +47,17 @@ public static void main(String[] args) throws IOException { String type = option.getType() == OptionType.CONST ? " Const" : "Define"; System.out.println( - "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] | " + type + " | " + - StringUtils.rightPad(option.getName(), 32, ' ') + " | " + - StringUtils.leftPad(option.getDefaultValue(), 8, ' ') + - " | " + option.getAllowedValues()); + "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] | " + type + " | " + + StringUtils.rightPad(option.getName(), 32, ' ') + " | " + + StringUtils.leftPad(option.getDefaultValue(), 8, ' ') + + " | " + option.getAllowedValues()); System.out.println(" " + option.getComment().orElse("(no comment)")); }); System.out.println("Diagnostics:"); source.getDiagnostics().forEach((index, diagnostic) -> { System.out.println( - "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] " + + "[" + StringUtils.leftPad(Integer.toString(index + 1), 4, ' ') + "] " + diagnostic); }); diff --git a/src/main/java/net/irisshaders/iris/shaderpack/option/OptionType.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionType.java new file mode 100644 index 0000000000..6b29beade3 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OptionType.java @@ -0,0 +1,5 @@ +package net.irisshaders.iris.shaderpack.option; + +public enum OptionType { + DEFINE, CONST +} diff --git a/src/main/java/net/irisshaders/iris/shaderpack/option/OrderBackedProperties.java b/src/main/java/net/irisshaders/iris/shaderpack/option/OrderBackedProperties.java new file mode 100644 index 0000000000..14711af16d --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/OrderBackedProperties.java @@ -0,0 +1,67 @@ +package net.irisshaders.iris.shaderpack.option; + +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectMaps; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.Enumeration; +import java.util.Map; +import java.util.Properties; +import java.util.function.BiConsumer; + +/** + * Properties backed by a {@link java.util.LinkedHashMap}, in order to preserve iteration order + */ +public class OrderBackedProperties extends Properties { + private transient final Map backing = Object2ObjectMaps.synchronize(new Object2ObjectLinkedOpenHashMap<>()); + + @Override + public synchronized Object put(Object key, Object value) { + backing.put(key, value); + + return super.put(key, value); + } + + @Override + public synchronized void forEach(BiConsumer action) { + this.backing.forEach(action); + } + + @Override + public void store(OutputStream out, String comments) throws IOException { + customStore0(new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.ISO_8859_1)), + comments, true); + } + + @Override + public void store(Writer out, String comments) throws IOException { + customStore0(new BufferedWriter(out), + comments, true); + } + + //Override to stop '/' or ':' chars from being replaced by not called + //saveConvert(key, true, escUnicode) + private void customStore0(BufferedWriter bw, String comments, boolean escUnicode) + throws IOException { + bw.write("#" + new Date()); + bw.newLine(); + synchronized (this) { + for (Enumeration e = keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + String val = (String) get(key); + // Commented out to stop '/' or ':' chars being replaced + //key = saveConvert(key, true, escUnicode); + //val = saveConvert(val, false, escUnicode); + bw.write(key + "=" + val); + bw.newLine(); + } + } + bw.flush(); + } +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/Profile.java b/src/main/java/net/irisshaders/iris/shaderpack/option/Profile.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/option/Profile.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/Profile.java index 4f6620f482..2162778b91 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/Profile.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/Profile.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/ProfileSet.java b/src/main/java/net/irisshaders/iris/shaderpack/option/ProfileSet.java similarity index 93% rename from src/main/java/net/coderbot/iris/shaderpack/option/ProfileSet.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/ProfileSet.java index fd6f086b7a..d87d991098 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/ProfileSet.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/ProfileSet.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; -import net.coderbot.iris.Iris; -import net.coderbot.iris.IrisLogging; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.IrisLogging; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -36,33 +36,6 @@ public ProfileSet(LinkedHashMap orderedProfiles) { this.orderedProfiles = orderedProfiles; } - public void forEach(BiConsumer action) { - orderedProfiles.forEach(action); - } - - public ProfileResult scan(OptionSet options, OptionValues values) { - if (sortedProfiles.size() <= 0) { - return new ProfileResult(null, null, null); - } - - for (int i = 0; i < sortedProfiles.size(); i++) { - Profile current = sortedProfiles.get(i); - - if (current.matches(options, values)) { - Profile next = sortedProfiles.get(Math.floorMod(i + 1, sortedProfiles.size())); - Profile prev = sortedProfiles.get(Math.floorMod(i - 1, sortedProfiles.size())); - - return new ProfileResult(current, next, prev); - } - } - - // Default return if no profiles matched - Profile next = sortedProfiles.get(0); - Profile prev = sortedProfiles.get(sortedProfiles.size() - 1); - - return new ProfileResult(null, next, prev); - } - public static ProfileSet fromTree(Map> tree, OptionSet optionSet) { LinkedHashMap profiles = new LinkedHashMap<>(); @@ -89,7 +62,7 @@ private static Profile parse(String name, List parents, Map parents, Map action) { + orderedProfiles.forEach(action); + } + + public ProfileResult scan(OptionSet options, OptionValues values) { + if (sortedProfiles.isEmpty()) { + return new ProfileResult(null, null, null); + } + + for (int i = 0; i < sortedProfiles.size(); i++) { + Profile current = sortedProfiles.get(i); + + if (current.matches(options, values)) { + Profile next = sortedProfiles.get(Math.floorMod(i + 1, sortedProfiles.size())); + Profile prev = sortedProfiles.get(Math.floorMod(i - 1, sortedProfiles.size())); + + return new ProfileResult(current, next, prev); + } + } + + // Default return if no profiles matched + Profile next = sortedProfiles.get(0); + Profile prev = sortedProfiles.get(sortedProfiles.size() - 1); + + return new ProfileResult(null, next, prev); + } + public int size() { return sortedProfiles.size(); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/ShaderPackOptions.java b/src/main/java/net/irisshaders/iris/shaderpack/option/ShaderPackOptions.java similarity index 86% rename from src/main/java/net/coderbot/iris/shaderpack/option/ShaderPackOptions.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/ShaderPackOptions.java index d3aabb9544..0f55b2f2e6 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/ShaderPackOptions.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/ShaderPackOptions.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.shaderpack.include.AbsolutePackPath; -import net.coderbot.iris.shaderpack.include.IncludeGraph; -import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.include.IncludeGraph; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; import java.util.Collections; import java.util.HashMap; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/StringOption.java b/src/main/java/net/irisshaders/iris/shaderpack/option/StringOption.java similarity index 97% rename from src/main/java/net/coderbot/iris/shaderpack/option/StringOption.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/StringOption.java index 791b6a534b..9f8931b8a8 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/StringOption.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/StringOption.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option; +package net.irisshaders.iris.shaderpack.option; import com.google.common.collect.ImmutableList; import org.jetbrains.annotations.NotNull; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java similarity index 60% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java index d40ee35399..2a19deaf55 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuBooleanOptionElement.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.BooleanOption; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.option.BooleanOption; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; public class OptionMenuBooleanOptionElement extends OptionMenuOptionElement { public final BooleanOption option; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuContainer.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuContainer.java similarity index 88% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuContainer.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuContainer.java index fa4712978f..0ab782379e 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuContainer.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuContainer.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; import com.google.common.collect.Lists; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.ProfileSet; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.option.ProfileSet; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.ArrayList; import java.util.Collections; @@ -39,7 +39,7 @@ public OptionMenuContainer(ShaderProperties shaderProperties, ShaderPackOptions Map subScreenColumnCounts = shaderProperties.getSubScreenColumnCount(); shaderProperties.getSubScreenOptions().forEach((screenKey, options) -> { subScreens.put(screenKey, new OptionMenuSubElementScreen( - screenKey, this, shaderProperties, shaderPackOptions, options, Optional.ofNullable(subScreenColumnCounts.get(screenKey)))); + screenKey, this, shaderProperties, shaderPackOptions, options, Optional.ofNullable(subScreenColumnCounts.get(screenKey)))); }); // Dump all unused options into screens containing "*" diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElement.java similarity index 86% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElement.java index 1e784534fd..db55440370 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElement.java @@ -1,14 +1,15 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.MergedBooleanOption; -import net.coderbot.iris.shaderpack.option.MergedStringOption; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.option.MergedBooleanOption; +import net.irisshaders.iris.shaderpack.option.MergedStringOption; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.Map; public abstract class OptionMenuElement { - public static final OptionMenuElement EMPTY = new OptionMenuElement() {}; + public static final OptionMenuElement EMPTY = new OptionMenuElement() { + }; private static final String ELEMENT_EMPTY = ""; private static final String ELEMENT_PROFILE = ""; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElementScreen.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElementScreen.java similarity index 84% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElementScreen.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElementScreen.java index 38185a3237..59e3826480 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuElementScreen.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuElementScreen.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuLinkElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuLinkElement.java similarity index 79% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuLinkElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuLinkElement.java index cc82cb72b8..18476c6fbb 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuLinkElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuLinkElement.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; public class OptionMenuLinkElement extends OptionMenuElement { public final String targetScreenId; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java similarity index 69% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java index fbd9476f4a..2e2951f497 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuMainElementScreen.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.List; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuOptionElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuOptionElement.java similarity index 77% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuOptionElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuOptionElement.java index c25646f884..4e069ee63c 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuOptionElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuOptionElement.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; public abstract class OptionMenuOptionElement extends OptionMenuElement { public final boolean slider; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuProfileElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuProfileElement.java similarity index 66% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuProfileElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuProfileElement.java index 78ba4fa13e..e510a3c66b 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuProfileElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuProfileElement.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.option.OptionSet; -import net.coderbot.iris.shaderpack.option.ProfileSet; -import net.coderbot.iris.shaderpack.option.values.MutableOptionValues; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.shaderpack.option.ProfileSet; +import net.irisshaders.iris.shaderpack.option.values.MutableOptionValues; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; public class OptionMenuProfileElement extends OptionMenuElement { public final ProfileSet profiles; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java similarity index 60% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java index 63f27b20a8..283c4ddc47 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuStringOptionElement.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.StringOption; -import net.coderbot.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.option.StringOption; +import net.irisshaders.iris.shaderpack.option.values.OptionValues; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; public class OptionMenuStringOptionElement extends OptionMenuOptionElement { public final StringOption option; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java similarity index 72% rename from src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java index dd1bd854f9..ebf4cfd18e 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/menu/OptionMenuSubElementScreen.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.shaderpack.option.menu; +package net.irisshaders.iris.shaderpack.option.menu; -import net.coderbot.iris.shaderpack.ShaderProperties; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.List; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/values/ImmutableOptionValues.java b/src/main/java/net/irisshaders/iris/shaderpack/option/values/ImmutableOptionValues.java similarity index 89% rename from src/main/java/net/coderbot/iris/shaderpack/option/values/ImmutableOptionValues.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/values/ImmutableOptionValues.java index 1e3935fb36..661f9359a3 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/values/ImmutableOptionValues.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/values/ImmutableOptionValues.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option.values; +package net.irisshaders.iris.shaderpack.option.values; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.shaderpack.option.OptionSet; import java.util.HashMap; import java.util.Optional; diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/values/MutableOptionValues.java b/src/main/java/net/irisshaders/iris/shaderpack/option/values/MutableOptionValues.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/option/values/MutableOptionValues.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/values/MutableOptionValues.java index ca1a446ac0..e34ff940e5 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/values/MutableOptionValues.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/values/MutableOptionValues.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.option.values; +package net.irisshaders.iris.shaderpack.option.values; import com.google.common.collect.ImmutableMap; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.shaderpack.option.OptionSet; import java.util.HashMap; import java.util.Map; @@ -124,7 +124,7 @@ public MutableOptionValues mutableCopy() { @Override public ImmutableOptionValues toImmutable() { return new ImmutableOptionValues(options, ImmutableMap.copyOf(booleanValues), - ImmutableMap.copyOf(stringValues)); + ImmutableMap.copyOf(stringValues)); } @Override diff --git a/src/main/java/net/coderbot/iris/shaderpack/option/values/OptionValues.java b/src/main/java/net/irisshaders/iris/shaderpack/option/values/OptionValues.java similarity index 81% rename from src/main/java/net/coderbot/iris/shaderpack/option/values/OptionValues.java rename to src/main/java/net/irisshaders/iris/shaderpack/option/values/OptionValues.java index 1abb3f189d..db74ed7af4 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/option/values/OptionValues.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/option/values/OptionValues.java @@ -1,13 +1,14 @@ -package net.coderbot.iris.shaderpack.option.values; +package net.irisshaders.iris.shaderpack.option.values; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.option.OptionSet; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.shaderpack.option.OptionSet; import java.util.Optional; public interface OptionValues { OptionalBoolean getBooleanValue(String name); + Optional getStringValue(String name); default boolean getBooleanValueOrDefault(String name) { @@ -27,6 +28,8 @@ default String getStringValueOrDefault(String name) { int getOptionsChanged(); MutableOptionValues mutableCopy(); + ImmutableOptionValues toImmutable(); + OptionSet getOptionSet(); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/CommentDirective.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirective.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/CommentDirective.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirective.java index 8d64506c24..29fe14c4d3 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/CommentDirective.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirective.java @@ -1,11 +1,6 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; public class CommentDirective { - public enum Type { - DRAWBUFFERS, - RENDERTARGETS - } - private final Type type; private final String directive; private final int location; @@ -35,4 +30,9 @@ public String getDirective() { public int getLocation() { return location; } + + public enum Type { + DRAWBUFFERS, + RENDERTARGETS + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/CommentDirectiveParser.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirectiveParser.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/CommentDirectiveParser.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirectiveParser.java index 88808c61fc..8fe23d4450 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/CommentDirectiveParser.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/CommentDirectiveParser.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; import java.util.Optional; import java.util.function.Supplier; @@ -132,10 +132,12 @@ public static void main(String[] args) { test("multi-line", Optional.of("It works"), () -> { String lines = - "/* Here's a random comment line */\n" + - "/* RENDERTARGETS:Duplicate handling? */\n" + - "uniform sampler2D test;\n" + - "/* RENDERTARGETS:Duplicate handling within a line? */ Let's see /* RENDERTARGETS:It works */\n"; + """ + /* Here's a random comment line */ + /* RENDERTARGETS:Duplicate handling? */ + """ + + "uniform sampler2D test;\n" + + "/* RENDERTARGETS:Duplicate handling within a line? */ Let's see /* RENDERTARGETS:It works */\n"; return CommentDirectiveParser.findDirective(lines, CommentDirective.Type.RENDERTARGETS).map(CommentDirective::getDirective); }); diff --git a/src/main/java/net/coderbot/iris/shaderpack/ComputeDirectiveParser.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ComputeDirectiveParser.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/ComputeDirectiveParser.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/ComputeDirectiveParser.java index 8ef4e266bd..006b01a6cc 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ComputeDirectiveParser.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ComputeDirectiveParser.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; import org.joml.Vector2f; import org.joml.Vector3i; diff --git a/src/main/java/net/coderbot/iris/shaderpack/ConstDirectiveParser.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ConstDirectiveParser.java similarity index 99% rename from src/main/java/net/coderbot/iris/shaderpack/ConstDirectiveParser.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/ConstDirectiveParser.java index f8d80d232c..8e5be91bdb 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ConstDirectiveParser.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ConstDirectiveParser.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; import java.util.ArrayList; import java.util.List; @@ -139,6 +139,15 @@ private static boolean isWord(String text) { return true; } + public enum Type { + INT, + FLOAT, + VEC2, + IVEC3, + VEC4, + BOOL + } + public static class ConstDirective { private final Type type; private final String key; @@ -166,13 +175,4 @@ public String toString() { return "ConstDirective { " + type + " " + key + " = " + value + "; }"; } } - - public enum Type { - INT, - FLOAT, - VEC2, - IVEC3, - VEC4, - BOOL - } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/DirectiveHolder.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/DirectiveHolder.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/DirectiveHolder.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/DirectiveHolder.java index f821d8df17..6c01695a74 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/DirectiveHolder.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/DirectiveHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import it.unimi.dsi.fastutil.floats.FloatConsumer; @@ -11,14 +11,24 @@ public interface DirectiveHolder { void acceptUniformDirective(String name, Runnable onDetected); + void acceptCommentStringDirective(String name, Consumer consumer); + void acceptCommentIntDirective(String name, IntConsumer consumer); + void acceptCommentFloatDirective(String name, FloatConsumer consumer); + void acceptConstBooleanDirective(String name, BooleanConsumer consumer); + void acceptConstStringDirective(String name, Consumer consumer); + void acceptConstIntDirective(String name, IntConsumer consumer); + void acceptConstFloatDirective(String name, FloatConsumer consumer); + void acceptConstVec2Directive(String name, Consumer consumer); + void acceptConstIVec3Directive(String name, Consumer consumer); + void acceptConstVec4Directive(String name, Consumer consumer); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/DispatchingDirectiveHolder.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/DispatchingDirectiveHolder.java similarity index 97% rename from src/main/java/net/coderbot/iris/shaderpack/DispatchingDirectiveHolder.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/DispatchingDirectiveHolder.java index 2101306d95..f863cc59d1 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/DispatchingDirectiveHolder.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/DispatchingDirectiveHolder.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.parsing; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import it.unimi.dsi.fastutil.floats.FloatConsumer; -import net.coderbot.iris.Iris; -import net.coderbot.iris.IrisLogging; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.IrisLogging; import org.joml.Vector2f; import org.joml.Vector3i; import org.joml.Vector4f; @@ -248,7 +248,7 @@ public void processDirective(ConstDirectiveParser.ConstDirective directive) { } } - private void typeCheckHelper(String expected, Map candidates, ConstDirectiveParser.ConstDirective directive) { + private void typeCheckHelper(String expected, Map candidates, ConstDirectiveParser.ConstDirective directive) { if (candidates.containsKey(directive.getKey())) { Iris.logger.warn("Ignoring " + directive + " because it is of the wrong type, a type of " + expected + " is expected."); } diff --git a/src/main/java/net/coderbot/iris/shaderpack/parsing/ParsedString.java b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ParsedString.java similarity index 91% rename from src/main/java/net/coderbot/iris/shaderpack/parsing/ParsedString.java rename to src/main/java/net/irisshaders/iris/shaderpack/parsing/ParsedString.java index abe7a3ad16..dfad869035 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/parsing/ParsedString.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/parsing/ParsedString.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.parsing; +package net.irisshaders.iris.shaderpack.parsing; import org.jetbrains.annotations.Nullable; @@ -100,8 +100,8 @@ public String takeNumber() { int position = 0; while (position < text.length()) { - if(position + 1 < text.length()) { - if(!Character.isDigit(text.charAt(position)) && !Character.isDigit(text.charAt(position + 1))) { + if (position + 1 < text.length()) { + if (!Character.isDigit(text.charAt(position)) && !Character.isDigit(text.charAt(position + 1))) { break; } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/GlslCollectingListener.java b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/GlslCollectingListener.java similarity index 94% rename from src/main/java/net/coderbot/iris/shaderpack/preprocessor/GlslCollectingListener.java rename to src/main/java/net/irisshaders/iris/shaderpack/preprocessor/GlslCollectingListener.java index df3c879aab..f95ea975ad 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/GlslCollectingListener.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/GlslCollectingListener.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.preprocessor; +package net.irisshaders.iris.shaderpack.preprocessor; import org.anarres.cpp.DefaultPreprocessorListener; import org.anarres.cpp.LexerException; diff --git a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/JcppProcessor.java b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/JcppProcessor.java similarity index 89% rename from src/main/java/net/coderbot/iris/shaderpack/preprocessor/JcppProcessor.java rename to src/main/java/net/irisshaders/iris/shaderpack/preprocessor/JcppProcessor.java index 6b62ee7093..b9304bdaa9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/JcppProcessor.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/JcppProcessor.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.shaderpack.preprocessor; +package net.irisshaders.iris.shaderpack.preprocessor; -import net.coderbot.iris.shaderpack.StringPair; +import net.irisshaders.iris.helpers.StringPair; import org.anarres.cpp.Feature; import org.anarres.cpp.LexerException; import org.anarres.cpp.Preprocessor; @@ -11,7 +11,7 @@ public class JcppProcessor { // Derived from GlShader from Canvas, licenced under LGPL public static String glslPreprocessSource(String source, Iterable environmentDefines) { if (source.contains(GlslCollectingListener.VERSION_MARKER) - || source.contains(GlslCollectingListener.EXTENSION_MARKER)) { + || source.contains(GlslCollectingListener.EXTENSION_MARKER)) { throw new RuntimeException("Some shader author is trying to exploit internal Iris implementation details, stop!"); } @@ -33,15 +33,14 @@ public static String glslPreprocessSource(String source, Iterable en GlslCollectingListener listener = new GlslCollectingListener(); - @SuppressWarnings("resource") - final Preprocessor pp = new Preprocessor(); + @SuppressWarnings("resource") final Preprocessor pp = new Preprocessor(); // Add the values of the environment defines without actually modifying the source code // of the shader program, one step down the road of having accurate line number reporting // in errors... try { for (StringPair envDefine : environmentDefines) { - pp.addMacro(envDefine.getKey(), envDefine.getValue()); + pp.addMacro(envDefine.key(), envDefine.value()); } } catch (LexerException e) { throw new RuntimeException("Unexpected LexerException processing macros", e); @@ -54,7 +53,7 @@ public static String glslPreprocessSource(String source, Iterable en final StringBuilder builder = new StringBuilder(); try { - for (;;) { + for (; ; ) { final Token tok = pp.token(); if (tok == null) break; if (tok.getType() == Token.EOF) break; diff --git a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesCommentListener.java b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesCommentListener.java similarity index 93% rename from src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesCommentListener.java rename to src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesCommentListener.java index 20d33d1551..081d0cc8b8 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesCommentListener.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesCommentListener.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.preprocessor; +package net.irisshaders.iris.shaderpack.preprocessor; import org.anarres.cpp.DefaultPreprocessorListener; import org.anarres.cpp.LexerException; diff --git a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesPreprocessor.java b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesPreprocessor.java similarity index 76% rename from src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesPreprocessor.java rename to src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesPreprocessor.java index 414e877203..30b6c721e9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertiesPreprocessor.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertiesPreprocessor.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.preprocessor; +package net.irisshaders.iris.shaderpack.preprocessor; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shaderpack.StringPair; -import net.coderbot.iris.shaderpack.option.ShaderPackOptions; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.helpers.StringPair; +import net.irisshaders.iris.shaderpack.option.ShaderPackOptions; import org.anarres.cpp.Feature; import org.anarres.cpp.LexerException; import org.anarres.cpp.Preprocessor; @@ -35,14 +35,14 @@ public static String preprocessSource(String source, ShaderPackOptions shaderPac } for (StringPair envDefine : environmentDefines) { - pp.addMacro(envDefine.getKey(), envDefine.getValue()); + pp.addMacro(envDefine.key(), envDefine.value()); } stringValues.forEach((name, value) -> { try { pp.addMacro(name, value); } catch (LexerException e) { - e.printStackTrace(); + Iris.logger.fatal("Failed to preprocess property file!", e); } }); @@ -63,10 +63,10 @@ public static String preprocessSource(String source, Iterable enviro try { for (StringPair envDefine : environmentDefines) { - preprocessor.addMacro(envDefine.getKey(), envDefine.getValue()); + preprocessor.addMacro(envDefine.key(), envDefine.value()); } } catch (LexerException e) { - e.printStackTrace(); + Iris.logger.fatal("Failed to preprocess property file!", e); } return process(preprocessor, source); @@ -80,21 +80,21 @@ private static String process(Preprocessor preprocessor, String source) { // Not super efficient, but this removes trailing whitespace on lines, fixing an issue with whitespace after // line continuations (see PreprocessorTest#testWeirdPropertiesLineContinuation) // Required for Voyager Shader - source = Arrays.stream(source.split("\\R")).map(String::trim) - .map(line -> { - if (line.startsWith("#")) { - for (PreprocessorCommand command : PreprocessorCommand.values()) { - if (line.startsWith("#" + (command.name().replace("PP_", "").toLowerCase(Locale.ROOT)))) { - return line; - } + source = Arrays.stream(source.split("\\R")).map(String::trim).filter(s -> !s.isBlank()) + .map(line -> { + if (line.startsWith("#")) { + for (PreprocessorCommand command : PreprocessorCommand.values()) { + if (line.startsWith("#" + (command.name().replace("PP_", "").toLowerCase(Locale.ROOT)))) { + return line; } - return ""; } - // In PropertyCollectingListener we suppress "unknown preprocessor directive errors" and - // assume the line to be a comment, since in .properties files `#` also functions as a comment - // marker. - return line.replace("#", ""); - }).collect(Collectors.joining("\n")) + "\n"; + return ""; + } + // In PropertyCollectingListener we suppress "unknown preprocessor directive errors" and + // assume the line to be a comment, since in .properties files `#` also functions as a comment + // marker. + return line.replace("#", ""); + }).collect(Collectors.joining("\n")) + "\n"; // TODO: This is a horrible fix to trick the preprocessor into not seeing the backslashes during processing. We need a better way to do this. source = source.replace("\\", "IRIS_PASSTHROUGHBACKSLASH"); @@ -104,7 +104,7 @@ private static String process(Preprocessor preprocessor, String source) { final StringBuilder builder = new StringBuilder(); try { - for (;;) { + for (; ; ) { final Token tok = preprocessor.token(); if (tok == null) break; if (tok.getType() == Token.EOF) break; @@ -137,7 +137,7 @@ private static Map getStringValues(ShaderPackOptions shaderPackO Map stringValues = new HashMap<>(); shaderPackOptions.getOptionSet().getStringOptions().forEach( - (optionName, value) -> stringValues.put(optionName, shaderPackOptions.getOptionValues().getStringValueOrDefault(optionName))); + (optionName, value) -> stringValues.put(optionName, shaderPackOptions.getOptionValues().getStringValueOrDefault(optionName))); return stringValues; } diff --git a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertyCollectingListener.java b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertyCollectingListener.java similarity index 90% rename from src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertyCollectingListener.java rename to src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertyCollectingListener.java index 031ea61836..578cef481a 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/preprocessor/PropertyCollectingListener.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/preprocessor/PropertyCollectingListener.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.preprocessor; +package net.irisshaders.iris.shaderpack.preprocessor; import org.anarres.cpp.DefaultPreprocessorListener; import org.anarres.cpp.LexerException; @@ -26,7 +26,7 @@ public void handleWarning(Source source, int line, int column, String msg) throw @Override public void handleError(Source source, int line, int column, String msg) throws LexerException { if (msg.contains("Unknown preprocessor directive") - || msg.contains("Preprocessor directive not a word")) { + || msg.contains("Preprocessor directive not a word")) { // Suppress log spam since hashed lines also function as comments in preprocessed files. return; } diff --git a/src/main/java/net/coderbot/iris/shaderpack/ComputeSource.java b/src/main/java/net/irisshaders/iris/shaderpack/programs/ComputeSource.java similarity index 73% rename from src/main/java/net/coderbot/iris/shaderpack/ComputeSource.java rename to src/main/java/net/irisshaders/iris/shaderpack/programs/ComputeSource.java index c5f94f405f..4d209fc7e9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ComputeSource.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/programs/ComputeSource.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.programs; -import net.coderbot.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.shaderpack.properties.IndirectPointer; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import org.joml.Vector2f; import org.joml.Vector3i; @@ -10,13 +11,15 @@ public class ComputeSource { private final String name; private final String source; private final ProgramSet parent; + private final IndirectPointer indirectPointer; private Vector3i workGroups; private Vector2f workGroupRelative; - public ComputeSource(String name, String source, ProgramSet parent) { + public ComputeSource(String name, String source, ProgramSet parent, ShaderProperties properties) { this.name = name; this.source = source; this.parent = parent; + this.indirectPointer = properties.getIndirectPointers().get(name); } public String getName() { @@ -35,22 +38,26 @@ public boolean isValid() { return source != null; } - public void setWorkGroups(Vector3i workGroups) { - this.workGroups = workGroups; + public Vector2f getWorkGroupRelative() { + return workGroupRelative; } public void setWorkGroupRelative(Vector2f workGroupRelative) { this.workGroupRelative = workGroupRelative; } - public Vector2f getWorkGroupRelative() { - return workGroupRelative; - } - public Vector3i getWorkGroups() { return workGroups; } + public void setWorkGroups(Vector3i workGroups) { + this.workGroups = workGroups; + } + + public IndirectPointer getIndirectPointer() { + return indirectPointer; + } + public Optional requireValid() { if (this.isValid()) { return Optional.of(this); diff --git a/src/main/java/net/coderbot/iris/shaderpack/ProgramFallbackResolver.java b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramFallbackResolver.java similarity index 89% rename from src/main/java/net/coderbot/iris/shaderpack/ProgramFallbackResolver.java rename to src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramFallbackResolver.java index f8c20ef680..e6ab2c4343 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ProgramFallbackResolver.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramFallbackResolver.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.programs; -import net.coderbot.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.loading.ProgramId; import org.jetbrains.annotations.Nullable; import java.util.HashMap; diff --git a/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java similarity index 81% rename from src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java rename to src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java index 10d5a25a4a..d7bedc0027 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ProgramSet.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSet.java @@ -1,12 +1,17 @@ -package net.coderbot.iris.shaderpack; - -import net.coderbot.iris.Iris; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gl.blending.BlendMode; -import net.coderbot.iris.gl.blending.BlendModeFunction; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.shaderpack.include.AbsolutePackPath; -import net.coderbot.iris.shaderpack.loading.ProgramId; +package net.irisshaders.iris.shaderpack.programs; + +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.shaderpack.ShaderPack; +import net.irisshaders.iris.shaderpack.include.AbsolutePackPath; +import net.irisshaders.iris.shaderpack.loading.ProgramId; +import net.irisshaders.iris.shaderpack.parsing.ComputeDirectiveParser; +import net.irisshaders.iris.shaderpack.parsing.ConstDirectiveParser; +import net.irisshaders.iris.shaderpack.parsing.DispatchingDirectiveHolder; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.ArrayList; import java.util.Arrays; @@ -37,7 +42,6 @@ public class ProgramSet implements ProgramSetInterface { private final ProgramSource gbuffersTerrain; private final ProgramSource gbuffersTerrainSolid; private final ProgramSource gbuffersTerrainCutout; - private ProgramSource gbuffersDamagedBlock; private final ProgramSource gbuffersSkyBasic; private final ProgramSource gbuffersSkyTextured; private final ProgramSource gbuffersClouds; @@ -52,20 +56,19 @@ public class ProgramSet implements ProgramSetInterface { private final ProgramSource gbuffersBlock; private final ProgramSource gbuffersBlockTrans; private final ProgramSource gbuffersHand; - private final ProgramSource[] deferred; private final ComputeSource[][] deferredCompute; - private final ProgramSource gbuffersWater; private final ProgramSource gbuffersHandWater; - private final ProgramSource[] composite; private final ComputeSource[][] compositeCompute; private final ProgramSource compositeFinal; private final ComputeSource[] finalCompute; - - + private final ProgramSource dhTerrain; + private final ProgramSource dhWater; + private final ProgramSource dhShadow; private final ShaderPack pack; + private final ProgramSource gbuffersDamagedBlock; public ProgramSet(AbsolutePackPath directory, Function sourceProvider, ShaderProperties shaderProperties, ShaderPack pack) { @@ -85,28 +88,28 @@ public ProgramSet(AbsolutePackPath directory, Function boolean readTesselation = pack.hasFeature(FeatureFlags.TESSELATION_SHADERS); this.shadow = readProgramSource(directory, sourceProvider, "shadow", this, shaderProperties, - BlendModeOverride.OFF, readTesselation); - this.shadowCompute = readComputeArray(directory, sourceProvider, "shadow"); + BlendModeOverride.OFF, readTesselation); + this.shadowCompute = readComputeArray(directory, sourceProvider, "shadow", shaderProperties); this.shadowcomp = readProgramArray(directory, sourceProvider, "shadowcomp", shaderProperties, readTesselation); this.shadowCompCompute = new ComputeSource[shadowcomp.length][]; for (int i = 0; i < shadowcomp.length; i++) { - this.shadowCompCompute[i] = readComputeArray(directory, sourceProvider, "shadowcomp" + ((i == 0) ? "" : i)); + this.shadowCompCompute[i] = readComputeArray(directory, sourceProvider, "shadowcomp" + ((i == 0) ? "" : i), shaderProperties); } - this.setup = readProgramArray(directory, sourceProvider, "setup"); + this.setup = readProgramArray(directory, sourceProvider, "setup", shaderProperties); this.begin = readProgramArray(directory, sourceProvider, "begin", shaderProperties, readTesselation); this.beginCompute = new ComputeSource[begin.length][]; for (int i = 0; i < begin.length; i++) { - this.beginCompute[i] = readComputeArray(directory, sourceProvider, "begin" + ((i == 0) ? "" : i)); + this.beginCompute[i] = readComputeArray(directory, sourceProvider, "begin" + ((i == 0) ? "" : i), shaderProperties); } this.prepare = readProgramArray(directory, sourceProvider, "prepare", shaderProperties, readTesselation); this.prepareCompute = new ComputeSource[prepare.length][]; for (int i = 0; i < prepare.length; i++) { - this.prepareCompute[i] = readComputeArray(directory, sourceProvider, "prepare" + ((i == 0) ? "" : i)); + this.prepareCompute[i] = readComputeArray(directory, sourceProvider, "prepare" + ((i == 0) ? "" : i), shaderProperties); } this.gbuffersBasic = readProgramSource(directory, sourceProvider, "gbuffers_basic", this, shaderProperties, readTesselation); @@ -132,11 +135,14 @@ public ProgramSet(AbsolutePackPath directory, Function this.gbuffersBlock = readProgramSource(directory, sourceProvider, "gbuffers_block", this, shaderProperties, readTesselation); this.gbuffersBlockTrans = readProgramSource(directory, sourceProvider, "gbuffers_block_translucent", this, shaderProperties, readTesselation); this.gbuffersHand = readProgramSource(directory, sourceProvider, "gbuffers_hand", this, shaderProperties, readTesselation); + this.dhTerrain = readProgramSource(directory, sourceProvider, "dh_terrain", this, shaderProperties, readTesselation); + this.dhWater = readProgramSource(directory, sourceProvider, "dh_water", this, shaderProperties, readTesselation); + this.dhShadow = readProgramSource(directory, sourceProvider, "dh_shadow", this, shaderProperties, readTesselation); this.deferred = readProgramArray(directory, sourceProvider, "deferred", shaderProperties, readTesselation); this.deferredCompute = new ComputeSource[deferred.length][]; for (int i = 0; i < deferred.length; i++) { - this.deferredCompute[i] = readComputeArray(directory, sourceProvider, "deferred" + ((i == 0) ? "" : i)); + this.deferredCompute[i] = readComputeArray(directory, sourceProvider, "deferred" + ((i == 0) ? "" : i), shaderProperties); } this.gbuffersWater = readProgramSource(directory, sourceProvider, "gbuffers_water", this, shaderProperties, readTesselation); @@ -145,22 +151,12 @@ public ProgramSet(AbsolutePackPath directory, Function this.composite = readProgramArray(directory, sourceProvider, "composite", shaderProperties, readTesselation); this.compositeCompute = new ComputeSource[composite.length][]; for (int i = 0; i < deferred.length; i++) { - this.compositeCompute[i] = readComputeArray(directory, sourceProvider, "composite" + ((i == 0) ? "" : i)); + this.compositeCompute[i] = readComputeArray(directory, sourceProvider, "composite" + ((i == 0) ? "" : i), shaderProperties); } this.compositeFinal = readProgramSource(directory, sourceProvider, "final", this, shaderProperties, readTesselation); - this.finalCompute = readComputeArray(directory, sourceProvider, "final"); + this.finalCompute = readComputeArray(directory, sourceProvider, "final", shaderProperties); locateDirectives(); - - if (!gbuffersDamagedBlock.isValid()) { - // Special behavior inherited by OptiFine & Iris from old ShadersMod - // Presumably this was added before DRAWBUFFERS was a thing? Or just a hardcoded hacky fix for some - // shader packs - in any case, Sildurs Vibrant Shaders and other packs rely on it. - first(getGbuffersTerrain(), getGbuffersTexturedLit(), getGbuffersTextured(), getGbuffersBasic()).ifPresent(src -> { - ProgramDirectives overrideDirectives = src.getDirectives().withOverriddenDrawBuffers(new int[] { 0 }); - this.gbuffersDamagedBlock = src.withDirectiveOverride(overrideDirectives); - }); - } } @SafeVarargs @@ -174,6 +170,72 @@ private static Optional first(Optional... candidates) { return Optional.empty(); } + private static ProgramSource readProgramSource(AbsolutePackPath directory, + Function sourceProvider, String program, + ProgramSet programSet, ShaderProperties properties, boolean readTesselation) { + return readProgramSource(directory, sourceProvider, program, programSet, properties, null, readTesselation); + } + + private static ProgramSource readProgramSource(AbsolutePackPath directory, + Function sourceProvider, String program, + ProgramSet programSet, ShaderProperties properties, + BlendModeOverride defaultBlendModeOverride, boolean readTesselation) { + AbsolutePackPath vertexPath = directory.resolve(program + ".vsh"); + String vertexSource = sourceProvider.apply(vertexPath); + + AbsolutePackPath geometryPath = directory.resolve(program + ".gsh"); + String geometrySource = sourceProvider.apply(geometryPath); + + String tessControlSource = null; + String tessEvalSource = null; + + if (readTesselation) { + AbsolutePackPath tessControlPath = directory.resolve(program + ".tcs"); + tessControlSource = sourceProvider.apply(tessControlPath); + + AbsolutePackPath tessEvalPath = directory.resolve(program + ".tes"); + tessEvalSource = sourceProvider.apply(tessEvalPath); + } + + AbsolutePackPath fragmentPath = directory.resolve(program + ".fsh"); + String fragmentSource = sourceProvider.apply(fragmentPath); + + if (vertexSource == null && fragmentSource != null) { + // This is for really old packs that do not use a vertex shader. + Iris.logger.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right."); + vertexSource = """ + #version 120 + + varying vec4 irs_texCoords[3]; + varying vec4 irs_Color; + + void main() { + gl_Position = ftransform(); + irs_texCoords[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; + irs_texCoords[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1; + irs_texCoords[2] = gl_TextureMatrix[1] * gl_MultiTexCoord2; + irs_Color = gl_Color; + } + """; + } + + return new ProgramSource(program, vertexSource, geometrySource, tessControlSource, tessEvalSource, fragmentSource, programSet, properties, + defaultBlendModeOverride); + } + + private static ComputeSource readComputeSource(AbsolutePackPath directory, + Function sourceProvider, String program, + ProgramSet programSet, ShaderProperties properties) { + AbsolutePackPath computePath = directory.resolve(program + ".csh"); + String computeSource = sourceProvider.apply(computePath); + + if (computeSource == null) { + return null; + } + + return new ComputeSource(program, computeSource, programSet, properties); + } + private ProgramSource[] readProgramArray(AbsolutePackPath directory, Function sourceProvider, String name, ShaderProperties shaderProperties, boolean readTesselation) { @@ -189,28 +251,28 @@ private ProgramSource[] readProgramArray(AbsolutePackPath directory, } private ComputeSource[] readProgramArray(AbsolutePackPath directory, - Function sourceProvider, String name) { + Function sourceProvider, String name, ShaderProperties properties) { ComputeSource[] programs = new ComputeSource[100]; for (int i = 0; i < programs.length; i++) { String suffix = i == 0 ? "" : Integer.toString(i); - programs[i] = readComputeSource(directory, sourceProvider, name + suffix, this); + programs[i] = readComputeSource(directory, sourceProvider, name + suffix, this, properties); } return programs; } private ComputeSource[] readComputeArray(AbsolutePackPath directory, - Function sourceProvider, String name) { + Function sourceProvider, String name, ShaderProperties properties) { ComputeSource[] programs = new ComputeSource[27]; - programs[0] = readComputeSource(directory, sourceProvider, name, this); + programs[0] = readComputeSource(directory, sourceProvider, name, this, properties); for (char c = 'a'; c <= 'z'; ++c) { String suffix = "_" + c; - programs[c - 96] = readComputeSource(directory, sourceProvider, name + suffix, this); + programs[c - 96] = readComputeSource(directory, sourceProvider, name + suffix, this, properties); if (programs[c - 96] == null) { break; @@ -229,11 +291,11 @@ private void locateDirectives() { programs.addAll(Arrays.asList(begin)); programs.addAll(Arrays.asList(prepare)); - programs.addAll (Arrays.asList( - gbuffersBasic, gbuffersBeaconBeam, gbuffersTextured, gbuffersTexturedLit, gbuffersTerrain, gbuffersTerrainSolid, gbuffersTerrainCutout, - gbuffersDamagedBlock, gbuffersSkyBasic, gbuffersSkyTextured, gbuffersClouds, gbuffersWeather, - gbuffersEntities, gbuffersEntitiesTrans, gbuffersEntitiesGlowing, gbuffersGlint, gbuffersEntityEyes, gbuffersBlock, gbuffersBlockTrans, - gbuffersHand + programs.addAll(Arrays.asList( + gbuffersBasic, gbuffersBeaconBeam, gbuffersTextured, gbuffersTexturedLit, gbuffersTerrain, gbuffersTerrainSolid, gbuffersTerrainCutout, + gbuffersDamagedBlock, gbuffersSkyBasic, gbuffersSkyTextured, gbuffersClouds, gbuffersWeather, + gbuffersEntities, gbuffersEntitiesTrans, gbuffersEntitiesGlowing, gbuffersGlint, gbuffersEntityEyes, gbuffersBlock, gbuffersBlockTrans, + gbuffersHand, dhShadow, dhTerrain, dhWater )); for (ComputeSource computeSource : setup) { @@ -413,37 +475,52 @@ public Optional getGbuffersHand() { return gbuffersHand.requireValid(); } + public Optional getDhTerrain() { + return dhTerrain.requireValid(); + } + + public Optional getDhWater() { + return dhWater.requireValid(); + } + + public Optional getDhShadow() { + return dhShadow.requireValid(); + } + public Optional get(ProgramId programId) { - switch (programId) { - case Shadow: return getShadow(); - case Basic: return getGbuffersBasic(); - case Line: return gbuffersLine.requireValid(); - case Textured: return getGbuffersTextured(); - case TexturedLit: return getGbuffersTexturedLit(); - case SkyBasic: return getGbuffersSkyBasic(); - case SkyTextured: return getGbuffersSkyTextured(); - case Clouds: return getGbuffersClouds(); - case Terrain: return getGbuffersTerrain(); - case TerrainSolid: return getGbuffersTerrainSolid(); - case TerrainCutout: return getGbuffersTerrainCutout(); - case DamagedBlock: return getGbuffersDamagedBlock(); - case Block: return getGbuffersBlock(); - case BlockTrans: return getGbuffersBlockTrans(); - case BeaconBeam: return getGbuffersBeaconBeam(); - case Entities: return getGbuffersEntities(); - case EntitiesTrans: return getGbuffersEntitiesTrans(); - case Particles: return getGbuffersParticles(); - case ParticlesTrans: return getGbuffersParticlesTrans(); - case EntitiesGlowing: return getGbuffersEntitiesGlowing(); - case ArmorGlint: return getGbuffersGlint(); - case SpiderEyes: return getGbuffersEntityEyes(); - case Hand: return getGbuffersHand(); - case Weather: return getGbuffersWeather(); - case Water: return getGbuffersWater(); - case HandWater: return getGbuffersHandWater(); - case Final: return getCompositeFinal(); - default: return Optional.empty(); - } + return switch (programId) { + case Shadow -> getShadow(); + case Basic -> getGbuffersBasic(); + case Line -> gbuffersLine.requireValid(); + case Textured -> getGbuffersTextured(); + case TexturedLit -> getGbuffersTexturedLit(); + case SkyBasic -> getGbuffersSkyBasic(); + case SkyTextured -> getGbuffersSkyTextured(); + case Clouds -> getGbuffersClouds(); + case Terrain -> getGbuffersTerrain(); + case TerrainSolid -> getGbuffersTerrainSolid(); + case TerrainCutout -> getGbuffersTerrainCutout(); + case DamagedBlock -> getGbuffersDamagedBlock(); + case Block -> getGbuffersBlock(); + case BlockTrans -> getGbuffersBlockTrans(); + case BeaconBeam -> getGbuffersBeaconBeam(); + case Entities -> getGbuffersEntities(); + case EntitiesTrans -> getGbuffersEntitiesTrans(); + case Particles -> getGbuffersParticles(); + case ParticlesTrans -> getGbuffersParticlesTrans(); + case EntitiesGlowing -> getGbuffersEntitiesGlowing(); + case ArmorGlint -> getGbuffersGlint(); + case SpiderEyes -> getGbuffersEntityEyes(); + case Hand -> getGbuffersHand(); + case Weather -> getGbuffersWeather(); + case Water -> getGbuffersWater(); + case HandWater -> getGbuffersHandWater(); + case Final -> getCompositeFinal(); + case DhTerrain -> getDhTerrain(); + case DhWater -> getDhWater(); + case DhShadow -> getDhShadow(); + default -> Optional.empty(); + }; } public ProgramSource[] getDeferred() { @@ -501,70 +578,4 @@ public PackDirectives getPackDirectives() { public ShaderPack getPack() { return pack; } - - private static ProgramSource readProgramSource(AbsolutePackPath directory, - Function sourceProvider, String program, - ProgramSet programSet, ShaderProperties properties, boolean readTesselation) { - return readProgramSource(directory, sourceProvider, program, programSet, properties, null, readTesselation); - } - - private static ProgramSource readProgramSource(AbsolutePackPath directory, - Function sourceProvider, String program, - ProgramSet programSet, ShaderProperties properties, - BlendModeOverride defaultBlendModeOverride, boolean readTesselation) { - AbsolutePackPath vertexPath = directory.resolve(program + ".vsh"); - String vertexSource = sourceProvider.apply(vertexPath); - - AbsolutePackPath geometryPath = directory.resolve(program + ".gsh"); - String geometrySource = sourceProvider.apply(geometryPath); - - String tessControlSource = null; - String tessEvalSource = null; - - if (readTesselation) { - AbsolutePackPath tessControlPath = directory.resolve(program + ".tcs"); - tessControlSource = sourceProvider.apply(tessControlPath); - - AbsolutePackPath tessEvalPath = directory.resolve(program + ".tes"); - tessEvalSource = sourceProvider.apply(tessEvalPath); - } - - AbsolutePackPath fragmentPath = directory.resolve(program + ".fsh"); - String fragmentSource = sourceProvider.apply(fragmentPath); - - if (vertexSource == null && fragmentSource != null) { - // This is for really old packs that do not use a vertex shader. - Iris.logger.warn("Found a program (" + program + ") that has a fragment shader but no vertex shader? This is very legacy behavior and might not work right."); - vertexSource = """ - #version 120 - - varying vec4 irs_texCoords[3]; - varying vec4 irs_Color; - - void main() { - gl_Position = ftransform(); - irs_texCoords[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; - irs_texCoords[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1; - irs_texCoords[2] = gl_TextureMatrix[1] * gl_MultiTexCoord2; - irs_Color = gl_Color; - } - """; - } - - return new ProgramSource(program, vertexSource, geometrySource, tessControlSource, tessEvalSource, fragmentSource, programSet, properties, - defaultBlendModeOverride); - } - - private static ComputeSource readComputeSource(AbsolutePackPath directory, - Function sourceProvider, String program, - ProgramSet programSet) { - AbsolutePackPath computePath = directory.resolve(program + ".csh"); - String computeSource = sourceProvider.apply(computePath); - - if (computeSource == null) { - return null; - } - - return new ComputeSource(program, computeSource, programSet); - } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/ProgramSetInterface.java b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSetInterface.java similarity index 75% rename from src/main/java/net/coderbot/iris/shaderpack/ProgramSetInterface.java rename to src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSetInterface.java index 0a83774ec5..26a231be05 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ProgramSetInterface.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSetInterface.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.programs; public interface ProgramSetInterface { class Empty implements ProgramSetInterface { diff --git a/src/main/java/net/coderbot/iris/shaderpack/ProgramSource.java b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSource.java similarity index 83% rename from src/main/java/net/coderbot/iris/shaderpack/ProgramSource.java rename to src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSource.java index c519567dc8..d6a6401294 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ProgramSource.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/programs/ProgramSource.java @@ -1,6 +1,9 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.programs; -import net.coderbot.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import net.irisshaders.iris.shaderpack.properties.ShaderProperties; import java.util.Optional; @@ -15,7 +18,7 @@ public class ProgramSource { private final ProgramSet parent; private ProgramSource(String name, String vertexSource, String geometrySource, String tessControlSource, String tessEvalSource, String fragmentSource, - ProgramDirectives directives, ProgramSet parent) { + ProgramDirectives directives, ProgramSet parent) { this.name = name; this.vertexSource = vertexSource; this.geometrySource = geometrySource; @@ -36,7 +39,7 @@ public ProgramSource(String name, String vertexSource, String geometrySource, St this.fragmentSource = fragmentSource; this.parent = parent; this.directives = new ProgramDirectives(this, properties, - PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, defaultBlendModeOverride); + PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, defaultBlendModeOverride); } public ProgramSource withDirectiveOverride(ProgramDirectives overrideDirectives) { diff --git a/src/main/java/net/coderbot/iris/shaderpack/CloudSetting.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/CloudSetting.java similarity index 53% rename from src/main/java/net/coderbot/iris/shaderpack/CloudSetting.java rename to src/main/java/net/irisshaders/iris/shaderpack/properties/CloudSetting.java index 18a69f6f2f..8d51a8e212 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/CloudSetting.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/CloudSetting.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.properties; public enum CloudSetting { DEFAULT, diff --git a/src/main/java/net/irisshaders/iris/shaderpack/properties/IndirectPointer.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/IndirectPointer.java new file mode 100644 index 0000000000..2f3d9ae2f5 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/IndirectPointer.java @@ -0,0 +1,4 @@ +package net.irisshaders.iris.shaderpack.properties; + +public record IndirectPointer(int buffer, long offset) { +} diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackDirectives.java similarity index 90% rename from src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java rename to src/main/java/net/irisshaders/iris/shaderpack/properties/PackDirectives.java index 9bbd257b79..d1b7e3a51b 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackDirectives.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackDirectives.java @@ -1,30 +1,32 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.properties; import com.google.common.collect.ImmutableMap; -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.objects.Object2BooleanMap; import it.unimi.dsi.fastutil.objects.Object2BooleanMaps; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.buffer.ShaderStorageInfo; -import net.coderbot.iris.gl.texture.TextureScaleOverride; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.helpers.Tri; -import net.coderbot.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.buffer.ShaderStorageInfo; +import net.irisshaders.iris.gl.texture.TextureScaleOverride; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.helpers.Tri; +import net.irisshaders.iris.shaderpack.parsing.DirectiveHolder; +import net.irisshaders.iris.shaderpack.texture.TextureStage; import org.joml.Vector2i; import java.util.Optional; import java.util.Set; public class PackDirectives { + private final PackRenderTargetDirectives renderTargetDirectives; + private final PackShadowDirectives shadowDirectives; + private final float drynessHalfLife; private boolean supportsColorCorrection; private int noiseTextureResolution; private float sunPathRotation; private float ambientOcclusionLevel; private float wetnessHalfLife; - private float drynessHalfLife; private float eyeBrightnessHalfLife; private float centerDepthHalfLife; private CloudSetting cloudSetting; @@ -37,6 +39,7 @@ public class PackDirectives { private boolean voxelizeLightBlocks; private boolean separateEntityDraws; private boolean frustumCulling; + private boolean occlusionCulling; private boolean oldLighting; private boolean concurrentCompute; private boolean oldHandLight; @@ -45,9 +48,6 @@ public class PackDirectives { private Object2ObjectMap scaleOverrides = new Object2ObjectOpenHashMap<>(); private Object2ObjectMap, String> textureMap; private Int2ObjectArrayMap bufferObjects; - - private final PackRenderTargetDirectives renderTargetDirectives; - private final PackShadowDirectives shadowDirectives; private Optional particleRenderingSettings; private PackDirectives(Set supportedRenderTargets, PackShadowDirectives packShadowDirectives) { @@ -64,7 +64,7 @@ private PackDirectives(Set supportedRenderTargets, PackShadowDirectives shadowDirectives = packShadowDirectives; } - PackDirectives(Set supportedRenderTargets, ShaderProperties properties) { + public PackDirectives(Set supportedRenderTargets, ShaderProperties properties) { this(supportedRenderTargets, new PackShadowDirectives(properties)); cloudSetting = properties.getCloudSetting(); underwaterOverlay = properties.getUnderwaterOverlay().orElse(false); @@ -76,6 +76,7 @@ private PackDirectives(Set supportedRenderTargets, PackShadowDirectives voxelizeLightBlocks = properties.getVoxelizeLightBlocks().orElse(false); separateEntityDraws = properties.getSeparateEntityDraws().orElse(false); frustumCulling = properties.getFrustumCulling().orElse(true); + occlusionCulling = properties.getOcclusionCulling().orElse(true); oldLighting = properties.getOldLighting().orElse(false); supportsColorCorrection = properties.supportsColorCorrection().orElse(false); concurrentCompute = properties.getConcurrentCompute().orElse(false); @@ -105,6 +106,10 @@ private PackDirectives(Set supportedRenderTargets, PackShadowDirectives bufferObjects = directives.bufferObjects; } + private static float clamp(float val, float lo, float hi) { + return Math.max(lo, Math.min(hi, val)); + } + public int getNoiseTextureResolution() { return noiseTextureResolution; } @@ -177,6 +182,10 @@ public boolean shouldUseFrustumCulling() { return frustumCulling; } + public boolean shouldUseOcclusionCulling() { + return occlusionCulling; + } + public boolean isOldLighting() { return oldLighting; } @@ -184,6 +193,7 @@ public boolean isOldLighting() { public boolean isOldHandLight() { return oldHandLight; } + public boolean getConcurrentCompute() { return concurrentCompute; } @@ -212,22 +222,18 @@ public boolean supportsColorCorrection() { return supportsColorCorrection; } - private static float clamp(float val, float lo, float hi) { - return Math.max(lo, Math.min(hi, val)); - } - public void acceptDirectivesFrom(DirectiveHolder directives) { renderTargetDirectives.acceptDirectives(directives); shadowDirectives.acceptDirectives(directives); directives.acceptConstIntDirective("noiseTextureResolution", - noiseTextureResolution -> this.noiseTextureResolution = noiseTextureResolution); + noiseTextureResolution -> this.noiseTextureResolution = noiseTextureResolution); directives.acceptConstFloatDirective("sunPathRotation", - sunPathRotation -> this.sunPathRotation = sunPathRotation); + sunPathRotation -> this.sunPathRotation = sunPathRotation); directives.acceptConstFloatDirective("ambientOcclusionLevel", - ambientOcclusionLevel -> this.ambientOcclusionLevel = clamp(ambientOcclusionLevel, 0.0f, 1.0f)); + ambientOcclusionLevel -> this.ambientOcclusionLevel = clamp(ambientOcclusionLevel, 0.0f, 1.0f)); directives.acceptConstFloatDirective("wetnessHalflife", wetnessHalfLife -> this.wetnessHalfLife = wetnessHalfLife); @@ -268,7 +274,7 @@ public ImmutableMap getExplicitFlips(String pass) { explicitFlips.put(index, shouldFlip); } else { Iris.logger.warn("Unknown buffer with ID " + buffer + " specified in flip directive for pass " - + pass); + + pass); } }); diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackRenderTargetDirectives.java similarity index 89% rename from src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java rename to src/main/java/net/irisshaders/iris/shaderpack/properties/PackRenderTargetDirectives.java index 3276e564e7..0bee631ac6 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackRenderTargetDirectives.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackRenderTargetDirectives.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.properties; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; @@ -6,8 +6,10 @@ import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.IrisLimits; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.shaderpack.parsing.DirectiveHolder; import org.joml.Vector4f; import java.util.Collections; @@ -47,7 +49,7 @@ public class PackRenderTargetDirectives { this.renderTargetSettings = new Int2ObjectOpenHashMap<>(); supportedRenderTargets.forEach( - (index) -> renderTargetSettings.put(index.intValue(), new RenderTargetSettings())); + (index) -> renderTargetSettings.put(index.intValue(), new RenderTargetSettings())); } public IntList getBuffersToBeCleared() { @@ -116,14 +118,14 @@ private void acceptBufferDirectives(DirectiveHolder directives, RenderTargetSett // TODO: Only for composite and deferred directives.acceptConstBooleanDirective(bufferName + "Clear", - shouldClear -> settings.clear = shouldClear); + shouldClear -> settings.clear = shouldClear); // TODO: Only for composite, deferred, and final // Note: This is still relevant even if shouldClear is false, // since this will be the initial color of the buffer. directives.acceptConstVec4Directive(bufferName + "ClearColor", - clearColor -> settings.clearColor = clearColor); + clearColor -> settings.clearColor = clearColor); } public static final class RenderTargetSettings { @@ -152,10 +154,10 @@ public Optional getClearColor() { @Override public String toString() { return "RenderTargetSettings{" + - "requestedFormat=" + requestedFormat + - ", clear=" + clear + - ", clearColor=" + clearColor + - '}'; + "requestedFormat=" + requestedFormat + + ", clear=" + clear + + ", clearColor=" + clearColor + + '}'; } } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackShadowDirectives.java similarity index 88% rename from src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java rename to src/main/java/net/irisshaders/iris/shaderpack/properties/PackShadowDirectives.java index 50240965d4..2ca39d5089 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/PackShadowDirectives.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/PackShadowDirectives.java @@ -1,14 +1,14 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.properties; import com.google.common.collect.ImmutableList; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.helpers.OptionalBoolean; +import net.irisshaders.iris.shaderpack.parsing.DirectiveHolder; import org.joml.Vector4f; -import java.util.ArrayList; -import java.util.List; import java.util.Optional; public class PackShadowDirectives { @@ -19,27 +19,28 @@ public class PackShadowDirectives { public static final int MAX_SHADOW_COLOR_BUFFERS_OF = 2; private final OptionalBoolean shadowEnabled; - + private final OptionalBoolean dhShadowEnabled; + private final boolean shouldRenderTerrain; + private final boolean shouldRenderTranslucent; + private final boolean shouldRenderEntities; + private final boolean shouldRenderPlayer; + private final boolean shouldRenderBlockEntities; + private final boolean shouldRenderLightBlockEntities; + private final ShadowCullState cullingState; + private final ImmutableList depthSamplingSettings; + private final Int2ObjectMap colorSamplingSettings; private int resolution; // Use a boxed form so we can use null to indicate that there is not an FOV specified. private Float fov; private float distance; + private float nearPlane; + private float farPlane; private float voxelDistance; private float distanceRenderMul; private float entityShadowDistanceMul; private boolean explicitRenderDistance; private float intervalSize; - private final boolean shouldRenderTerrain; - private final boolean shouldRenderTranslucent; - private final boolean shouldRenderEntities; - private final boolean shouldRenderPlayer; - private final boolean shouldRenderBlockEntities; - private final ShadowCullState cullingState; - - private final ImmutableList depthSamplingSettings; - private final Int2ObjectMap colorSamplingSettings; - public PackShadowDirectives(ShaderProperties properties) { // By default, the shadow map has a resolution of 1024x1024. It's recommended to increase this for better // quality. @@ -59,6 +60,8 @@ public PackShadowDirectives(ShaderProperties properties) { // shadowRenderDistanceMul to a nonzero value, since having a high shadow render distance will impact // performance quite heavily on most systems. this.distance = 160.0f; + this.nearPlane = 0.05f; + this.farPlane = 256.0f; this.voxelDistance = 0.0f; // By default, shadows are not culled based on distance from the player. However, pack authors may @@ -85,8 +88,10 @@ public PackShadowDirectives(ShaderProperties properties) { this.shouldRenderEntities = properties.getShadowEntities().orElse(true); this.shouldRenderPlayer = properties.getShadowPlayer().orElse(false); this.shouldRenderBlockEntities = properties.getShadowBlockEntities().orElse(true); + this.shouldRenderLightBlockEntities = properties.getShadowLightBlockEntities().orElse(false); this.cullingState = properties.getShadowCulling(); this.shadowEnabled = properties.getShadowEnabled(); + this.dhShadowEnabled = properties.getDhShadowEnabled(); this.depthSamplingSettings = ImmutableList.of(new DepthSamplingSettings(), new DepthSamplingSettings()); @@ -99,6 +104,8 @@ public PackShadowDirectives(PackShadowDirectives shadowDirectives) { this.resolution = shadowDirectives.resolution; this.fov = shadowDirectives.fov; this.distance = shadowDirectives.distance; + this.nearPlane = shadowDirectives.nearPlane; + this.farPlane = shadowDirectives.farPlane; this.voxelDistance = shadowDirectives.voxelDistance; this.distanceRenderMul = shadowDirectives.distanceRenderMul; this.entityShadowDistanceMul = shadowDirectives.entityShadowDistanceMul; @@ -109,10 +116,102 @@ public PackShadowDirectives(PackShadowDirectives shadowDirectives) { this.shouldRenderEntities = shadowDirectives.shouldRenderEntities; this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer; this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities; + this.shouldRenderLightBlockEntities = shadowDirectives.shouldRenderLightBlockEntities; this.cullingState = shadowDirectives.cullingState; this.depthSamplingSettings = shadowDirectives.depthSamplingSettings; this.colorSamplingSettings = shadowDirectives.colorSamplingSettings; this.shadowEnabled = shadowDirectives.shadowEnabled; + this.dhShadowEnabled = shadowDirectives.dhShadowEnabled; + } + + /** + * Handles shadowHardwareFiltering* directives + */ + private static void acceptHardwareFilteringSettings(DirectiveHolder directives, ImmutableList samplers) { + // Get the default base value for the hardware filtering setting + directives.acceptConstBooleanDirective("shadowHardwareFiltering", hardwareFiltering -> { + for (DepthSamplingSettings samplerSettings : samplers) { + samplerSettings.setHardwareFiltering(hardwareFiltering); + } + }); + + // Find any per-sampler overrides for the hardware filtering setting + for (int i = 0; i < samplers.size(); i++) { + String name = "shadowHardwareFiltering" + i; + + directives.acceptConstBooleanDirective(name, samplers.get(i)::setHardwareFiltering); + } + } + + private static void acceptDepthMipmapSettings(DirectiveHolder directives, ImmutableList samplers) { + // Get the default base value for the shadow depth mipmap setting + directives.acceptConstBooleanDirective("generateShadowMipmap", mipmap -> { + for (SamplingSettings samplerSettings : samplers) { + samplerSettings.setMipmap(mipmap); + } + }); + + // Find any per-sampler overrides for the shadow depth mipmap setting + + // Legacy override option: shadowtexMipmap, an alias for shadowtex0Mipmap + if (!samplers.isEmpty()) { + directives.acceptConstBooleanDirective("shadowtexMipmap", samplers.get(0)::setMipmap); + } + + // Standard override option: shadowtex0Mipmap and shadowtex1Mipmap + for (int i = 0; i < samplers.size(); i++) { + String name = "shadowtex" + i + "Mipmap"; + + directives.acceptConstBooleanDirective(name, samplers.get(i)::setMipmap); + } + } + + private static void acceptColorMipmapSettings(DirectiveHolder directives, Int2ObjectMap samplers) { + // Get the default base value for the shadow depth mipmap setting + directives.acceptConstBooleanDirective("generateShadowColorMipmap", mipmap -> { + samplers.forEach((i, sampler) -> sampler.setMipmap(mipmap)); + }); + + // Find any per-sampler overrides for the shadow depth mipmap setting + for (int i = 0; i < samplers.size(); i++) { + String name = "shadowcolor" + i + "Mipmap"; + directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setMipmap); + + name = "shadowColor" + i + "Mipmap"; + directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setMipmap); + } + } + + private static void acceptDepthFilteringSettings(DirectiveHolder directives, ImmutableList samplers) { + if (!samplers.isEmpty()) { + directives.acceptConstBooleanDirective("shadowtexNearest", samplers.get(0)::setNearest); + } + + for (int i = 0; i < samplers.size(); i++) { + String name = "shadowtex" + i + "Nearest"; + + directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); + + name = "shadow" + i + "MinMagNearest"; + + directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); + } + } + + private static void acceptColorFilteringSettings(DirectiveHolder directives, Int2ObjectMap samplers) { + for (int i = 0; i < samplers.size(); i++) { + String name = "shadowcolor" + i + "Nearest"; + + directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); + + name = "shadowColor" + i + "Nearest"; + + directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); + + name = "shadowColor" + i + "MinMagNearest"; + + directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); + } } public int getResolution() { @@ -127,6 +226,14 @@ public float getDistance() { return distance; } + public float getNearPlane() { + return nearPlane; + } + + public float getFarPlane() { + return farPlane; + } + public float getVoxelDistance() { return voxelDistance; } @@ -167,6 +274,10 @@ public boolean shouldRenderBlockEntities() { return shouldRenderBlockEntities; } + public boolean shouldRenderLightBlockEntities() { + return shouldRenderLightBlockEntities; + } + public ShadowCullState getCullingState() { return cullingState; } @@ -175,6 +286,10 @@ public OptionalBoolean isShadowEnabled() { return shadowEnabled; } + public OptionalBoolean isDhShadowEnabled() { + return dhShadowEnabled; + } + public ImmutableList getDepthSamplingSettings() { return depthSamplingSettings; } @@ -192,6 +307,8 @@ public void acceptDirectives(DirectiveHolder directives) { directives.acceptCommentFloatDirective("SHADOWHPL", distance -> this.distance = distance); directives.acceptConstFloatDirective("shadowDistance", distance -> this.distance = distance); + directives.acceptConstFloatDirective("shadowNearPlane", nearPlane -> this.nearPlane = nearPlane); + directives.acceptConstFloatDirective("shadowFarPlane", farPlane -> this.farPlane = farPlane); directives.acceptConstFloatDirective("voxelDistance", distance -> this.voxelDistance = distance); directives.acceptConstFloatDirective("entityShadowDistanceMul", distance -> this.entityShadowDistanceMul = distance); @@ -202,7 +319,7 @@ public void acceptDirectives(DirectiveHolder directives) { }); directives.acceptConstFloatDirective("shadowIntervalSize", - intervalSize -> this.intervalSize = intervalSize); + intervalSize -> this.intervalSize = intervalSize); acceptHardwareFilteringSettings(directives, depthSamplingSettings); acceptDepthMipmapSettings(directives, depthSamplingSettings); @@ -212,96 +329,6 @@ public void acceptDirectives(DirectiveHolder directives) { acceptBufferDirectives(directives, colorSamplingSettings); } - /** - * Handles shadowHardwareFiltering* directives - */ - private static void acceptHardwareFilteringSettings(DirectiveHolder directives, ImmutableList samplers) { - // Get the default base value for the hardware filtering setting - directives.acceptConstBooleanDirective("shadowHardwareFiltering", hardwareFiltering -> { - for (DepthSamplingSettings samplerSettings : samplers) { - samplerSettings.setHardwareFiltering(hardwareFiltering); - } - }); - - // Find any per-sampler overrides for the hardware filtering setting - for (int i = 0; i < samplers.size(); i++) { - String name = "shadowHardwareFiltering" + i; - - directives.acceptConstBooleanDirective(name, samplers.get(i)::setHardwareFiltering); - } - } - - private static void acceptDepthMipmapSettings(DirectiveHolder directives, ImmutableList samplers) { - // Get the default base value for the shadow depth mipmap setting - directives.acceptConstBooleanDirective("generateShadowMipmap", mipmap -> { - for (SamplingSettings samplerSettings : samplers) { - samplerSettings.setMipmap(mipmap); - } - }); - - // Find any per-sampler overrides for the shadow depth mipmap setting - - // Legacy override option: shadowtexMipmap, an alias for shadowtex0Mipmap - if (samplers.size() >= 1) { - directives.acceptConstBooleanDirective("shadowtexMipmap", samplers.get(0)::setMipmap); - } - - // Standard override option: shadowtex0Mipmap and shadowtex1Mipmap - for (int i = 0; i < samplers.size(); i++) { - String name = "shadowtex" + i + "Mipmap"; - - directives.acceptConstBooleanDirective(name, samplers.get(i)::setMipmap); - } - } - - private static void acceptColorMipmapSettings(DirectiveHolder directives, Int2ObjectMap samplers) { - // Get the default base value for the shadow depth mipmap setting - directives.acceptConstBooleanDirective("generateShadowColorMipmap", mipmap -> { - samplers.forEach((i, sampler) -> sampler.setMipmap(mipmap)); - }); - - // Find any per-sampler overrides for the shadow depth mipmap setting - for (int i = 0; i < samplers.size(); i++) { - String name = "shadowcolor" + i + "Mipmap"; - directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setMipmap); - - name = "shadowColor" + i + "Mipmap"; - directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setMipmap); - } - } - - private static void acceptDepthFilteringSettings(DirectiveHolder directives, ImmutableList samplers) { - if (samplers.size() >= 1) { - directives.acceptConstBooleanDirective("shadowtexNearest", samplers.get(0)::setNearest); - } - - for (int i = 0; i < samplers.size(); i++) { - String name = "shadowtex" + i + "Nearest"; - - directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); - - name = "shadow" + i + "MinMagNearest"; - - directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); - } - } - - private static void acceptColorFilteringSettings(DirectiveHolder directives, Int2ObjectMap samplers) { - for (int i = 0; i < samplers.size(); i++) { - String name = "shadowcolor" + i + "Nearest"; - - directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); - - name = "shadowColor" + i + "Nearest"; - - directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); - - name = "shadowColor" + i + "MinMagNearest"; - - directives.acceptConstBooleanDirective(name, samplers.computeIfAbsent(i, sa -> new SamplingSettings())::setNearest); - } - } - private void acceptBufferDirectives(DirectiveHolder directives, Int2ObjectMap settings) { for (int i = 0; i < PackShadowDirectives.MAX_SHADOW_COLOR_BUFFERS_IRIS; i++) { String bufferName = "shadowcolor" + i; @@ -332,15 +359,15 @@ private void acceptBufferDirectives(DirectiveHolder directives, Int2ObjectMap getAppliedDirective(Optional optionalDrawbuffersDirective, Optional optionalRendertargetsDirective) { @@ -159,13 +155,16 @@ private static Optional getAppliedDirective(Optional> profiles = new LinkedHashMap<>(); + private final Map> subScreenOptions = new HashMap<>(); + private final Map subScreenColumnCount = new HashMap<>(); + // TODO: private Map optifineVersionRequirements; + // TODO: Parse custom uniforms / variables + private final Object2ObjectMap alphaTestOverrides = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap viewportScaleOverrides = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap textureScaleOverrides = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap blendModeOverrides = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap indirectPointers = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap> bufferBlendOverrides = new Object2ObjectOpenHashMap<>(); + private final EnumMap> customTextures = new EnumMap<>(TextureStage.class); + private final Object2ObjectMap, String> customTexturePatching = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap irisCustomTextures = new Object2ObjectOpenHashMap<>(); + private final List irisCustomImages = new ArrayList<>(); + private final Int2ObjectArrayMap bufferObjects = new Int2ObjectArrayMap<>(); + private final Object2ObjectMap> explicitFlips = new Object2ObjectOpenHashMap<>(); + private final Object2ObjectMap conditionallyEnabledPrograms = new Object2ObjectOpenHashMap<>(); + CustomUniforms.Builder customUniforms = new CustomUniforms.Builder(); private int customTexAmount; private CloudSetting cloudSetting = CloudSetting.DEFAULT; private OptionalBoolean oldHandLight = OptionalBoolean.DEFAULT; @@ -65,6 +85,7 @@ public class ShaderProperties { private OptionalBoolean shadowEntities = OptionalBoolean.DEFAULT; private OptionalBoolean shadowPlayer = OptionalBoolean.DEFAULT; private OptionalBoolean shadowBlockEntities = OptionalBoolean.DEFAULT; + private OptionalBoolean shadowLightBlockEntities = OptionalBoolean.DEFAULT; private OptionalBoolean underwaterOverlay = OptionalBoolean.DEFAULT; private OptionalBoolean sun = OptionalBoolean.DEFAULT; private OptionalBoolean moon = OptionalBoolean.DEFAULT; @@ -80,32 +101,16 @@ public class ShaderProperties { private OptionalBoolean voxelizeLightBlocks = OptionalBoolean.DEFAULT; private OptionalBoolean separateEntityDraws = OptionalBoolean.DEFAULT; private OptionalBoolean frustumCulling = OptionalBoolean.DEFAULT; + private OptionalBoolean occlusionCulling = OptionalBoolean.DEFAULT; private ShadowCullState shadowCulling = ShadowCullState.DEFAULT; private OptionalBoolean shadowEnabled = OptionalBoolean.DEFAULT; + private OptionalBoolean dhShadowEnabled = OptionalBoolean.DEFAULT; private Optional particleRenderingSettings = Optional.empty(); private OptionalBoolean prepareBeforeShadow = OptionalBoolean.DEFAULT; private List sliderOptions = new ArrayList<>(); - private final Map> profiles = new LinkedHashMap<>(); private List mainScreenOptions = null; - private final Map> subScreenOptions = new HashMap<>(); private Integer mainScreenColumnCount = null; - private final Map subScreenColumnCount = new HashMap<>(); - // TODO: private Map optifineVersionRequirements; - // TODO: Parse custom uniforms / variables - private final Object2ObjectMap alphaTestOverrides = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap viewportScaleOverrides = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap textureScaleOverrides = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap blendModeOverrides = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap> bufferBlendOverrides = new Object2ObjectOpenHashMap<>(); - private final EnumMap> customTextures = new EnumMap<>(TextureStage.class); - private final Object2ObjectMap, String> customTexturePatching = new Object2ObjectOpenHashMap<>(); - private final Object2ObjectMap irisCustomTextures = new Object2ObjectOpenHashMap<>(); - private final List irisCustomImages = new ArrayList<>(); - private final Int2ObjectArrayMap bufferObjects = new Int2ObjectArrayMap<>(); - private final Object2ObjectMap> explicitFlips = new Object2ObjectOpenHashMap<>(); private String noiseTexturePath = null; - CustomUniforms.Builder customUniforms = new CustomUniforms.Builder(); - private Object2ObjectMap conditionallyEnabledPrograms = new Object2ObjectOpenHashMap<>(); private List requiredFeatureFlags = new ArrayList<>(); private List optionalFeatureFlags = new ArrayList<>(); @@ -176,6 +181,7 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It handleBooleanDirective(key, value, "shadowEntities", bool -> shadowEntities = bool); handleBooleanDirective(key, value, "shadowPlayer", bool -> shadowPlayer = bool); handleBooleanDirective(key, value, "shadowBlockEntities", bool -> shadowBlockEntities = bool); + handleBooleanDirective(key, value, "shadowLightBlockEntities", bool -> shadowLightBlockEntities = bool); handleBooleanDirective(key, value, "underwaterOverlay", bool -> underwaterOverlay = bool); handleBooleanDirective(key, value, "sun", bool -> sun = bool); handleBooleanDirective(key, value, "moon", bool -> moon = bool); @@ -191,7 +197,9 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It handleBooleanDirective(key, value, "voxelizeLightBlocks", bool -> voxelizeLightBlocks = bool); handleBooleanDirective(key, value, "separateEntityDraws", bool -> separateEntityDraws = bool); handleBooleanDirective(key, value, "frustum.culling", bool -> frustumCulling = bool); + handleBooleanDirective(key, value, "occlusion.culling", bool -> occlusionCulling = bool); handleBooleanDirective(key, value, "shadow.enabled", bool -> shadowEnabled = bool); + handleBooleanDirective(key, value, "dhShadow.enabled", bool -> dhShadowEnabled = bool); handleBooleanDirective(key, value, "particles.before.deferred", bool -> { if (bool.orElse(false) && particleRenderingSettings.isEmpty()) { particleRenderingSettings = Optional.of(ParticleRenderingSettings.BEFORE); @@ -336,6 +344,16 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It blendModeOverrides.put(pass, new BlendModeOverride(new BlendMode(modes[0], modes[1], modes[2], modes[3]))); }); + handlePassDirective("indirect.", key, value, pass -> { + try { + String[] locations = value.split(" "); + + indirectPointers.put(pass, new IndirectPointer(Integer.parseInt(locations[0]), Long.parseLong(locations[1]))); + } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { + Iris.logger.fatal("Failed to parse indirect command for " + pass + "! " + value); + } + }); + handleProgramEnabledDirective("program.", key, value, program -> { conditionallyEnabledPrograms.put(program, value); }); @@ -360,6 +378,11 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It return; } + if (trueSize < 1) { + // Assume the shader dev intended to disable the buffer + return; + } + bufferObjects.put(trueIndex, new ShaderStorageInfo(trueSize, false, 0, 0)); } else { // Assume it's a long one @@ -379,6 +402,11 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It return; } + if (trueSize < 1) { + // Assume the shader dev intended to disable the buffer + return; + } + bufferObjects.put(trueIndex, new ShaderStorageInfo(trueSize, isRelative, scaleX, scaleY)); } }); @@ -424,7 +452,7 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It } customTextures.computeIfAbsent(stage, _stage -> new Object2ObjectOpenHashMap<>()) - .put(samplerName, new TextureDefinition.PNGDefinition(value)); + .put(samplerName, new TextureDefinition.PNGDefinition(value)); }); handlePassDirective("customTexture.", key, value, (samplerName) -> { @@ -514,13 +542,13 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It handleTwoArgDirective("flip.", key, value, (pass, buffer) -> { handleBooleanValue(key, value, shouldFlip -> { explicitFlips.computeIfAbsent(pass, _pass -> new Object2BooleanOpenHashMap<>()) - .put(buffer, shouldFlip); + .put(buffer, shouldFlip); }); }); handlePassDirective("variable.", key, value, pass -> { String[] parts = pass.split("\\."); - if(parts.length != 2){ + if (parts.length != 2) { Iris.logger.warn("Custom variables should take the form of `variable.. = . Ignoring " + key); return; } @@ -530,7 +558,7 @@ public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, It handlePassDirective("uniform.", key, value, pass -> { String[] parts = pass.split("\\."); - if(parts.length != 2){ + if (parts.length != 2) { Iris.logger.warn("Custom uniforms should take the form of `uniform.. = . Ignoring " + key); return; } @@ -682,6 +710,10 @@ public static ShaderProperties empty() { return new ShaderProperties(); } + public OptionalBoolean getDhShadowEnabled() { + return dhShadowEnabled; + } + public CloudSetting getCloudSetting() { return cloudSetting; } @@ -718,6 +750,10 @@ public OptionalBoolean getShadowBlockEntities() { return shadowBlockEntities; } + public OptionalBoolean getShadowLightBlockEntities() { + return shadowLightBlockEntities; + } + public OptionalBoolean getUnderwaterOverlay() { return underwaterOverlay; } @@ -774,6 +810,10 @@ public OptionalBoolean getFrustumCulling() { return frustumCulling; } + public OptionalBoolean getOcclusionCulling() { + return occlusionCulling; + } + public ShadowCullState getShadowCulling() { return shadowCulling; } @@ -812,6 +852,10 @@ public Object2ObjectMap getBlendModeOverrides() { return blendModeOverrides; } + public Object2ObjectMap getIndirectPointers() { + return indirectPointers; + } + public Object2ObjectMap> getBufferBlendOverrides() { return bufferBlendOverrides; } @@ -884,4 +928,8 @@ public List getOptionalFeatureFlags() { public OptionalBoolean supportsColorCorrection() { return supportsColorCorrection; } + + public CustomUniforms.Builder getCustomUniforms() { + return customUniforms; + } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/ShadowCullState.java b/src/main/java/net/irisshaders/iris/shaderpack/properties/ShadowCullState.java similarity index 59% rename from src/main/java/net/coderbot/iris/shaderpack/ShadowCullState.java rename to src/main/java/net/irisshaders/iris/shaderpack/properties/ShadowCullState.java index d407e1c628..5870ea4169 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/ShadowCullState.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/properties/ShadowCullState.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack; +package net.irisshaders.iris.shaderpack.properties; public enum ShadowCullState { DEFAULT, diff --git a/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java b/src/main/java/net/irisshaders/iris/shaderpack/texture/CustomTextureData.java similarity index 88% rename from src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java rename to src/main/java/net/irisshaders/iris/shaderpack/texture/CustomTextureData.java index a3f24d9fff..58c6d80848 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/texture/CustomTextureData.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/texture/CustomTextureData.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.shaderpack.texture; +package net.irisshaders.iris.shaderpack.texture; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.PixelFormat; +import net.irisshaders.iris.gl.texture.PixelType; public abstract class CustomTextureData { private CustomTextureData() { @@ -50,7 +50,7 @@ public ResourceData(String namespace, String location) { /** * @return The namespace of the texture. The caller is responsible for checking whether this is actually - * a valid namespace. + * a valid namespace. */ public String getNamespace() { return namespace; @@ -58,7 +58,7 @@ public String getNamespace() { /** * @return The path / location of the texture. The caller is responsible for checking whether this is actually - * a valid path. + * a valid path. */ public String getLocation() { return location; @@ -106,7 +106,7 @@ public static final class RawData1D extends RawData { private final int sizeX; public RawData1D(byte[] content, TextureFilteringData filteringData, InternalTextureFormat internalFormat, - PixelFormat pixelFormat, PixelType pixelType, int sizeX) { + PixelFormat pixelFormat, PixelType pixelType, int sizeX) { super(content, filteringData, internalFormat, pixelFormat, pixelType); this.sizeX = sizeX; @@ -122,7 +122,7 @@ public static class RawData2D extends RawData { int sizeY; public RawData2D(byte[] content, TextureFilteringData filteringData, InternalTextureFormat internalFormat, - PixelFormat pixelFormat, PixelType pixelType, int sizeX, int sizeY) { + PixelFormat pixelFormat, PixelType pixelType, int sizeX, int sizeY) { super(content, filteringData, internalFormat, pixelFormat, pixelType); this.sizeX = sizeX; @@ -144,7 +144,7 @@ public static final class RawData3D extends RawData { int sizeZ; public RawData3D(byte[] content, TextureFilteringData filteringData, InternalTextureFormat internalFormat, - PixelFormat pixelFormat, PixelType pixelType, int sizeX, int sizeY, int sizeZ) { + PixelFormat pixelFormat, PixelType pixelType, int sizeX, int sizeY, int sizeZ) { super(content, filteringData, internalFormat, pixelFormat, pixelType); this.sizeX = sizeX; diff --git a/src/main/java/net/coderbot/iris/shaderpack/texture/TextureFilteringData.java b/src/main/java/net/irisshaders/iris/shaderpack/texture/TextureFilteringData.java similarity index 86% rename from src/main/java/net/coderbot/iris/shaderpack/texture/TextureFilteringData.java rename to src/main/java/net/irisshaders/iris/shaderpack/texture/TextureFilteringData.java index 55ea5bc9a2..b7430fc348 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/texture/TextureFilteringData.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/texture/TextureFilteringData.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.texture; +package net.irisshaders.iris.shaderpack.texture; public final class TextureFilteringData { private final boolean blur; diff --git a/src/main/java/net/coderbot/iris/shaderpack/texture/TextureStage.java b/src/main/java/net/irisshaders/iris/shaderpack/texture/TextureStage.java similarity index 59% rename from src/main/java/net/coderbot/iris/shaderpack/texture/TextureStage.java rename to src/main/java/net/irisshaders/iris/shaderpack/texture/TextureStage.java index 34dd868ca6..36cdc411f9 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/texture/TextureStage.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/texture/TextureStage.java @@ -1,29 +1,29 @@ -package net.coderbot.iris.shaderpack.texture; +package net.irisshaders.iris.shaderpack.texture; import java.util.Optional; public enum TextureStage { /** * The setup passes. - * + *

    * Exclusive to Iris 1.6. */ SETUP, /** * The begin pass. - * + *

    * Exclusive to Iris 1.6. */ BEGIN, /** * The shadowcomp passes. - * + *

    * While this is not documented in shaders.txt, it is a valid stage for defining custom textures. */ SHADOWCOMP, /** * The prepare passes. - * + *

    * While this is not documented in shaders.txt, it is a valid stage for defining custom textures. */ PREPARE, @@ -41,23 +41,15 @@ public enum TextureStage { COMPOSITE_AND_FINAL; public static Optional parse(String name) { - switch (name) { - case "setup": - return Optional.of(SETUP); - case "begin": - return Optional.of(BEGIN); - case "shadowcomp": - return Optional.of(SHADOWCOMP); - case "prepare": - return Optional.of(PREPARE); - case "gbuffers": - return Optional.of(GBUFFERS_AND_SHADOW); - case "deferred": - return Optional.of(DEFERRED); - case "composite": - return Optional.of(COMPOSITE_AND_FINAL); - default: - return Optional.empty(); - } + return switch (name) { + case "setup" -> Optional.of(SETUP); + case "begin" -> Optional.of(BEGIN); + case "shadowcomp" -> Optional.of(SHADOWCOMP); + case "prepare" -> Optional.of(PREPARE); + case "gbuffers" -> Optional.of(GBUFFERS_AND_SHADOW); + case "deferred" -> Optional.of(DEFERRED); + case "composite" -> Optional.of(COMPOSITE_AND_FINAL); + default -> Optional.empty(); + }; } } diff --git a/src/main/java/net/coderbot/iris/shaderpack/transform/StringTransformations.java b/src/main/java/net/irisshaders/iris/shaderpack/transform/StringTransformations.java similarity index 98% rename from src/main/java/net/coderbot/iris/shaderpack/transform/StringTransformations.java rename to src/main/java/net/irisshaders/iris/shaderpack/transform/StringTransformations.java index ecd91d847d..a69154593c 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/transform/StringTransformations.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/transform/StringTransformations.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shaderpack.transform; +package net.irisshaders.iris.shaderpack.transform; public class StringTransformations implements Transformations { private String prefix; diff --git a/src/main/java/net/coderbot/iris/shaderpack/transform/Transformations.java b/src/main/java/net/irisshaders/iris/shaderpack/transform/Transformations.java similarity index 86% rename from src/main/java/net/coderbot/iris/shaderpack/transform/Transformations.java rename to src/main/java/net/irisshaders/iris/shaderpack/transform/Transformations.java index 68f2a5de1e..1fde5a3318 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/transform/Transformations.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/transform/Transformations.java @@ -1,12 +1,18 @@ -package net.coderbot.iris.shaderpack.transform; +package net.irisshaders.iris.shaderpack.transform; public interface Transformations { boolean contains(String content); + void injectLine(InjectionPoint at, String line); + void replaceExact(String from, String to); + void replaceRegex(String regex, String to); + String getPrefix(); + void setPrefix(String prefix); + void define(String key, String value); enum InjectionPoint { diff --git a/src/main/java/net/coderbot/iris/shaderpack/transform/line/LineTransform.java b/src/main/java/net/irisshaders/iris/shaderpack/transform/line/LineTransform.java similarity index 88% rename from src/main/java/net/coderbot/iris/shaderpack/transform/line/LineTransform.java rename to src/main/java/net/irisshaders/iris/shaderpack/transform/line/LineTransform.java index 1595268252..d53e00e1bb 100644 --- a/src/main/java/net/coderbot/iris/shaderpack/transform/line/LineTransform.java +++ b/src/main/java/net/irisshaders/iris/shaderpack/transform/line/LineTransform.java @@ -1,10 +1,8 @@ -package net.coderbot.iris.shaderpack.transform.line; +package net.irisshaders.iris.shaderpack.transform.line; import com.google.common.collect.ImmutableList; public interface LineTransform { - String transform(int index, String line); - static ImmutableList apply(ImmutableList lines, LineTransform transform) { ImmutableList.Builder newLines = ImmutableList.builder(); int index = 0; @@ -16,4 +14,6 @@ static ImmutableList apply(ImmutableList lines, LineTransform tr return newLines.build(); } + + String transform(int index, String line); } diff --git a/src/main/java/net/coderbot/iris/shadows/CullingDataCache.java b/src/main/java/net/irisshaders/iris/shadows/CullingDataCache.java similarity index 67% rename from src/main/java/net/coderbot/iris/shadows/CullingDataCache.java rename to src/main/java/net/irisshaders/iris/shadows/CullingDataCache.java index 0105795618..4a526f4ba6 100644 --- a/src/main/java/net/coderbot/iris/shadows/CullingDataCache.java +++ b/src/main/java/net/irisshaders/iris/shadows/CullingDataCache.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.shadows; +package net.irisshaders.iris.shadows; public interface CullingDataCache { void saveState(); + void restoreState(); } diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java b/src/main/java/net/irisshaders/iris/shadows/ShadowCompositeRenderer.java similarity index 84% rename from src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java rename to src/main/java/net/irisshaders/iris/shadows/ShadowCompositeRenderer.java index 6185064ffe..7a1e2cda59 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowCompositeRenderer.java +++ b/src/main/java/net/irisshaders/iris/shadows/ShadowCompositeRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shadows; +package net.irisshaders.iris.shadows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -6,43 +6,43 @@ import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.framebuffer.ViewportData; -import net.coderbot.iris.gl.image.GlImage; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.program.Program; -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.texture.TextureAccess; -import net.coderbot.iris.pipeline.ShaderPrinter; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.pipeline.transform.PatchShaderType; -import net.coderbot.iris.pipeline.transform.TransformPatcher; -import net.coderbot.iris.postprocess.FullScreenQuadRenderer; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.samplers.IrisImages; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; -import net.coderbot.iris.shaderpack.ProgramDirectives; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.texture.TextureStage; -import net.coderbot.iris.uniforms.CommonUniforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.buffer.ShaderStorageBufferHolder; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.framebuffer.ViewportData; +import net.irisshaders.iris.gl.image.GlImage; +import net.irisshaders.iris.gl.program.ComputeProgram; +import net.irisshaders.iris.gl.program.Program; +import net.irisshaders.iris.gl.program.ProgramBuilder; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.pathways.FullScreenQuadRenderer; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.pipeline.transform.PatchShaderType; +import net.irisshaders.iris.pipeline.transform.ShaderPrinter; +import net.irisshaders.iris.pipeline.transform.TransformPatcher; +import net.irisshaders.iris.samplers.IrisImages; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.shaderpack.FilledIndirectPointer; +import net.irisshaders.iris.shaderpack.programs.ComputeSource; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.ProgramDirectives; +import net.irisshaders.iris.shaderpack.texture.TextureStage; +import net.irisshaders.iris.targets.RenderTarget; +import net.irisshaders.iris.uniforms.CommonUniforms; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL15C; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; import org.lwjgl.opengl.GL43C; -import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -60,7 +60,7 @@ public class ShadowCompositeRenderer { private final WorldRenderingPipeline pipeline; private final Set irisCustomImages; - public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, ShadowRenderTargets renderTargets, + public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, ShadowRenderTargets renderTargets, ShaderStorageBufferHolder holder, TextureAccess noiseTexture, FrameUpdateNotifier updateNotifier, Object2ObjectMap customTextureIds, Set customImages, ImmutableMap explicitPreFlips, Object2ObjectMap irisCustomTextures, CustomUniforms customUniforms) { this.pipeline = pipeline; @@ -74,7 +74,7 @@ public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives p final PackRenderTargetDirectives renderTargetDirectives = packDirectives.getRenderTargetDirectives(); final Map renderTargetSettings = - renderTargetDirectives.getRenderTargetSettings(); + renderTargetDirectives.getRenderTargetSettings(); final ImmutableList.Builder passes = ImmutableList.builder(); final ImmutableSet.Builder flippedAtLeastOnce = new ImmutableSet.Builder<>(); @@ -95,7 +95,7 @@ public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives p if (source == null || !source.isValid()) { if (computes[i] != null) { ComputeOnlyPass pass = new ComputeOnlyPass(); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets, holder); passes.add(pass); } continue; @@ -105,7 +105,7 @@ public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives p ProgramDirectives directives = source.getDirectives(); pass.program = createProgram(source, flipped, flippedAtLeastOnceSnapshot, renderTargets); - pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets); + pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, renderTargets, holder); int[] drawBuffers = source.getDirectives().hasUnknownDrawBuffers() ? new int[]{0, 1} : source.getDirectives().getDrawBuffers(); GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers); @@ -145,38 +145,39 @@ public ShadowCompositeRenderer(WorldRenderingPipeline pipeline, PackDirectives p GlStateManager._glBindFramebuffer(GL30C.GL_READ_FRAMEBUFFER, 0); } - public ImmutableSet getFlippedAtLeastOnceFinal() { - return this.flippedAtLeastOnceFinal; + private static void setupMipmapping(net.irisshaders.iris.targets.RenderTarget target, boolean readFromAlt) { + int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); + + // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer + // (since the last mipmap was generated) + // + // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the + // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a + // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the + // sampling mode is always reset between frames, so this only persists after the first program to use + // mipmapping on this buffer. + // + // Also note that this only applies to one of the two buffers in a render target buffer pair - making it + // unlikely that this issue occurs in practice with most shader packs. + IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); + IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, target.getInternalFormat().getPixelFormat().isInteger() ? GL20C.GL_NEAREST_MIPMAP_NEAREST : GL20C.GL_LINEAR_MIPMAP_LINEAR); } - private static class Pass { - Program program; - GlFramebuffer framebuffer; - ImmutableSet flippedAtLeastOnce; - ImmutableSet stageReadsFromAlt; - ImmutableSet mipmappedBuffers; - ViewportData viewportScale; - ComputeProgram[] computes; + private static void resetRenderTarget(RenderTarget target) { + // Resets the sampling mode of the given render target and then unbinds it to prevent accidental sampling of it + // elsewhere. - protected void destroy() { - this.program.destroy(); - for (ComputeProgram compute : this.computes) { - if (compute != null) { - compute.destroy(); - } - } + int filter = GL20C.GL_LINEAR; + if (target.getInternalFormat().getPixelFormat().isInteger()) { + filter = GL20C.GL_NEAREST; } + + IrisRenderSystem.texParameteri(target.getMainTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); + IrisRenderSystem.texParameteri(target.getAltTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); } - private static class ComputeOnlyPass extends Pass { - @Override - protected void destroy() { - for (ComputeProgram compute : this.computes) { - if (compute != null) { - compute.destroy(); - } - } - } + public ImmutableSet getFlippedAtLeastOnceFinal() { + return this.flippedAtLeastOnceFinal; } public void renderAll() { @@ -244,40 +245,9 @@ public void renderAll() { RenderSystem.activeTexture(GL15C.GL_TEXTURE0); } - private static void setupMipmapping(net.coderbot.iris.rendertarget.RenderTarget target, boolean readFromAlt) { - int texture = readFromAlt ? target.getAltTexture() : target.getMainTexture(); - - // TODO: Only generate the mipmap if a valid mipmap hasn't been generated or if we've written to the buffer - // (since the last mipmap was generated) - // - // NB: We leave mipmapping enabled even if the buffer is written to again, this appears to match the - // behavior of ShadersMod/OptiFine, however I'm not sure if it's desired behavior. It's possible that a - // program could use mipmapped sampling with a stale mipmap, which probably isn't great. However, the - // sampling mode is always reset between frames, so this only persists after the first program to use - // mipmapping on this buffer. - // - // Also note that this only applies to one of the two buffers in a render target buffer pair - making it - // unlikely that this issue occurs in practice with most shader packs. - IrisRenderSystem.generateMipmaps(texture, GL20C.GL_TEXTURE_2D); - IrisRenderSystem.texParameteri(texture, GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, target.getInternalFormat().getPixelFormat().isInteger() ? GL20C.GL_NEAREST_MIPMAP_NEAREST : GL20C.GL_LINEAR_MIPMAP_LINEAR); - } - - private static void resetRenderTarget(RenderTarget target) { - // Resets the sampling mode of the given render target and then unbinds it to prevent accidental sampling of it - // elsewhere. - - int filter = GL20C.GL_LINEAR; - if (target.getInternalFormat().getPixelFormat().isInteger()) { - filter = GL20C.GL_NEAREST; - } - - IrisRenderSystem.texParameteri(target.getMainTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - IrisRenderSystem.texParameteri(target.getAltTexture(), GL20C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_FILTER, filter); - } - // TODO: Don't just copy this from DeferredWorldRenderingPipeline private Program createProgram(ProgramSource source, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, - ShadowRenderTargets targets) { + ShadowRenderTargets targets) { // TODO: Properly handle empty shaders Map transformed = TransformPatcher.patchComposite( source.getName(), @@ -319,7 +289,7 @@ private Program createProgram(ProgramSource source, ImmutableSet flippe } private ComputeProgram[] createComputes(ComputeSource[] sources, ImmutableSet flipped, ImmutableSet flippedAtLeastOnceSnapshot, - ShadowRenderTargets targets) { + ShadowRenderTargets targets, ShaderStorageBufferHolder holder) { ComputeProgram[] programs = new ComputeProgram[sources.length]; for (int i = 0; i < programs.length; i++) { ComputeSource source = sources[i]; @@ -357,7 +327,7 @@ private ComputeProgram[] createComputes(ComputeSource[] sources, ImmutableSet flippedAtLeastOnce; + ImmutableSet stageReadsFromAlt; + ImmutableSet mipmappedBuffers; + ViewportData viewportScale; + ComputeProgram[] computes; + + protected void destroy() { + this.program.destroy(); + for (ComputeProgram compute : this.computes) { + if (compute != null) { + compute.destroy(); + } + } + } + } + + private static class ComputeOnlyPass extends Pass { + @Override + protected void destroy() { + for (ComputeProgram compute : this.computes) { + if (compute != null) { + compute.destroy(); + } + } + } + } } diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowMatrices.java b/src/main/java/net/irisshaders/iris/shadows/ShadowMatrices.java similarity index 74% rename from src/main/java/net/coderbot/iris/shadows/ShadowMatrices.java rename to src/main/java/net/irisshaders/iris/shadows/ShadowMatrices.java index 88aec6e5c5..3b317576aa 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowMatrices.java +++ b/src/main/java/net/irisshaders/iris/shadows/ShadowMatrices.java @@ -1,28 +1,25 @@ -package net.coderbot.iris.shadows; +package net.irisshaders.iris.shadows; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; import org.joml.Matrix4f; - -import java.nio.FloatBuffer; - public class ShadowMatrices { private static final float NEAR = 0.05f; private static final float FAR = 256.0f; // NB: These matrices are in column-major order, not row-major order like what you'd expect! - public static Matrix4f createOrthoMatrix(float halfPlaneLength) { + public static Matrix4f createOrthoMatrix(float halfPlaneLength, float nearPlane, float farPlane) { return new Matrix4f( - // column 1 - 1.0f / halfPlaneLength, 0f, 0f, 0f, - // column 2 - 0f, 1.0f / halfPlaneLength, 0f, 0f, - // column 3 - 0f, 0f, 2.0f / (NEAR - FAR), 0f, - // column 4 - 0f, 0f, -(FAR + NEAR) / (FAR - NEAR), 1f + // column 1 + 1.0f / halfPlaneLength, 0f, 0f, 0f, + // column 2 + 0f, 1.0f / halfPlaneLength, 0f, 0f, + // column 3 + 0f, 0f, 2.0f / (nearPlane - farPlane), 0f, + // column 4 + 0f, 0f, -(farPlane + nearPlane) / (farPlane - nearPlane), 1f ); } @@ -30,14 +27,14 @@ public static Matrix4f createPerspectiveMatrix(float fov) { // This converts from degrees to radians. float yScale = (float) (1.0f / Math.tan(Math.toRadians(fov) * 0.5f)); return new Matrix4f( - // column 1 - yScale, 0f, 0f, 0f, - // column 2 - 0f, yScale, 0f, 0f, - // column 3 - 0f, 0f, (FAR + NEAR) / (NEAR - FAR), -1.0F, - // column 4 - 0f, 0f, 2.0F * FAR * NEAR / (NEAR - FAR), 1f + // column 1 + yScale, 0f, 0f, 0f, + // column 2 + 0f, yScale, 0f, 0f, + // column 3 + 0f, 0f, (FAR + NEAR) / (NEAR - FAR), -1.0F, + // column 4 + 0f, 0f, 2.0F * FAR * NEAR / (NEAR - FAR), 1f ); } @@ -101,55 +98,55 @@ public static void main(String[] args) { // const float shadowDistance = 32.0; // /* SHADOWHPL:32.0 */ Matrix4f expected = new Matrix4f( - 0.03125f, 0f, 0f, 0f, - 0f, 0.03125f, 0f, 0f, - 0f, 0f, -0.007814026437699795f, 0f, - 0f, 0f, -1.000390648841858f, 1f + 0.03125f, 0f, 0f, 0f, + 0f, 0.03125f, 0f, 0f, + 0f, 0f, -0.007814026437699795f, 0f, + 0f, 0f, -1.000390648841858f, 1f ); - test("ortho projection hpl=32", expected, createOrthoMatrix(32.0f)); + test("ortho projection hpl=32", expected, createOrthoMatrix(32.0f, 0.05f, 256.0f)); // const float shadowDistance = 110.0; // /* SHADOWHPL:110.0 */ Matrix4f expected110 = new Matrix4f( - 0.00909090880304575f, 0, 0, 0, - 0, 0.00909090880304575f, 0, 0, - 0, 0, -0.007814026437699795f, 0, - 0, 0, -1.000390648841858f, 1 + 0.00909090880304575f, 0, 0, 0, + 0, 0.00909090880304575f, 0, 0, + 0, 0, -0.007814026437699795f, 0, + 0, 0, -1.000390648841858f, 1 ); - test("ortho projection hpl=110", expected110, createOrthoMatrix(110.0f)); + test("ortho projection hpl=110", expected110, createOrthoMatrix(110.0f, 0.05f, 256.0f)); Matrix4f expected90Proj = new Matrix4f( - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, -1.0003906f, -1.0f, - 0.0f, 0.0f, -0.10001954f, 0.0f + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, -1.0003906f, -1.0f, + 0.0f, 0.0f, -0.10001954f, 0.0f ); test("perspective projection fov=90", expected90Proj, createPerspectiveMatrix(90.0f)); Matrix4f expectedModelViewAtDawn = new Matrix4f( - // column 1 - 0.21545040607452393f, - 5.820481518981069E-8f, - 0.9765146970748901f, - 0, - // column 2 - -0.9765147466795349f, - 1.2841844920785661E-8f, - 0.21545039117336273f, - 0, - // column 3 - 0, - -0.9999999403953552f, - 5.960464477539063E-8f, - 0, - // column 4 - 0.38002151250839233f, - 1.0264281034469604f, - -100.4463119506836f, - 1 + // column 1 + 0.21545040607452393f, + 5.820481518981069E-8f, + 0.9765146970748901f, + 0, + // column 2 + -0.9765147466795349f, + 1.2841844920785661E-8f, + 0.21545039117336273f, + 0, + // column 3 + 0, + -0.9999999403953552f, + 5.960464477539063E-8f, + 0, + // column 4 + 0.38002151250839233f, + 1.0264281034469604f, + -100.4463119506836f, + 1 ); PoseStack modelView = new PoseStack(); @@ -158,7 +155,7 @@ public static void main(String[] args) { // When DayTime=0, skyAngle = 282 degrees. // Thus, sunAngle = shadowAngle = 0.03451777f createModelViewMatrix(modelView, 0.03451777f, 2.0f, - 0.0f, 0.646045982837677f, 82.53274536132812f, -514.0264282226562f); + 0.0f, 0.646045982837677f, 82.53274536132812f, -514.0264282226562f); test("model view at dawn", expectedModelViewAtDawn, modelView.last().pose()); } @@ -167,7 +164,7 @@ private static void test(String name, Matrix4f expected, Matrix4f created) { if (expected.equals(created, 0.0005f)) { System.err.println("test " + name + " failed: "); System.err.println(" expected: "); - System.err.print(expected.toString()); + System.err.print(expected); System.err.println(" created: "); System.err.print(created.toString()); } else { diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderTargets.java similarity index 83% rename from src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java rename to src/main/java/net/irisshaders/iris/shadows/ShadowRenderTargets.java index 5f62d3be7f..2bfc0281de 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowRenderTargets.java +++ b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderTargets.java @@ -1,25 +1,22 @@ -package net.coderbot.iris.shadows; +package net.irisshaders.iris.shadows; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; -import net.coderbot.iris.Iris; -import net.coderbot.iris.features.FeatureFlags; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.gl.texture.DepthCopyStrategy; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.rendertarget.DepthTexture; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.shaderpack.PackShadowDirectives; +import net.irisshaders.iris.features.FeatureFlags; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.gl.texture.DepthCopyStrategy; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.targets.DepthTexture; +import net.irisshaders.iris.targets.RenderTarget; import org.lwjgl.opengl.GL30C; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.Objects; public class ShadowRenderTargets { private final RenderTarget[] targets; @@ -33,14 +30,14 @@ public class ShadowRenderTargets { private final List ownedFramebuffers; private final int resolution; private final WorldRenderingPipeline pipeline; - + private final boolean[] hardwareFiltered; + private final boolean[] linearFiltered; + private final InternalTextureFormat[] formats; + private final IntList buffersToBeCleared; + private final int size; + private final boolean shouldRefresh; private boolean fullClearRequired; private boolean translucentDepthDirty; - private boolean[] hardwareFiltered; - private boolean[] linearFiltered; - private InternalTextureFormat[] formats; - private IntList buffersToBeCleared; - private int size; public ShadowRenderTargets(WorldRenderingPipeline pipeline, int resolution, PackShadowDirectives shadowDirectives) { this.pipeline = pipeline; @@ -53,28 +50,28 @@ public ShadowRenderTargets(WorldRenderingPipeline pipeline, int resolution, Pack linearFiltered = new boolean[size]; buffersToBeCleared = new IntArrayList(); - this.mainDepth = new DepthTexture(resolution, resolution, DepthBufferFormat.DEPTH); - this.noTranslucents = new DepthTexture(resolution, resolution, DepthBufferFormat.DEPTH); + this.mainDepth = new DepthTexture("shadowtex0", resolution, resolution, DepthBufferFormat.DEPTH); + this.noTranslucents = new DepthTexture("shadowtex1", resolution, resolution, DepthBufferFormat.DEPTH); + + this.ownedFramebuffers = new ArrayList<>(); + this.resolution = resolution; for (int i = 0; i < shadowDirectives.getDepthSamplingSettings().size(); i++) { this.hardwareFiltered[i] = shadowDirectives.getDepthSamplingSettings().get(i).getHardwareFiltering(); this.linearFiltered[i] = !shadowDirectives.getDepthSamplingSettings().get(i).getNearest(); } - this.resolution = resolution; - - this.ownedFramebuffers = new ArrayList<>(); - // NB: Make sure all buffers are cleared so that they don't contain undefined // data. Otherwise very weird things can happen. fullClearRequired = true; - this.depthSourceFb = createFramebufferWritingToMain(new int[] {0}); + this.depthSourceFb = createFramebufferWritingToMain(new int[]{0}); - this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[] {0}); + this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[]{0}); this.noTranslucentsDestFb.addDepthAttachment(this.noTranslucents.getTextureId()); this.translucentDepthDirty = true; + this.shouldRefresh = false; } // TODO: Actually flip. This is required for shadow composites! @@ -112,6 +109,7 @@ public RenderTarget get(int index) { /** * Gets the render target assigned to an index, and creates it if it does not exist. * This is a expensive opetation nad may block other tasks! Use it sparingly, and use {@code get()} if possible. + * * @param index The index of the render target to get * @return The existing or a new render target, if no existing one exists */ @@ -133,6 +131,7 @@ private void create(int index) { PackShadowDirectives.SamplingSettings settings = shadowDirectives.getColorSamplingSettings().computeIfAbsent(index, i -> new PackShadowDirectives.SamplingSettings()); targets[index] = RenderTarget.builder().setDimensions(resolution, resolution) .setInternalFormat(settings.getFormat()) + .setName("shadowcolor" + index) .setPixelFormat(settings.getFormat().getPixelFormat()).build(); formats[index] = settings.getFormat(); if (settings.getClear()) { @@ -144,7 +143,6 @@ private void create(int index) { } fullClearRequired = true; - pipeline.onShadowBufferChange(); } public void createIfEmpty(int index) { @@ -224,6 +222,20 @@ private GlFramebuffer createEmptyFramebuffer() { return framebuffer; } + public GlFramebuffer createDHFramebuffer(ImmutableSet stageWritesToAlt, int[] drawBuffers) { + if (drawBuffers.length == 0) { + return createEmptyFramebuffer(); + } + + ImmutableSet stageWritesToMain = invert(stageWritesToAlt, drawBuffers); + + GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); + + framebuffer.addDepthAttachment(mainDepth.getTextureId()); + + return framebuffer; + } + public GlFramebuffer createShadowFramebuffer(ImmutableSet stageWritesToAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); @@ -231,7 +243,7 @@ public GlFramebuffer createShadowFramebuffer(ImmutableSet stageWritesTo ImmutableSet stageWritesToMain = invert(stageWritesToAlt, drawBuffers); - GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); + GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(mainDepth.getTextureId()); @@ -279,7 +291,7 @@ public GlFramebuffer createColorFramebuffer(ImmutableSet stageWritesToM // Iris.logger.warn("Invalid framebuffer was attempted to be created! Forcing a framebuffer with DRAWBUFFERS 01 for shadow."); ownedFramebuffers.remove(framebuffer); framebuffer.destroy(); - return createColorFramebuffer(stageWritesToMain, new int[] { 0, 1 }); + return createColorFramebuffer(stageWritesToMain, new int[]{0, 1}); } RenderTarget target = this.getOrCreate(drawBuffers[i]); diff --git a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderer.java similarity index 85% rename from src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java rename to src/main/java/net/irisshaders/iris/shadows/ShadowRenderer.java index cdba7eacd4..0a6772ca6d 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ShadowRenderer.java +++ b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderer.java @@ -1,43 +1,34 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.shadows; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import net.coderbot.batchedentityrendering.impl.BatchingDebugMessageHelper; -import net.coderbot.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; -import net.coderbot.batchedentityrendering.impl.FullyBufferedMultiBufferSource; -import net.coderbot.batchedentityrendering.impl.MemoryTrackingRenderBuffers; -import net.coderbot.batchedentityrendering.impl.RenderBuffersExt; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.program.ComputeProgram; -import net.coderbot.iris.gl.texture.DepthCopyStrategy; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.coderbot.iris.mixin.LevelRendererAccessor; -import net.coderbot.iris.shaderpack.ComputeSource; -import net.coderbot.iris.shaderpack.OptionalBoolean; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shaderpack.ProgramSource; -import net.coderbot.iris.shaderpack.ShadowCullState; -import net.coderbot.iris.shadows.ShadowMatrices; -import net.coderbot.iris.shadows.CullingDataCache; -import net.coderbot.iris.shadows.Matrix4fAccess; -import net.coderbot.iris.shadows.ShadowCompositeRenderer; -import net.coderbot.iris.shadows.ShadowRenderTargets; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.coderbot.iris.shadows.frustum.BoxCuller; -import net.coderbot.iris.shadows.frustum.CullEverythingFrustum; -import net.coderbot.iris.shadows.frustum.FrustumHolder; -import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum; -import net.coderbot.iris.shadows.frustum.advanced.ReversedAdvancedShadowCullingFrustum; -import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum; -import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; -import net.coderbot.iris.uniforms.custom.CustomUniforms; -import net.coderbot.iris.uniforms.CameraUniforms; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.CelestialUniforms; +import net.irisshaders.batchedentityrendering.impl.BatchingDebugMessageHelper; +import net.irisshaders.batchedentityrendering.impl.DrawCallTrackingRenderBuffers; +import net.irisshaders.batchedentityrendering.impl.FullyBufferedMultiBufferSource; +import net.irisshaders.batchedentityrendering.impl.MemoryTrackingRenderBuffers; +import net.irisshaders.batchedentityrendering.impl.RenderBuffersExt; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.mixin.LevelRendererAccessor; +import net.irisshaders.iris.shaderpack.programs.ProgramSource; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.shaderpack.properties.ShadowCullState; +import net.irisshaders.iris.shadows.frustum.BoxCuller; +import net.irisshaders.iris.shadows.frustum.CullEverythingFrustum; +import net.irisshaders.iris.shadows.frustum.FrustumHolder; +import net.irisshaders.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum; +import net.irisshaders.iris.shadows.frustum.advanced.ReversedAdvancedShadowCullingFrustum; +import net.irisshaders.iris.shadows.frustum.fallback.BoxCullingFrustum; +import net.irisshaders.iris.shadows.frustum.fallback.NonCullingFrustum; +import net.irisshaders.iris.uniforms.CameraUniforms; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.CelestialUniforms; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; @@ -68,49 +59,51 @@ public class ShadowRenderer { public static boolean ACTIVE = false; public static List visibleBlockEntities; public static int renderDistance; - + public static Matrix4f MODELVIEW; + public static Matrix4f PROJECTION; + public static Frustum FRUSTUM; private final float halfPlaneLength; + private final float nearPlane, farPlane; private final float voxelDistance; private final float renderDistanceMultiplier; private final float entityShadowDistanceMultiplier; private final int resolution; private final float intervalSize; private final Float fov; - public static Matrix4f MODELVIEW; - private final ShadowRenderTargets targets; private final ShadowCullState packCullingState; private final ShadowCompositeRenderer compositeRenderer; - private boolean packHasVoxelization; private final boolean shouldRenderTerrain; private final boolean shouldRenderTranslucent; private final boolean shouldRenderEntities; private final boolean shouldRenderPlayer; private final boolean shouldRenderBlockEntities; + private final boolean shouldRenderDH; private final float sunPathRotation; private final RenderBuffers buffers; private final RenderBuffersExt renderBuffersExt; private final List mipmapPasses = new ArrayList<>(); private final String debugStringOverall; + private final boolean separateHardwareSamplers; + private final boolean shouldRenderLightBlockEntities; + private boolean packHasVoxelization; private FrustumHolder terrainFrustumHolder; private FrustumHolder entityFrustumHolder; private String debugStringTerrain = "(unavailable)"; private int renderedShadowEntities = 0; private int renderedShadowBlockEntities = 0; - private final CustomUniforms customUniforms; - private final boolean separateHardwareSamplers; - public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets, ShadowCompositeRenderer compositeRenderer, CustomUniforms customUniforms, boolean separateHardwareSamplers) { - this.customUniforms = customUniforms; - this.separateHardwareSamplers = separateHardwareSamplers; final PackShadowDirectives shadowDirectives = directives.getShadowDirectives(); this.halfPlaneLength = shadowDirectives.getDistance(); + this.nearPlane = shadowDirectives.getNearPlane(); + this.farPlane = shadowDirectives.getFarPlane(); + this.voxelDistance = shadowDirectives.getVoxelDistance(); this.renderDistanceMultiplier = shadowDirectives.getDistanceRenderMul(); this.entityShadowDistanceMultiplier = shadowDirectives.getEntityShadowDistanceMul(); @@ -121,6 +114,8 @@ public ShadowRenderer(ProgramSource shadow, PackDirectives directives, this.shouldRenderEntities = shadowDirectives.shouldRenderEntities(); this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer(); this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities(); + this.shouldRenderLightBlockEntities = shadowDirectives.shouldRenderLightBlockEntities(); + this.shouldRenderDH = shadowDirectives.isDhShadowEnabled().orElse(false); this.compositeRenderer = compositeRenderer; @@ -155,10 +150,6 @@ public ShadowRenderer(ProgramSource shadow, PackDirectives directives, configureSamplingSettings(shadowDirectives); } - public void setUsesImages(boolean usesImages) { - this.packHasVoxelization = packHasVoxelization || usesImages; - } - public static PoseStack createShadowModelView(float sunPathRotation, float intervalSize) { // Determine the camera position Vector3d cameraPos = CameraUniforms.getUnshiftedCameraPosition(); @@ -202,6 +193,10 @@ private static float getShadowAngle() { return shadowAngle; } + public void setUsesImages(boolean usesImages) { + this.packHasVoxelization = packHasVoxelization || usesImages; + } + private void configureSamplingSettings(PackShadowDirectives shadowDirectives) { final ImmutableList depthSamplingSettings = shadowDirectives.getDepthSamplingSettings(); @@ -236,7 +231,7 @@ private void configureDepthSampler(int glTextureId, PackShadowDirectives.DepthSa // They expected the driver to put the depth value in z, but it's supposed to only // be available in r. So we set up the swizzle to fix that. IrisRenderSystem.texParameteriv(glTextureId, GL20C.GL_TEXTURE_2D, ARBTextureSwizzle.GL_TEXTURE_SWIZZLE_RGBA, - new int[] { GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_ONE }); + new int[]{GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_RED, GL30C.GL_ONE}); configureSampler(glTextureId, settings); } @@ -261,7 +256,7 @@ private void generateMipmaps() { RenderSystem.activeTexture(GL20C.GL_TEXTURE4); for (MipmapPass mipmapPass : mipmapPasses) { - setupMipmappingForTexture(mipmapPass.getTexture(), mipmapPass.getTargetFilteringMode()); + setupMipmappingForTexture(mipmapPass.texture(), mipmapPass.targetFilteringMode()); } RenderSystem.activeTexture(GL20C.GL_TEXTURE0); @@ -342,10 +337,10 @@ private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder if (isReversed) { return holder.setInfo(new ReversedAdvancedShadowCullingFrustum(CapturedRenderingState.INSTANCE.getGbufferModelView(), - CapturedRenderingState.INSTANCE.getGbufferProjection(), shadowLightVectorFromOrigin, boxCuller, new BoxCuller(halfPlaneLength * renderMultiplier)), distanceInfo, cullingInfo); + (shouldRenderDH && DHCompat.hasRenderingEnabled()) ? DHCompat.getProjection() : CapturedRenderingState.INSTANCE.getGbufferProjection(), shadowLightVectorFromOrigin, boxCuller, new BoxCuller(halfPlaneLength * renderMultiplier)), distanceInfo, cullingInfo); } else { return holder.setInfo(new AdvancedShadowCullingFrustum(CapturedRenderingState.INSTANCE.getGbufferModelView(), - CapturedRenderingState.INSTANCE.getGbufferProjection(), shadowLightVectorFromOrigin, boxCuller), distanceInfo, cullingInfo); + (shouldRenderDH && DHCompat.hasRenderingEnabled()) ? DHCompat.getProjection() : CapturedRenderingState.INSTANCE.getGbufferProjection(), shadowLightVectorFromOrigin, boxCuller), distanceInfo, cullingInfo); } } @@ -374,7 +369,6 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame } - visibleBlockEntities = new ArrayList<>(); // NB: We store the previous player buffers in order to be able to allow mods rendering entities in the shadow pass (Flywheel) to use the shadow buffers instead. @@ -382,6 +376,7 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame levelRenderer.setRenderBuffers(buffers); visibleBlockEntities = new ArrayList<>(); + setupShadowViewport(); // Create our camera PoseStack modelView = createShadowModelView(this.sunPathRotation, this.intervalSize); @@ -397,6 +392,8 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder); + FRUSTUM = terrainFrustumHolder.getFrustum(); + // Determine the player camera position Vector3d cameraPos = CameraUniforms.getUnshiftedCameraPosition(); @@ -436,7 +433,6 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame levelRenderer.getLevel().getProfiler().popPush("terrain"); - setupShadowViewport(); // Set up our orthographic projection matrix and load it into RenderSystem Matrix4f shadowProjection; @@ -444,11 +440,13 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame // If FOV is not null, the pack wants a perspective based projection matrix. (This is to support legacy packs) shadowProjection = ShadowMatrices.createPerspectiveMatrix(this.fov); } else { - shadowProjection = ShadowMatrices.createOrthoMatrix(halfPlaneLength); + shadowProjection = ShadowMatrices.createOrthoMatrix(halfPlaneLength, nearPlane < 0 ? -DHCompat.getRenderDistance() : nearPlane, farPlane < 0 ? DHCompat.getRenderDistance() : farPlane); } IrisRenderSystem.setShadowProjection(shadowProjection); + PROJECTION = shadowProjection; + // Disable backface culling // This partially works around an issue where if the front face of a mountain isn't visible, it casts no // shadow. @@ -512,7 +510,9 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame levelRenderer.getLevel().getProfiler().popPush("build blockentities"); if (shouldRenderBlockEntities) { - renderedShadowBlockEntities = ShadowRenderingState.renderBlockEntities(this, bufferSource, modelView, playerCamera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum); + renderedShadowBlockEntities = ShadowRenderingState.renderBlockEntities(this, bufferSource, modelView, playerCamera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum, false); + } else if (shouldRenderLightBlockEntities) { + renderedShadowBlockEntities = ShadowRenderingState.renderBlockEntities(this, bufferSource, modelView, playerCamera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum, true); } levelRenderer.getLevel().getProfiler().popPush("draw entities"); @@ -520,7 +520,8 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame // NB: Don't try to draw the translucent parts of entities afterwards in the shadow pass. It'll cause problems since some // shader packs assume that everything drawn afterwards is actually translucent and should cast a colored // shadow... - if (bufferSource instanceof FullyBufferedMultiBufferSource fullyBufferedMultiBufferSource) fullyBufferedMultiBufferSource.readyUp(); + if (bufferSource instanceof FullyBufferedMultiBufferSource fullyBufferedMultiBufferSource) + fullyBufferedMultiBufferSource.readyUp(); bufferSource.endBatch(); @@ -575,7 +576,7 @@ public void renderShadows(LevelRendererAccessor levelRenderer, Camera playerCame levelRenderer.getLevel().getProfiler().popPush("updatechunks"); } - public int renderBlockEntities(MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum) { + public int renderBlockEntities(MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum, boolean lightsOnly) { getLevel().getProfiler().push("build blockentities"); int shadowBlockEntities = 0; @@ -586,6 +587,10 @@ public int renderBlockEntities(MultiBufferSource.BufferSource bufferSource, Pose } for (BlockEntity entity : visibleBlockEntities) { + if (lightsOnly && entity.getBlockState().getLightEmission() == 0) { + continue; + } + BlockPos pos = entity.getBlockPos(); if (hasEntityFrustum) { if (culler.isCulled(pos.getX() - 1, pos.getY() - 1, pos.getZ() - 1, pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1)) { @@ -627,7 +632,8 @@ private int renderEntities(LevelRendererAccessor levelRenderer, EntityRenderDisp levelRenderer.getLevel().getProfiler().popPush("build entity geometry"); for (Entity entity : renderedEntities) { - levelRenderer.invokeRenderEntity(entity, cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource); + float realTickDelta = CapturedRenderingState.INSTANCE.getRealTickDelta(); + levelRenderer.invokeRenderEntity(entity, cameraX, cameraY, cameraZ, realTickDelta, modelView, bufferSource); } levelRenderer.getLevel().getProfiler().pop(); @@ -651,17 +657,20 @@ private int renderPlayerEntity(LevelRendererAccessor levelRenderer, EntityRender if (!player.getPassengers().isEmpty()) { for (int i = 0; i < player.getPassengers().size(); i++) { - levelRenderer.invokeRenderEntity(player.getPassengers().get(i), cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource); + float realTickDelta = CapturedRenderingState.INSTANCE.getRealTickDelta(); + levelRenderer.invokeRenderEntity(player.getPassengers().get(i), cameraX, cameraY, cameraZ, realTickDelta, modelView, bufferSource); shadowEntities++; } } if (player.getVehicle() != null) { - levelRenderer.invokeRenderEntity(player.getVehicle(), cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource); + float realTickDelta = CapturedRenderingState.INSTANCE.getRealTickDelta(); + levelRenderer.invokeRenderEntity(player.getVehicle(), cameraX, cameraY, cameraZ, realTickDelta, modelView, bufferSource); shadowEntities++; } - levelRenderer.invokeRenderEntity(player, cameraX, cameraY, cameraZ, tickDelta, modelView, bufferSource); + float realTickDelta = CapturedRenderingState.INSTANCE.getRealTickDelta(); + levelRenderer.invokeRenderEntity(player, cameraX, cameraY, cameraZ, realTickDelta, modelView, bufferSource); shadowEntities++; @@ -691,8 +700,7 @@ public void addDebugText(List messages) { messages.add("[" + Iris.MODNAME + "] Shadow Entities: " + getEntitiesDebugString()); messages.add("[" + Iris.MODNAME + "] Shadow Block Entities: " + getBlockEntitiesDebugString()); - if (buffers instanceof DrawCallTrackingRenderBuffers && (shouldRenderEntities || shouldRenderPlayer)) { - DrawCallTrackingRenderBuffers drawCallTracker = (DrawCallTrackingRenderBuffers) buffers; + if (buffers instanceof DrawCallTrackingRenderBuffers drawCallTracker && (shouldRenderEntities || shouldRenderPlayer)) { messages.add("[" + Iris.MODNAME + "] Shadow Entity Batching: " + BatchingDebugMessageHelper.getDebugMessage(drawCallTracker)); } } else { @@ -707,7 +715,7 @@ private String getEntitiesDebugString() { } private String getBlockEntitiesDebugString() { - return shouldRenderBlockEntities ? renderedShadowBlockEntities + "" : "disabled by pack"; // TODO: + "/" + MinecraftClient.getInstance().world.blockEntities.size(); + return (shouldRenderBlockEntities || shouldRenderLightBlockEntities) ? renderedShadowBlockEntities + "" : "disabled by pack"; // TODO: + "/" + MinecraftClient.getInstance().world.blockEntities.size(); } public void destroy() { @@ -715,21 +723,8 @@ public void destroy() { ((MemoryTrackingRenderBuffers) buffers).freeAndDeleteBuffers(); } - private static class MipmapPass { - private final int texture; - private final int targetFilteringMode; + private record MipmapPass(int texture, int targetFilteringMode) { - public MipmapPass(int texture, int targetFilteringMode) { - this.texture = texture; - this.targetFilteringMode = targetFilteringMode; - } - public int getTexture() { - return texture; - } - - public int getTargetFilteringMode() { - return targetFilteringMode; - } } } diff --git a/src/main/java/net/coderbot/iris/shadows/ShadowRenderingState.java b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderingState.java similarity index 78% rename from src/main/java/net/coderbot/iris/shadows/ShadowRenderingState.java rename to src/main/java/net/irisshaders/iris/shadows/ShadowRenderingState.java index a3f83e302c..205e7c15b6 100644 --- a/src/main/java/net/coderbot/iris/shadows/ShadowRenderingState.java +++ b/src/main/java/net/irisshaders/iris/shadows/ShadowRenderingState.java @@ -1,30 +1,29 @@ -package net.coderbot.iris.shadows; +package net.irisshaders.iris.shadows; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Camera; import net.minecraft.client.renderer.MultiBufferSource; -import net.coderbot.iris.pipeline.ShadowRenderer; public class ShadowRenderingState { + private static BlockEntityRenderFunction function = (ShadowRenderer::renderBlockEntities); + public static boolean areShadowsCurrentlyBeingRendered() { return ShadowRenderer.ACTIVE; } - private static BlockEntityRenderFunction function = (ShadowRenderer::renderBlockEntities); - public static void setBlockEntityRenderFunction(BlockEntityRenderFunction function) { ShadowRenderingState.function = function; } - public static int renderBlockEntities(ShadowRenderer shadowRenderer, MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum) { - return function.renderBlockEntities(shadowRenderer, bufferSource, modelView, camera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum); + public static int renderBlockEntities(ShadowRenderer shadowRenderer, MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum, boolean lightsOnly) { + return function.renderBlockEntities(shadowRenderer, bufferSource, modelView, camera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum, lightsOnly); } - public static int getRenderDistance() { + public static int getRenderDistance() { return ShadowRenderer.renderDistance; - } + } - public interface BlockEntityRenderFunction { - int renderBlockEntities(ShadowRenderer shadowRenderer, MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum); + public interface BlockEntityRenderFunction { + int renderBlockEntities(ShadowRenderer shadowRenderer, MultiBufferSource.BufferSource bufferSource, PoseStack modelView, Camera camera, double cameraX, double cameraY, double cameraZ, float tickDelta, boolean hasEntityFrustum, boolean lightsOnly); } } diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java b/src/main/java/net/irisshaders/iris/shadows/frustum/BoxCuller.java similarity index 83% rename from src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/BoxCuller.java index 6133f04c81..ae61ef5ad2 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/BoxCuller.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/BoxCuller.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shadows.frustum; +package net.irisshaders.iris.shadows.frustum; import net.minecraft.world.phys.AABB; @@ -27,7 +27,7 @@ public void setPosition(double cameraX, double cameraY, double cameraZ) { public boolean isCulled(AABB aabb) { return isCulled((float) aabb.minX, (float) aabb.minY, (float) aabb.minZ, - (float) aabb.maxX, (float) aabb.maxY, (float) aabb.maxZ); + (float) aabb.maxX, (float) aabb.maxY, (float) aabb.maxZ); } public boolean isCulled(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { @@ -39,11 +39,7 @@ public boolean isCulled(double minX, double minY, double minZ, double maxX, doub return true; } - if (maxZ < this.minAllowedZ || minZ > this.maxAllowedZ) { - return true; - } - - return false; + return maxZ < this.minAllowedZ || minZ > this.maxAllowedZ; } public boolean isCulledSodium(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { @@ -55,11 +51,7 @@ public boolean isCulledSodium(double minX, double minY, double minZ, double maxX return true; } - if (maxZ < -this.maxDistance || minZ > this.maxDistance) { - return true; - } - - return false; + return maxZ < -this.maxDistance || minZ > this.maxDistance; } @Override diff --git a/src/main/java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java b/src/main/java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java new file mode 100644 index 0000000000..6e7708b5f9 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/CullEverythingFrustum.java @@ -0,0 +1,33 @@ +package net.irisshaders.iris.shadows.frustum; + +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum; +import com.seibel.distanthorizons.coreapi.util.math.Mat4f; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.world.phys.AABB; +import org.joml.Matrix4f; + +public class CullEverythingFrustum extends Frustum implements IDhApiShadowCullingFrustum { + public CullEverythingFrustum() { + super(new Matrix4f(), new Matrix4f()); + } + + // For Immersive Portals + // We return false here since isVisible is going to return false anyways. + public boolean canDetermineInvisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + return false; + } + + public boolean isVisible(AABB box) { + return false; + } + + @Override + public void update(int worldMinBlockY, int worldMaxBlockY, Mat4f worldViewProjection) { + + } + + @Override + public boolean intersects(int lodBlockPosMinX, int lodBlockPosMinZ, int lodBlockWidth, int lodDetailLevel) { + return false; + } +} diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/FrustumHolder.java b/src/main/java/net/irisshaders/iris/shadows/frustum/FrustumHolder.java similarity index 92% rename from src/main/java/net/coderbot/iris/shadows/frustum/FrustumHolder.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/FrustumHolder.java index 61a20b6c5b..00492bf888 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/FrustumHolder.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/FrustumHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shadows.frustum; +package net.irisshaders.iris.shadows.frustum; import net.minecraft.client.renderer.culling.Frustum; diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java similarity index 89% rename from src/main/java/net/coderbot/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java index 94f655ca3b..03b3f2ad1d 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/AdvancedShadowCullingFrustum.java @@ -1,12 +1,14 @@ -package net.coderbot.iris.shadows.frustum.advanced; +package net.irisshaders.iris.shadows.frustum.advanced; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum; +import com.seibel.distanthorizons.coreapi.util.math.Mat4f; +import net.irisshaders.iris.shadows.frustum.BoxCuller; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.world.phys.AABB; import org.joml.Math; -import net.coderbot.iris.shadows.frustum.BoxCuller; import org.joml.Matrix4f; import org.joml.Vector3f; import org.joml.Vector4f; -import net.minecraft.client.renderer.culling.Frustum; -import net.minecraft.world.phys.AABB; /** * A Frustum implementation that derives a tightly-fitted shadow pass frustum based on the player's camera frustum and @@ -28,9 +30,9 @@ * are not sensitive to the specific internal ordering of planes and corners, in order to avoid potential bugs at the * cost of slightly more computations.

    */ -public class AdvancedShadowCullingFrustum extends Frustum { +public class AdvancedShadowCullingFrustum extends Frustum implements IDhApiShadowCullingFrustum { private static final int MAX_CLIPPING_PLANES = 13; - + protected final BoxCuller boxCuller; /** * We store each plane equation as a Vector4f. * @@ -60,15 +62,14 @@ public class AdvancedShadowCullingFrustum extends Frustum { *

    */ private final Vector4f[] planes = new Vector4f[MAX_CLIPPING_PLANES]; - private int planeCount = 0; - + private final Vector3f shadowLightVectorFromOrigin; // The center coordinates of this frustum. - public double x; + public double x; public double y; public double z; - - private final Vector3f shadowLightVectorFromOrigin; - protected final BoxCuller boxCuller; + private int worldMinYDH; + private int worldMaxYDH; + private int planeCount = 0; public AdvancedShadowCullingFrustum(Matrix4f playerView, Matrix4f playerProjection, Vector3f shadowLightVectorFromOrigin, BoxCuller boxCuller) { @@ -136,20 +137,20 @@ private void addEdgePlanes(BaseClippingPlanes baseClippingPlanes, boolean[] isBa NeighboringPlaneSet neighbors = NeighboringPlaneSet.forPlane(planeIndex); - if (!isBack[neighbors.getPlane0()]) { - addEdgePlane(plane, planes[neighbors.getPlane0()]); + if (!isBack[neighbors.plane0()]) { + addEdgePlane(plane, planes[neighbors.plane0()]); } - if (!isBack[neighbors.getPlane1()]) { - addEdgePlane(plane, planes[neighbors.getPlane1()]); + if (!isBack[neighbors.plane1()]) { + addEdgePlane(plane, planes[neighbors.plane1()]); } - if (!isBack[neighbors.getPlane2()]) { - addEdgePlane(plane, planes[neighbors.getPlane2()]); + if (!isBack[neighbors.plane2()]) { + addEdgePlane(plane, planes[neighbors.plane2()]); } - if (!isBack[neighbors.getPlane3()]) { - addEdgePlane(plane, planes[neighbors.getPlane3()]); + if (!isBack[neighbors.plane3()]) { + addEdgePlane(plane, planes[neighbors.plane3()]); } } } @@ -303,18 +304,19 @@ public boolean canDetermineInvisible(double minX, double minY, double minZ, doub } protected int isVisible(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - float f = (float)(minX - this.x); - float g = (float)(minY - this.y); - float h = (float)(minZ - this.z); - float i = (float)(maxX - this.x); - float j = (float)(maxY - this.y); - float k = (float)(maxZ - this.z); + float f = (float) (minX - this.x); + float g = (float) (minY - this.y); + float h = (float) (minZ - this.z); + float i = (float) (maxX - this.x); + float j = (float) (maxY - this.y); + float k = (float) (maxZ - this.z); return this.checkCornerVisibility(f, g, h, i, j, k); } /** * Checks corner visibility. + * * @param minX Minimum X value of the AABB. * @param minY Minimum Y value of the AABB. * @param minZ Minimum Z value of the AABB. @@ -363,6 +365,7 @@ protected int checkCornerVisibility(float minX, float minY, float minZ, float ma /** * Checks corner visibility. + * * @param minX Minimum X value of the AABB. * @param minY Minimum Y value of the AABB. * @param minZ Minimum Z value of the AABB. @@ -380,4 +383,15 @@ public boolean checkCornerVisibilityBool(float minX, float minY, float minZ, flo return true; } + + @Override + public void update(int worldMinBlockY, int worldMaxBlockY, Mat4f worldViewProjection) { + this.worldMinYDH = worldMinBlockY; + this.worldMaxYDH = worldMaxBlockY; + } + + @Override + public boolean intersects(int lodBlockPosMinX, int lodBlockPosMinZ, int lodBlockWidth, int lodDetailLevel) { + return this.isVisible(lodBlockPosMinX, this.worldMinYDH, lodBlockPosMinZ, lodBlockPosMinX + lodBlockWidth, this.worldMaxYDH, lodBlockPosMinZ + lodBlockWidth) != 0; + } } diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/BaseClippingPlanes.java b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/BaseClippingPlanes.java similarity index 95% rename from src/main/java/net/coderbot/iris/shadows/frustum/advanced/BaseClippingPlanes.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/advanced/BaseClippingPlanes.java index c4d1553503..168a4395a9 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/BaseClippingPlanes.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/BaseClippingPlanes.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.shadows.frustum.advanced; +package net.irisshaders.iris.shadows.frustum.advanced; import org.joml.Matrix4f; import org.joml.Vector4f; @@ -10,6 +10,14 @@ public BaseClippingPlanes(Matrix4f playerView, Matrix4f playerProjection) { this.init(playerView, playerProjection); } + private static Vector4f transform(Matrix4f transform, float x, float y, float z) { + Vector4f vector4f = new Vector4f(x, y, z, 1.0F); + vector4f.mul(transform); + vector4f.normalize(); + + return vector4f; + } + private void init(Matrix4f view, Matrix4f projection) { // Transform = Transpose(Projection x View) @@ -27,14 +35,6 @@ private void init(Matrix4f view, Matrix4f projection) { planes[5] = transform(transform, 0, 0, 1); } - private static Vector4f transform(Matrix4f transform, float x, float y, float z) { - Vector4f vector4f = new Vector4f(x, y, z, 1.0F); - vector4f.mul(transform); - vector4f.normalize(); - - return vector4f; - } - public Vector4f[] getPlanes() { return planes; } diff --git a/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/NeighboringPlaneSet.java b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/NeighboringPlaneSet.java new file mode 100644 index 0000000000..cb411cfa33 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/NeighboringPlaneSet.java @@ -0,0 +1,19 @@ +package net.irisshaders.iris.shadows.frustum.advanced; + +public record NeighboringPlaneSet(int plane0, int plane1, int plane2, int plane3) { + private static final NeighboringPlaneSet FOR_PLUS_X = new NeighboringPlaneSet(2, 3, 4, 5); + private static final NeighboringPlaneSet FOR_PLUS_Y = new NeighboringPlaneSet(0, 1, 4, 5); + private static final NeighboringPlaneSet FOR_PLUS_Z = new NeighboringPlaneSet(0, 1, 2, 3); + + private static final NeighboringPlaneSet[] TABLE = new NeighboringPlaneSet[]{ + FOR_PLUS_X, + FOR_PLUS_Y, + FOR_PLUS_Z + }; + + public static NeighboringPlaneSet forPlane(int planeIndex) { + return TABLE[planeIndex >>> 1]; + } + + +} diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java similarity index 93% rename from src/main/java/net/coderbot/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java index 9fd0689bd1..4d7527c83f 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/advanced/ReversedAdvancedShadowCullingFrustum.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.shadows.frustum.advanced; +package net.irisshaders.iris.shadows.frustum.advanced; -import net.coderbot.iris.Iris; -import net.coderbot.iris.shadows.frustum.BoxCuller; +import net.irisshaders.iris.shadows.frustum.BoxCuller; import net.minecraft.world.phys.AABB; import org.joml.Matrix4f; import org.joml.Vector3f; diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/fallback/BoxCullingFrustum.java b/src/main/java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java similarity index 54% rename from src/main/java/net/coderbot/iris/shadows/frustum/fallback/BoxCullingFrustum.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java index 61bedeacdc..60781cd5d7 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/fallback/BoxCullingFrustum.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/fallback/BoxCullingFrustum.java @@ -1,13 +1,17 @@ -package net.coderbot.iris.shadows.frustum.fallback; +package net.irisshaders.iris.shadows.frustum.fallback; -import org.joml.Matrix4f; -import net.coderbot.iris.shadows.frustum.BoxCuller; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum; +import com.seibel.distanthorizons.coreapi.util.math.Mat4f; +import net.irisshaders.iris.shadows.frustum.BoxCuller; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.world.phys.AABB; +import org.joml.Matrix4f; -public class BoxCullingFrustum extends Frustum { +public class BoxCullingFrustum extends Frustum implements IDhApiShadowCullingFrustum { private final BoxCuller boxCuller; private double x, y, z; + private int worldMinYDH; + private int worldMaxYDH; public BoxCullingFrustum(BoxCuller boxCuller) { super(new Matrix4f(), new Matrix4f()); @@ -33,4 +37,15 @@ public boolean canDetermineInvisible(double minX, double minY, double minZ, doub public boolean isVisible(AABB box) { return !boxCuller.isCulled(box); } + + @Override + public void update(int worldMinBlockY, int worldMaxBlockY, Mat4f worldViewProjection) { + this.worldMinYDH = worldMinBlockY; + this.worldMaxYDH = worldMaxBlockY; + } + + @Override + public boolean intersects(int lodBlockPosMinX, int lodBlockPosMinZ, int lodBlockWidth, int lodDetailLevel) { + return !boxCuller.isCulled(lodBlockPosMinX, this.worldMinYDH, lodBlockPosMinZ, lodBlockPosMinX + lodBlockWidth, this.worldMaxYDH, lodBlockPosMinZ + lodBlockWidth); + } } diff --git a/src/main/java/net/coderbot/iris/shadows/frustum/fallback/NonCullingFrustum.java b/src/main/java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java similarity index 57% rename from src/main/java/net/coderbot/iris/shadows/frustum/fallback/NonCullingFrustum.java rename to src/main/java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java index aa205b02d0..2bf8ba4aa6 100644 --- a/src/main/java/net/coderbot/iris/shadows/frustum/fallback/NonCullingFrustum.java +++ b/src/main/java/net/irisshaders/iris/shadows/frustum/fallback/NonCullingFrustum.java @@ -1,10 +1,12 @@ -package net.coderbot.iris.shadows.frustum.fallback; +package net.irisshaders.iris.shadows.frustum.fallback; -import org.joml.Matrix4f; +import com.seibel.distanthorizons.api.interfaces.override.rendering.IDhApiShadowCullingFrustum; +import com.seibel.distanthorizons.coreapi.util.math.Mat4f; import net.minecraft.client.renderer.culling.Frustum; import net.minecraft.world.phys.AABB; +import org.joml.Matrix4f; -public class NonCullingFrustum extends Frustum { +public class NonCullingFrustum extends Frustum implements IDhApiShadowCullingFrustum { public NonCullingFrustum() { super(new Matrix4f(), new Matrix4f()); } @@ -20,4 +22,14 @@ public boolean canDetermineInvisible(double minX, double minY, double minZ, doub public boolean isVisible(AABB box) { return true; } + + @Override + public void update(int worldMinBlockY, int worldMaxBlockY, Mat4f worldViewProjection) { + + } + + @Override + public boolean intersects(int lodBlockPosMinX, int lodBlockPosMinZ, int lodBlockWidth, int lodDetailLevel) { + return true; + } } diff --git a/src/main/java/net/coderbot/iris/rendertarget/Blaze3dRenderTargetExt.java b/src/main/java/net/irisshaders/iris/targets/Blaze3dRenderTargetExt.java similarity index 74% rename from src/main/java/net/coderbot/iris/rendertarget/Blaze3dRenderTargetExt.java rename to src/main/java/net/irisshaders/iris/targets/Blaze3dRenderTargetExt.java index 207ece1d0d..4e764d6bb0 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/Blaze3dRenderTargetExt.java +++ b/src/main/java/net/irisshaders/iris/targets/Blaze3dRenderTargetExt.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets; public interface Blaze3dRenderTargetExt { int iris$getDepthBufferVersion(); diff --git a/src/main/java/net/coderbot/iris/postprocess/BufferFlipper.java b/src/main/java/net/irisshaders/iris/targets/BufferFlipper.java similarity index 95% rename from src/main/java/net/coderbot/iris/postprocess/BufferFlipper.java rename to src/main/java/net/irisshaders/iris/targets/BufferFlipper.java index a4b6f32ef4..28041fadc6 100644 --- a/src/main/java/net/coderbot/iris/postprocess/BufferFlipper.java +++ b/src/main/java/net/irisshaders/iris/targets/BufferFlipper.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.postprocess; +package net.irisshaders.iris.targets; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.IntIterator; @@ -21,9 +21,9 @@ public void flip(int target) { /** * Returns true if this buffer is flipped. - * + *

    * If this buffer is not flipped, then users should write to the alternate variant and read from the main variant. - * + *

    * If this buffer is flipped, then users should write to the main variant and read from the alternate variant. */ public boolean isFlipped(int target) { diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java b/src/main/java/net/irisshaders/iris/targets/ClearPass.java similarity index 92% rename from src/main/java/net/coderbot/iris/pipeline/ClearPass.java rename to src/main/java/net/irisshaders/iris/targets/ClearPass.java index 09dd5272de..96dcd8f8b5 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPass.java +++ b/src/main/java/net/irisshaders/iris/targets/ClearPass.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.targets; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; import net.minecraft.client.Minecraft; import org.joml.Vector4f; diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java b/src/main/java/net/irisshaders/iris/targets/ClearPassCreator.java similarity index 74% rename from src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java rename to src/main/java/net/irisshaders/iris/targets/ClearPassCreator.java index 6b7d09650d..a612200345 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPassCreator.java +++ b/src/main/java/net/irisshaders/iris/targets/ClearPassCreator.java @@ -1,14 +1,12 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.targets; import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; -import net.coderbot.iris.rendertarget.RenderTarget; -import net.coderbot.iris.rendertarget.RenderTargets; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; -import net.coderbot.iris.shaderpack.PackShadowDirectives; -import net.coderbot.iris.shadows.ShadowRenderTargets; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; +import net.irisshaders.iris.shaderpack.properties.PackShadowDirectives; +import net.irisshaders.iris.shadows.ShadowRenderTargets; import org.joml.Vector2i; import org.joml.Vector4f; import org.lwjgl.opengl.GL21C; @@ -53,30 +51,28 @@ public static ImmutableList createClearPasses(RenderTargets renderTar List clearPasses = new ArrayList<>(); - clearByColor.forEach((passSize, vector4fIntListMap) -> { - vector4fIntListMap.forEach((clearInfo, buffers) -> { - int startIndex = 0; + clearByColor.forEach((passSize, vector4fIntListMap) -> vector4fIntListMap.forEach((clearInfo, buffers) -> { + int startIndex = 0; - while (startIndex < buffers.size()) { - // clear up to the maximum number of draw buffers per each clear pass. - // This allows us to handle having more than 8 buffers with the same clear color on systems with - // a max draw buffers of 8 (ie, most systems). - int[] clearBuffers = new int[Math.min(buffers.size() - startIndex, maxDrawBuffers)]; + while (startIndex < buffers.size()) { + // clear up to the maximum number of draw buffers per each clear pass. + // This allows us to handle having more than 8 buffers with the same clear color on systems with + // a max draw buffers of 8 (ie, most systems). + int[] clearBuffers = new int[Math.min(buffers.size() - startIndex, maxDrawBuffers)]; - for (int i = 0; i < clearBuffers.length; i++) { - clearBuffers[i] = buffers.getInt(startIndex); - startIndex++; - } + for (int i = 0; i < clearBuffers.length; i++) { + clearBuffers[i] = buffers.getInt(startIndex); + startIndex++; + } - // No need to clear the depth buffer, since we're using Minecraft's depth buffer. - clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, - renderTargets.createClearFramebuffer(true, clearBuffers), GL21C.GL_COLOR_BUFFER_BIT)); + // No need to clear the depth buffer, since we're using Minecraft's depth buffer. + clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, + renderTargets.createClearFramebuffer(true, clearBuffers), GL21C.GL_COLOR_BUFFER_BIT)); - clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, - renderTargets.createClearFramebuffer(false, clearBuffers), GL21C.GL_COLOR_BUFFER_BIT)); - } - }); - }); + clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, + renderTargets.createClearFramebuffer(false, clearBuffers), GL21C.GL_COLOR_BUFFER_BIT)); + } + })); return ImmutableList.copyOf(clearPasses); } diff --git a/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java b/src/main/java/net/irisshaders/iris/targets/ClearPassInformation.java similarity index 80% rename from src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java rename to src/main/java/net/irisshaders/iris/targets/ClearPassInformation.java index 42197a5dcd..3d0cc40b23 100644 --- a/src/main/java/net/coderbot/iris/pipeline/ClearPassInformation.java +++ b/src/main/java/net/irisshaders/iris/targets/ClearPassInformation.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.pipeline; +package net.irisshaders.iris.targets; import org.joml.Vector4f; @@ -27,12 +27,10 @@ public int getHeight() { @Override public boolean equals(Object obj) { - if (!(obj instanceof ClearPassInformation)) { + if (!(obj instanceof ClearPassInformation information)) { return false; } - ClearPassInformation information = (ClearPassInformation) obj; - return information.color.equals(this.color) && information.height == this.height && information.width == this.width; } } diff --git a/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java b/src/main/java/net/irisshaders/iris/targets/DepthTexture.java similarity index 74% rename from src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java rename to src/main/java/net/irisshaders/iris/targets/DepthTexture.java index 2c3241d339..9c4fda15c6 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/DepthTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/DepthTexture.java @@ -1,19 +1,21 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; +import org.lwjgl.opengl.GL43C; public class DepthTexture extends GlResource { - public DepthTexture(int width, int height, DepthBufferFormat format) { + public DepthTexture(String name, int width, int height, DepthBufferFormat format) { super(IrisRenderSystem.createTexture(GL11C.GL_TEXTURE_2D)); int texture = getGlId(); resize(width, height, format); + GLDebug.nameObject(GL43C.GL_TEXTURE, texture, name); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_NEAREST); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_NEAREST); diff --git a/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java b/src/main/java/net/irisshaders/iris/targets/RenderTarget.java similarity index 87% rename from src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java rename to src/main/java/net/irisshaders/iris/targets/RenderTarget.java index 977b0e7481..7e480c6907 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/RenderTarget.java +++ b/src/main/java/net/irisshaders/iris/targets/RenderTarget.java @@ -1,29 +1,28 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.InternalTextureFormat; -import net.coderbot.iris.gl.texture.PixelFormat; -import net.coderbot.iris.gl.texture.PixelType; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.InternalTextureFormat; +import net.irisshaders.iris.gl.texture.PixelFormat; +import net.irisshaders.iris.gl.texture.PixelType; import org.joml.Vector2i; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; +import org.lwjgl.opengl.GL43C; import java.nio.ByteBuffer; -import java.nio.IntBuffer; public class RenderTarget { + private static final ByteBuffer NULL_BUFFER = null; private final InternalTextureFormat internalFormat; private final PixelFormat format; private final PixelType type; + private final int mainTexture; + private final int altTexture; private int width; private int height; - private boolean isValid; - private final int mainTexture; - private final int altTexture; - - private static final ByteBuffer NULL_BUFFER = null; public RenderTarget(Builder builder) { this.isValid = true; @@ -45,11 +44,20 @@ public RenderTarget(Builder builder) { setupTexture(mainTexture, builder.width, builder.height, !isPixelFormatInteger); setupTexture(altTexture, builder.width, builder.height, !isPixelFormatInteger); + if (builder.name != null) { + GLDebug.nameObject(GL43C.GL_TEXTURE, mainTexture, builder.name + " main"); + GLDebug.nameObject(GL43C.GL_TEXTURE, mainTexture, builder.name + " alt"); + } + // Clean up after ourselves // This is strictly defensive to ensure that other buggy code doesn't tamper with our textures GlStateManager._bindTexture(0); } + public static Builder builder() { + return new Builder(); + } + private void setupTexture(int texture, int width, int height, boolean allowsLinear) { resizeTexture(texture, width, height); @@ -116,21 +124,24 @@ private void requireValid() { } } - public static Builder builder() { - return new Builder(); - } - public static class Builder { private InternalTextureFormat internalFormat = InternalTextureFormat.RGBA8; private int width = 0; private int height = 0; private PixelFormat format = PixelFormat.RGBA; private PixelType type = PixelType.UNSIGNED_BYTE; + private String name = null; private Builder() { // No-op } + public Builder setName(String name) { + this.name = name; + + return this; + } + public Builder setInternalFormat(InternalTextureFormat format) { this.internalFormat = format; diff --git a/src/main/java/net/irisshaders/iris/targets/RenderTargetStateListener.java b/src/main/java/net/irisshaders/iris/targets/RenderTargetStateListener.java new file mode 100644 index 0000000000..0c2606a46c --- /dev/null +++ b/src/main/java/net/irisshaders/iris/targets/RenderTargetStateListener.java @@ -0,0 +1,9 @@ +package net.irisshaders.iris.targets; + +public interface RenderTargetStateListener { + RenderTargetStateListener NOP = bound -> { + + }; + + void setIsMainBound(boolean bound); +} diff --git a/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java b/src/main/java/net/irisshaders/iris/targets/RenderTargets.java similarity index 89% rename from src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java rename to src/main/java/net/irisshaders/iris/targets/RenderTargets.java index d5559f80c0..b4e0c4166f 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/RenderTargets.java +++ b/src/main/java/net/irisshaders/iris/targets/RenderTargets.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets; import com.google.common.collect.ImmutableSet; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.framebuffer.GlFramebuffer; -import net.coderbot.iris.gl.texture.DepthBufferFormat; -import net.coderbot.iris.gl.texture.DepthCopyStrategy; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shaderpack.PackRenderTargetDirectives; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.gl.texture.DepthBufferFormat; +import net.irisshaders.iris.gl.texture.DepthCopyStrategy; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shaderpack.properties.PackRenderTargetDirectives; import org.joml.Vector2i; import org.lwjgl.opengl.GL20C; import org.lwjgl.opengl.GL30C; @@ -19,20 +19,17 @@ public class RenderTargets { private final RenderTarget[] targets; - private int currentDepthTexture; - private DepthBufferFormat currentDepthFormat; - private final DepthTexture noTranslucents; private final DepthTexture noHand; private final GlFramebuffer depthSourceFb; private final GlFramebuffer noTranslucentsDestFb; private final GlFramebuffer noHandDestFb; - private DepthCopyStrategy copyStrategy; - private final List ownedFramebuffers; private final Map targetSettingsMap; private final PackDirectives packDirectives; - + private int currentDepthTexture; + private DepthBufferFormat currentDepthFormat; + private DepthCopyStrategy copyStrategy; private int cachedWidth; private int cachedHeight; private boolean fullClearRequired; @@ -62,15 +59,15 @@ public RenderTargets(int width, int height, int depthTexture, int depthBufferVer // data. Otherwise very weird things can happen. fullClearRequired = true; - this.depthSourceFb = createFramebufferWritingToMain(new int[] {0}); + this.depthSourceFb = createFramebufferWritingToMain(new int[]{0}); - this.noTranslucents = new DepthTexture(width, height, currentDepthFormat); - this.noHand = new DepthTexture(width, height, currentDepthFormat); + this.noTranslucents = new DepthTexture("depthtex1", width, height, currentDepthFormat); + this.noHand = new DepthTexture("dephtex2", width, height, currentDepthFormat); - this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[] {0}); + this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[]{0}); this.noTranslucentsDestFb.addDepthAttachment(this.noTranslucents.getTextureId()); - this.noHandDestFb = createFramebufferWritingToMain(new int[] {0}); + this.noHandDestFb = createFramebufferWritingToMain(new int[]{0}); this.noHandDestFb.addDepthAttachment(this.noHand.getTextureId()); this.translucentDepthDirty = true; @@ -126,6 +123,7 @@ private void create(int index) { PackRenderTargetDirectives.RenderTargetSettings settings = targetSettingsMap.get(index); Vector2i dimensions = packDirectives.getTextureScaleOverride(index, cachedWidth, cachedHeight); targets[index] = RenderTarget.builder().setDimensions(dimensions.x, dimensions.y) + .setName("colortex" + index) .setInternalFormat(settings.getInternalFormat()) .setPixelFormat(settings.getInternalFormat().getPixelFormat()).build(); } @@ -184,7 +182,7 @@ public boolean resizeIfNeeded(int newDepthBufferVersion, int newDepthTextureId, } } - if (depthFormatChanged || sizeChanged) { + if (depthFormatChanged || sizeChanged) { // Reallocate depth buffers noTranslucents.resize(newWidth, newHeight, newDepthFormat); noHand.resize(newWidth, newHeight, newDepthFormat); @@ -284,6 +282,19 @@ private GlFramebuffer createEmptyFramebuffer() { return framebuffer; } + public GlFramebuffer createDHFramebuffer(ImmutableSet stageWritesToAlt, int[] drawBuffers) { + if (drawBuffers.length == 0) { + return createEmptyFramebuffer(); + } + + ImmutableSet stageWritesToMain = invert(stageWritesToAlt, drawBuffers); + + GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); + + return framebuffer; + } + + public GlFramebuffer createGbufferFramebuffer(ImmutableSet stageWritesToAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); @@ -291,7 +302,7 @@ public GlFramebuffer createGbufferFramebuffer(ImmutableSet stageWritesT ImmutableSet stageWritesToMain = invert(stageWritesToAlt, drawBuffers); - GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); + GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(currentDepthTexture); @@ -338,7 +349,7 @@ public GlFramebuffer createColorFramebuffer(ImmutableSet stageWritesToM framebuffer.destroy(); ownedFramebuffers.remove(framebuffer); throw new IllegalStateException("Render target with index " + drawBuffers[i] + " is not supported, only " - + getRenderTargetCount() + " render targets are supported."); + + getRenderTargetCount() + " render targets are supported."); } RenderTarget target = this.getOrCreate(drawBuffers[i]); diff --git a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedCustomTexture.java similarity index 85% rename from src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java rename to src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedCustomTexture.java index b6d4b339b3..ea73ef7c5c 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedCustomTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedCustomTexture.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets.backed; import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.shaderpack.texture.CustomTextureData; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.shaderpack.texture.CustomTextureData; import net.minecraft.client.renderer.texture.DynamicTexture; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; diff --git a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedNoiseTexture.java b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedNoiseTexture.java similarity index 87% rename from src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedNoiseTexture.java rename to src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedNoiseTexture.java index 5ac9ae9d6f..22d9c658d1 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedNoiseTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedNoiseTexture.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets.backed; import com.mojang.blaze3d.platform.NativeImage; -import net.coderbot.iris.gl.texture.TextureAccess; -import net.coderbot.iris.gl.texture.TextureType; +import net.irisshaders.iris.gl.texture.TextureAccess; +import net.irisshaders.iris.gl.texture.TextureType; import net.minecraft.client.renderer.texture.DynamicTexture; import java.util.Objects; diff --git a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedSingleColorTexture.java b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedSingleColorTexture.java similarity index 93% rename from src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedSingleColorTexture.java rename to src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedSingleColorTexture.java index 14b0afe58c..3d87a1c37a 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/NativeImageBackedSingleColorTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/backed/NativeImageBackedSingleColorTexture.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets.backed; import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.client.renderer.texture.DynamicTexture; diff --git a/src/main/java/net/coderbot/iris/rendertarget/NoiseTexture.java b/src/main/java/net/irisshaders/iris/targets/backed/NoiseTexture.java similarity index 87% rename from src/main/java/net/coderbot/iris/rendertarget/NoiseTexture.java rename to src/main/java/net/irisshaders/iris/targets/backed/NoiseTexture.java index 9fb56eb4b3..ca3d11fc3a 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/NoiseTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/backed/NoiseTexture.java @@ -1,13 +1,14 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets.backed; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.TextureUploadHelper; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.TextureUploadHelper; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; import org.lwjgl.opengl.GL20C; +import org.lwjgl.opengl.GL43C; import java.nio.ByteBuffer; import java.util.Random; @@ -31,10 +32,12 @@ public NoiseTexture(int width, int height) { IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MAX_LEVEL, 0); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MIN_LOD, 0); - IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MAX_LOD,0); + IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_MAX_LOD, 0); IrisRenderSystem.texParameterf(texture, GL11C.GL_TEXTURE_2D, GL20C.GL_TEXTURE_LOD_BIAS, 0.0F); resize(texture, width, height); + GLDebug.nameObject(GL43C.GL_TEXTURE, texture, "noise texture"); + GlStateManager._bindTexture(0); } diff --git a/src/main/java/net/coderbot/iris/rendertarget/SingleColorTexture.java b/src/main/java/net/irisshaders/iris/targets/backed/SingleColorTexture.java similarity index 77% rename from src/main/java/net/coderbot/iris/rendertarget/SingleColorTexture.java rename to src/main/java/net/irisshaders/iris/targets/backed/SingleColorTexture.java index 5cfede1f10..af4a93c791 100644 --- a/src/main/java/net/coderbot/iris/rendertarget/SingleColorTexture.java +++ b/src/main/java/net/irisshaders/iris/targets/backed/SingleColorTexture.java @@ -1,13 +1,14 @@ -package net.coderbot.iris.rendertarget; +package net.irisshaders.iris.targets.backed; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.GlResource; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.texture.TextureUploadHelper; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.GlResource; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.texture.TextureUploadHelper; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11C; import org.lwjgl.opengl.GL13C; +import org.lwjgl.opengl.GL43C; import java.nio.ByteBuffer; @@ -23,6 +24,8 @@ public SingleColorTexture(int red, int green, int blue, int alpha) { int texture = getGlId(); + GLDebug.nameObject(GL43C.GL_TEXTURE, texture, "single color (" + red + ", " + green + "," + blue + "," + alpha + ")"); + IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MIN_FILTER, GL11C.GL_LINEAR); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_MAG_FILTER, GL11C.GL_LINEAR); IrisRenderSystem.texParameteri(texture, GL11C.GL_TEXTURE_2D, GL11C.GL_TEXTURE_WRAP_S, GL13C.GL_REPEAT); diff --git a/src/main/java/net/coderbot/iris/texture/SpriteContentsExtension.java b/src/main/java/net/irisshaders/iris/texture/SpriteContentsExtension.java similarity index 84% rename from src/main/java/net/coderbot/iris/texture/SpriteContentsExtension.java rename to src/main/java/net/irisshaders/iris/texture/SpriteContentsExtension.java index 4ebab48ba1..9da6a78260 100644 --- a/src/main/java/net/coderbot/iris/texture/SpriteContentsExtension.java +++ b/src/main/java/net/irisshaders/iris/texture/SpriteContentsExtension.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture; +package net.irisshaders.iris.texture; import net.minecraft.client.renderer.texture.SpriteContents; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/texture/TextureInfoCache.java b/src/main/java/net/irisshaders/iris/texture/TextureInfoCache.java similarity index 94% rename from src/main/java/net/coderbot/iris/texture/TextureInfoCache.java rename to src/main/java/net/irisshaders/iris/texture/TextureInfoCache.java index 681dcf7f31..cc99256c15 100644 --- a/src/main/java/net/coderbot/iris/texture/TextureInfoCache.java +++ b/src/main/java/net/irisshaders/iris/texture/TextureInfoCache.java @@ -1,10 +1,9 @@ -package net.coderbot.iris.texture; +package net.irisshaders.iris.texture; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.coderbot.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL20C; diff --git a/src/main/java/net/coderbot/iris/texture/TextureTracker.java b/src/main/java/net/irisshaders/iris/texture/TextureTracker.java similarity index 77% rename from src/main/java/net/coderbot/iris/texture/TextureTracker.java rename to src/main/java/net/irisshaders/iris/texture/TextureTracker.java index 350001c648..fb478534a4 100644 --- a/src/main/java/net/coderbot/iris/texture/TextureTracker.java +++ b/src/main/java/net/irisshaders/iris/texture/TextureTracker.java @@ -1,17 +1,14 @@ -package net.coderbot.iris.texture; +package net.irisshaders.iris.texture; -import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.gl.texture.TextureType; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; import net.minecraft.client.renderer.texture.AbstractTexture; import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL20C; public class TextureTracker { public static final TextureTracker INSTANCE = new TextureTracker(); diff --git a/src/main/java/net/irisshaders/iris/texture/format/LabPBRTextureFormat.java b/src/main/java/net/irisshaders/iris/texture/format/LabPBRTextureFormat.java new file mode 100644 index 0000000000..f757270f97 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/texture/format/LabPBRTextureFormat.java @@ -0,0 +1,45 @@ +package net.irisshaders.iris.texture.format; + +import net.irisshaders.iris.texture.mipmap.ChannelMipmapGenerator; +import net.irisshaders.iris.texture.mipmap.CustomMipmapGenerator; +import net.irisshaders.iris.texture.mipmap.DiscreteBlendFunction; +import net.irisshaders.iris.texture.mipmap.LinearBlendFunction; +import net.irisshaders.iris.texture.pbr.PBRType; +import org.jetbrains.annotations.Nullable; + +import java.util.Objects; + +public record LabPBRTextureFormat(String name, @Nullable String version) implements TextureFormat { + public static final ChannelMipmapGenerator SPECULAR_MIPMAP_GENERATOR = new ChannelMipmapGenerator( + LinearBlendFunction.INSTANCE, + new DiscreteBlendFunction(v -> v < 230 ? 0 : v - 229), + new DiscreteBlendFunction(v -> v < 65 ? 0 : 1), + new DiscreteBlendFunction(v -> v < 255 ? 0 : 1) + ); + + + @Override + public boolean canInterpolateValues(PBRType pbrType) { + return pbrType != PBRType.SPECULAR; + } + + @Override + public @Nullable CustomMipmapGenerator getMipmapGenerator(PBRType pbrType) { + if (pbrType == PBRType.SPECULAR) { + return SPECULAR_MIPMAP_GENERATOR; + } + return null; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + LabPBRTextureFormat other = (LabPBRTextureFormat) obj; + return Objects.equals(name, other.name) && Objects.equals(version, other.version); + } +} diff --git a/src/main/java/net/coderbot/iris/texture/format/TextureFormat.java b/src/main/java/net/irisshaders/iris/texture/format/TextureFormat.java similarity index 81% rename from src/main/java/net/coderbot/iris/texture/format/TextureFormat.java rename to src/main/java/net/irisshaders/iris/texture/format/TextureFormat.java index 58359d59c2..e13f6af78a 100644 --- a/src/main/java/net/coderbot/iris/texture/format/TextureFormat.java +++ b/src/main/java/net/irisshaders/iris/texture/format/TextureFormat.java @@ -1,9 +1,8 @@ -package net.coderbot.iris.texture.format; +package net.irisshaders.iris.texture.format; -import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.texture.mipmap.CustomMipmapGenerator; -import net.coderbot.iris.texture.pbr.PBRType; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.texture.mipmap.CustomMipmapGenerator; +import net.irisshaders.iris.texture.pbr.PBRType; import net.minecraft.client.renderer.texture.AbstractTexture; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; @@ -13,19 +12,19 @@ import java.util.Locale; public interface TextureFormat { - String getName(); + String name(); @Nullable - String getVersion(); + String version(); default List getDefines() { List defines = new ArrayList<>(); - String defineName = getName().toUpperCase(Locale.ROOT).replaceAll("-", "_"); + String defineName = name().toUpperCase(Locale.ROOT).replaceAll("-", "_"); String define = "MC_TEXTURE_FORMAT_" + defineName; defines.add(define); - String version = getVersion(); + String version = version(); if (version != null) { String defineVersion = version.replaceAll("[.-]", "_"); String versionDefine = define + "_" + defineVersion; @@ -59,7 +58,7 @@ default void setupTextureParameters(PBRType pbrType, AbstractTexture texture) { @Nullable CustomMipmapGenerator getMipmapGenerator(PBRType pbrType); - public interface Factory { + interface Factory { TextureFormat createFormat(String name, @Nullable String version); } } diff --git a/src/main/java/net/coderbot/iris/texture/format/TextureFormatLoader.java b/src/main/java/net/irisshaders/iris/texture/format/TextureFormatLoader.java similarity index 96% rename from src/main/java/net/coderbot/iris/texture/format/TextureFormatLoader.java rename to src/main/java/net/irisshaders/iris/texture/format/TextureFormatLoader.java index acf47c5546..1bd264f9cc 100644 --- a/src/main/java/net/coderbot/iris/texture/format/TextureFormatLoader.java +++ b/src/main/java/net/irisshaders/iris/texture/format/TextureFormatLoader.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.texture.format; +package net.irisshaders.iris.texture.format; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; diff --git a/src/main/java/net/coderbot/iris/texture/format/TextureFormatRegistry.java b/src/main/java/net/irisshaders/iris/texture/format/TextureFormatRegistry.java similarity index 92% rename from src/main/java/net/coderbot/iris/texture/format/TextureFormatRegistry.java rename to src/main/java/net/irisshaders/iris/texture/format/TextureFormatRegistry.java index 513524d679..54872e70d4 100644 --- a/src/main/java/net/coderbot/iris/texture/format/TextureFormatRegistry.java +++ b/src/main/java/net/irisshaders/iris/texture/format/TextureFormatRegistry.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.format; +package net.irisshaders.iris.texture.format; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/texture/mipmap/AbstractMipmapGenerator.java b/src/main/java/net/irisshaders/iris/texture/mipmap/AbstractMipmapGenerator.java similarity index 78% rename from src/main/java/net/coderbot/iris/texture/mipmap/AbstractMipmapGenerator.java rename to src/main/java/net/irisshaders/iris/texture/mipmap/AbstractMipmapGenerator.java index d57acd9eb8..d0293c7f7e 100644 --- a/src/main/java/net/coderbot/iris/texture/mipmap/AbstractMipmapGenerator.java +++ b/src/main/java/net/irisshaders/iris/texture/mipmap/AbstractMipmapGenerator.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.mipmap; +package net.irisshaders.iris.texture.mipmap; import com.mojang.blaze3d.platform.NativeImage; @@ -20,10 +20,10 @@ public NativeImage[] generateMipLevels(NativeImage[] image, int mipLevel) { for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { mipmap.setPixelRGBA(x, y, blend( - prevMipmap.getPixelRGBA(x * 2 + 0, y * 2 + 0), - prevMipmap.getPixelRGBA(x * 2 + 1, y * 2 + 0), - prevMipmap.getPixelRGBA(x * 2 + 0, y * 2 + 1), - prevMipmap.getPixelRGBA(x * 2 + 1, y * 2 + 1) + prevMipmap.getPixelRGBA(x * 2, y * 2), + prevMipmap.getPixelRGBA(x * 2 + 1, y * 2), + prevMipmap.getPixelRGBA(x * 2, y * 2 + 1), + prevMipmap.getPixelRGBA(x * 2 + 1, y * 2 + 1) )); } } diff --git a/src/main/java/net/coderbot/iris/texture/mipmap/ChannelMipmapGenerator.java b/src/main/java/net/irisshaders/iris/texture/mipmap/ChannelMipmapGenerator.java similarity index 50% rename from src/main/java/net/coderbot/iris/texture/mipmap/ChannelMipmapGenerator.java rename to src/main/java/net/irisshaders/iris/texture/mipmap/ChannelMipmapGenerator.java index 3b423b0659..86700bec69 100644 --- a/src/main/java/net/coderbot/iris/texture/mipmap/ChannelMipmapGenerator.java +++ b/src/main/java/net/irisshaders/iris/texture/mipmap/ChannelMipmapGenerator.java @@ -1,6 +1,5 @@ -package net.coderbot.iris.texture.mipmap; +package net.irisshaders.iris.texture.mipmap; -import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.util.FastColor; public class ChannelMipmapGenerator extends AbstractMipmapGenerator { @@ -19,30 +18,30 @@ public ChannelMipmapGenerator(BlendFunction redFunc, BlendFunction greenFunc, Bl @Override public int blend(int c0, int c1, int c2, int c3) { return FastColor.ABGR32.color( - alphaFunc.blend( - FastColor.ABGR32.alpha(c0), - FastColor.ABGR32.alpha(c1), - FastColor.ABGR32.alpha(c2), - FastColor.ABGR32.alpha(c3) - ), - blueFunc.blend( - FastColor.ABGR32.blue(c0), - FastColor.ABGR32.blue(c1), - FastColor.ABGR32.blue(c2), - FastColor.ABGR32.blue(c3) - ), - greenFunc.blend( - FastColor.ABGR32.green(c0), - FastColor.ABGR32.green(c1), - FastColor.ABGR32.green(c2), - FastColor.ABGR32.green(c3) - ), - redFunc.blend( - FastColor.ABGR32.red(c0), - FastColor.ABGR32.red(c1), - FastColor.ABGR32.red(c2), - FastColor.ABGR32.red(c3) - ) + alphaFunc.blend( + FastColor.ABGR32.alpha(c0), + FastColor.ABGR32.alpha(c1), + FastColor.ABGR32.alpha(c2), + FastColor.ABGR32.alpha(c3) + ), + blueFunc.blend( + FastColor.ABGR32.blue(c0), + FastColor.ABGR32.blue(c1), + FastColor.ABGR32.blue(c2), + FastColor.ABGR32.blue(c3) + ), + greenFunc.blend( + FastColor.ABGR32.green(c0), + FastColor.ABGR32.green(c1), + FastColor.ABGR32.green(c2), + FastColor.ABGR32.green(c3) + ), + redFunc.blend( + FastColor.ABGR32.red(c0), + FastColor.ABGR32.red(c1), + FastColor.ABGR32.red(c2), + FastColor.ABGR32.red(c3) + ) ); } diff --git a/src/main/java/net/coderbot/iris/texture/mipmap/CustomMipmapGenerator.java b/src/main/java/net/irisshaders/iris/texture/mipmap/CustomMipmapGenerator.java similarity index 57% rename from src/main/java/net/coderbot/iris/texture/mipmap/CustomMipmapGenerator.java rename to src/main/java/net/irisshaders/iris/texture/mipmap/CustomMipmapGenerator.java index 9143c23159..a298c03e23 100644 --- a/src/main/java/net/coderbot/iris/texture/mipmap/CustomMipmapGenerator.java +++ b/src/main/java/net/irisshaders/iris/texture/mipmap/CustomMipmapGenerator.java @@ -1,14 +1,12 @@ -package net.coderbot.iris.texture.mipmap; +package net.irisshaders.iris.texture.mipmap; import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.client.renderer.texture.SpriteContents; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import org.jetbrains.annotations.Nullable; public interface CustomMipmapGenerator { NativeImage[] generateMipLevels(NativeImage[] image, int mipLevel); - public interface Provider { + interface Provider { @Nullable CustomMipmapGenerator getMipmapGenerator(); } diff --git a/src/main/java/net/coderbot/iris/texture/mipmap/DiscreteBlendFunction.java b/src/main/java/net/irisshaders/iris/texture/mipmap/DiscreteBlendFunction.java similarity index 96% rename from src/main/java/net/coderbot/iris/texture/mipmap/DiscreteBlendFunction.java rename to src/main/java/net/irisshaders/iris/texture/mipmap/DiscreteBlendFunction.java index 9abc05879d..ea97e1abf0 100644 --- a/src/main/java/net/coderbot/iris/texture/mipmap/DiscreteBlendFunction.java +++ b/src/main/java/net/irisshaders/iris/texture/mipmap/DiscreteBlendFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.mipmap; +package net.irisshaders.iris.texture.mipmap; import java.util.function.IntUnaryOperator; @@ -9,6 +9,22 @@ public DiscreteBlendFunction(IntUnaryOperator typeFunc) { this.typeFunc = typeFunc; } + /** + * Selects the type that appears most often among the arguments. + * In the case of a tie, types that appear first in the argument list are given priority. + * A type is represented by an integer. + */ + public static int selectTargetType(int t0, int t1, int t2, int t3) { + if (t0 != t1 && t0 != t2) { + if (t2 == t3) { + return t2; + } else if (t0 != t3 && (t1 == t2 || t1 == t3)) { + return t1; + } + } + return t0; + } + @Override public int blend(int v0, int v1, int v2, int v3) { int t0 = typeFunc.applyAsInt(v0); @@ -39,20 +55,4 @@ public int blend(int v0, int v1, int v2, int v3) { return sum / amount; } - - /** - * Selects the type that appears most often among the arguments. - * In the case of a tie, types that appear first in the argument list are given priority. - * A type is represented by an integer. - * */ - public static int selectTargetType(int t0, int t1, int t2, int t3) { - if (t0 != t1 && t0 != t2) { - if (t2 == t3) { - return t2; - } else if (t0 != t3 && (t1 == t2 || t1 == t3)) { - return t1; - } - } - return t0; - } } diff --git a/src/main/java/net/coderbot/iris/texture/mipmap/LinearBlendFunction.java b/src/main/java/net/irisshaders/iris/texture/mipmap/LinearBlendFunction.java similarity index 85% rename from src/main/java/net/coderbot/iris/texture/mipmap/LinearBlendFunction.java rename to src/main/java/net/irisshaders/iris/texture/mipmap/LinearBlendFunction.java index 22faccc7bc..f3f5662bfc 100644 --- a/src/main/java/net/coderbot/iris/texture/mipmap/LinearBlendFunction.java +++ b/src/main/java/net/irisshaders/iris/texture/mipmap/LinearBlendFunction.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.mipmap; +package net.irisshaders.iris.texture.mipmap; public class LinearBlendFunction implements ChannelMipmapGenerator.BlendFunction { public static final LinearBlendFunction INSTANCE = new LinearBlendFunction(); diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasHolder.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasHolder.java similarity index 94% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasHolder.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasHolder.java index 49e781712a..3c82c96534 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasHolder.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import org.jetbrains.annotations.Nullable; @@ -11,15 +11,15 @@ public PBRAtlasTexture getNormalAtlas() { return normalAtlas; } + public void setNormalAtlas(PBRAtlasTexture atlas) { + normalAtlas = atlas; + } + @Nullable public PBRAtlasTexture getSpecularAtlas() { return specularAtlas; } - public void setNormalAtlas(PBRAtlasTexture atlas) { - normalAtlas = atlas; - } - public void setSpecularAtlas(PBRAtlasTexture atlas) { specularAtlas = atlas; } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasTexture.java similarity index 86% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasTexture.java index 7664214fcd..d2eee91901 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRAtlasTexture.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRAtlasTexture.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import com.mojang.blaze3d.platform.TextureUtil; -import net.coderbot.iris.Iris; -import net.coderbot.iris.mixin.texture.SpriteContentsAnimatedTextureAccessor; -import net.coderbot.iris.mixin.texture.SpriteContentsFrameInfoAccessor; -import net.coderbot.iris.mixin.texture.SpriteContentsTickerAccessor; -import net.coderbot.iris.texture.pbr.loader.AtlasPBRLoader.PBRTextureAtlasSprite; -import net.coderbot.iris.texture.util.TextureManipulationUtil; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.mixin.texture.SpriteContentsAnimatedTextureAccessor; +import net.irisshaders.iris.mixin.texture.SpriteContentsFrameInfoAccessor; +import net.irisshaders.iris.mixin.texture.SpriteContentsTickerAccessor; +import net.irisshaders.iris.texture.pbr.loader.AtlasPBRLoader.PBRTextureAtlasSprite; +import net.irisshaders.iris.texture.util.TextureManipulationUtil; import net.minecraft.CrashReport; import net.minecraft.CrashReportCategory; import net.minecraft.ReportedException; @@ -45,6 +45,52 @@ public PBRAtlasTexture(TextureAtlas atlasTexture, PBRType type) { id = new ResourceLocation(atlasTexture.location().getNamespace(), atlasTexture.location().getPath().replace(".png", "") + type.getSuffix() + ".png"); } + public static void syncAnimation(SpriteContents.Ticker source, SpriteContents.Ticker target) { + SpriteContentsTickerAccessor sourceAccessor = (SpriteContentsTickerAccessor) source; + List sourceFrames = ((SpriteContentsAnimatedTextureAccessor) sourceAccessor.getAnimationInfo()).getFrames(); + + int ticks = 0; + for (int f = 0; f < sourceAccessor.getFrame(); f++) { + ticks += ((SpriteContentsFrameInfoAccessor) sourceFrames.get(f)).getTime(); + } + + SpriteContentsTickerAccessor targetAccessor = (SpriteContentsTickerAccessor) target; + List targetFrames = ((SpriteContentsAnimatedTextureAccessor) targetAccessor.getAnimationInfo()).getFrames(); + + int cycleTime = 0; + int frameCount = targetFrames.size(); + for (FrameInfo frame : targetFrames) { + cycleTime += ((SpriteContentsFrameInfoAccessor) frame).getTime(); + } + ticks %= cycleTime; + + int targetFrame = 0; + while (true) { + int time = ((SpriteContentsFrameInfoAccessor) targetFrames.get(targetFrame)).getTime(); + if (ticks >= time) { + targetFrame++; + ticks -= time; + } else { + break; + } + } + + targetAccessor.setFrame(targetFrame); + targetAccessor.setSubFrame(ticks + sourceAccessor.getSubFrame()); + } + + protected static void dumpSpriteNames(Path dir, String fileName, Map sprites) { + Path path = dir.resolve(fileName + ".txt"); + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + for (Map.Entry entry : sprites.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { + PBRTextureAtlasSprite sprite = entry.getValue(); + writer.write(String.format(Locale.ROOT, "%s\tx=%d\ty=%d\tw=%d\th=%d%n", entry.getKey(), sprite.getX(), sprite.getY(), sprite.contents().width(), sprite.contents().height())); + } + } catch (IOException e) { + Iris.logger.warn("Failed to write file {}", path, e); + } + } + public PBRType getType() { return type; } @@ -114,8 +160,8 @@ protected void uploadSprite(PBRTextureAtlasSprite sprite) { if (spriteTicker != null) { animatedTextures.add(spriteTicker); - SpriteContents.Ticker sourceTicker = ((net.coderbot.iris.texture.SpriteContentsExtension) sprite.getBaseSprite().contents()).getCreatedTicker(); - SpriteContents.Ticker targetTicker = ((net.coderbot.iris.texture.SpriteContentsExtension) sprite.contents()).getCreatedTicker(); + SpriteContents.Ticker sourceTicker = ((net.irisshaders.iris.texture.SpriteContentsExtension) sprite.getBaseSprite().contents()).getCreatedTicker(); + SpriteContents.Ticker targetTicker = ((net.irisshaders.iris.texture.SpriteContentsExtension) sprite.contents()).getCreatedTicker(); if (sourceTicker != null && targetTicker != null) { syncAnimation(sourceTicker, targetTicker); @@ -130,40 +176,6 @@ protected void uploadSprite(PBRTextureAtlasSprite sprite) { sprite.uploadFirstFrame(); } - public static void syncAnimation(SpriteContents.Ticker source, SpriteContents.Ticker target) { - SpriteContentsTickerAccessor sourceAccessor = (SpriteContentsTickerAccessor) source; - List sourceFrames = ((SpriteContentsAnimatedTextureAccessor) sourceAccessor.getAnimationInfo()).getFrames(); - - int ticks = 0; - for (int f = 0; f < sourceAccessor.getFrame(); f++) { - ticks += ((SpriteContentsFrameInfoAccessor) sourceFrames.get(f)).getTime(); - } - - SpriteContentsTickerAccessor targetAccessor = (SpriteContentsTickerAccessor) target; - List targetFrames = ((SpriteContentsAnimatedTextureAccessor) targetAccessor.getAnimationInfo()).getFrames(); - - int cycleTime = 0; - int frameCount = targetFrames.size(); - for (int f = 0; f < frameCount; f++) { - cycleTime += ((SpriteContentsFrameInfoAccessor) targetFrames.get(f)).getTime(); - } - ticks %= cycleTime; - - int targetFrame = 0; - while (true) { - int time = ((SpriteContentsFrameInfoAccessor) targetFrames.get(targetFrame)).getTime(); - if (ticks >= time) { - targetFrame++; - ticks -= time; - } else { - break; - } - } - - targetAccessor.setFrame(targetFrame); - targetAccessor.setSubFrame(ticks + sourceAccessor.getSubFrame()); - } - public void cycleAnimationFrames() { bind(); for (TextureAtlasSprite.Ticker ticker : animatedTextures) { @@ -176,12 +188,12 @@ public void close() { PBRAtlasHolder pbrHolder = ((TextureAtlasExtension) atlasTexture).getPBRHolder(); if (pbrHolder != null) { switch (type) { - case NORMAL: - pbrHolder.setNormalAtlas(null); - break; - case SPECULAR: - pbrHolder.setSpecularAtlas(null); - break; + case NORMAL: + pbrHolder.setNormalAtlas(null); + break; + case SPECULAR: + pbrHolder.setSpecularAtlas(null); + break; } } clear(); @@ -192,24 +204,12 @@ public void load(ResourceManager manager) { } @Override - public void dumpContents(ResourceLocation id, Path path) throws IOException { + public void dumpContents(ResourceLocation id, Path path) { String fileName = id.toDebugFileName(); TextureUtil.writeAsPNG(path, fileName, getId(), mipLevel, width, height); dumpSpriteNames(path, fileName, texturesByName); } - protected static void dumpSpriteNames(Path dir, String fileName, Map sprites) { - Path path = dir.resolve(fileName + ".txt"); - try (BufferedWriter writer = Files.newBufferedWriter(path)) { - for (Map.Entry entry : sprites.entrySet().stream().sorted(Map.Entry.comparingByKey()).toList()) { - PBRTextureAtlasSprite sprite = entry.getValue(); - writer.write(String.format(Locale.ROOT, "%s\tx=%d\ty=%d\tw=%d\th=%d%n", entry.getKey(), sprite.getX(), sprite.getY(), sprite.contents().width(), sprite.contents().height())); - } - } catch (IOException e) { - Iris.logger.warn("Failed to write file {}", path, e); - } - } - @Override public ResourceLocation getDefaultDumpLocation() { return id; diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRDumpable.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRDumpable.java similarity index 82% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRDumpable.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRDumpable.java index b28ca6ce87..f357ed5062 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRDumpable.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRDumpable.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import net.minecraft.client.renderer.texture.Dumpable; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRSpriteHolder.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRSpriteHolder.java similarity index 94% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRSpriteHolder.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRSpriteHolder.java index bc55248ac2..9dce08ca05 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRSpriteHolder.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRSpriteHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import org.jetbrains.annotations.Nullable; @@ -12,15 +12,15 @@ public TextureAtlasSprite getNormalSprite() { return normalSprite; } + public void setNormalSprite(TextureAtlasSprite sprite) { + normalSprite = sprite; + } + @Nullable public TextureAtlasSprite getSpecularSprite() { return specularSprite; } - public void setNormalSprite(TextureAtlasSprite sprite) { - normalSprite = sprite; - } - public void setSpecularSprite(TextureAtlasSprite sprite) { specularSprite = sprite; } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRTextureHolder.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureHolder.java similarity index 58% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRTextureHolder.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureHolder.java index defaf949ff..08e1074b9e 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRTextureHolder.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureHolder.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import net.minecraft.client.renderer.texture.AbstractTexture; import org.jetbrains.annotations.NotNull; public interface PBRTextureHolder { @NotNull - AbstractTexture getNormalTexture(); + AbstractTexture normalTexture(); @NotNull - AbstractTexture getSpecularTexture(); + AbstractTexture specularTexture(); } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRTextureManager.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureManager.java similarity index 78% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRTextureManager.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureManager.java index 9cc0b2d858..fa0e8923f7 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRTextureManager.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRTextureManager.java @@ -1,16 +1,16 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import com.mojang.blaze3d.platform.GlStateManager; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.rendertarget.NativeImageBackedSingleColorTexture; -import net.coderbot.iris.texture.TextureTracker; -import net.coderbot.iris.texture.pbr.loader.PBRTextureLoader; -import net.coderbot.iris.texture.pbr.loader.PBRTextureLoader.PBRTextureConsumer; -import net.coderbot.iris.texture.pbr.loader.PBRTextureLoaderRegistry; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.targets.backed.NativeImageBackedSingleColorTexture; +import net.irisshaders.iris.texture.TextureTracker; +import net.irisshaders.iris.texture.pbr.loader.PBRTextureLoader; +import net.irisshaders.iris.texture.pbr.loader.PBRTextureLoader.PBRTextureConsumer; +import net.irisshaders.iris.texture.pbr.loader.PBRTextureLoaderRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.Dumpable; @@ -40,12 +40,12 @@ public class PBRTextureManager { // Not PBRTextureHolderImpl to directly reference fields private final PBRTextureHolder defaultHolder = new PBRTextureHolder() { @Override - public @NotNull AbstractTexture getNormalTexture() { + public @NotNull AbstractTexture normalTexture() { return defaultNormalTexture; } @Override - public @NotNull AbstractTexture getSpecularTexture() { + public @NotNull AbstractTexture specularTexture() { return defaultSpecularTexture; } }; @@ -53,6 +53,33 @@ public class PBRTextureManager { private PBRTextureManager() { } + private static void dumpTexture(Dumpable dumpable, ResourceLocation id, Path path) { + try { + dumpable.dumpContents(id, path); + } catch (IOException e) { + Iris.logger.error("Failed to dump texture {}", id, e); + } + } + + private static void closeTexture(AbstractTexture texture) { + try { + texture.close(); + } catch (Exception e) { + // + } + texture.releaseId(); + } + + public static void notifyPBRTexturesChanged() { + if (normalTextureChangeListener != null) { + normalTextureChangeListener.run(); + } + + if (specularTextureChangeListener != null) { + specularTextureChangeListener.run(); + } + } + public void init() { defaultNormalTexture = new NativeImageBackedSingleColorTexture(PBRType.NORMAL.getDefaultValue()); defaultSpecularTexture = new NativeImageBackedSingleColorTexture(PBRType.SPECULAR.getDefaultValue()); @@ -75,7 +102,7 @@ public PBRTextureHolder getOrLoadHolder(int id) { return holder; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private PBRTextureHolder loadHolder(int id) { AbstractTexture texture = TextureTracker.INSTANCE.getTexture(id); if (texture != null) { @@ -113,8 +140,8 @@ public void dumpTextures(Path path) { } private void dumpHolder(PBRTextureHolder holder, Path path) { - AbstractTexture normalTexture = holder.getNormalTexture(); - AbstractTexture specularTexture = holder.getSpecularTexture(); + AbstractTexture normalTexture = holder.normalTexture(); + AbstractTexture specularTexture = holder.specularTexture(); if (normalTexture != defaultNormalTexture && normalTexture instanceof PBRDumpable dumpable) { dumpTexture(dumpable, dumpable.getDefaultDumpLocation(), path); } @@ -123,14 +150,6 @@ private void dumpHolder(PBRTextureHolder holder, Path path) { } } - private static void dumpTexture(Dumpable dumpable, ResourceLocation id, Path path) { - try { - dumpable.dumpContents(id, path); - } catch (IOException e) { - Iris.logger.error("Failed to dump texture {}", id, e); - } - } - public void clear() { for (PBRTextureHolder holder : holders.values()) { if (holder != defaultHolder) { @@ -147,8 +166,8 @@ public void close() { } private void closeHolder(PBRTextureHolder holder) { - AbstractTexture normalTexture = holder.getNormalTexture(); - AbstractTexture specularTexture = holder.getSpecularTexture(); + AbstractTexture normalTexture = holder.normalTexture(); + AbstractTexture specularTexture = holder.specularTexture(); if (normalTexture != defaultNormalTexture) { closeTexture(normalTexture); } @@ -157,23 +176,17 @@ private void closeHolder(PBRTextureHolder holder) { } } - private static void closeTexture(AbstractTexture texture) { - try { - texture.close(); - } catch (Exception e) { - // - } - texture.releaseId(); - } - - public static void notifyPBRTexturesChanged() { - if (normalTextureChangeListener != null) { - normalTextureChangeListener.run(); - } + private record PBRTextureHolderImpl(AbstractTexture normalTexture, + AbstractTexture specularTexture) implements PBRTextureHolder { + @Override + public @NotNull AbstractTexture normalTexture() { + return normalTexture; + } - if (specularTextureChangeListener != null) { - specularTextureChangeListener.run(); - } + @Override + public @NotNull AbstractTexture specularTexture() { + return specularTexture; + } } private class PBRTextureConsumerImpl implements PBRTextureConsumer { @@ -207,24 +220,4 @@ public PBRTextureHolder toHolder() { } } } - - private static class PBRTextureHolderImpl implements PBRTextureHolder { - private final AbstractTexture normalTexture; - private final AbstractTexture specularTexture; - - public PBRTextureHolderImpl(AbstractTexture normalTexture, AbstractTexture specularTexture) { - this.normalTexture = normalTexture; - this.specularTexture = specularTexture; - } - - @Override - public @NotNull AbstractTexture getNormalTexture() { - return normalTexture; - } - - @Override - public @NotNull AbstractTexture getSpecularTexture() { - return specularTexture; - } - } } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/PBRType.java b/src/main/java/net/irisshaders/iris/texture/pbr/PBRType.java similarity index 97% rename from src/main/java/net/coderbot/iris/texture/pbr/PBRType.java rename to src/main/java/net/irisshaders/iris/texture/pbr/PBRType.java index 5ff7c412a6..0591a86d11 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/PBRType.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/PBRType.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import org.apache.commons.io.FilenameUtils; import org.jetbrains.annotations.Nullable; @@ -17,23 +17,6 @@ public enum PBRType { this.defaultValue = defaultValue; } - public String getSuffix() { - return suffix; - } - - public int getDefaultValue() { - return defaultValue; - } - - public String appendSuffix(String path) { - int extensionIndex = FilenameUtils.indexOfExtension(path); - if (extensionIndex != -1) { - return path.substring(0, extensionIndex) + suffix + path.substring(extensionIndex); - } else { - return path + suffix; - } - } - @Nullable public static String removeSuffix(String path) { int extensionIndex = FilenameUtils.indexOfExtension(path); @@ -62,4 +45,21 @@ public static PBRType fromFileLocation(String location) { } return null; } + + public String getSuffix() { + return suffix; + } + + public int getDefaultValue() { + return defaultValue; + } + + public String appendSuffix(String path) { + int extensionIndex = FilenameUtils.indexOfExtension(path); + if (extensionIndex != -1) { + return path.substring(0, extensionIndex) + suffix + path.substring(extensionIndex); + } else { + return path + suffix; + } + } } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/SpriteContentsExtension.java b/src/main/java/net/irisshaders/iris/texture/pbr/SpriteContentsExtension.java similarity index 80% rename from src/main/java/net/coderbot/iris/texture/pbr/SpriteContentsExtension.java rename to src/main/java/net/irisshaders/iris/texture/pbr/SpriteContentsExtension.java index 7957679bde..a0ab9728df 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/SpriteContentsExtension.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/SpriteContentsExtension.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/texture/pbr/TextureAtlasExtension.java b/src/main/java/net/irisshaders/iris/texture/pbr/TextureAtlasExtension.java similarity index 80% rename from src/main/java/net/coderbot/iris/texture/pbr/TextureAtlasExtension.java rename to src/main/java/net/irisshaders/iris/texture/pbr/TextureAtlasExtension.java index d8ce9fcbab..d1e1ea131e 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/TextureAtlasExtension.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/TextureAtlasExtension.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr; +package net.irisshaders.iris.texture.pbr; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/net/coderbot/iris/texture/pbr/loader/AtlasPBRLoader.java b/src/main/java/net/irisshaders/iris/texture/pbr/loader/AtlasPBRLoader.java similarity index 88% rename from src/main/java/net/coderbot/iris/texture/pbr/loader/AtlasPBRLoader.java rename to src/main/java/net/irisshaders/iris/texture/pbr/loader/AtlasPBRLoader.java index 8c6ddb3223..c0e895cf2d 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/loader/AtlasPBRLoader.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/loader/AtlasPBRLoader.java @@ -1,19 +1,19 @@ -package net.coderbot.iris.texture.pbr.loader; +package net.irisshaders.iris.texture.pbr.loader; import com.mojang.blaze3d.platform.NativeImage; -import net.coderbot.iris.Iris; -import net.coderbot.iris.mixin.texture.AnimationMetadataSectionAccessor; -import net.coderbot.iris.mixin.texture.TextureAtlasAccessor; -import net.coderbot.iris.texture.format.TextureFormat; -import net.coderbot.iris.texture.format.TextureFormatLoader; -import net.coderbot.iris.texture.mipmap.ChannelMipmapGenerator; -import net.coderbot.iris.texture.mipmap.CustomMipmapGenerator; -import net.coderbot.iris.texture.mipmap.LinearBlendFunction; -import net.coderbot.iris.texture.pbr.PBRAtlasTexture; -import net.coderbot.iris.texture.pbr.PBRSpriteHolder; -import net.coderbot.iris.texture.pbr.PBRType; -import net.coderbot.iris.texture.pbr.SpriteContentsExtension; -import net.coderbot.iris.texture.util.ImageManipulationUtil; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.mixin.texture.AnimationMetadataSectionAccessor; +import net.irisshaders.iris.mixin.texture.TextureAtlasAccessor; +import net.irisshaders.iris.texture.format.TextureFormat; +import net.irisshaders.iris.texture.format.TextureFormatLoader; +import net.irisshaders.iris.texture.mipmap.ChannelMipmapGenerator; +import net.irisshaders.iris.texture.mipmap.CustomMipmapGenerator; +import net.irisshaders.iris.texture.mipmap.LinearBlendFunction; +import net.irisshaders.iris.texture.pbr.PBRAtlasTexture; +import net.irisshaders.iris.texture.pbr.PBRSpriteHolder; +import net.irisshaders.iris.texture.pbr.PBRType; +import net.irisshaders.iris.texture.pbr.SpriteContentsExtension; +import net.irisshaders.iris.texture.util.ImageManipulationUtil; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -31,10 +31,10 @@ public class AtlasPBRLoader implements PBRTextureLoader { public static final ChannelMipmapGenerator LINEAR_MIPMAP_GENERATOR = new ChannelMipmapGenerator( - LinearBlendFunction.INSTANCE, - LinearBlendFunction.INSTANCE, - LinearBlendFunction.INSTANCE, - LinearBlendFunction.INSTANCE + LinearBlendFunction.INSTANCE, + LinearBlendFunction.INSTANCE, + LinearBlendFunction.INSTANCE, + LinearBlendFunction.INSTANCE ); @Override @@ -85,7 +85,7 @@ protected PBRTextureAtlasSprite createPBRSprite(TextureAtlasSprite sprite, Resou ResourceLocation pbrImageLocation = getPBRImageLocation(spriteName, pbrType); Optional optionalResource = resourceManager.getResource(pbrImageLocation); - if (!optionalResource.isPresent()) { + if (optionalResource.isEmpty()) { return null; } Resource resource = optionalResource.get(); @@ -151,7 +151,7 @@ protected PBRTextureAtlasSprite createPBRSprite(TextureAtlasSprite sprite, Resou } ResourceLocation pbrSpriteName = new ResourceLocation(spriteName.getNamespace(), spriteName.getPath() + pbrType.getSuffix()); - PBRSpriteContents pbrSpriteContents = new PBRSpriteContents(pbrSpriteName, new FrameSize(frameWidth, frameHeight), nativeImage, animationMetadata, pbrType); + PBRSpriteContents pbrSpriteContents = new PBRSpriteContents(pbrSpriteName, new FrameSize(frameWidth, frameHeight), nativeImage, metadataSection, pbrType); pbrSpriteContents.increaseMipLevel(mipLevel); return new PBRTextureAtlasSprite(pbrSpriteName, pbrSpriteContents, atlasWidth, atlasHeight, sprite.getX(), sprite.getY(), sprite); } diff --git a/src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoader.java b/src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoader.java similarity index 75% rename from src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoader.java rename to src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoader.java index 366e6a3e98..1924a54b54 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoader.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoader.java @@ -1,16 +1,15 @@ -package net.coderbot.iris.texture.pbr.loader; +package net.irisshaders.iris.texture.pbr.loader; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.server.packs.resources.ResourceManager; import org.jetbrains.annotations.NotNull; -import org.lwjgl.opengl.GL11; public interface PBRTextureLoader { /** - * This method must not modify global GL state except the texture binding for {@link GL11.GL_TEXTURE_2D}. + * This method must not modify global GL state except the texture binding for {@code GL_TEXTURE_2D}. * - * @param texture The base texture. - * @param resourceManager The resource manager. + * @param texture The base texture. + * @param resourceManager The resource manager. * @param pbrTextureConsumer The consumer that accepts resulting PBR textures. */ void load(T texture, ResourceManager resourceManager, PBRTextureConsumer pbrTextureConsumer); diff --git a/src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java b/src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java similarity index 95% rename from src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java rename to src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java index 21b5ff63e0..0212ad5c4c 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/loader/PBRTextureLoaderRegistry.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.pbr.loader; +package net.irisshaders.iris.texture.pbr.loader; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.SimpleTexture; diff --git a/src/main/java/net/coderbot/iris/texture/pbr/loader/SimplePBRLoader.java b/src/main/java/net/irisshaders/iris/texture/pbr/loader/SimplePBRLoader.java similarity index 89% rename from src/main/java/net/coderbot/iris/texture/pbr/loader/SimplePBRLoader.java rename to src/main/java/net/irisshaders/iris/texture/pbr/loader/SimplePBRLoader.java index ba0ce82b13..8131af67c5 100644 --- a/src/main/java/net/coderbot/iris/texture/pbr/loader/SimplePBRLoader.java +++ b/src/main/java/net/irisshaders/iris/texture/pbr/loader/SimplePBRLoader.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.texture.pbr.loader; +package net.irisshaders.iris.texture.pbr.loader; -import net.coderbot.iris.mixin.texture.SimpleTextureAccessor; -import net.coderbot.iris.texture.pbr.PBRType; +import net.irisshaders.iris.mixin.texture.SimpleTextureAccessor; +import net.irisshaders.iris.texture.pbr.PBRType; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.SimpleTexture; import net.minecraft.resources.ResourceLocation; diff --git a/src/main/java/net/coderbot/iris/texture/util/ImageManipulationUtil.java b/src/main/java/net/irisshaders/iris/texture/util/ImageManipulationUtil.java similarity index 80% rename from src/main/java/net/coderbot/iris/texture/util/ImageManipulationUtil.java rename to src/main/java/net/irisshaders/iris/texture/util/ImageManipulationUtil.java index 03a25f3fab..286a97716d 100644 --- a/src/main/java/net/coderbot/iris/texture/util/ImageManipulationUtil.java +++ b/src/main/java/net/irisshaders/iris/texture/util/ImageManipulationUtil.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.util; +package net.irisshaders.iris.texture.util; import com.mojang.blaze3d.platform.NativeImage; import net.minecraft.util.FastColor; @@ -96,10 +96,10 @@ public static NativeImage scaleBilinear(NativeImage image, int newWidth, int new private static int blendColor(int c0, int c1, int c2, int c3, float w0, float w1, float w2, float w3) { return FastColor.ABGR32.color( - blendChannel(FastColor.ABGR32.alpha(c0), FastColor.ABGR32.alpha(c1), FastColor.ABGR32.alpha(c2), FastColor.ABGR32.alpha(c3), w0, w1, w2, w3), - blendChannel(FastColor.ABGR32.blue(c0), FastColor.ABGR32.blue(c1), FastColor.ABGR32.blue(c2), FastColor.ABGR32.blue(c3), w0, w1, w2, w3), - blendChannel(FastColor.ABGR32.green(c0), FastColor.ABGR32.green(c1), FastColor.ABGR32.green(c2), FastColor.ABGR32.green(c3), w0, w1, w2, w3), - blendChannel(FastColor.ABGR32.red(c0), FastColor.ABGR32.red(c1), FastColor.ABGR32.red(c2), FastColor.ABGR32.red(c3), w0, w1, w2, w3) + blendChannel(FastColor.ABGR32.alpha(c0), FastColor.ABGR32.alpha(c1), FastColor.ABGR32.alpha(c2), FastColor.ABGR32.alpha(c3), w0, w1, w2, w3), + blendChannel(FastColor.ABGR32.blue(c0), FastColor.ABGR32.blue(c1), FastColor.ABGR32.blue(c2), FastColor.ABGR32.blue(c3), w0, w1, w2, w3), + blendChannel(FastColor.ABGR32.green(c0), FastColor.ABGR32.green(c1), FastColor.ABGR32.green(c2), FastColor.ABGR32.green(c3), w0, w1, w2, w3), + blendChannel(FastColor.ABGR32.red(c0), FastColor.ABGR32.red(c1), FastColor.ABGR32.red(c2), FastColor.ABGR32.red(c3), w0, w1, w2, w3) ); } @@ -109,10 +109,10 @@ private static int blendChannel(int v0, int v1, int v2, int v3, float w0, float private static int blendColor(int c0, int c1, float w0, float w1) { return FastColor.ABGR32.color( - blendChannel(FastColor.ABGR32.alpha(c0), FastColor.ABGR32.alpha(c1), w0, w1), - blendChannel(FastColor.ABGR32.blue(c0), FastColor.ABGR32.blue(c1), w0, w1), - blendChannel(FastColor.ABGR32.green(c0), FastColor.ABGR32.green(c1), w0, w1), - blendChannel(FastColor.ABGR32.red(c0), FastColor.ABGR32.red(c1), w0, w1) + blendChannel(FastColor.ABGR32.alpha(c0), FastColor.ABGR32.alpha(c1), w0, w1), + blendChannel(FastColor.ABGR32.blue(c0), FastColor.ABGR32.blue(c1), w0, w1), + blendChannel(FastColor.ABGR32.green(c0), FastColor.ABGR32.green(c1), w0, w1), + blendChannel(FastColor.ABGR32.red(c0), FastColor.ABGR32.red(c1), w0, w1) ); } diff --git a/src/main/java/net/coderbot/iris/texture/util/TextureExporter.java b/src/main/java/net/irisshaders/iris/texture/util/TextureExporter.java similarity index 96% rename from src/main/java/net/coderbot/iris/texture/util/TextureExporter.java rename to src/main/java/net/irisshaders/iris/texture/util/TextureExporter.java index 2500a65318..57f515e28c 100644 --- a/src/main/java/net/coderbot/iris/texture/util/TextureExporter.java +++ b/src/main/java/net/irisshaders/iris/texture/util/TextureExporter.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.texture.util; +package net.irisshaders.iris.texture.util; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; diff --git a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java b/src/main/java/net/irisshaders/iris/texture/util/TextureManipulationUtil.java similarity index 90% rename from src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java rename to src/main/java/net/irisshaders/iris/texture/util/TextureManipulationUtil.java index 470451c9b2..50a361c34f 100644 --- a/src/main/java/net/coderbot/iris/texture/util/TextureManipulationUtil.java +++ b/src/main/java/net/irisshaders/iris/texture/util/TextureManipulationUtil.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.texture.util; +package net.irisshaders.iris.texture.util; import com.mojang.blaze3d.platform.GlStateManager; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.IrisRenderSystem; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL30; @@ -23,10 +23,10 @@ public static void fillWithColor(int textureId, int maxLevel, int rgba) { GlStateManager._glBindFramebuffer(GL30.GL_FRAMEBUFFER, colorFillFBO); GlStateManager._clearColor( - (rgba >> 24 & 0xFF) / 255.0f, - (rgba >> 16 & 0xFF) / 255.0f, - (rgba >> 8 & 0xFF) / 255.0f, - (rgba & 0xFF) / 255.0f + (rgba >> 24 & 0xFF) / 255.0f, + (rgba >> 16 & 0xFF) / 255.0f, + (rgba >> 8 & 0xFF) / 255.0f, + (rgba & 0xFF) / 255.0f ); GlStateManager._bindTexture(textureId); for (int level = 0; level <= maxLevel; ++level) { diff --git a/src/main/java/net/coderbot/iris/uniforms/BiomeParameters.java b/src/main/java/net/irisshaders/iris/uniforms/BiomeUniforms.java similarity index 62% rename from src/main/java/net/coderbot/iris/uniforms/BiomeParameters.java rename to src/main/java/net/irisshaders/iris/uniforms/BiomeUniforms.java index 4638325977..0487391525 100644 --- a/src/main/java/net/coderbot/iris/uniforms/BiomeParameters.java +++ b/src/main/java/net/irisshaders/iris/uniforms/BiomeUniforms.java @@ -1,28 +1,24 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.coderbot.iris.gl.uniform.FloatSupplier; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.parsing.BiomeCategories; -import net.coderbot.iris.parsing.ExtendedBiome; +import net.irisshaders.iris.gl.uniform.FloatSupplier; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.parsing.BiomeCategories; +import net.irisshaders.iris.parsing.ExtendedBiome; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BiomeTags; import net.minecraft.world.level.biome.Biome; -import java.util.Locale; import java.util.function.IntSupplier; import java.util.function.ToIntFunction; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; -public class BiomeParameters { +public class BiomeUniforms { private static final Object2IntMap> biomeMap = new Object2IntOpenHashMap<>(); public static Object2IntMap> getBiomeMap() { @@ -31,31 +27,30 @@ public static Object2IntMap> getBiomeMap() { public static void addBiomeUniforms(UniformHolder uniforms) { uniforms - .uniform1i(PER_TICK, "biome", playerI(player -> - biomeMap.getInt(player.level().getBiome(player.blockPosition()).unwrapKey().orElse(null)))) - .uniform1i(PER_TICK, "biome_category", playerI(player -> { - Holder holder = player.level().getBiome(player.blockPosition()); - ExtendedBiome extendedBiome = ((ExtendedBiome) (Object) holder.value()); - if (extendedBiome.getBiomeCategory() == -1) { - extendedBiome.setBiomeCategory(getBiomeCategory(holder).ordinal()); - return extendedBiome.getBiomeCategory(); - } else { - return extendedBiome.getBiomeCategory(); - } - })) - .uniform1i(PER_TICK, "biome_precipitation", playerI(player -> { - Biome.Precipitation precipitation = player.level().getBiome(player.blockPosition()).value().getPrecipitationAt(player.blockPosition()); - switch (precipitation){ - case NONE: return 0; - case RAIN: return 1; - case SNOW: return 2; - } - throw new IllegalStateException("Unknown precipitation type:" + precipitation); - })) - .uniform1f(PER_TICK, "rainfall", playerF(player -> - ((ExtendedBiome) (Object) player.level().getBiome(player.blockPosition()).value()).getDownfall())) - .uniform1f(PER_TICK, "temperature", playerF(player -> - player.level().getBiome(player.blockPosition()).value().getBaseTemperature())); + .uniform1i(PER_TICK, "biome", playerI(player -> + biomeMap.getInt(player.level().getBiome(player.blockPosition()).unwrapKey().orElse(null)))) + .uniform1i(PER_TICK, "biome_category", playerI(player -> { + Holder holder = player.level().getBiome(player.blockPosition()); + ExtendedBiome extendedBiome = ((ExtendedBiome) (Object) holder.value()); + if (extendedBiome.getBiomeCategory() == -1) { + extendedBiome.setBiomeCategory(getBiomeCategory(holder).ordinal()); + return extendedBiome.getBiomeCategory(); + } else { + return extendedBiome.getBiomeCategory(); + } + })) + .uniform1i(PER_TICK, "biome_precipitation", playerI(player -> { + Biome.Precipitation precipitation = player.level().getBiome(player.blockPosition()).value().getPrecipitationAt(player.blockPosition()); + return switch (precipitation) { + case NONE -> 0; + case RAIN -> 1; + case SNOW -> 2; + }; + })) + .uniform1f(PER_TICK, "rainfall", playerF(player -> + ((ExtendedBiome) (Object) player.level().getBiome(player.blockPosition()).value()).getDownfall())) + .uniform1f(PER_TICK, "temperature", playerF(player -> + player.level().getBiome(player.blockPosition()).value().getBaseTemperature())); } private static BiomeCategories getBiomeCategory(Holder holder) { diff --git a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/CameraUniforms.java similarity index 69% rename from src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/CameraUniforms.java index 74bc038a2a..02b3d8823e 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CameraUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/CameraUniforms.java @@ -1,12 +1,14 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.JomlConversions; -import net.coderbot.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.helpers.JomlConversions; import net.minecraft.client.Minecraft; import org.joml.Vector3d; +import org.joml.Vector3f; +import org.joml.Vector3i; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.ONCE; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * @see Uniforms: Camera @@ -25,7 +27,11 @@ public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier .uniform1f(PER_FRAME, "far", CameraUniforms::getRenderDistanceInBlocks) .uniform3d(PER_FRAME, "cameraPosition", tracker::getCurrentCameraPosition) .uniform1f(PER_FRAME, "eyeAltitude", tracker::getCurrentCameraPositionY) - .uniform3d(PER_FRAME, "previousCameraPosition", tracker::getPreviousCameraPosition); + .uniform3d(PER_FRAME, "previousCameraPosition", tracker::getPreviousCameraPosition) + .uniform3i(PER_FRAME, "cameraPositionInt", () -> getCameraPositionInt(getUnshiftedCameraPosition())) + .uniform3f(PER_FRAME, "cameraPositionFract", () -> getCameraPositionFract(getUnshiftedCameraPosition())) + .uniform3i(PER_FRAME, "previousCameraPositionInt", () -> getCameraPositionInt(tracker.getPreviousCameraPositionUnshifted())) + .uniform3f(PER_FRAME, "previousCameraPositionFract", () -> getCameraPositionFract(tracker.getPreviousCameraPositionUnshifted())); } private static int getRenderDistanceInBlocks() { @@ -37,6 +43,22 @@ public static Vector3d getUnshiftedCameraPosition() { return JomlConversions.fromVec3(client.gameRenderer.getMainCamera().getPosition()); } + public static Vector3f getCameraPositionFract(Vector3d originalPos) { + return new Vector3f( + (float) (originalPos.x - Math.floor(originalPos.x)), + (float) (originalPos.y - Math.floor(originalPos.y)), + (float) (originalPos.z - Math.floor(originalPos.z)) + ); + } + + public static Vector3i getCameraPositionInt(Vector3d originalPos) { + return new Vector3i( + (int) Math.floor(originalPos.x), + (int) Math.floor(originalPos.y), + (int) Math.floor(originalPos.z) + ); + } + static class CameraPositionTracker { /** * Value range of cameraPosition. We want this to be small enough that precision is maintained when we convert @@ -46,18 +68,30 @@ static class CameraPositionTracker { */ private static final double WALK_RANGE = 30000; private static final double TP_RANGE = 1000; - + private final Vector3d shift = new Vector3d(); private Vector3d previousCameraPosition = new Vector3d(); private Vector3d currentCameraPosition = new Vector3d(); - private final Vector3d shift = new Vector3d(); + private Vector3d previousCameraPositionUnshifted = new Vector3d(); + private Vector3d currentCameraPositionUnshifted = new Vector3d(); CameraPositionTracker(FrameUpdateNotifier notifier) { notifier.addListener(this::update); } + private static double getShift(double value, double prevValue) { + if (Math.abs(value) > WALK_RANGE || Math.abs(value - prevValue) > TP_RANGE) { + // Only shift by increments of WALK_RANGE - this is required for some packs (like SEUS PTGI) to work properly + return -(value - (value % WALK_RANGE)); + } else { + return 0.0; + } + } + private void update() { previousCameraPosition = currentCameraPosition; + previousCameraPositionUnshifted = currentCameraPositionUnshifted; currentCameraPosition = getUnshiftedCameraPosition().add(shift); + currentCameraPositionUnshifted = getUnshiftedCameraPosition(); updateShift(); } @@ -76,15 +110,6 @@ private void updateShift() { } } - private static double getShift(double value, double prevValue) { - if (Math.abs(value) > WALK_RANGE || Math.abs(value - prevValue) > TP_RANGE) { - // Only shift by increments of WALK_RANGE - this is required for some packs (like SEUS PTGI) to work properly - return -(value - (value % WALK_RANGE)); - } else { - return 0.0; - } - } - /** * Shifts all current and future positions by the given amount. This is done in such a way that the difference * between cameraPosition and previousCameraPosition remains the same, since they are completely arbitrary @@ -108,6 +133,10 @@ public Vector3d getPreviousCameraPosition() { return previousCameraPosition; } + public Vector3d getPreviousCameraPositionUnshifted() { + return previousCameraPositionUnshifted; + } + public double getCurrentCameraPositionY() { return currentCameraPosition.y; } diff --git a/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java b/src/main/java/net/irisshaders/iris/uniforms/CapturedRenderingState.java similarity index 93% rename from src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java rename to src/main/java/net/irisshaders/iris/uniforms/CapturedRenderingState.java index 06070953b5..38c27e7ac2 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CapturedRenderingState.java +++ b/src/main/java/net/irisshaders/iris/uniforms/CapturedRenderingState.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import net.minecraft.client.Minecraft; import org.joml.Matrix4f; @@ -63,22 +63,22 @@ public void setFogDensity(float fogDensity) { this.fogDensity = fogDensity; } - public void setTickDelta(float tickDelta) { - this.tickDelta = tickDelta; - } - - public void setRealTickDelta(float tickDelta) { - this.realTickDelta = tickDelta; - } - public float getTickDelta() { return tickDelta; } + public void setTickDelta(float tickDelta) { + this.tickDelta = tickDelta; + } + public float getRealTickDelta() { return realTickDelta; } + public void setRealTickDelta(float tickDelta) { + this.realTickDelta = tickDelta; + } + public void setCurrentBlockEntity(int entity) { this.currentRenderedBlockEntity = entity; } @@ -95,17 +95,17 @@ public int getCurrentRenderedEntity() { return currentRenderedEntity; } - public void setCurrentRenderedItem(int item) { - this.currentRenderedItem = item; - } - public int getCurrentRenderedItem() { return currentRenderedItem; } - public float getCurrentAlphaTest() { + public void setCurrentRenderedItem(int item) { + this.currentRenderedItem = item; + } + + public float getCurrentAlphaTest() { return currentAlphaTest; - } + } public void setCurrentAlphaTest(float alphaTest) { this.currentAlphaTest = alphaTest; @@ -115,13 +115,13 @@ public float getDarknessLightFactor() { return darknessLightFactor; } - public void setDarknessLightFactor(float factor) { + public void setDarknessLightFactor(float factor) { darknessLightFactor = factor; } - public float getCloudTime() { + public float getCloudTime() { return this.cloudTime; - } + } public void setCloudTime(float cloudTime) { this.cloudTime = cloudTime; diff --git a/src/main/java/net/coderbot/iris/uniforms/CelestialUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/CelestialUniforms.java similarity index 95% rename from src/main/java/net/coderbot/iris/uniforms/CelestialUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/CelestialUniforms.java index 5d47df2e09..da1eb7e9de 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CelestialUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/CelestialUniforms.java @@ -1,16 +1,15 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import com.mojang.math.Axis; -import org.joml.Matrix4f; -import net.coderbot.iris.JomlConversions; -import net.coderbot.iris.gl.uniform.UniformHolder; -import org.joml.Vector4f; +import net.irisshaders.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; +import org.joml.Matrix4f; +import org.joml.Vector4f; import java.util.Objects; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * @see Uniforms: Celestial bodies @@ -22,18 +21,6 @@ public CelestialUniforms(float sunPathRotation) { this.sunPathRotation = sunPathRotation; } - public void addCelestialUniforms(UniformHolder uniforms) { - uniforms - .uniform1f(PER_FRAME, "sunAngle", CelestialUniforms::getSunAngle) - .uniformTruncated3f(PER_FRAME, "sunPosition", this::getSunPosition) - .uniformTruncated3f(PER_FRAME, "moonPosition", this::getMoonPosition) - .uniform1f(PER_FRAME, "shadowAngle", CelestialUniforms::getShadowAngle) - .uniformTruncated3f(PER_FRAME, "shadowLightPosition", this::getShadowLightPosition) - .uniformTruncated3f(PER_FRAME, "upPosition", CelestialUniforms::getUpPosition); - - - } - public static float getSunAngle() { float skyAngle = getSkyAngle(); @@ -54,6 +41,47 @@ private static float getShadowAngle() { return shadowAngle; } + private static Vector4f getUpPosition() { + Vector4f upVector = new Vector4f(0.0F, 100.0F, 0.0F, 0.0F); + + // Get the current GBuffer model view matrix, since that is the basis of the celestial model view matrix + Matrix4f preCelestial = new Matrix4f(CapturedRenderingState.INSTANCE.getGbufferModelView()); + + // Apply the fixed -90.0F degrees rotation to mirror the same transformation in renderSky. + // But, notably, skip the rotation by the skyAngle. + preCelestial.rotate(Axis.YP.rotationDegrees(-90.0F)); + + // Use this matrix to transform the vector. + upVector = preCelestial.transform(upVector); + + return upVector; + } + + public static boolean isDay() { + // Determine whether it is day or night based on the sky angle. + // + // World#isDay appears to do some nontrivial calculations that appear to not entirely work for us here. + return getSunAngle() <= 0.5; + } + + private static ClientLevel getWorld() { + return Objects.requireNonNull(Minecraft.getInstance().level); + } + + private static float getSkyAngle() { + return getWorld().getTimeOfDay(CapturedRenderingState.INSTANCE.getTickDelta()); + } + + public void addCelestialUniforms(UniformHolder uniforms) { + uniforms + .uniform1f(PER_FRAME, "sunAngle", CelestialUniforms::getSunAngle) + .uniformTruncated3f(PER_FRAME, "sunPosition", this::getSunPosition) + .uniformTruncated3f(PER_FRAME, "moonPosition", this::getMoonPosition) + .uniform1f(PER_FRAME, "shadowAngle", CelestialUniforms::getShadowAngle) + .uniformTruncated3f(PER_FRAME, "shadowLightPosition", this::getShadowLightPosition) + .uniformTruncated3f(PER_FRAME, "upPosition", CelestialUniforms::getUpPosition); + } + private Vector4f getSunPosition() { return getCelestialPosition(100.0F); } @@ -103,35 +131,4 @@ private Vector4f getCelestialPosition(float y) { return position; } - - private static Vector4f getUpPosition() { - Vector4f upVector = new Vector4f(0.0F, 100.0F, 0.0F, 0.0F); - - // Get the current GBuffer model view matrix, since that is the basis of the celestial model view matrix - Matrix4f preCelestial = new Matrix4f(CapturedRenderingState.INSTANCE.getGbufferModelView()); - - // Apply the fixed -90.0F degrees rotation to mirror the same transformation in renderSky. - // But, notably, skip the rotation by the skyAngle. - preCelestial.rotate(Axis.YP.rotationDegrees(-90.0F)); - - // Use this matrix to transform the vector. - upVector = preCelestial.transform(upVector); - - return upVector; - } - - public static boolean isDay() { - // Determine whether it is day or night based on the sky angle. - // - // World#isDay appears to do some nontrivial calculations that appear to not entirely work for us here. - return getSunAngle() <= 0.5; - } - - private static ClientLevel getWorld() { - return Objects.requireNonNull(Minecraft.getInstance().level); - } - - private static float getSkyAngle() { - return getWorld().getTimeOfDay(CapturedRenderingState.INSTANCE.getTickDelta()); - } } diff --git a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/CommonUniforms.java similarity index 85% rename from src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/CommonUniforms.java index 0effb59387..ac48c56151 100644 --- a/src/main/java/net/coderbot/iris/uniforms/CommonUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/CommonUniforms.java @@ -1,23 +1,24 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.JomlConversions; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.gl.uniform.DynamicUniformHolder; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.layer.GbufferPrograms; -import net.coderbot.iris.mixin.GlStateManagerAccessor; -import net.coderbot.iris.mixin.statelisteners.BooleanStateAccessor; -import net.coderbot.iris.mixin.texture.TextureAtlasAccessor; -import net.coderbot.iris.pipeline.newshader.FogMode; -import net.coderbot.iris.shaderpack.IdMap; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.texture.TextureInfoCache; -import net.coderbot.iris.texture.TextureInfoCache.TextureInfo; -import net.coderbot.iris.texture.TextureTracker; -import net.coderbot.iris.uniforms.transforms.SmoothedFloat; -import net.coderbot.iris.uniforms.transforms.SmoothedVec2f; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.uniform.DynamicUniformHolder; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.helpers.JomlConversions; +import net.irisshaders.iris.layer.GbufferPrograms; +import net.irisshaders.iris.mixin.GlStateManagerAccessor; +import net.irisshaders.iris.mixin.statelisteners.BooleanStateAccessor; +import net.irisshaders.iris.mixin.texture.TextureAtlasAccessor; +import net.irisshaders.iris.shaderpack.IdMap; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.texture.TextureInfoCache; +import net.irisshaders.iris.texture.TextureInfoCache.TextureInfo; +import net.irisshaders.iris.texture.TextureTracker; +import net.irisshaders.iris.uniforms.transforms.SmoothedFloat; +import net.irisshaders.iris.uniforms.transforms.SmoothedVec2f; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.GameRenderer; @@ -27,6 +28,7 @@ import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.material.FogType; @@ -38,9 +40,9 @@ import org.joml.Vector4f; import org.joml.Vector4i; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.ONCE; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; public final class CommonUniforms { private static final Minecraft client = Minecraft.getInstance(); @@ -48,6 +50,10 @@ public final class CommonUniforms { private static final Vector4i ZERO_VECTOR_4i = new Vector4i(0, 0, 0, 0); private static final Vector3d ZERO_VECTOR_3d = new Vector3d(); + static { + GbufferPrograms.init(); + } + private CommonUniforms() { // no construction allowed } @@ -77,7 +83,8 @@ public static void addDynamicUniforms(DynamicUniformHolder uniforms, FogMode fog } return ZERO_VECTOR_2i; - }, listener -> {}); + }, listener -> { + }); uniforms.uniform2i("gtextureSize", () -> { int glId = GlStateManagerAccessor.getTEXTURES()[0].binding; @@ -110,7 +117,7 @@ public static void addNonDynamicUniforms(UniformHolder uniforms, IdMap idMap, Pa ViewportUniforms.addViewportUniforms(uniforms); WorldTimeUniforms.addWorldTimeUniforms(uniforms); SystemTimeUniforms.addSystemTimeUniforms(uniforms); - BiomeParameters.addBiomeUniforms(uniforms); + BiomeUniforms.addBiomeUniforms(uniforms); new CelestialUniforms(directives.getSunPathRotation()).addCelestialUniforms(uniforms); IrisExclusiveUniforms.addIrisExclusiveUniforms(uniforms); IrisTimeUniforms.addTimeUniforms(uniforms); @@ -126,6 +133,7 @@ public static void generalCommonUniforms(UniformHolder uniforms, FrameUpdateNoti uniforms .uniform1b(PER_FRAME, "hideGUI", () -> client.options.hideGui) + .uniform1b(PER_FRAME, "isRightHanded", () -> client.options.mainHand().get() == HumanoidArm.RIGHT) .uniform1i(PER_FRAME, "isEyeInWater", CommonUniforms::isEyeInWater) .uniform1f(PER_FRAME, "blindness", CommonUniforms::getBlindness) .uniform1f(PER_FRAME, "darknessFactor", CommonUniforms::getDarknessFactor) @@ -150,11 +158,14 @@ public static void generalCommonUniforms(UniformHolder uniforms, FrameUpdateNoti .uniform2i(PER_FRAME, "eyeBrightness", CommonUniforms::getEyeBrightness) .uniform2i(PER_FRAME, "eyeBrightnessSmooth", () -> { Vector2f smoothed = eyeBrightnessSmooth.get(); - return new Vector2i((int) smoothed.x(),(int) smoothed.y()); + return new Vector2i((int) smoothed.x(), (int) smoothed.y()); }) .uniform1f(PER_TICK, "rainStrength", CommonUniforms::getRainStrength) .uniform1f(PER_TICK, "wetness", new SmoothedFloat(directives.getWetnessHalfLife(), directives.getDrynessHalfLife(), CommonUniforms::getRainStrength, updateNotifier)) - .uniform3d(PER_FRAME, "skyColor", CommonUniforms::getSkyColor); + .uniform3d(PER_FRAME, "skyColor", CommonUniforms::getSkyColor) + .uniform1f(PER_FRAME, "dhFarPlane", DHCompat::getFarPlane) + .uniform1f(PER_FRAME, "dhNearPlane", DHCompat::getNearPlane) + .uniform1i(PER_FRAME, "dhRenderDistance", DHCompat::getRenderDistance); } private static boolean isOnGround() { @@ -207,7 +218,7 @@ private static Vector3d getSkyColor() { } return JomlConversions.fromVec3(client.level.getSkyColor(client.cameraEntity.position(), - CapturedRenderingState.INSTANCE.getTickDelta())); + CapturedRenderingState.INSTANCE.getTickDelta())); } static float getBlindness() { @@ -219,7 +230,11 @@ static float getBlindness() { if (blindness != null) { // Guessing that this is what OF uses, based on how vanilla calculates the fog value in FogRenderer // TODO: Add this to ShaderDoc - return Math.clamp(0.0F, 1.0F, blindness.getDuration() / 20.0F); + if (blindness.isInfiniteDuration()) { + return 1.0f; + } else { + return Math.clamp(0.0F, 1.0F, blindness.getDuration() / 20.0F); + } } } @@ -277,8 +292,7 @@ private static Vector2i getEyeBrightness() { private static float getNightVision() { Entity cameraEntity = client.getCameraEntity(); - if (cameraEntity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) cameraEntity; + if (cameraEntity instanceof LivingEntity livingEntity) { try { // See MixinGameRenderer#iris$safecheckNightvisionStrength. @@ -289,7 +303,7 @@ private static float getNightVision() { // // See: https://github.com/apace100/apoli/blob/320b0ef547fbbf703de7154f60909d30366f6500/src/main/java/io/github/apace100/apoli/mixin/GameRendererMixin.java#L153 float nightVisionStrength = - GameRenderer.getNightVisionScale(livingEntity, CapturedRenderingState.INSTANCE.getTickDelta()); + GameRenderer.getNightVisionScale(livingEntity, CapturedRenderingState.INSTANCE.getTickDelta()); if (nightVisionStrength > 0) { // Just protecting against potential weird mod behavior @@ -337,8 +351,4 @@ static int isEyeInWater() { return 0; } } - - static { - GbufferPrograms.init(); - } } diff --git a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/ExternallyManagedUniforms.java similarity index 95% rename from src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/ExternallyManagedUniforms.java index 525514984a..9a2becc4db 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ExternallyManagedUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/ExternallyManagedUniforms.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformType; public class ExternallyManagedUniforms { private ExternallyManagedUniforms() { diff --git a/src/main/java/net/coderbot/iris/uniforms/FogUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/FogUniforms.java similarity index 76% rename from src/main/java/net/coderbot/iris/uniforms/FogUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/FogUniforms.java index da0754dc57..2ec2522da1 100644 --- a/src/main/java/net/coderbot/iris/uniforms/FogUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/FogUniforms.java @@ -1,15 +1,15 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import com.mojang.blaze3d.shaders.FogShape; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.state.StateUpdateNotifiers; -import net.coderbot.iris.gl.uniform.DynamicUniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.pipeline.newshader.FogMode; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.state.StateUpdateNotifiers; +import net.irisshaders.iris.gl.uniform.DynamicUniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.joml.Vector3f; import org.lwjgl.opengl.GL11; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public class FogUniforms { private FogUniforms() { @@ -42,13 +42,9 @@ public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode }, notifier -> { }); - uniforms.uniform1f("fogStart", RenderSystem::getShaderFogStart, listener -> { - StateUpdateNotifiers.fogStartNotifier.setListener(listener); - }); + uniforms.uniform1f("fogStart", RenderSystem::getShaderFogStart, listener -> StateUpdateNotifiers.fogStartNotifier.setListener(listener)); - uniforms.uniform1f("fogEnd", RenderSystem::getShaderFogEnd, listener -> { - StateUpdateNotifiers.fogEndNotifier.setListener(listener); - }); + uniforms.uniform1f("fogEnd", RenderSystem::getShaderFogEnd, listener -> StateUpdateNotifiers.fogEndNotifier.setListener(listener)); uniforms // TODO: Update frequency of continuous? diff --git a/src/main/java/net/coderbot/iris/uniforms/FrameUpdateNotifier.java b/src/main/java/net/irisshaders/iris/uniforms/FrameUpdateNotifier.java similarity index 89% rename from src/main/java/net/coderbot/iris/uniforms/FrameUpdateNotifier.java rename to src/main/java/net/irisshaders/iris/uniforms/FrameUpdateNotifier.java index b7745ffce6..acfeae527c 100644 --- a/src/main/java/net/coderbot/iris/uniforms/FrameUpdateNotifier.java +++ b/src/main/java/net/irisshaders/iris/uniforms/FrameUpdateNotifier.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/net/coderbot/iris/uniforms/HardcodedCustomUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/HardcodedCustomUniforms.java similarity index 94% rename from src/main/java/net/coderbot/iris/uniforms/HardcodedCustomUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/HardcodedCustomUniforms.java index a319197bf9..c331d38e81 100644 --- a/src/main/java/net/coderbot/iris/uniforms/HardcodedCustomUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/HardcodedCustomUniforms.java @@ -1,10 +1,8 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.mixin.DimensionTypeAccessor; -import net.coderbot.iris.uniforms.transforms.SmoothedFloat; -import org.joml.Math; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.uniforms.transforms.SmoothedFloat; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; @@ -14,6 +12,7 @@ import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.phys.Vec3; +import org.joml.Math; // These expressions are copied directly from BSL and Complementary. @@ -137,7 +136,7 @@ private static float getVelocity(CameraUniforms.CameraPositionTracker tracker) { float difX = (float) (tracker.getCurrentCameraPosition().x - tracker.getPreviousCameraPosition().x); float difY = (float) (tracker.getCurrentCameraPosition().y - tracker.getPreviousCameraPosition().y); float difZ = (float) (tracker.getCurrentCameraPosition().z - tracker.getPreviousCameraPosition().z); - return Math.sqrt(difX*difX + difY*difY + difZ*difZ); + return Math.sqrt(difX * difX + difY * difY + difZ * difZ); } private static SmoothedFloat getStarter(CameraUniforms.CameraPositionTracker tracker, FrameUpdateNotifier notifier) { @@ -158,18 +157,18 @@ private static float getTimeAngle() { private static int getWorldDayTime() { Level level = Minecraft.getInstance().level; - long timeOfDay = level.getDayTime(); + long timeOfDay = level.getDayTime(); long dayTime = level.dimensionType().fixedTime().orElse(timeOfDay % 24000L); return (int) dayTime; } private static float getTimeBrightness() { - return (float) java.lang.Math.max(java.lang.Math.sin(getTimeAngle() * java.lang.Math.PI * 2.0),0.0); + return (float) java.lang.Math.max(java.lang.Math.sin(getTimeAngle() * java.lang.Math.PI * 2.0), 0.0); } private static float getMoonBrightness() { - return (float) java.lang.Math.max(java.lang.Math.sin(getTimeAngle() * java.lang.Math.PI * (-2.0)),0.0); + return (float) java.lang.Math.max(java.lang.Math.sin(getTimeAngle() * java.lang.Math.PI * (-2.0)), 0.0); } private static float getShadowFade() { @@ -185,14 +184,11 @@ private static float getRawPrecipitation() { return 0; } Biome.Precipitation precipitation = storedBiome.value().getPrecipitationAt(Minecraft.getInstance().cameraEntity.blockPosition()); - switch (precipitation) { - case RAIN: - return 1; - case SNOW: - return 2; - default: - return 0; - } + return switch (precipitation) { + case RAIN -> 1; + case SNOW -> 2; + default -> 0; + }; } private static float getBlindFactor() { diff --git a/src/main/java/net/coderbot/iris/uniforms/IdMapUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/IdMapUniforms.java similarity index 89% rename from src/main/java/net/coderbot/iris/uniforms/IdMapUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/IdMapUniforms.java index 673641884b..606ac2bfbe 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IdMapUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/IdMapUniforms.java @@ -1,28 +1,22 @@ -package net.coderbot.iris.uniforms; - -import net.coderbot.iris.gl.uniform.UniformHolder; -import java.util.function.IntSupplier; +package net.irisshaders.iris.uniforms; import it.unimi.dsi.fastutil.objects.Object2IntFunction; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.shaderpack.IdMap; -import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.api.v0.item.IrisItemLightProvider; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.shaderpack.IdMap; +import net.irisshaders.iris.shaderpack.materialmap.NamespacedId; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import org.joml.Vector3f; import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; -import java.util.Map; -import java.util.function.IntSupplier; - -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public final class IdMapUniforms { @@ -118,7 +112,7 @@ private IrisItemLightProvider applyOldHandLighting(@NotNull LocalPlayer player, } IrisItemLightProvider lightProvider = (IrisItemLightProvider) offHandItem; - int newEmission = lightProvider.getLightEmission(Minecraft.getInstance().player, offHandStack); + int newEmission = lightProvider.getLightEmission(Minecraft.getInstance().player, offHandStack); if (lightValue < newEmission) { lightValue = newEmission; diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/IrisExclusiveUniforms.java similarity index 87% rename from src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/IrisExclusiveUniforms.java index bf0a0c3f67..ffa204339d 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisExclusiveUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/IrisExclusiveUniforms.java @@ -1,27 +1,25 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.JomlConversions; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.coderbot.iris.mixin.DimensionTypeAccessor; -import org.joml.Math; -import org.joml.Vector3d; -import org.joml.Vector3f; -import org.joml.Vector4f; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.helpers.JomlConversions; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.LightningBolt; -import net.minecraft.world.entity.player.Player; +import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.GameType; import net.minecraft.world.phys.Vec3; +import org.joml.Math; +import org.joml.Vector3d; +import org.joml.Vector4f; import java.util.Objects; import java.util.stream.StreamSupport; public class IrisExclusiveUniforms { + private static final Vector3d ZERO = new Vector3d(0); + public static void addIrisExclusiveUniforms(UniformHolder uniforms) { WorldInfoUniforms.addWorldInfoUniforms(uniforms); @@ -41,15 +39,15 @@ public static void addIrisExclusiveUniforms(UniformHolder uniforms) { uniforms.uniform1b(UniformUpdateFrequency.PER_TICK, "isSpectator", IrisExclusiveUniforms::isSpectator); uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "eyePosition", IrisExclusiveUniforms::getEyePosition); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "cloudTime", CapturedRenderingState.INSTANCE::getCloudTime); - uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "relativeEyePosition", () -> { - return CameraUniforms.getUnshiftedCameraPosition().sub(getEyePosition()); - }); + uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "relativeEyePosition", () -> CameraUniforms.getUnshiftedCameraPosition().sub(getEyePosition())); uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "playerLookVector", () -> { - return JomlConversions.fromVec3(Minecraft.getInstance().getCameraEntity().getLookAngle()); - }); - uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "playerBodyVector", () -> { - return JomlConversions.fromVec3(Minecraft.getInstance().getCameraEntity().getForward()); + if (Minecraft.getInstance().cameraEntity instanceof LivingEntity livingEntity) { + return JomlConversions.fromVec3(livingEntity.getViewVector(CapturedRenderingState.INSTANCE.getTickDelta())); + } else { + return ZERO; + } }); + uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "playerBodyVector", () -> JomlConversions.fromVec3(Minecraft.getInstance().getCameraEntity().getForward())); Vector4f zero = new Vector4f(0, 0, 0, 0); uniforms.uniform4f(UniformUpdateFrequency.PER_TICK, "lightningBoltPosition", () -> { if (Minecraft.getInstance().level != null) { @@ -99,7 +97,7 @@ private static float getCurrentArmor() { return -1; } - return (float) (Minecraft.getInstance().player.getArmorValue() / 50.0f); + return Minecraft.getInstance().player.getArmorValue() / 50.0f; } private static float getMaxAir() { @@ -119,15 +117,12 @@ private static float getMaxHealth() { } - private static boolean isFirstPersonCamera() { // If camera type is not explicitly third-person, assume it's first-person. - switch (Minecraft.getInstance().options.getCameraType()) { - case THIRD_PERSON_BACK: - case THIRD_PERSON_FRONT: - return false; - default: return true; - } + return switch (Minecraft.getInstance().options.getCameraType()) { + case THIRD_PERSON_BACK, THIRD_PERSON_FRONT -> false; + default -> true; + }; } private static boolean isSpectator() { diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/IrisInternalUniforms.java similarity index 50% rename from src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/IrisInternalUniforms.java index b4d07b03c9..4d008eead5 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisInternalUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/IrisInternalUniforms.java @@ -1,15 +1,11 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.uniform.DynamicLocationalUniformHolder; -import net.coderbot.iris.gl.uniform.DynamicUniformHolder; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.pipeline.newshader.FogMode; +import net.irisshaders.iris.gl.state.FogMode; +import net.irisshaders.iris.gl.uniform.DynamicUniformHolder; import org.joml.Vector4f; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * Internal Iris uniforms that are not directly accessible by shaders. @@ -21,11 +17,10 @@ private IrisInternalUniforms() { public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode) { uniforms - // TODO: Update frequency of continuous? - .uniform4f(PER_FRAME, "iris_FogColor", () -> { - float[] fogColor = RenderSystem.getShaderFogColor(); - return new Vector4f(fogColor[0], fogColor[1], fogColor[2], fogColor[3]); - }); + .uniform4f(PER_FRAME, "iris_FogColor", () -> { + float[] fogColor = RenderSystem.getShaderFogColor(); + return new Vector4f(fogColor[0], fogColor[1], fogColor[2], fogColor[3]); + }); uniforms.uniform1f(PER_FRAME, "iris_FogStart", RenderSystem::getShaderFogStart) .uniform1f(PER_FRAME, "iris_FogEnd", RenderSystem::getShaderFogEnd); @@ -33,11 +28,14 @@ public static void addFogUniforms(DynamicUniformHolder uniforms, FogMode fogMode uniforms.uniform1f("iris_FogDensity", () -> { // ensure that the minimum value is 0.0 return Math.max(0.0F, CapturedRenderingState.INSTANCE.getFogDensity()); - }, notifier -> {}); + }, notifier -> { + }); - uniforms.uniform1f("iris_currentAlphaTest", CapturedRenderingState.INSTANCE::getCurrentAlphaTest, notifier -> {}); + uniforms.uniform1f("iris_currentAlphaTest", CapturedRenderingState.INSTANCE::getCurrentAlphaTest, notifier -> { + }); // Optifine compatibility - uniforms.uniform1f("alphaTestRef", CapturedRenderingState.INSTANCE::getCurrentAlphaTest, notifier -> {}); + uniforms.uniform1f("alphaTestRef", CapturedRenderingState.INSTANCE::getCurrentAlphaTest, notifier -> { + }); } } diff --git a/src/main/java/net/coderbot/iris/uniforms/IrisTimeUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/IrisTimeUniforms.java similarity index 79% rename from src/main/java/net/coderbot/iris/uniforms/IrisTimeUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/IrisTimeUniforms.java index f86422697d..40e3861198 100644 --- a/src/main/java/net/coderbot/iris/uniforms/IrisTimeUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/IrisTimeUniforms.java @@ -1,19 +1,18 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.joml.Vector2i; import org.joml.Vector3i; import java.time.LocalDateTime; -import java.time.temporal.ChronoField; -import java.time.temporal.TemporalField; -import java.util.GregorianCalendar; public class IrisTimeUniforms { private static LocalDateTime dateTime; + static { + } + public static void updateTime() { dateTime = LocalDateTime.now(); } @@ -29,7 +28,4 @@ public static void addTimeUniforms(UniformHolder uniforms) { (dateTime.toLocalDate().lengthOfYear() * 86400) - (((dateTime.getDayOfYear() - 1) * 86400) + (dateTime.getHour() * 3600) + (dateTime.getMinute() * 60) + dateTime.getSecond()) )); } - - static { - } } diff --git a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/MatrixUniforms.java similarity index 56% rename from src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/MatrixUniforms.java index a0c4713fb6..16c826dd2c 100644 --- a/src/main/java/net/coderbot/iris/uniforms/MatrixUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/MatrixUniforms.java @@ -1,15 +1,15 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; +import net.irisshaders.iris.compat.dh.DHCompat; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.shaderpack.properties.PackDirectives; +import net.irisshaders.iris.shadows.ShadowMatrices; +import net.irisshaders.iris.shadows.ShadowRenderer; import org.joml.Matrix4f; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.pipeline.ShadowRenderer; -import net.coderbot.iris.shaderpack.PackDirectives; -import net.coderbot.iris.shadows.ShadowMatrices; -import java.nio.FloatBuffer; import java.util.function.Supplier; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public final class MatrixUniforms { private MatrixUniforms() { @@ -17,12 +17,13 @@ private MatrixUniforms() { public static void addMatrixUniforms(UniformHolder uniforms, PackDirectives directives) { addMatrix(uniforms, "ModelView", CapturedRenderingState.INSTANCE::getGbufferModelView); - // TODO: In some cases, gbufferProjectionInverse takes on a value much different than OptiFine... - // We need to audit Mojang's linear algebra. addMatrix(uniforms, "Projection", CapturedRenderingState.INSTANCE::getGbufferProjection); + addDHMatrix(uniforms, "Projection", DHCompat::getProjection); addShadowMatrix(uniforms, "ModelView", () -> - new Matrix4f(ShadowRenderer.createShadowModelView(directives.getSunPathRotation(), directives.getShadowDirectives().getIntervalSize()).last().pose())); - addShadowMatrix(uniforms, "Projection", () -> ShadowMatrices.createOrthoMatrix(directives.getShadowDirectives().getDistance())); + new Matrix4f(ShadowRenderer.createShadowModelView(directives.getSunPathRotation(), directives.getShadowDirectives().getIntervalSize()).last().pose())); + addShadowMatrix(uniforms, "Projection", () -> ShadowMatrices.createOrthoMatrix(directives.getShadowDirectives().getDistance(), + directives.getShadowDirectives().getNearPlane() < 0 ? -DHCompat.getRenderDistance() : directives.getShadowDirectives().getNearPlane(), + directives.getShadowDirectives().getFarPlane() < 0 ? DHCompat.getRenderDistance() : directives.getShadowDirectives().getFarPlane())); } private static void addMatrix(UniformHolder uniforms, String name, Supplier supplier) { @@ -32,10 +33,17 @@ private static void addMatrix(UniformHolder uniforms, String name, Supplier supplier) { + uniforms + .uniformMatrix(PER_FRAME, "dh" + name, supplier) + .uniformMatrix(PER_FRAME, "dh" + name + "Inverse", new Inverted(supplier)) + .uniformMatrix(PER_FRAME, "dhPrevious" + name, new Previous(supplier)); + } + private static void addShadowMatrix(UniformHolder uniforms, String name, Supplier supplier) { uniforms - .uniformMatrix(PER_FRAME, "shadow" + name, supplier) - .uniformMatrix(PER_FRAME, "shadow" + name + "Inverse", new Inverted(supplier)); + .uniformMatrix(PER_FRAME, "shadow" + name, supplier) + .uniformMatrix(PER_FRAME, "shadow" + name + "Inverse", new Inverted(supplier)); } private static class Inverted implements Supplier { diff --git a/src/main/java/net/coderbot/iris/uniforms/SystemTimeUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/SystemTimeUniforms.java similarity index 86% rename from src/main/java/net/coderbot/iris/uniforms/SystemTimeUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/SystemTimeUniforms.java index b67c8452c1..39e88828e9 100644 --- a/src/main/java/net/coderbot/iris/uniforms/SystemTimeUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/SystemTimeUniforms.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import java.util.OptionalLong; import java.util.function.IntSupplier; @@ -26,16 +26,10 @@ private SystemTimeUniforms() { public static void addSystemTimeUniforms(UniformHolder uniforms) { uniforms .uniform1i(UniformUpdateFrequency.PER_FRAME, "frameCounter", COUNTER) - // TODO: Don't hardcode framemod8 here for Sildur's Vibrant Shaders - // .uniform1i(UniformUpdateFrequency.PER_FRAME, "framemod8", () -> COUNTER.getAsInt() % 8) .uniform1f(UniformUpdateFrequency.PER_FRAME, "frameTime", TIMER::getLastFrameTime) .uniform1f(UniformUpdateFrequency.PER_FRAME, "frameTimeCounter", TIMER::getFrameTimeCounter); } - public static void addFloatFrameMod8Uniform(UniformHolder uniforms) { - uniforms.uniform1f(UniformUpdateFrequency.PER_FRAME, "framemod8", () -> COUNTER.getAsInt() % 8); - } - /** * A simple frame counter. On each frame, it is incremented by 1, and it wraps around every 720720 frames. It starts * at zero and goes from there. diff --git a/src/main/java/net/coderbot/iris/uniforms/VanillaUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/VanillaUniforms.java similarity index 63% rename from src/main/java/net/coderbot/iris/uniforms/VanillaUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/VanillaUniforms.java index 745722867f..c03a7777ec 100644 --- a/src/main/java/net/coderbot/iris/uniforms/VanillaUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/VanillaUniforms.java @@ -1,19 +1,17 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; -import net.coderbot.iris.gl.uniform.DynamicUniformHolder; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.pipeline.newshader.ExtendedShader; +import net.irisshaders.iris.gl.uniform.DynamicUniformHolder; import org.joml.Vector2f; -import org.joml.Vector2i; public class VanillaUniforms { public static void addVanillaUniforms(DynamicUniformHolder uniforms) { Vector2f cachedScreenSize = new Vector2f(); // listener -> {} dictates we want this to run on every shader update, not just on a new frame. These are dynamic. - uniforms.uniform1f("iris_LineWidth", RenderSystem::getShaderLineWidth, listener -> {}); - uniforms.uniform2f("iris_ScreenSize", () -> cachedScreenSize.set(GlStateManager.Viewport.width(), GlStateManager.Viewport.height()), listener -> {}); + uniforms.uniform1f("iris_LineWidth", RenderSystem::getShaderLineWidth, listener -> { + }); + uniforms.uniform2f("iris_ScreenSize", () -> cachedScreenSize.set(GlStateManager.Viewport.width(), GlStateManager.Viewport.height()), listener -> { + }); } } diff --git a/src/main/java/net/coderbot/iris/uniforms/ViewportUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/ViewportUniforms.java similarity index 88% rename from src/main/java/net/coderbot/iris/uniforms/ViewportUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/ViewportUniforms.java index d1296c706f..4fe6f98ad0 100644 --- a/src/main/java/net/coderbot/iris/uniforms/ViewportUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/ViewportUniforms.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * Implements uniforms relating the current viewport diff --git a/src/main/java/net/coderbot/iris/uniforms/WorldTimeUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/WorldTimeUniforms.java similarity index 80% rename from src/main/java/net/coderbot/iris/uniforms/WorldTimeUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/WorldTimeUniforms.java index 510188c58b..af53a9e272 100644 --- a/src/main/java/net/coderbot/iris/uniforms/WorldTimeUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/WorldTimeUniforms.java @@ -1,15 +1,14 @@ -package net.coderbot.iris.uniforms; +package net.irisshaders.iris.uniforms; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.mixin.DimensionTypeAccessor; -import net.coderbot.iris.shaderpack.DimensionId; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.shaderpack.DimensionId; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import java.util.Objects; -import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; +import static net.irisshaders.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; public final class WorldTimeUniforms { private WorldTimeUniforms() { @@ -37,7 +36,7 @@ static int getWorldDayTime() { } long dayTime = getWorld().dimensionType().fixedTime() - .orElse(timeOfDay % 24000L); + .orElse(timeOfDay % 24000L); return (int) dayTime; } diff --git a/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/builtin/BuiltinReplacementUniforms.java similarity index 57% rename from src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/builtin/BuiltinReplacementUniforms.java index 76e1a19693..1bca1a7b14 100644 --- a/src/main/java/net/coderbot/iris/uniforms/builtin/BuiltinReplacementUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/builtin/BuiltinReplacementUniforms.java @@ -1,9 +1,8 @@ -package net.coderbot.iris.uniforms.builtin; +package net.irisshaders.iris.uniforms.builtin; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.joml.Matrix4f; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; public class BuiltinReplacementUniforms { private static final Matrix4f lightmapTextureMatrix; @@ -15,8 +14,8 @@ public class BuiltinReplacementUniforms { public static void addBuiltinReplacementUniforms(UniformHolder uniforms) { uniforms.uniformMatrix(UniformUpdateFrequency.ONCE, "iris_LightmapTextureMatrix", () -> { - //Iris.logger.warn("A shader appears to require the lightmap texture matrix even after transformations have occurred"); - //Iris.logger.warn("Iris handles this correctly but it indicates that the shader is doing weird things with lightmap coordinates"); + //Iris.logger.warn("A shader appears to require the lightmap texture matrix even after transformations have occurred"); + //Iris.logger.warn("Iris handles this correctly but it indicates that the shader is doing weird things with lightmap coordinates"); return lightmapTextureMatrix; }); diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java b/src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java similarity index 79% rename from src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java index 185ae4f6be..eb960b19cc 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniformFixedInputUniformsHolder.java @@ -1,20 +1,31 @@ -package net.coderbot.iris.uniforms.custom; +package net.irisshaders.iris.uniforms.custom; import com.google.common.collect.ImmutableMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import kroppeb.stareval.function.Type; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.FloatSupplier; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.gl.uniform.UniformType; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.uniforms.custom.cached.*; -import org.joml.*; -import net.minecraft.world.phys.Vec2; -import net.minecraft.world.phys.Vec3; -import org.lwjgl.BufferUtils; - -import java.nio.FloatBuffer; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.uniform.FloatSupplier; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.gl.uniform.UniformType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.uniforms.custom.cached.BooleanCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.CachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Float2VectorCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Float3VectorCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Float4MatrixCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Float4VectorCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.FloatCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Int2VectorCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.Int3VectorCachedUniform; +import net.irisshaders.iris.uniforms.custom.cached.IntCachedUniform; +import org.joml.Matrix4f; +import org.joml.Vector2f; +import org.joml.Vector2i; +import org.joml.Vector3d; +import org.joml.Vector3f; +import org.joml.Vector3i; +import org.joml.Vector4f; + import java.util.Collection; import java.util.Map; import java.util.function.BooleanSupplier; @@ -26,7 +37,7 @@ public class CustomUniformFixedInputUniformsHolder { final private ImmutableMap inputVariables; public CustomUniformFixedInputUniformsHolder( - ImmutableMap inputVariables) { + ImmutableMap inputVariables) { this.inputVariables = inputVariables; } @@ -154,13 +165,13 @@ public UniformHolder uniform4fArray(UniformUpdateFrequency updateFrequency, Stri @Override public UniformHolder uniformMatrix( - UniformUpdateFrequency updateFrequency, String name, Supplier value) { + UniformUpdateFrequency updateFrequency, String name, Supplier value) { return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, value)); } @Override public UniformHolder uniformMatrixFromArray( - UniformUpdateFrequency updateFrequency, String name, Supplier value) { + UniformUpdateFrequency updateFrequency, String name, Supplier value) { Matrix4f held = new Matrix4f(); return this.put(name, new Float4MatrixCachedUniform(name, updateFrequency, () -> { diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java b/src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniforms.java similarity index 81% rename from src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniforms.java index c898f352a5..b7793869fd 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/CustomUniforms.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/CustomUniforms.java @@ -1,7 +1,12 @@ -package net.coderbot.iris.uniforms.custom; +package net.irisshaders.iris.uniforms.custom; import com.google.common.collect.ImmutableMap; -import it.unimi.dsi.fastutil.objects.*; +import it.unimi.dsi.fastutil.objects.Object2IntMap; +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.ObjectArrayList; +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import kroppeb.stareval.element.ExpressionElement; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.expression.VariableExpression; @@ -10,15 +15,19 @@ import kroppeb.stareval.function.Type; import kroppeb.stareval.parser.Parser; import kroppeb.stareval.resolver.ExpressionResolver; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.LocationalUniformHolder; -import net.coderbot.iris.gl.uniform.UniformHolder; -import net.coderbot.iris.parsing.IrisFunctions; -import net.coderbot.iris.parsing.IrisOptions; -import net.coderbot.iris.parsing.VectorType; -import net.coderbot.iris.uniforms.custom.cached.CachedUniform; - -import java.util.*; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.uniform.LocationalUniformHolder; +import net.irisshaders.iris.gl.uniform.UniformHolder; +import net.irisshaders.iris.parsing.IrisFunctions; +import net.irisshaders.iris.parsing.IrisOptions; +import net.irisshaders.iris.parsing.VectorType; +import net.irisshaders.iris.uniforms.custom.cached.CachedUniform; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.OptionalInt; +import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -36,23 +45,23 @@ public class CustomUniforms implements FunctionContext { private CustomUniforms(CustomUniformFixedInputUniformsHolder inputHolder, Map variables) { this.inputHolder = inputHolder; ExpressionResolver resolver = new ExpressionResolver( - IrisFunctions.functions, - (name) -> { - Type type = this.inputHolder.getType(name); - if (type != null) - return type; - Builder.Variable variable = variables.get(name); - if (variable != null) - return variable.type; - return null; - }, - true); + IrisFunctions.functions, + (name) -> { + Type type = this.inputHolder.getType(name); + if (type != null) + return type; + Builder.Variable variable = variables.get(name); + if (variable != null) + return variable.type; + return null; + }, + true); for (Builder.Variable variable : variables.values()) { try { Expression expression = resolver.resolveExpression(variable.type, variable.expression); CachedUniform cachedUniform = CachedUniform - .forExpression(variable.name, variable.type, expression, this); + .forExpression(variable.name, variable.type, expression, this); this.addVariable(expression, cachedUniform); if (variable.uniform) { this.uniforms.add(cachedUniform); @@ -60,8 +69,8 @@ private CustomUniforms(CustomUniformFixedInputUniformsHolder inputHolder, Map entry.getKey().getName() + " (" + entry.getIntValue() + ")") - .collect(Collectors.joining(", ")) + dependsOnCount.object2IntEntrySet() + .stream() + .map(entry -> entry.getKey().getName() + " (" + entry.getIntValue() + ")") + .collect(Collectors.joining(", ")) ); } @@ -186,7 +195,7 @@ public void assignTo(LocationalUniformHolder targetHolder) { if (location.isPresent()) { locations.put(uniform, location.getAsInt()); } - } catch (Exception e){ + } catch (Exception e) { throw new RuntimeException(uniform.getName(), e); } } @@ -288,6 +297,14 @@ public Expression getVariable(String name) { } public static class Builder { + final private static Map types = new ImmutableMap.Builder() + .put("bool", Type.Boolean) + .put("float", Type.Float) + .put("int", Type.Int) + .put("vec2", VectorType.VEC2) + .put("vec3", VectorType.VEC3) + .put("vec4", VectorType.VEC4) + .build(); Map variables = new Object2ObjectLinkedOpenHashMap<>(); public void addVariable(String type, String name, String expression, boolean isUniform) { @@ -311,16 +328,15 @@ public void addVariable(String type, String name, String expression, boolean isU } public CustomUniforms build( - CustomUniformFixedInputUniformsHolder inputHolder + CustomUniformFixedInputUniformsHolder inputHolder ) { Iris.logger.info("Starting custom uniform resolving"); return new CustomUniforms(inputHolder, this.variables); } - @SafeVarargs public final CustomUniforms build( - Consumer... uniforms + Consumer... uniforms ) { CustomUniformFixedInputUniformsHolder.Builder inputs = new CustomUniformFixedInputUniformsHolder.Builder(); for (Consumer uniform : uniforms) { @@ -329,29 +345,9 @@ public final CustomUniforms build( return this.build(inputs.build()); } - private static class Variable { - final public Type type; - final public String name; - final public ExpressionElement expression; - final public boolean uniform; - - public Variable(Type type, String name, ExpressionElement expression, boolean uniform) { - this.type = type; - this.name = name; - this.expression = expression; - this.uniform = uniform; - } + private record Variable(Type type, String name, ExpressionElement expression, boolean uniform) { } - final private static Map types = new ImmutableMap.Builder() - .put("bool", Type.Boolean) - .put("float", Type.Float) - .put("int", Type.Int) - .put("vec2", VectorType.VEC2) - .put("vec3", VectorType.VEC3) - .put("vec4", VectorType.VEC4) - .build(); - } } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/BooleanCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/BooleanCachedUniform.java similarity index 71% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/BooleanCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/BooleanCachedUniform.java index a49737746d..bbd037c39b 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/BooleanCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/BooleanCachedUniform.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.lwjgl.opengl.GL21; import java.util.function.BooleanSupplier; @@ -18,19 +18,19 @@ public BooleanCachedUniform(String name, UniformUpdateFrequency updateFrequency, } @Override - protected boolean doUpdate(){ + protected boolean doUpdate() { boolean prev = this.cached; this.cached = this.supplier.getAsBoolean(); return prev != cached; } @Override - public void push(int location){ - GL21.glUniform1i(location, this.cached?1:0); + public void push(int location) { + GL21.glUniform1i(location, this.cached ? 1 : 0); } @Override - public void writeTo(FunctionReturn functionReturn){ + public void writeTo(FunctionReturn functionReturn) { functionReturn.booleanReturn = this.cached; } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/CachedUniform.java similarity index 94% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/CachedUniform.java index 725e2ca772..7afe9d39a5 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/CachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/CachedUniform.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.expression.VariableExpression; import kroppeb.stareval.function.FunctionContext; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector2f; import org.joml.Vector3f; import org.joml.Vector4f; @@ -21,36 +21,6 @@ public CachedUniform(String name, UniformUpdateFrequency updateFrequency) { this.updateFrequency = updateFrequency; } - public void markUnchanged() { - this.changed = false; - } - - public void update() { - doUpdate(); - // TODO: Works around a logic error / architectural flaw - there's no way to - // know when a uniform has been uploaded to all programs, so we can never - // safely change this to false with the current design. - this.changed = true; - } - - protected abstract boolean doUpdate(); - - public abstract void push(int location); - - public void pushIfChanged(int location) { - if (this.changed) - push(location); - } - - @Override - public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { - this.writeTo(functionReturn); - } - - public abstract void writeTo(FunctionReturn functionReturn); - - public abstract Type getType(); - static public CachedUniform forExpression(String name, Type type, Expression expression, FunctionContext context) { final FunctionReturn held = new FunctionReturn(); final UniformUpdateFrequency frequency = UniformUpdateFrequency.CUSTOM; @@ -89,6 +59,36 @@ static public CachedUniform forExpression(String name, Type type, Expression exp } } + public void markUnchanged() { + this.changed = false; + } + + public void update() { + doUpdate(); + // TODO: Works around a logic error / architectural flaw - there's no way to + // know when a uniform has been uploaded to all programs, so we can never + // safely change this to false with the current design. + this.changed = true; + } + + protected abstract boolean doUpdate(); + + public abstract void push(int location); + + public void pushIfChanged(int location) { + if (this.changed) + push(location); + } + + @Override + public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { + this.writeTo(functionReturn); + } + + public abstract void writeTo(FunctionReturn functionReturn); + + public abstract Type getType(); + public String getName() { return name; } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float2VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float2VectorCachedUniform.java similarity index 74% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Float2VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float2VectorCachedUniform.java index 39bf6d4fa9..d891647983 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float2VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float2VectorCachedUniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector2f; import org.lwjgl.opengl.GL21; @@ -19,7 +19,7 @@ protected void setFrom(Vector2f other) { } @Override - public void push(int location){ + public void push(int location) { GL21.glUniform2f(location, this.cached.x, this.cached.y); } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float3VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float3VectorCachedUniform.java similarity index 79% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Float3VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float3VectorCachedUniform.java index 0131c6dd55..269a8c11e8 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float3VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float3VectorCachedUniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector3f; import org.lwjgl.opengl.GL21; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java similarity index 82% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java index 407fe3c0ba..4e58242f8b 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4MatrixCachedUniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.MatrixType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.MatrixType; import org.joml.Matrix4f; import org.lwjgl.opengl.GL21; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4VectorCachedUniform.java similarity index 79% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4VectorCachedUniform.java index 250d7d1c0a..fc2fed99cd 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Float4VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Float4VectorCachedUniform.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector4f; import org.lwjgl.opengl.GL21; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/FloatCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/FloatCachedUniform.java similarity index 70% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/FloatCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/FloatCachedUniform.java index 1ca5374a91..59e76d0211 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/FloatCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/FloatCachedUniform.java @@ -1,38 +1,38 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import net.coderbot.iris.gl.uniform.FloatSupplier; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gl.uniform.FloatSupplier; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.lwjgl.opengl.GL21; public class FloatCachedUniform extends CachedUniform { - + final private FloatSupplier supplier; private float cached; - + public FloatCachedUniform(String name, UniformUpdateFrequency updateFrequency, FloatSupplier supplier) { super(name, updateFrequency); this.supplier = supplier; } - + @Override - protected boolean doUpdate(){ + protected boolean doUpdate() { float prev = this.cached; this.cached = this.supplier.getAsFloat(); return prev != cached; } - + @Override - public void push(int location){ + public void push(int location) { GL21.glUniform1f(location, this.cached); } - + @Override - public void writeTo(FunctionReturn functionReturn){ + public void writeTo(FunctionReturn functionReturn) { functionReturn.floatReturn = this.cached; } - + @Override public Type getType() { return Type.Float; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Int2VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int2VectorCachedUniform.java similarity index 79% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Int2VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int2VectorCachedUniform.java index e5a57d9703..9b568b8469 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Int2VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int2VectorCachedUniform.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.function.FunctionReturn; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector2i; import org.lwjgl.opengl.GL21; @@ -20,7 +20,7 @@ protected void setFrom(Vector2i other) { } @Override - public void push(int location){ + public void push(int location) { GL21.glUniform2i(location, this.cached.x, this.cached.y); } diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Int3VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int3VectorCachedUniform.java similarity index 77% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/Int3VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int3VectorCachedUniform.java index 7b91ea647d..b974ebbaef 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/Int3VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/Int3VectorCachedUniform.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; -import net.coderbot.iris.parsing.VectorType; -import org.joml.Vector3f; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.parsing.VectorType; import org.joml.Vector3i; import org.lwjgl.opengl.GL21; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/IntCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/IntCachedUniform.java similarity index 74% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/IntCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/IntCachedUniform.java index aaa7c0d04c..a9182b6605 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/IntCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/IntCachedUniform.java @@ -1,39 +1,39 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.lwjgl.opengl.GL21; import java.util.function.IntSupplier; public class IntCachedUniform extends CachedUniform { - + final private IntSupplier supplier; private int cached; - + public IntCachedUniform(String name, UniformUpdateFrequency updateFrequency, IntSupplier supplier) { super(name, updateFrequency); this.supplier = supplier; } - + @Override - protected boolean doUpdate(){ + protected boolean doUpdate() { int prev = this.cached; this.cached = this.supplier.getAsInt(); return prev != cached; } - + @Override - public void push(int location){ + public void push(int location) { GL21.glUniform1i(location, this.cached); } - + @Override - public void writeTo(FunctionReturn functionReturn){ + public void writeTo(FunctionReturn functionReturn) { functionReturn.intReturn = this.cached; } - + @Override public Type getType() { return Type.Int; diff --git a/src/main/java/net/coderbot/iris/uniforms/custom/cached/VectorCachedUniform.java b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/VectorCachedUniform.java similarity index 72% rename from src/main/java/net/coderbot/iris/uniforms/custom/cached/VectorCachedUniform.java rename to src/main/java/net/irisshaders/iris/uniforms/custom/cached/VectorCachedUniform.java index e92c982112..b9f484c2b2 100644 --- a/src/main/java/net/coderbot/iris/uniforms/custom/cached/VectorCachedUniform.java +++ b/src/main/java/net/irisshaders/iris/uniforms/custom/cached/VectorCachedUniform.java @@ -1,46 +1,45 @@ -package net.coderbot.iris.uniforms.custom.cached; +package net.irisshaders.iris.uniforms.custom.cached; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gl.uniform.UniformUpdateFrequency; import org.jetbrains.annotations.NotNull; import java.util.function.Supplier; public abstract class VectorCachedUniform extends CachedUniform { - - final private Supplier supplier; + final protected T cached; - + final private Supplier supplier; + public VectorCachedUniform(String name, UniformUpdateFrequency updateFrequency, T cache, Supplier<@NotNull T> supplier) { super(name, updateFrequency); this.supplier = supplier; this.cached = cache; } - + abstract protected void setFrom(T other); - + @Override - protected boolean doUpdate(){ + protected boolean doUpdate() { T other = this.supplier.get(); - if(other == null){ + if (other == null) { Iris.logger.warn("Cached Uniform supplier gave null back"); return false; } - if (!this.cached.equals(other)){ + if (!this.cached.equals(other)) { this.setFrom(other); return true; - } - else return false; + } else return false; } - + @Override - public void writeTo(FunctionReturn functionReturn){ - + public void writeTo(FunctionReturn functionReturn) { + functionReturn.objectReturn = this.cached; } - + @Override public Type getType() { return Type.Float; diff --git a/src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedFloat.java b/src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedFloat.java similarity index 92% rename from src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedFloat.java rename to src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedFloat.java index 76ac51ca10..a3e56438a3 100644 --- a/src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedFloat.java +++ b/src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedFloat.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.uniforms.transforms; +package net.irisshaders.iris.uniforms.transforms; -import net.coderbot.iris.gl.uniform.FloatSupplier; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; -import net.coderbot.iris.uniforms.SystemTimeUniforms; +import net.irisshaders.iris.gl.uniform.FloatSupplier; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.SystemTimeUniforms; /** * An implementation of basic exponential smoothing that converts a sequence of unsmoothed values into a sequence of @@ -21,32 +21,28 @@ public class SmoothedFloat implements FloatSupplier { * The input sequence of unsmoothed values */ private final FloatSupplier unsmoothed; - + /** + * The decay constant upward, k (as used in e^(-kt)) + */ + private final float decayConstantUp; + /** + * The decay constant downward, k (as used in e^(-kt)) + */ + private final float decayConstantDown; /** * An accumulator for smoothed values. */ private float accumulator; - /** * Tracks whether an initial value has already been generated, because otherwise there will be nothing to smooth * with. */ private boolean hasInitialValue; - /** - * The decay constant upward, k (as used in e^(-kt)) - */ - private final float decayConstantUp; - - /** - * The decay constant downward, k (as used in e^(-kt)) - */ - private final float decayConstantDown; - /** * Creates a new SmoothedFloat with a given half life. * - * @param halfLifeUp the half life in the exponential decay, in deciseconds (1/10th of a second) / 2 ticks. + * @param halfLifeUp the half life in the exponential decay, in deciseconds (1/10th of a second) / 2 ticks. * For example, a half life of value of 2.0 is 4 ticks or 0.2 seconds * @param unsmoothed the input sequence of unsmoothed values to be smoothed. {@code unsmoothed.getAsFloat()} will be * called exactly once for every time {@code smoothed.getAsFloat()} is called. @@ -62,6 +58,30 @@ public SmoothedFloat(float halfLifeUp, float halfLifeDown, FloatSupplier unsmoot updateNotifier.addListener(this::update); } + /** + * Computes an exponential decay factor based on the given decay constant and time value + * + * @param k the decay constant, derived from the half life + * @param t the time that has passed since the decay started + */ + private static float exponentialDecayFactor(float k, float t) { + // https://en.wikipedia.org/wiki/Exponential_decay + // e^(-kt) + return (float) Math.exp(-k * t); + } + + /** + * Computes a linearly interpolated value between v0 and v1 + * + * @param v0 the starting value (t = 0) + * @param v1 the ending value (t = 1) + * @param t the time/progress value - should be in the range of 0.0 to 1.0 + */ + private static float lerp(float v0, float v1, float t) { + // https://en.wikipedia.org/wiki/Linear_interpolation + return (1 - t) * v0 + t * v1; + } + /** * Takes one value from the unsmoothed value sequence, and smooths it into our accumulator */ @@ -114,28 +134,4 @@ public float getAsFloat() { return accumulator; } - - /** - * Computes an exponential decay factor based on the given decay constant and time value - * - * @param k the decay constant, derived from the half life - * @param t the time that has passed since the decay started - */ - private static float exponentialDecayFactor(float k, float t) { - // https://en.wikipedia.org/wiki/Exponential_decay - // e^(-kt) - return (float) Math.exp(-k * t); - } - - /** - * Computes a linearly interpolated value between v0 and v1 - * - * @param v0 the starting value (t = 0) - * @param v1 the ending value (t = 1) - * @param t the time/progress value - should be in the range of 0.0 to 1.0 - */ - private static float lerp(float v0, float v1, float t) { - // https://en.wikipedia.org/wiki/Linear_interpolation - return (1 - t) * v0 + t * v1; - } } diff --git a/src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedVec2f.java b/src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedVec2f.java similarity index 85% rename from src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedVec2f.java rename to src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedVec2f.java index aba7a642aa..7ae2f24309 100644 --- a/src/main/java/net/coderbot/iris/uniforms/transforms/SmoothedVec2f.java +++ b/src/main/java/net/irisshaders/iris/uniforms/transforms/SmoothedVec2f.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.uniforms.transforms; +package net.irisshaders.iris.uniforms.transforms; -import net.coderbot.iris.uniforms.FrameUpdateNotifier; +import net.irisshaders.iris.uniforms.FrameUpdateNotifier; import org.joml.Vector2f; import org.joml.Vector2i; diff --git a/src/main/java/net/coderbot/iris/vertices/BlockSensitiveBufferBuilder.java b/src/main/java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java similarity index 80% rename from src/main/java/net/coderbot/iris/vertices/BlockSensitiveBufferBuilder.java rename to src/main/java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java index 4a8d123c7e..5aa38163a7 100644 --- a/src/main/java/net/coderbot/iris/vertices/BlockSensitiveBufferBuilder.java +++ b/src/main/java/net/irisshaders/iris/vertices/BlockSensitiveBufferBuilder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; public interface BlockSensitiveBufferBuilder { void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ); diff --git a/src/main/java/net/coderbot/iris/vertices/BufferBuilderPolygonView.java b/src/main/java/net/irisshaders/iris/vertices/BufferBuilderPolygonView.java similarity index 91% rename from src/main/java/net/coderbot/iris/vertices/BufferBuilderPolygonView.java rename to src/main/java/net/irisshaders/iris/vertices/BufferBuilderPolygonView.java index 6bf47c07be..1e4728de31 100644 --- a/src/main/java/net/coderbot/iris/vertices/BufferBuilderPolygonView.java +++ b/src/main/java/net/irisshaders/iris/vertices/BufferBuilderPolygonView.java @@ -1,4 +1,6 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; + +import net.irisshaders.iris.vertices.views.QuadView; import java.nio.ByteBuffer; diff --git a/src/main/java/net/coderbot/iris/vertices/ExtendedDataHelper.java b/src/main/java/net/irisshaders/iris/vertices/ExtendedDataHelper.java similarity index 79% rename from src/main/java/net/coderbot/iris/vertices/ExtendedDataHelper.java rename to src/main/java/net/irisshaders/iris/vertices/ExtendedDataHelper.java index 8f1b7f3eb8..635d759e87 100644 --- a/src/main/java/net/coderbot/iris/vertices/ExtendedDataHelper.java +++ b/src/main/java/net/irisshaders/iris/vertices/ExtendedDataHelper.java @@ -1,9 +1,11 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; public final class ExtendedDataHelper { // TODO: Resolve render types for normal blocks? public static final short BLOCK_RENDER_TYPE = -1; - /** All fluids have a ShadersMod render type of 1, to match behavior of Minecraft 1.7 and earlier. */ + /** + * All fluids have a ShadersMod render type of 1, to match behavior of Minecraft 1.7 and earlier. + */ public static final short FLUID_RENDER_TYPE = 1; public static int packMidBlock(float x, float y, float z) { diff --git a/src/main/java/net/coderbot/iris/vertices/ExtendingBufferBuilder.java b/src/main/java/net/irisshaders/iris/vertices/ExtendingBufferBuilder.java similarity index 82% rename from src/main/java/net/coderbot/iris/vertices/ExtendingBufferBuilder.java rename to src/main/java/net/irisshaders/iris/vertices/ExtendingBufferBuilder.java index cc8040a5f9..3ccb77d1ba 100644 --- a/src/main/java/net/coderbot/iris/vertices/ExtendingBufferBuilder.java +++ b/src/main/java/net/irisshaders/iris/vertices/ExtendingBufferBuilder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; import com.mojang.blaze3d.vertex.VertexFormat; diff --git a/src/main/java/net/coderbot/iris/vertices/ImmediateState.java b/src/main/java/net/irisshaders/iris/vertices/ImmediateState.java similarity index 86% rename from src/main/java/net/coderbot/iris/vertices/ImmediateState.java rename to src/main/java/net/irisshaders/iris/vertices/ImmediateState.java index 7e13ce2970..d112bdfb99 100644 --- a/src/main/java/net/coderbot/iris/vertices/ImmediateState.java +++ b/src/main/java/net/irisshaders/iris/vertices/ImmediateState.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; /** * Some annoying global state needed for rendering. diff --git a/src/main/java/net/irisshaders/iris/vertices/IrisExtendedBufferBuilder.java b/src/main/java/net/irisshaders/iris/vertices/IrisExtendedBufferBuilder.java new file mode 100644 index 0000000000..04db9e9e05 --- /dev/null +++ b/src/main/java/net/irisshaders/iris/vertices/IrisExtendedBufferBuilder.java @@ -0,0 +1,31 @@ +package net.irisshaders.iris.vertices; + +import com.mojang.blaze3d.vertex.VertexFormat; + +public interface IrisExtendedBufferBuilder { + VertexFormat iris$format(); + + VertexFormat.Mode iris$mode(); + + boolean iris$extending(); + + boolean iris$isTerrain(); + + boolean iris$injectNormalAndUV1(); + + int iris$vertexCount(); + + void iris$incrementVertexCount(); + + void iris$resetVertexCount(); + + short iris$currentBlock(); + + short iris$currentRenderType(); + + int iris$currentLocalPosX(); + + int iris$currentLocalPosY(); + + int iris$currentLocalPosZ(); +} diff --git a/src/main/java/net/coderbot/iris/vertices/IrisTextVertexSinkImpl.java b/src/main/java/net/irisshaders/iris/vertices/IrisTextVertexSinkImpl.java similarity index 93% rename from src/main/java/net/coderbot/iris/vertices/IrisTextVertexSinkImpl.java rename to src/main/java/net/irisshaders/iris/vertices/IrisTextVertexSinkImpl.java index ffb1c2db92..109f350528 100644 --- a/src/main/java/net/coderbot/iris/vertices/IrisTextVertexSinkImpl.java +++ b/src/main/java/net/irisshaders/iris/vertices/IrisTextVertexSinkImpl.java @@ -1,21 +1,28 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; import com.mojang.blaze3d.vertex.VertexFormat; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import org.joml.Vector3f; import net.irisshaders.iris.api.v0.IrisTextVertexSink; -import net.minecraft.client.renderer.texture.OverlayTexture; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.views.QuadView; +import org.joml.Vector3f; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; import java.util.function.IntFunction; public class IrisTextVertexSinkImpl implements IrisTextVertexSink { + private static final int STRIDE = IrisVertexFormats.GLYPH.getVertexSize(); + private static final int OFFSET_POSITION = 0; + private static final int OFFSET_COLOR = 12; + private static final int OFFSET_TEXTURE = 16; + private static final int OFFSET_MID_TEXTURE = 38; + private static final int OFFSET_LIGHT = 24; + private static final int OFFSET_NORMAL = 28; + private static final int OFFSET_TANGENT = 46; static VertexFormat format = IrisVertexFormats.GLYPH; private final ByteBuffer buffer; private final TextQuadView quad = new TextQuadView(); private final Vector3f saveNormal = new Vector3f(); - private static final int STRIDE = IrisVertexFormats.GLYPH.getVertexSize(); private int vertexCount; private long elementOffset; private float uSum; @@ -35,13 +42,7 @@ public VertexFormat getUnderlyingVertexFormat() { public ByteBuffer getUnderlyingByteBuffer() { return buffer; } - private static final int OFFSET_POSITION = 0; - private static final int OFFSET_COLOR = 12; - private static final int OFFSET_TEXTURE = 16; - private static final int OFFSET_MID_TEXTURE = 38; - private static final int OFFSET_LIGHT = 24; - private static final int OFFSET_NORMAL = 28; - private static final int OFFSET_TANGENT = 46; + @Override public void quad(float minX, float minY, float maxX, float maxY, float z, int color, float minU, float minV, float maxU, float maxV, int light) { vertex(minX, minY, z, color, minU, minV, light); @@ -57,13 +58,13 @@ private void vertex(float x, float y, float z, int color, float u, float v, int long ptr = elementOffset; - MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 0, x); + MemoryUtil.memPutFloat(ptr + OFFSET_POSITION, x); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 4, y); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 8, z); MemoryUtil.memPutInt(ptr + OFFSET_COLOR, color); - MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 0, u); + MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE, u); MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 4, v); MemoryUtil.memPutInt(ptr + OFFSET_LIGHT, light); @@ -75,8 +76,8 @@ private void vertex(float x, float y, float z, int color, float u, float v, int if (vertexCount == 4) { // TODO: compute this at the head of quad() vertexCount = 0; - uSum *= 0.25; - vSum *= 0.25; + uSum *= 0.25f; + vSum *= 0.25f; quad.setup(elementOffset, IrisVertexFormats.GLYPH.getVertexSize()); NormalHelper.computeFaceNormal(saveNormal, quad); diff --git a/src/main/java/net/coderbot/iris/vertices/IrisVertexFormats.java b/src/main/java/net/irisshaders/iris/vertices/IrisVertexFormats.java similarity index 98% rename from src/main/java/net/coderbot/iris/vertices/IrisVertexFormats.java rename to src/main/java/net/irisshaders/iris/vertices/IrisVertexFormats.java index ad21c5aaf8..c1904acf61 100644 --- a/src/main/java/net/coderbot/iris/vertices/IrisVertexFormats.java +++ b/src/main/java/net/irisshaders/iris/vertices/IrisVertexFormats.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; import com.google.common.collect.ImmutableMap; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormatElement; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; public class IrisVertexFormats { public static final VertexFormatElement ENTITY_ELEMENT; diff --git a/src/main/java/net/coderbot/iris/vertices/NormI8.java b/src/main/java/net/irisshaders/iris/vertices/NormI8.java similarity index 98% rename from src/main/java/net/coderbot/iris/vertices/NormI8.java rename to src/main/java/net/irisshaders/iris/vertices/NormI8.java index 12cc002ecb..fc18edfd98 100644 --- a/src/main/java/net/coderbot/iris/vertices/NormI8.java +++ b/src/main/java/net/irisshaders/iris/vertices/NormI8.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; import net.minecraft.util.Mth; import org.joml.Vector3f; @@ -7,7 +7,7 @@ * Provides some utilities for working with packed normal vectors. Each normal component provides 8 bits of * precision in the range of [-1.0,1.0]. * Copied from Sodium, licensed under the LGPLv3. Modified to support a W component. - * + *

    * | 32 | 24 | 16 | 8 | * | 0000 0000 | 0110 1100 | 0110 1100 | 0110 1100 | * | W | X | Y | Z | @@ -36,6 +36,7 @@ public static int pack(Vector3f normal) { /** * Packs the specified vector components into a 32-bit integer in XYZ ordering with the 8 bits of padding at the * end. + * * @param x The x component of the normal's vector * @param y The y component of the normal's vector * @param z The z component of the normal's vector @@ -43,9 +44,11 @@ public static int pack(Vector3f normal) { public static int pack(float x, float y, float z, float w) { return ((int) (x * 127) & 0xFF) | (((int) (y * 127) & 0xFF) << 8) | (((int) (z * 127) & 0xFF) << 16) | (((int) (w * 127) & 0xFF) << 24); } + /** * Packs the specified vector components into a 32-bit integer in XYZ ordering with the 8 bits of padding at the * end. + * * @param x The x component of the normal's vector * @param y The y component of the normal's vector * @param z The z component of the normal's vector @@ -65,6 +68,7 @@ private static int encode(float comp) { /** * Unpacks the x-component of the packed normal, denormalizing it to a float in the range of -1.0..1.0. + * * @param norm The packed normal */ public static float unpackX(int norm) { @@ -73,6 +77,7 @@ public static float unpackX(int norm) { /** * Unpacks the y-component of the packed normal, denormalizing it to a float in the range of -1.0..1.0. + * * @param norm The packed normal */ public static float unpackY(int norm) { @@ -81,6 +86,7 @@ public static float unpackY(int norm) { /** * Unpacks the z-component of the packed normal, denormalizing it to a float in the range of -1.0..1.0. + * * @param norm The packed normal */ public static float unpackZ(int norm) { @@ -89,6 +95,7 @@ public static float unpackZ(int norm) { /** * Unpacks the w-component of the packed normal, denormalizing it to a float in the range of -1.0..1.0. + * * @param norm The packed normal */ public static float unpackW(int norm) { diff --git a/src/main/java/net/coderbot/iris/vertices/NormalHelper.java b/src/main/java/net/irisshaders/iris/vertices/NormalHelper.java similarity index 94% rename from src/main/java/net/coderbot/iris/vertices/NormalHelper.java rename to src/main/java/net/irisshaders/iris/vertices/NormalHelper.java index 44aca7fff9..ef6af70d3f 100644 --- a/src/main/java/net/coderbot/iris/vertices/NormalHelper.java +++ b/src/main/java/net/irisshaders/iris/vertices/NormalHelper.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices; /* * Copyright (c) 2016, 2017, 2018, 2019 FabricMC @@ -16,12 +16,14 @@ * limitations under the License. */ -import org.joml.Vector3f; -import net.minecraft.util.Mth; +import net.irisshaders.iris.vertices.views.QuadView; +import net.irisshaders.iris.vertices.views.TriView; import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; public abstract class NormalHelper { - private NormalHelper() { } + private NormalHelper() { + } public static int invertPackedNormal(int packed) { int ix = -(packed & 255); @@ -42,14 +44,6 @@ public static int invertPackedNormal(int packed) { * Expects convex quads with all points co-planar. */ public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { -// final Direction nominalFace = q.nominalFace(); -// -// if (GeometryHelper.isQuadParallelToFace(nominalFace, q)) { -// Vec3i vec = nominalFace.getVector(); -// saveTo.set(vec.getX(), vec.getY(), vec.getZ()); -// return; -// } - final float x0 = q.x(0); final float y0 = q.y(0); final float z0 = q.z(0); @@ -92,14 +86,6 @@ public static void computeFaceNormal(@NotNull Vector3f saveTo, QuadView q) { * Expects convex quads with all points co-planar. */ public static void computeFaceNormalFlipped(@NotNull Vector3f saveTo, QuadView q) { -// final Direction nominalFace = q.nominalFace(); -// -// if (GeometryHelper.isQuadParallelToFace(nominalFace, q)) { -// Vec3i vec = nominalFace.getVector(); -// saveTo.set(vec.getX(), vec.getY(), vec.getZ()); -// return; -// } - final float x0 = q.x(3); final float y0 = q.y(3); final float z0 = q.z(3); @@ -141,14 +127,6 @@ public static void computeFaceNormalFlipped(@NotNull Vector3f saveTo, QuadView q *

    Assumes counter-clockwise winding order, which is the norm. */ public static void computeFaceNormalTri(@NotNull Vector3f saveTo, TriView t) { -// final Direction nominalFace = q.nominalFace(); -// -// if (GeometryHelper.isQuadParallelToFace(nominalFace, q)) { -// Vec3i vec = nominalFace.getVector(); -// saveTo.set(vec.getX(), vec.getY(), vec.getZ()); -// return; -// } - final float x0 = t.x(0); final float y0 = t.y(0); final float z0 = t.z(0); diff --git a/src/main/java/net/coderbot/iris/vertices/PolygonView.java b/src/main/java/net/irisshaders/iris/vertices/views/PolygonView.java similarity index 76% rename from src/main/java/net/coderbot/iris/vertices/PolygonView.java rename to src/main/java/net/irisshaders/iris/vertices/views/PolygonView.java index 017793cd9f..433aea1d3d 100644 --- a/src/main/java/net/coderbot/iris/vertices/PolygonView.java +++ b/src/main/java/net/irisshaders/iris/vertices/views/PolygonView.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices.views; public interface PolygonView { float x(int index); diff --git a/src/main/java/net/coderbot/iris/vertices/QuadView.java b/src/main/java/net/irisshaders/iris/vertices/views/QuadView.java similarity index 73% rename from src/main/java/net/coderbot/iris/vertices/QuadView.java rename to src/main/java/net/irisshaders/iris/vertices/views/QuadView.java index 3db4377902..8563ad37a5 100644 --- a/src/main/java/net/coderbot/iris/vertices/QuadView.java +++ b/src/main/java/net/irisshaders/iris/vertices/views/QuadView.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices.views; /** * Implementations of this class must support at least four vertices. diff --git a/src/main/java/net/coderbot/iris/vertices/TriView.java b/src/main/java/net/irisshaders/iris/vertices/views/TriView.java similarity index 74% rename from src/main/java/net/coderbot/iris/vertices/TriView.java rename to src/main/java/net/irisshaders/iris/vertices/views/TriView.java index e33996f8b6..5d3b918800 100644 --- a/src/main/java/net/coderbot/iris/vertices/TriView.java +++ b/src/main/java/net/irisshaders/iris/vertices/views/TriView.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.vertices; +package net.irisshaders.iris.vertices.views; /** * Implementations of this class must support at least three vertices. diff --git a/src/main/resources/META-INF/MANIFEST.MF b/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..ef6ec595ac --- /dev/null +++ b/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Main-Class: net.irisshaders.iris.LaunchWarn diff --git a/src/main/resources/assets/iris/lang/de_ch.json b/src/main/resources/assets/iris/lang/de_ch.json index dde6b03a9c..89d0fef72d 100644 --- a/src/main/resources/assets/iris/lang/de_ch.json +++ b/src/main/resources/assets/iris/lang/de_ch.json @@ -7,7 +7,6 @@ "iris.keybinds": "Oculus", "iris.shaders.reloaded.failure": "Shader neu lade hed ned funktioniert! Grund: %s", "iris.shaders.toggled.failure": "Shader i/uschalte hed ned funktioniert! Grund: %s", - "options.iris.apply": "Awende", "options.iris.refresh": "Neu lade", "options.iris.openShaderPackFolder": "Shader Pack Ordner öffne...", @@ -22,7 +21,6 @@ "options.iris.shaderPackSelection.copyErrorAlreadyExists": "\"%s\" isch bereits i dim Shader Pack Ordner", "options.iris.shaders.disabled": "Shaders: Usgschalte", "options.iris.shaders.enabled": "Shaders: Igschalte", - "pack.iris.select.title": "Uswähle", "pack.iris.list.label": "+ zum hinzuefüege Shader Packs hie ine zieh" } diff --git a/src/main/resources/assets/iris/lang/en_us.json b/src/main/resources/assets/iris/lang/en_us.json index dd92ae4ac2..b23a959e02 100644 --- a/src/main/resources/assets/iris/lang/en_us.json +++ b/src/main/resources/assets/iris/lang/en_us.json @@ -66,11 +66,9 @@ "options.iris.colorSpace.sodium_tooltip": "The color space to transform the screen to. Works on top of shader packs. Use SRGB if unsure.", "options.iris.gui.hide": "Hide GUI", "options.iris.gui.show": "Show GUI", - "pack.iris.select.title": "Select", "pack.iris.configure.title": "Configure", "pack.iris.list.label": "+ Drag and Drop Shader Packs to add", - "label.iris.true": "On", "label.iris.false": "Off" } diff --git a/src/main/resources/assets/iris/lang/es_ar.json b/src/main/resources/assets/iris/lang/es_ar.json index 11df1183bf..c50c648cac 100644 --- a/src/main/resources/assets/iris/lang/es_ar.json +++ b/src/main/resources/assets/iris/lang/es_ar.json @@ -58,11 +58,9 @@ "options.iris.shadowDistance.disabled": "Tu paquete de shaders actual ya estableció una distancia de renderizado para las sombras; no podés cambiarla.", "options.iris.gui.hide": "Esconder GUI", "options.iris.gui.show": "Mostrar GUI", - "pack.iris.select.title": "Seleccionar", "pack.iris.configure.title": "Configurar", "pack.iris.list.label": "+ Arrastrá y soltá Shader Packs para agregar", - "label.iris.true": "Activado", "label.iris.false": "Desactivado" } diff --git a/src/main/resources/assets/iris/lang/es_es.json b/src/main/resources/assets/iris/lang/es_es.json index ac92b8f5a4..2061eb65c3 100644 --- a/src/main/resources/assets/iris/lang/es_es.json +++ b/src/main/resources/assets/iris/lang/es_es.json @@ -9,9 +9,7 @@ "iris.keybind.reload": "Recargar Shaders", "iris.keybind.shaderPackSelection": "Pantalla de Selección de Shaders", "iris.keybind.toggleShaders": "Alternar Shaders", - "iris.shaders.reloaded.failure": "¡Error al recargar los Shaders! Razón: %s", - "iris.shaders.toggled.failure": "¡Error al activar shaders! Razón: %s", "iris.sodium.failure.title": "¡Oculus no pudo iniciarse!", "iris.sodium.failure.download": "Descarga Rubidium", @@ -22,7 +20,6 @@ "iris.unsupported.pc": "tu PC", "iris.unsupported.pack": "¡Shader incompatible!", "iris.unsupported.pack.description": "El Shader Pack que estás intentando cargar contiene características no soportadas por %s. Por favor, prueba otro pack. Lista %s", - "options.iris.apply": "Aplicar", "options.iris.refresh": "Recargar", "options.iris.openShaderPackFolder": "Abrir carpeta de Shader Packs...", @@ -58,7 +55,6 @@ "options.iris.shadowDistance.disabled": "Tu shader pack ya ha establecido una distáncia de renderizado para las sombreas; no puedes cambiarla.", "options.iris.gui.hide": "Ocultar GUI", "options.iris.gui.show": "Mostrar GUI", - "pack.iris.select.title": "Seleccionar", "pack.iris.configure.title": "Configurar", "pack.iris.list.label": "+ Arrastra Shader Packs aquí para añadirlos", diff --git a/src/main/resources/assets/iris/lang/et_ee.json b/src/main/resources/assets/iris/lang/et_ee.json index 872c8c6d27..ed1012810b 100644 --- a/src/main/resources/assets/iris/lang/et_ee.json +++ b/src/main/resources/assets/iris/lang/et_ee.json @@ -65,11 +65,9 @@ "options.iris.colorSpace.sodium_tooltip": "Värviruum, millesse kuva teisendada. Töötab varjutajapakkide peal. Kui ei tea millist valida, kasuta SRGB.", "options.iris.gui.hide": "Peida liides", "options.iris.gui.show": "Kuva liides", - "pack.iris.select.title": "Vali", "pack.iris.configure.title": "Seadista", "pack.iris.list.label": "+ Varjutajapakkide lisamiseks sikuta need siia", - "label.iris.true": "Sees", "label.iris.false": "Väljas" } diff --git a/src/main/resources/assets/iris/lang/fr_fr.json b/src/main/resources/assets/iris/lang/fr_fr.json index d20343f96f..a21b556866 100644 --- a/src/main/resources/assets/iris/lang/fr_fr.json +++ b/src/main/resources/assets/iris/lang/fr_fr.json @@ -7,7 +7,6 @@ "iris.keybinds": "Oculus", "iris.shaders.reloaded.failure": "Échec lors du rechargement des shaders ! Raison : %s", "iris.shaders.toggled.failure": "Échec lors de l'activation des shaders ! Raison : %s", - "options.iris.apply": "Appliquer", "options.iris.refresh": "Rafraichir", "options.iris.openShaderPackFolder": "Ouvrir le dossier des packs de shaders...", @@ -22,7 +21,6 @@ "options.iris.shaderPackSelection.copyErrorAlreadyExists": "\"%s\" est déjà dans votre dossier de packs de shaders !", "options.iris.shaders.disabled": "Shaders : Désactivés", "options.iris.shaders.enabled": "Shaders : Activés", - "pack.iris.select.title": "Sélectionner", "pack.iris.list.label": "+ Glissez-déposez vos packs de shaders ici pour les ajouter" } diff --git a/src/main/resources/assets/iris/lang/hu_hu.json b/src/main/resources/assets/iris/lang/hu_hu.json index a1695018d3..fa18c5eac7 100644 --- a/src/main/resources/assets/iris/lang/hu_hu.json +++ b/src/main/resources/assets/iris/lang/hu_hu.json @@ -58,11 +58,9 @@ "options.iris.shadowDistance.disabled": "A jelenlegi Shader Pack már állított be távolságot az árnyékokhoz; nem változtathatsz rajta.", "options.iris.gui.hide": "Grafikus kezelőfelület (GUI) elrejtése", "options.iris.gui.show": "Grafikus kezelőfelület (GUI) megjelenítése", - "pack.iris.select.title": "Kiválasztás", "pack.iris.configure.title": "Konfigurálás", "pack.iris.list.label": "+ Húzz és Dobj Shader Pack-okat ide hogy hozzáadj a listához", - "label.iris.true": "Be-", "label.iris.false": "Ki-" } diff --git a/src/main/resources/assets/iris/lang/ja_jp.json b/src/main/resources/assets/iris/lang/ja_jp.json index 52d0b9b27f..1c887bdadb 100644 --- a/src/main/resources/assets/iris/lang/ja_jp.json +++ b/src/main/resources/assets/iris/lang/ja_jp.json @@ -56,11 +56,9 @@ "options.iris.shadowDistance.disabled": "お使いのシェーダーパックでは既に最大描画距離が設定されているため、ここでは変更できません。", "options.iris.gui.hide": "GUIを非表示", "options.iris.gui.show": "GUIを表示", - "pack.iris.select.title": "シェーダー選択", "pack.iris.configure.title": "シェーダー設定", "pack.iris.list.label": "+ ドラッグアンドドロップでシェーダーを追加", - "label.iris.true": "ON", "label.iris.false": "OFF" } diff --git a/src/main/resources/assets/iris/lang/ko_kr.json b/src/main/resources/assets/iris/lang/ko_kr.json index ad0f2ceb97..e5df1c6bc7 100644 --- a/src/main/resources/assets/iris/lang/ko_kr.json +++ b/src/main/resources/assets/iris/lang/ko_kr.json @@ -61,11 +61,9 @@ "options.iris.shadowDistance.sodium_tooltip": "그림자 렌더링 거리는 잠재적으로 섀도 패스에서 지형을 렌더링할 수 있는 거리를 제어합니다. 이를 낮게 설정하면 지형이 덜 렌더링되지만 프레임레이트를 향상시킬 수 있습니다. 그림자 렌더링 거리를 명시적으로 지정하는 셰이더 팩을 사용하면 이 설정을 바꿀 수 없습니다. 실제로 그림자가 표시되는 범위는 렌더링 거리 설정으로 제한됩니다.", "options.iris.gui.hide": "GUI 숨기기", "options.iris.gui.show": "GUI 보이기", - "pack.iris.select.title": "선택", "pack.iris.configure.title": "설정", "pack.iris.list.label": "+ 추가할 셰이더 팩을 끌어다 놓으십시오.", - "label.iris.true": "켜짐", "label.iris.false": "꺼짐" } diff --git a/src/main/resources/assets/iris/lang/lzh.json b/src/main/resources/assets/iris/lang/lzh.json index 1d6fc45134..eaa18d7c1d 100644 --- a/src/main/resources/assets/iris/lang/lzh.json +++ b/src/main/resources/assets/iris/lang/lzh.json @@ -7,7 +7,6 @@ "iris.keybinds": "Oculus", "iris.shaders.reloaded.failure": "以%s故,弗能重載影!", "iris.shaders.toggled.failure": "以%s故,弗能用影!", - "options.iris.apply": "然", "options.iris.refresh": "重整", "options.iris.openShaderPackFolder": "啟影囊之資料夾……", @@ -22,7 +21,6 @@ "options.iris.shaderPackSelection.copyErrorAlreadyExists": "\"%s\" 旣存於影囊資料夾中!", "options.iris.shaders.disabled": "影:關", "options.iris.shaders.enabled": "影:開", - "pack.iris.select.title": "擇", "pack.iris.list.label": "曳影囊於此" } diff --git a/src/main/resources/assets/iris/lang/nl_nl.json b/src/main/resources/assets/iris/lang/nl_nl.json index 957876a874..8c7b39758f 100644 --- a/src/main/resources/assets/iris/lang/nl_nl.json +++ b/src/main/resources/assets/iris/lang/nl_nl.json @@ -65,11 +65,9 @@ "options.iris.colorSpace.sodium_tooltip": "De kleurruimte waarnaar het scherm moet worden getransformeerd. Werkt bovenop shader-packs. Gebruik SRGB als u het niet zeker weet.", "options.iris.gui.hide": "Verberg GUI", "options.iris.gui.show": "Toon GUI", - "pack.iris.select.title": "Selecteren", "pack.iris.configure.title": "Configureer", "pack.iris.list.label": "+ Voeg Shader Packs toe door te slepen en neer te zetten", - "label.iris.true": "Aan", "label.iris.false": "Uit" } diff --git a/src/main/resources/assets/iris/lang/pl_pl.json b/src/main/resources/assets/iris/lang/pl_pl.json index 2bd78ad588..9b67968a07 100644 --- a/src/main/resources/assets/iris/lang/pl_pl.json +++ b/src/main/resources/assets/iris/lang/pl_pl.json @@ -59,11 +59,9 @@ "options.iris.shadowDistance.sodium_tooltip": "Odległość renderowania cieni określa, jak daleko mogą być potencjalnie renderowane cienie. Mniejsza odległość oznacza, że mniejsza liczba cieni będzie renderowane, co poprawia liczbę klatek na sekundę. Opcja ta nie może być zmieniona w Shaderach, które jawnie określają odległość renderowania cieni. Rzeczywista odległość renderowania cieni jest ograniczona przez ustawienie Odległość widzenia.", "options.iris.gui.hide": "Ukryj GUI", "options.iris.gui.show": "Pokaż GUI", - "pack.iris.select.title": "Wybierz", "pack.iris.configure.title": "Konfiguracja", "pack.iris.list.label": "+ Przeciągnij i upuść pakiety Shaderów, aby dodać", - "label.iris.true": "Włączone", "label.iris.false": "Wyłączone" } diff --git a/src/main/resources/assets/iris/lang/pr_pt.json b/src/main/resources/assets/iris/lang/pr_pt.json index 7303584619..e840d37d27 100644 --- a/src/main/resources/assets/iris/lang/pr_pt.json +++ b/src/main/resources/assets/iris/lang/pr_pt.json @@ -2,7 +2,6 @@ "iris.shaders.reloaded": "Shaders Recarregados!", "iris.keybind.reload": "Recarregar Shaders", "iris.shaders.reloaded.failure": "Falha no Reload Shaders! Motivo: %s", - "options.iris.apply": "Aplicar", "options.iris.refresh": "Actualizar", "options.iris.openShaderPackFolder": "Pasta de Shader Pack Aberto......", @@ -17,7 +16,6 @@ "options.iris.shaderPackSelection.copyErrorAlreadyExists": "\"%s\" já está na sua pasta Shader Packs!", "options.iris.shaders.disabled": "Shaders: Deficientes", "options.iris.shaders.enabled": "Shaders: Activados", - "pack.iris.select.title": "Seleccionar", "pack.iris.list.label": "+ Trascina e rilascia Shader Pack da aggiungere" } diff --git a/src/main/resources/assets/iris/lang/pt_br.json b/src/main/resources/assets/iris/lang/pt_br.json index 3069e442f0..a131623a82 100644 --- a/src/main/resources/assets/iris/lang/pt_br.json +++ b/src/main/resources/assets/iris/lang/pt_br.json @@ -61,11 +61,9 @@ "options.iris.shadowDistance.sodium_tooltip": "A distância das sombras permite controlar o quão longe o terreno será carregado com sombras. Distâncias menores significam menos terrenos sendo carregados, o que melhora o desempenho do jogo. Esta opção não pode ser alterada por pacotes que definem uma distância das sombras e ela é limitada pelo alcance visual.", "options.iris.gui.hide": "Ocultar interface", "options.iris.gui.show": "Exibir interface", - "pack.iris.select.title": "Selecionar um pacote", "pack.iris.configure.title": "Configurando um pacote", "pack.iris.list.label": "Arraste os pacotes até esta janela para adicioná-los", - "label.iris.true": "Sim", "label.iris.false": "Não" } diff --git a/src/main/resources/assets/iris/lang/ru_ru.json b/src/main/resources/assets/iris/lang/ru_ru.json index 1f2f708f5c..cdc83413a8 100644 --- a/src/main/resources/assets/iris/lang/ru_ru.json +++ b/src/main/resources/assets/iris/lang/ru_ru.json @@ -61,14 +61,11 @@ "options.iris.shadowDistance.sodium_tooltip": "Дальность теней определяет, насколько далеко местность может обрабатываться на этапе просчёта теней. Меньшие значения соответствуют меньшей площади, что улучшает частоту кадров. Этот параметр нельзя изменить для наборов, в которых установлено своё расстояние рендеринга теней. Фактическое расстояние рендеринга ограничено дальностью прорисовки.", "options.iris.gui.hide": "Скрыть", "options.iris.gui.show": "Показать", - "pack.iris.select.title": "Список", "pack.iris.configure.title": "Настройки", "pack.iris.list.label": "+ Перетащите наборы шейдеров для добавления", - "label.iris.true": "Вкл", "label.iris.false": "Выкл", - - "modmenu.summaryTranslation.iris":"Современный графический мод для загрузки существующих наборов шейдеров Optifine.", + "modmenu.summaryTranslation.iris": "Современный графический мод для загрузки существующих наборов шейдеров Optifine.", "modmenu.descriptionTranslation.iris": "Современный графический мод для Minecraft, предназначенный для загрузки существующих наборов шейдеров формата Optifine." } diff --git a/src/main/resources/assets/iris/lang/uk_ua.json b/src/main/resources/assets/iris/lang/uk_ua.json index 5f6ed60765..66efb44974 100644 --- a/src/main/resources/assets/iris/lang/uk_ua.json +++ b/src/main/resources/assets/iris/lang/uk_ua.json @@ -59,11 +59,9 @@ "options.iris.shadowDistance.sodium_tooltip": "Відстань візуалізації тіней визначає, наскільки далеко місцевість може бути візуалізована під час проходу тіней. Менші значення відповідають меншій ділянці, що буде візуалізована, у такий спосіб покращуючи частоту кадрів. Цей параметр не можна змінити для шейдерів, в яких указана власна відстань візуалізації тіней. Фактична відстань візуалізації тіней обмежена відстанню промальовування.", "options.iris.gui.hide": "Приховати інтерфейс", "options.iris.gui.show": "Показати інтерфейс", - "pack.iris.select.title": "Виберіть шейдери", "pack.iris.configure.title": "Налаштувати", "pack.iris.list.label": "+ Перетягніть пакети шейдерів, щоб додати", - "label.iris.true": "Увімк", "label.iris.false": "Вимк" } diff --git a/src/main/resources/assets/iris/lang/zh_cn.json b/src/main/resources/assets/iris/lang/zh_cn.json index c74ee7f0a8..7c8ee88867 100644 --- a/src/main/resources/assets/iris/lang/zh_cn.json +++ b/src/main/resources/assets/iris/lang/zh_cn.json @@ -61,11 +61,9 @@ "options.iris.shadowDistance.sodium_tooltip": "阴影渲染距离控制在阴影通道中可以渲染到多远的地形。更短的距离意味着将渲染更少的地形,从而提高帧率。在明确指定了阴影渲染距离的光影包上无法更改此选项。实际阴影渲染的距离受“渲染距离”设置的限制。", "options.iris.gui.hide": "隐藏 GUI", "options.iris.gui.show": "显示 GUI", - "pack.iris.select.title": "选择", "pack.iris.configure.title": "配置", "pack.iris.list.label": "+ 拖放光影包至此以添加", - "label.iris.true": "开", "label.iris.false": "关" } diff --git a/src/main/resources/assets/iris/lang/zh_tw.json b/src/main/resources/assets/iris/lang/zh_tw.json index 43a8e5d194..41f484a023 100644 --- a/src/main/resources/assets/iris/lang/zh_tw.json +++ b/src/main/resources/assets/iris/lang/zh_tw.json @@ -61,11 +61,9 @@ "options.iris.shadowDistance.sodium_tooltip": "陰影繪製距離控制著在陰影通道中可以繪製多遠的地形。較低的距離意味著繪製的地形較少,從而提高 FPS。在明確指定了陰影繪製距離的光影包中,此選項無法更改。實際的陰影繪製距離受顯示距離設定的限制。", "options.iris.gui.hide": "隱藏介面", "options.iris.gui.show": "顯示介面", - "pack.iris.select.title": "選擇", "pack.iris.configure.title": "設定", "pack.iris.list.label": "+ 將要新增的光影包拖曳至此", - "label.iris.true": "開啟", "label.iris.false": "關閉" } diff --git a/src/main/resources/iris.accesswidener b/src/main/resources/iris.accesswidener index 6d3e780aea..05420d5285 100644 --- a/src/main/resources/iris.accesswidener +++ b/src/main/resources/iris.accesswidener @@ -11,7 +11,6 @@ accessible class net/minecraft/client/renderer/RenderType$CompositeState accessible class net/minecraft/client/renderer/FogRenderer$FogData accessible class net/minecraft/client/renderer/texture/Stitcher$Holder accessible class net/minecraft/world/level/biome/Biome$ClimateSettings -accessible class net/minecraft/client/renderer/LevelRenderer$RenderChunkInfo accessible class net/minecraft/client/Options$FieldAccess accessible class net/minecraft/client/renderer/texture/SpriteContents$AnimatedTexture accessible class net/minecraft/client/renderer/texture/SpriteContents$FrameInfo @@ -32,3 +31,4 @@ accessible field net/minecraft/client/renderer/ShaderInstance uniforms Ljava/uti mutable field net/minecraft/client/renderer/LevelRenderer renderBuffers Lnet/minecraft/client/renderer/RenderBuffers; accessible class net/minecraft/client/gui/components/AbstractSelectionList$Entry accessible field com/mojang/blaze3d/platform/GlStateManager$BooleanState enabled Z +accessible method com/mojang/blaze3d/shaders/Program getId ()I diff --git a/src/main/resources/mixins.iris.devenvironment.json b/src/main/resources/mixins.iris.devenvironment.json new file mode 100644 index 0000000000..a71916a99f --- /dev/null +++ b/src/main/resources/mixins.iris.devenvironment.json @@ -0,0 +1,14 @@ +{ + "required": true, + "minVersion": "0.8", + "package": "net.irisshaders.iris.mixin.devenvironment", + "compatibilityLevel": "JAVA_8", + "client": [ + "MixinMinecraft_NoAuthInDev", + "MixinProfileKeyPairManager", + "MixinSharedConstants_LazyDfu" + ], + "injectors": { + "defaultRequire": 1 + } +} diff --git a/src/main/resources/mixins.oculus.bettermipmaps.json b/src/main/resources/mixins.oculus.bettermipmaps.json index e55a01139b..cb81f4904f 100644 --- a/src/main/resources/mixins.oculus.bettermipmaps.json +++ b/src/main/resources/mixins.oculus.bettermipmaps.json @@ -1,7 +1,7 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin.bettermipmaps", + "package": "net.irisshaders.iris.mixin.bettermipmaps", "compatibilityLevel": "JAVA_8", "client": [ ], diff --git a/src/main/resources/mixins.oculus.compat.dh.json b/src/main/resources/mixins.oculus.compat.dh.json deleted file mode 100644 index b9ab960fd0..0000000000 --- a/src/main/resources/mixins.oculus.compat.dh.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "required": true, - "minVersion": "0.8", - "plugin": "net.coderbot.iris.compat.dh.mixin.IrisDHCompatMixinPlugin", - "package": "net.coderbot.iris.compat.dh.mixin", - "compatibilityLevel": "JAVA_8", - "client": [ - "MixinDHApplyShader" - ], - "injectors": { - "defaultRequire": 1 - } -} diff --git a/src/main/resources/mixins.oculus.compat.indigo.json b/src/main/resources/mixins.oculus.compat.indigo.json index 7a9c3c4be9..40aae10b96 100644 --- a/src/main/resources/mixins.oculus.compat.indigo.json +++ b/src/main/resources/mixins.oculus.compat.indigo.json @@ -1,8 +1,8 @@ { "required": true, "minVersion": "0.8", - "plugin": "net.coderbot.iris.compat.indigo.mixin.IrisIndigoCompatMixinPlugin", - "package": "net.coderbot.iris.compat.indigo.mixin", + "plugin": "net.irisshaders.iris.compat.indigo.mixin.IrisIndigoCompatMixinPlugin", + "package": "net.irisshaders.iris.compat.indigo.mixin", "compatibilityLevel": "JAVA_8", "client": [ "MixinAbstractBlockRenderContext" diff --git a/src/main/resources/mixins.oculus.compat.indium.json b/src/main/resources/mixins.oculus.compat.indium.json index 5632398a5d..748bc999cd 100644 --- a/src/main/resources/mixins.oculus.compat.indium.json +++ b/src/main/resources/mixins.oculus.compat.indium.json @@ -1,8 +1,8 @@ { "required": true, "minVersion": "0.8", - "plugin": "net.coderbot.iris.compat.indium.mixin.IrisIndiumCompatMixinPlugin", - "package": "net.coderbot.iris.compat.indium.mixin", + "plugin": "net.irisshaders.iris.compat.indium.mixin.IrisIndiumCompatMixinPlugin", + "package": "net.irisshaders.iris.compat.indium.mixin", "compatibilityLevel": "JAVA_8", "client": [ "MixinAbstractBlockRenderContext" diff --git a/src/main/resources/mixins.oculus.compat.pixelmon.json b/src/main/resources/mixins.oculus.compat.pixelmon.json deleted file mode 100644 index ac57cce946..0000000000 --- a/src/main/resources/mixins.oculus.compat.pixelmon.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "required": true, - "minVersion": "0.8", - "plugin": "net.coderbot.iris.compat.pixelmon.mixin.OculusPixelmonCompatMixinPlugin", - "package": "net.coderbot.iris.compat.pixelmon.mixin", - "compatibilityLevel": "JAVA_8", - "client": [ - "MixinNormalizedFace" - ], - "injectors": { - "defaultRequire": 1 - } -} diff --git a/src/main/resources/mixins.oculus.fantastic.json b/src/main/resources/mixins.oculus.fantastic.json index bf8adaf4d7..d47eec72de 100644 --- a/src/main/resources/mixins.oculus.fantastic.json +++ b/src/main/resources/mixins.oculus.fantastic.json @@ -1,7 +1,7 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin.fantastic", + "package": "net.irisshaders.iris.mixin.fantastic", "compatibilityLevel": "JAVA_8", "client": [ "MixinFireworkSparkParticle", diff --git a/src/main/resources/mixins.oculus.fixes.maxfpscrash.json b/src/main/resources/mixins.oculus.fixes.maxfpscrash.json index e62f2ccb6b..8f747bb13b 100644 --- a/src/main/resources/mixins.oculus.fixes.maxfpscrash.json +++ b/src/main/resources/mixins.oculus.fixes.maxfpscrash.json @@ -1,7 +1,7 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin", + "package": "net.irisshaders.iris.mixin", "compatibilityLevel": "JAVA_8", "client": [ "MixinMaxFpsCrashFix" diff --git a/src/main/resources/mixins.oculus.integrationtest.json b/src/main/resources/mixins.oculus.integrationtest.json index 1e03280b7c..6d0fca412c 100644 --- a/src/main/resources/mixins.oculus.integrationtest.json +++ b/src/main/resources/mixins.oculus.integrationtest.json @@ -1,7 +1,7 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin.integrationtest", + "package": "net.irisshaders.iris.mixin.integrationtest", "compatibilityLevel": "JAVA_8", "client": [ "MixinRenderTarget_StencilBufferTest" diff --git a/src/main/resources/mixins.oculus.json b/src/main/resources/mixins.oculus.json index d0b332451f..1533dceae1 100644 --- a/src/main/resources/mixins.oculus.json +++ b/src/main/resources/mixins.oculus.json @@ -1,8 +1,7 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin", - "plugin": "net.coderbot.iris.mixin.OculusMixinPlugin", + "package": "net.irisshaders.iris.mixin", "compatibilityLevel": "JAVA_8", "client": [ "DimensionTypeAccessor", @@ -10,28 +9,20 @@ "GlStateManagerAccessor", "LevelRendererAccessor", "LightTextureAccessor", - "ProgramTypeAccessor", - "MixinBlockStateBehavior", "MixinBiome", "MixinBiomes", - "MixinChainedJsonException", + "MixinBlockStateBehavior", "MixinBooleanState", "MixinBiomes", - "MixinChunkRenderDispatcherRebuildTask", + "MixinChainedJsonException", "MixinClientLanguage", "MixinClientPacketListener", "MixinDebugScreenOverlay", - "MixinTheEndPortalRenderer", "MixinEntityRenderDispatcher", "MixinFogRenderer", "MixinGameRenderer", "MixinGameRenderer_NightVisionCompat", - "MixinProgram", - "MixinProgramManager", - "MixinProgramType", - "MixinScreenEffectRenderer", "MixinGlStateManager", - "MixinGlStateManager_AlphaTestOverride", "MixinGlStateManager_BlendOverride", "MixinGlStateManager_DepthColorOverride", "MixinGlStateManager_FramebufferBinding", @@ -40,20 +31,26 @@ "MixinItemInHandRenderer", "MixinLevelRenderer", "MixinLightningBoltRenderer", + "MixinLightTexture", + "MixinMinecraft_Images", + "MixinMinecraft_Keybinds", "MixinMinecraft_PipelineManagement", "MixinModelViewBobbing", "MixinOptions_Entrypoint", "MixinParticleEngine", + "MixinProgram", + "MixinProgramManager", + "MixinProgramType", "MixinRenderSystem", "MixinRenderTarget", - "MixinShaderInstance", + "MixinScreenEffectRenderer", + "MixinSystemReport", "MixinTheEndPortalRenderer", "MixinTitleScreen", - "MixinLightTexture", - "MixinWindow", - "MixinSystemReport", "MixinUniform", "MixinVertexBuffer", + "MixinWindow", + "ProgramTypeAccessor", "entity_render_context.MixinBlockEntityRenderDispatcher", "entity_render_context.MixinCapeLayer", "entity_render_context.MixinElytraLayer", @@ -65,12 +62,8 @@ "gui.MixinForgeGui", "gui.MixinGui", "gui.MixinVideoSettingsScreen", - "math.MixinMatrix4f", - "rendertype.MixinRenderStateShard_Tagging", - "rendertype.RenderTypeAccessor", "rendertype.RenderStateShardAccessor", "rendertype.RenderTypeAccessor", - "shadows.ChunkInfoAccessor", "shadows.MixinBeaconRenderer", "shadows.MixinLevelRenderer", "shadows.MixinPreventRebuildNearInShadowPass", @@ -78,6 +71,8 @@ "sky.MixinDimensionSpecialEffects", "sky.MixinLevelRenderer_SunMoonToggle", "sky.MixinOptions_CloudsOverride", + "state_tracking.MixinPostChain", + "state_tracking.MixinRenderTarget", "statelisteners.BooleanStateAccessor", "statelisteners.MixinGlStateManager", "statelisteners.MixinRenderSystem", @@ -95,9 +90,7 @@ "texture.TextureAtlasAccessor", "texture.pbr.MixinDirectoryLister", "texture.pbr.MixinSpriteContents", - "texture.pbr.MixinTextureAtlas", - "state_tracking.MixinPostChain", - "state_tracking.MixinRenderTarget" + "texture.pbr.MixinTextureAtlas" ], "injectors": { "defaultRequire": 1, diff --git a/src/main/resources/mixins.oculus.vertexformat.json b/src/main/resources/mixins.oculus.vertexformat.json index cfef46b48a..412b4530ef 100644 --- a/src/main/resources/mixins.oculus.vertexformat.json +++ b/src/main/resources/mixins.oculus.vertexformat.json @@ -1,12 +1,12 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.iris.mixin.vertices", + "package": "net.irisshaders.iris.mixin.vertices", "compatibilityLevel": "JAVA_8", "client": [ "MixinBufferBuilder", - "MixinVertexFormatElement", "MixinVertexFormat", + "MixinVertexFormatElement", "block_rendering.MixinBufferBuilder_SeparateAo", "block_rendering.MixinChunkRebuildTask", "block_rendering.MixinClientLevel", diff --git a/src/main/resources/oculus-batched-entity-rendering.mixins.json b/src/main/resources/oculus-batched-entity-rendering.mixins.json index 32c2d62f33..fafa6f3a38 100644 --- a/src/main/resources/oculus-batched-entity-rendering.mixins.json +++ b/src/main/resources/oculus-batched-entity-rendering.mixins.json @@ -1,26 +1,26 @@ { "required": true, "minVersion": "0.8", - "package": "net.coderbot.batchedentityrendering.mixin", + "package": "net.irisshaders.batchedentityrendering.mixin", "compatibilityLevel": "JAVA_8", "client": [ - "SectionBufferBuilderPackAccessor", - "OutlineBufferSourceAccessor", + "BufferSourceAccessor", + "CompositeStateAccessor", "MixinBufferBuilder", "MixinBufferBuilder_SegmentRendering", - "MixinRenderBuffers", - "MixinRenderType", - "MixinSheets", - "MixinDebugScreenOverlay", - "MixinFishingHookRenderer", "MixinBufferSource", "MixinCompositeRenderType", + "MixinDebugScreenOverlay", + "MixinFishingHookRenderer", "MixinLevelRenderer", "MixinLevelRenderer_EntityListSorting", - "BufferSourceAccessor", - "CompositeStateAccessor", + "MixinRenderBuffers", + "MixinRenderType", + "MixinSheets", + "OutlineBufferSourceAccessor", + "RenderStateShardAccessor", "RenderTypeAccessor", - "RenderStateShardAccessor" + "ChunkBufferBuilderPackAccessor" ], "injectors": { "defaultRequire": 1 diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/IrisSodiumOptions.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/IrisSodiumOptions.java deleted file mode 100644 index cd41caf349..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/IrisSodiumOptions.java +++ /dev/null @@ -1,87 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.options; - -import me.jellysquid.mods.sodium.client.gui.options.OptionFlag; -import me.jellysquid.mods.sodium.client.gui.options.OptionImpact; -import me.jellysquid.mods.sodium.client.gui.options.OptionImpl; -import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter; -import me.jellysquid.mods.sodium.client.gui.options.control.CyclingControl; -import me.jellysquid.mods.sodium.client.gui.options.control.SliderControl; -import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage; -import net.coderbot.iris.Iris; -import net.coderbot.iris.colorspace.ColorSpace; -import net.coderbot.iris.gui.option.IrisVideoSettings; -import net.minecraft.client.Options; -import net.minecraft.network.chat.Component; - - - -import java.io.IOException; - -public class IrisSodiumOptions { - public static OptionImpl createMaxShadowDistanceSlider(MinecraftOptionsStorage vanillaOpts) { - OptionImpl maxShadowDistanceSlider = OptionImpl.createBuilder(int.class, vanillaOpts) - .setName(Component.translatable("options.iris.shadowDistance")) - .setTooltip(Component.translatable("options.iris.shadowDistance.sodium_tooltip")) - .setControl(option -> new SliderControl(option, 0, 32, 1, translateVariableOrDisabled("options.chunks", "Disabled"))) - .setBinding((options, value) -> { - IrisVideoSettings.shadowDistance = value; - try { - Iris.getIrisConfig().save(); - } catch (IOException e) { - e.printStackTrace(); - } - }, - options -> IrisVideoSettings.getOverriddenShadowDistance(IrisVideoSettings.shadowDistance)) - .setImpact(OptionImpact.HIGH) - .setEnabled(true) - .build(); - - ((OptionImplExtended) maxShadowDistanceSlider).iris$dynamicallyEnable(IrisVideoSettings::isShadowDistanceSliderEnabled); - - return maxShadowDistanceSlider; - } - - public static OptionImpl createColorSpaceButton(MinecraftOptionsStorage vanillaOpts) { - OptionImpl colorSpace = OptionImpl.createBuilder(ColorSpace.class, vanillaOpts) - .setName(Component.translatable("options.iris.colorSpace")) - .setTooltip(Component.translatable("options.iris.colorSpace.sodium_tooltip")) - .setControl(option -> new CyclingControl<>(option, ColorSpace.class, - new Component[] { Component.literal("sRGB"), Component.literal("DCI_P3"), Component.literal("Display P3"), Component.literal("REC2020"), Component.literal("Adobe RGB") })) - .setBinding((options, value) -> { - IrisVideoSettings.colorSpace = value; - try { - Iris.getIrisConfig().save(); - } catch (IOException e) { - e.printStackTrace(); - } - }, - options -> IrisVideoSettings.colorSpace) - .setImpact(OptionImpact.LOW) - .setEnabled(true) - .build(); - - - return colorSpace; - } - - static ControlValueFormatter translateVariableOrDisabled(String key, String disabled) { - return (v) -> { - return v == 0 ? Component.literal(disabled) : (Component.translatable(key, v)); - }; - } - - public static OptionImpl createLimitedVideoSettingsButton(MinecraftOptionsStorage vanillaOpts) { - return OptionImpl.createBuilder(SupportedGraphicsMode.class, vanillaOpts) - .setName(Component.translatable("options.graphics")) - // TODO: State that Fabulous Graphics is incompatible with Shader Packs in the tooltip - .setTooltip(Component.translatable("sodium.options.graphics_quality.tooltip")) - .setControl(option -> new CyclingControl<>(option, SupportedGraphicsMode.class, - new Component[] { Component.translatable("options.graphics.fast"), Component.translatable("options.graphics.fancy") })) - .setBinding( - (opts, value) -> opts.graphicsMode().set(value.toVanilla()), - opts -> SupportedGraphicsMode.fromVanilla(opts.graphicsMode().get())) - .setImpact(OptionImpact.HIGH) - .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) - .build(); - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java deleted file mode 100644 index af9baecec9..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java +++ /dev/null @@ -1,402 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; - -import me.jellysquid.mods.sodium.client.gl.GlObject; -import me.jellysquid.mods.sodium.client.gl.shader.*; -import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkFogMode; -import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints; -import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderOptions; -import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses; -import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; -import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.sodium.impl.IrisChunkShaderBindingPoints; -import net.coderbot.iris.gl.blending.AlphaTest; -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.SodiumTerrainPipeline; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.AlphaTests; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -public class IrisChunkProgramOverrides { - private boolean shadersCreated = false; - private final EnumMap> programs = new EnumMap<>(IrisTerrainPass.class); - - private int versionCounterForSodiumShaderReload = -1; - - private GlShader createVertexShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - Optional irisVertexShader; - - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - irisVertexShader = pipeline.getShadowVertexShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - irisVertexShader = pipeline.getTerrainSolidVertexShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - irisVertexShader = pipeline.getTerrainCutoutVertexShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - irisVertexShader = pipeline.getTranslucentVertexShaderSource(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - - String source = irisVertexShader.orElse(null); - - if (source == null) { - return null; - } - - return new GlShader(ShaderType.VERTEX, new ResourceLocation("iris", - "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".vsh"), source); - } - - private GlShader createGeometryShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - Optional irisGeometryShader; - - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - irisGeometryShader = pipeline.getShadowGeometryShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - irisGeometryShader = pipeline.getTerrainSolidGeometryShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - irisGeometryShader = pipeline.getTerrainCutoutGeometryShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - irisGeometryShader = pipeline.getTranslucentGeometryShaderSource(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - - String source = irisGeometryShader.orElse(null); - - if (source == null) { - return null; - } - - return new GlShader(IrisShaderTypes.GEOMETRY, new ResourceLocation("iris", - "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".gsh"), source); - } - - private GlShader createTessControlShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - Optional irisTessControlShader; - - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - irisTessControlShader = pipeline.getShadowTessControlShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - irisTessControlShader = pipeline.getTerrainSolidTessControlShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - irisTessControlShader = pipeline.getTerrainCutoutTessControlShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - irisTessControlShader = pipeline.getTranslucentTessControlShaderSource(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - - String source = irisTessControlShader.orElse(null); - - if (source == null) { - return null; - } - - return new GlShader(IrisShaderTypes.TESS_CONTROL, new ResourceLocation("iris", - "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tcs"), source); - } - - private GlShader createTessEvalShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - Optional irisTessEvalShader; - - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - irisTessEvalShader = pipeline.getShadowTessEvalShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - irisTessEvalShader = pipeline.getTerrainSolidTessEvalShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - irisTessEvalShader = pipeline.getTerrainCutoutTessEvalShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - irisTessEvalShader = pipeline.getTranslucentTessEvalShaderSource(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - - String source = irisTessEvalShader.orElse(null); - - if (source == null) { - return null; - } - - return new GlShader(IrisShaderTypes.TESS_EVAL, new ResourceLocation("iris", - "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tes"), source); - } - - private GlShader createFragmentShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - Optional irisFragmentShader; - - if (pass == IrisTerrainPass.SHADOW) { - irisFragmentShader = pipeline.getShadowFragmentShaderSource(); - } else if (pass == IrisTerrainPass.SHADOW_CUTOUT) { - irisFragmentShader = pipeline.getShadowCutoutFragmentShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - irisFragmentShader = pipeline.getTerrainSolidFragmentShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - irisFragmentShader = pipeline.getTerrainCutoutFragmentShaderSource(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - irisFragmentShader = pipeline.getTranslucentFragmentShaderSource(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - - String source = irisFragmentShader.orElse(null); - - if (source == null) { - return null; - } - - return new GlShader(ShaderType.FRAGMENT, new ResourceLocation("iris", - "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".fsh"), source); - } - - private BlendModeOverride getBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - return pipeline.getShadowBlendOverride(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - return pipeline.getTerrainSolidBlendOverride(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - return pipeline.getTerrainCutoutBlendOverride(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - return pipeline.getTranslucentBlendOverride(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - } - - private List getBufferBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - return pipeline.getShadowBufferOverrides(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - return pipeline.getTerrainSolidBufferOverrides(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - return pipeline.getTerrainCutoutBufferOverrides(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - return pipeline.getTranslucentBufferOverrides(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - } - - @Nullable - private GlProgram createShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline, ChunkVertexType vertexType) { - GlShader vertShader = createVertexShader(pass, pipeline); - GlShader geomShader = createGeometryShader(pass, pipeline); - GlShader tessCShader = createTessControlShader(pass, pipeline); - GlShader tessEShader = createTessEvalShader(pass, pipeline); - GlShader fragShader = createFragmentShader(pass, pipeline); - BlendModeOverride blendOverride = getBlendOverride(pass, pipeline); - List bufferOverrides = getBufferBlendOverride(pass, pipeline); - float alpha = getAlphaReference(pass, pipeline); - - if (vertShader == null || fragShader == null) { - if (vertShader != null) { - vertShader.delete(); - } - - if (geomShader != null) { - geomShader.delete(); - } - - if (tessCShader != null) { - tessCShader.delete(); - } - - if (tessEShader != null) { - tessEShader.delete(); - } - - if (fragShader != null) { - fragShader.delete(); - } - - // TODO: Partial shader programs? - return null; - } - - try { - GlProgram.Builder builder = GlProgram.builder(new ResourceLocation("sodium", "chunk_shader_for_" - + pass.getName())); - - if (geomShader != null) { - builder.attachShader(geomShader); - } - if (tessCShader != null) { - builder.attachShader(tessCShader); - } - if (tessEShader != null) { - builder.attachShader(tessEShader); - } - - return builder.attachShader(vertShader) - .attachShader(fragShader) - // The following 4 attributes are part of Sodium - .bindAttribute("a_PosId", IrisChunkShaderBindingPoints.ATTRIBUTE_POSITION_ID) - .bindAttribute("a_Color", IrisChunkShaderBindingPoints.ATTRIBUTE_COLOR) - .bindAttribute("a_TexCoord", IrisChunkShaderBindingPoints.ATTRIBUTE_BLOCK_TEXTURE) - .bindAttribute("a_LightCoord", IrisChunkShaderBindingPoints.ATTRIBUTE_LIGHT_TEXTURE) - .bindAttribute("mc_Entity", IrisChunkShaderBindingPoints.BLOCK_ID) - .bindAttribute("mc_midTexCoord", IrisChunkShaderBindingPoints.MID_TEX_COORD) - .bindAttribute("at_tangent", IrisChunkShaderBindingPoints.TANGENT) - .bindAttribute("iris_Normal", IrisChunkShaderBindingPoints.NORMAL) - .bindAttribute("at_midBlock", IrisChunkShaderBindingPoints.MID_BLOCK) - .link((shader) -> { - // TODO: Better way for this? It's a bit too much casting for me. - int handle = ((GlObject) shader).handle(); - ShaderBindingContextExt contextExt = (ShaderBindingContextExt) shader; - - return new IrisChunkShaderInterface(handle, contextExt, pipeline, new ChunkShaderOptions(ChunkFogMode.SMOOTH, pass.toTerrainPass(), vertexType), - tessCShader != null || tessEShader != null, pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT, blendOverride, bufferOverrides, alpha, pipeline.getCustomUniforms()); - }); - } finally { - vertShader.delete(); - if (geomShader != null) { - geomShader.delete(); - } - if (tessCShader != null) { - tessCShader.delete(); - } - if (tessEShader != null) { - tessEShader.delete(); - } - fragShader.delete(); - } - } - - private float getAlphaReference(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { - if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { - return pipeline.getShadowAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).getReference(); - } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { - return AlphaTest.ALWAYS.getReference(); - } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { - return pipeline.getTerrainCutoutAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).getReference(); - } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { - return pipeline.getTranslucentAlpha().orElse(AlphaTest.ALWAYS).getReference(); - } else { - throw new IllegalArgumentException("Unknown pass type " + pass); - } - } - - private SodiumTerrainPipeline getSodiumTerrainPipeline() { - WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable(); - - if (worldRenderingPipeline != null) { - return worldRenderingPipeline.getSodiumTerrainPipeline(); - } else { - return null; - } - } - - public void createShaders(SodiumTerrainPipeline pipeline, ChunkVertexType vertexType) { - if (pipeline != null) { - pipeline.patchShaders(vertexType); - for (IrisTerrainPass pass : IrisTerrainPass.values()) { - if (pass.isShadow() && !pipeline.hasShadowPass()) { - this.programs.put(pass, null); - continue; - } - - this.programs.put(pass, createShader(pass, pipeline, vertexType)); - } - } else { - for (GlProgram program : this.programs.values()) { - if (program != null) { - program.delete(); - } - } - this.programs.clear(); - } - - shadersCreated = true; - } - - @Nullable - public GlProgram getProgramOverride(TerrainRenderPass pass, ChunkVertexType vertexType) { - if (versionCounterForSodiumShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) { - versionCounterForSodiumShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload(); - deleteShaders(); - } - - WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable(); - SodiumTerrainPipeline sodiumTerrainPipeline = null; - - if (worldRenderingPipeline != null) { - sodiumTerrainPipeline = worldRenderingPipeline.getSodiumTerrainPipeline(); - } - - if (!shadersCreated) { - createShaders(sodiumTerrainPipeline, vertexType); - } - - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { - if (sodiumTerrainPipeline != null && !sodiumTerrainPipeline.hasShadowPass()) { - throw new IllegalStateException("Shadow program requested, but the pack does not have a shadow pass?"); - } - - if (pass.supportsFragmentDiscard()) { - return this.programs.get(IrisTerrainPass.SHADOW_CUTOUT); - } else { - return this.programs.get(IrisTerrainPass.SHADOW); - } - } else { - if (pass.supportsFragmentDiscard()) { - return this.programs.get(IrisTerrainPass.GBUFFER_CUTOUT); - } else if (pass.isReverseOrder()) { - return this.programs.get(IrisTerrainPass.GBUFFER_TRANSLUCENT); - } else { - return this.programs.get(IrisTerrainPass.GBUFFER_SOLID); - } - } - } - - public void bindFramebuffer(TerrainRenderPass pass) { - SodiumTerrainPipeline pipeline = getSodiumTerrainPipeline(); - boolean isShadowPass = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); - - if (pipeline != null) { - GlFramebuffer framebuffer; - - if (isShadowPass) { - framebuffer = pipeline.getShadowFramebuffer(); - } else if (pass.isReverseOrder()) { - framebuffer = pipeline.getTranslucentFramebuffer(); - } else { - framebuffer = pipeline.getTerrainSolidFramebuffer(); - } - - if (framebuffer != null) { - framebuffer.bind(); - } - } - } - - public void unbindFramebuffer() { - SodiumTerrainPipeline pipeline = getSodiumTerrainPipeline(); - - if (pipeline != null) { - // TODO: Bind the framebuffer to whatever fallback is specified by SodiumTerrainPipeline. - Minecraft.getInstance().getMainRenderTarget().bindWrite(false); - } - } - - public void deleteShaders() { - for (GlProgram program : this.programs.values()) { - if (program != null) { - program.delete(); - } - } - - this.programs.clear(); - shadersCreated = false; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java deleted file mode 100644 index 8bfd21b652..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; - -import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses; -import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; - -public enum IrisTerrainPass { - SHADOW("shadow"), - SHADOW_CUTOUT("shadow"), - GBUFFER_SOLID("gbuffers_terrain"), - GBUFFER_CUTOUT("gbuffers_terrain_cutout"), - GBUFFER_TRANSLUCENT("gbuffers_water"); - - private final String name; - - IrisTerrainPass(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public boolean isShadow() { - return this == SHADOW || this == SHADOW_CUTOUT; - } - - public TerrainRenderPass toTerrainPass() { - switch (this) { - case SHADOW, GBUFFER_SOLID: return DefaultTerrainRenderPasses.SOLID; - case SHADOW_CUTOUT, GBUFFER_CUTOUT: return DefaultTerrainRenderPasses.CUTOUT; - case GBUFFER_TRANSLUCENT: return DefaultTerrainRenderPasses.TRANSLUCENT; - default: return null; - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java deleted file mode 100644 index 862b3cee05..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.shadow_map; - -public interface SwappableRenderSectionManager { - void iris$swapVisibilityState(); -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java deleted file mode 100644 index fb89d196b5..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; - -import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.GlyphVertexExt; -import net.coderbot.iris.vertices.IrisVertexFormats; -import org.lwjgl.system.MemoryUtil; - -public class IrisEntityToTerrainVertexSerializer implements VertexSerializer { - @Override - public void serialize(long src, long dst, int vertexCount) { - for(int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) { - MemoryUtil.memPutFloat(dst, MemoryUtil.memGetFloat(src + 0L)); - MemoryUtil.memPutFloat(dst + 4, MemoryUtil.memGetFloat(src + 4L)); - MemoryUtil.memPutFloat(dst + 8, MemoryUtil.memGetFloat(src + 8L)); - MemoryUtil.memPutInt(dst + 12, MemoryUtil.memGetInt(src + 12L)); - MemoryUtil.memPutFloat(dst + 16, MemoryUtil.memGetFloat(src + 16L)); - MemoryUtil.memPutFloat(dst + 20, MemoryUtil.memGetFloat(src + 20L)); - MemoryUtil.memPutInt(dst + 24, MemoryUtil.memGetInt(src + 28L)); - MemoryUtil.memPutInt(dst + 28, MemoryUtil.memGetInt(src + 32L)); - MemoryUtil.memPutInt(dst + 32, 0); - MemoryUtil.memPutInt(dst + 36, MemoryUtil.memGetInt(src + 36L)); - MemoryUtil.memPutInt(dst + 40, MemoryUtil.memGetInt(src + 40L)); - MemoryUtil.memPutInt(dst + 44, MemoryUtil.memGetInt(src + 44L)); - - src += EntityVertex.STRIDE; - dst += IrisVertexFormats.TERRAIN.getVertexSize(); - } - - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java deleted file mode 100644 index 82865452d9..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; - -import net.coderbot.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType; - -public class IrisModelVertexFormats { - public static final XHFPModelVertexType MODEL_VERTEX_XHFP = new XHFPModelVertexType(); -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java deleted file mode 100644 index 5b1617e8ba..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.copyEntity; - -import me.jellysquid.mods.sodium.client.model.ModelCuboidAccessor; -import me.jellysquid.mods.sodium.client.render.immediate.model.ModelCuboid; -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.core.Direction; -import org.objectweb.asm.Opcodes; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.Set; - -@Mixin(ModelPart.Cube.class) -public class CuboidMixin implements ModelCuboidAccessor { - @Unique - private ModelCuboid sodium$cuboid; - - @Mutable - @Shadow - @Final - private float minX; - - // Inject at the start of the function, so we don't capture modified locals - @Redirect(method = "", at = @At(value = "FIELD", opcode = Opcodes.PUTFIELD, target = "Lnet/minecraft/client/model/geom/ModelPart$Cube;minX:F", ordinal = 0)) - private void onInit(ModelPart.Cube instance, float value, int u, int v, float x, float y, float z, float sizeX, float sizeY, float sizeZ, float extraX, float extraY, float extraZ, boolean mirror, float textureWidth, float textureHeight, Set renderDirections) { - this.sodium$cuboid = new ModelCuboid(u, v, x, y, z, sizeX, sizeY, sizeZ, extraX, extraY, extraZ, mirror, textureWidth, textureHeight, renderDirections); - - this.minX = value; - } - - @Override - public ModelCuboid sodium$copy() { - return this.sodium$cuboid; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java deleted file mode 100644 index 6ee0e494f3..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.copyEntity.cull; - -import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; -import net.minecraft.client.renderer.culling.Frustum; -import net.minecraft.client.renderer.entity.EntityRenderer; -import net.minecraft.world.entity.Entity; -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; - -@Mixin(EntityRenderer.class) -public abstract class EntityRendererMixin { - @Inject(method = "shouldRender", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/culling/Frustum;isVisible(Lnet/minecraft/world/phys/AABB;)Z", shift = At.Shift.AFTER), cancellable = true) - private void preShouldRender(T entity, Frustum frustum, double x, double y, double z, CallbackInfoReturnable cir) { - var renderer = SodiumWorldRenderer.instanceNullable(); - - if (renderer == null) { - return; - } - - // If the entity isn't culled already by other means, try to perform a second pass - if (cir.getReturnValue() && !renderer.isEntityVisible(entity)) { - cir.setReturnValue(false); - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java deleted file mode 100644 index 9551f36e23..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java +++ /dev/null @@ -1,26 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.options; - -import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; -import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; -import net.coderbot.iris.Iris; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -/** - * Disables fog occlusion when a shader pack is enabled, since shaders are not guaranteed to actually implement fog. - */ -@Mixin(RenderSectionManager.class) -public class MixinRenderSectionManager { - @Redirect(method = "getSearchDistance", remap = false, - at = @At(value = "FIELD", - target = "Lme/jellysquid/mods/sodium/client/gui/SodiumGameOptions$PerformanceSettings;useFogOcclusion:Z", - remap = false)) - private boolean iris$disableFogOcclusion(SodiumGameOptions.PerformanceSettings settings) { - if (Iris.getCurrentPack().isPresent()) { - return false; - } else { - return settings.useFogOcclusion; - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java deleted file mode 100644 index 57353d0c1d..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java +++ /dev/null @@ -1,81 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.options; - -import me.jellysquid.mods.sodium.client.gui.SodiumGameOptionPages; -import me.jellysquid.mods.sodium.client.gui.options.Option; -import me.jellysquid.mods.sodium.client.gui.options.OptionGroup; -import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.sodium.impl.options.IrisSodiumOptions; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.Slice; - -// TODO: Port this Mixin - -/** - * Adds the Iris-specific options / option changes to the Sodium game options pages. - */ -@Mixin(SodiumGameOptionPages.class) -public class MixinSodiumGameOptionPages { - @Shadow(remap = false) - @Final - private static MinecraftOptionsStorage vanillaOpts; - - @Redirect(method = "general", remap = false, - slice = @Slice( - from = @At(value = "CONSTANT", args = "stringValue=options.renderDistance"), - to = @At(value = "CONSTANT", args = "stringValue=options.simulationDistance") - ), - at = @At(value = "INVOKE", remap = false, - target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + - "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + - ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), - allow = 1) - private static OptionGroup.Builder iris$addMaxShadowDistanceOption(OptionGroup.Builder builder, - Option candidate) { - builder.add(candidate); - builder.add(IrisSodiumOptions.createMaxShadowDistanceSlider(vanillaOpts)); - - return builder; - } - - @Redirect(method = "quality", remap = false, - slice = @Slice( - from = @At(value = "CONSTANT", args = "stringValue=options.graphics"), - to = @At(value = "CONSTANT", args = "stringValue=options.renderClouds") - ), - at = @At(value = "INVOKE", remap = false, - target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + - "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + - ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), - allow = 1) - private static OptionGroup.Builder iris$addColorSpaceOption(OptionGroup.Builder builder, - Option candidate) { - builder.add(candidate); - builder.add(IrisSodiumOptions.createColorSpaceButton(vanillaOpts)); - - return builder; - } - - @ModifyArg(method = "quality", remap = false, - slice = @Slice( - from = @At(value = "CONSTANT", args = "stringValue=options.graphics"), - to = @At(value = "CONSTANT", args = "stringValue=options.renderClouds") - ), - at = @At(value = "INVOKE", remap = false, - target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + - "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + - ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), - allow = 1) - private static Option iris$replaceGraphicsQualityButton(Option candidate) { - if (!Iris.getIrisConfig().areShadersEnabled()) { - return candidate; - } else { - return IrisSodiumOptions.createLimitedVideoSettingsButton(vanillaOpts); - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java deleted file mode 100644 index e3f7b4e9a2..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.options; - -import com.google.common.collect.ImmutableList; -import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI; -import me.jellysquid.mods.sodium.client.gui.options.OptionPage; -import net.coderbot.iris.gui.screen.ShaderPackScreen; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; - -/** - * Adds our Shader Packs button to the Sodium options GUI. - */ -@Mixin(SodiumOptionsGUI.class) -public class MixinSodiumOptionsGUI extends Screen { - @Shadow(remap = false) - @Final - private List pages; - - @Unique - private OptionPage shaderPacks; - - // make compiler happy - protected MixinSodiumOptionsGUI(Component title) { - super(title); - } - - @Inject(method = "", at = @At("RETURN")) - private void iris$onInit(Screen prevScreen, CallbackInfo ci) { - Component shaderPacksTranslated = Component.translatable("options.iris.shaderPackSelection"); - shaderPacks = new OptionPage(shaderPacksTranslated, ImmutableList.of()); - pages.add(shaderPacks); - } - - @Inject(method = "setPage", at = @At("HEAD"), remap = false, cancellable = true) - private void iris$onSetPage(OptionPage page, CallbackInfo ci) { - if (page == shaderPacks) { - minecraft.setScreen(new ShaderPackScreen(this)); - ci.cancel(); - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBlockRenderer.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBlockRenderer.java deleted file mode 100644 index ec2696d103..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBlockRenderer.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.separate_ao; - -import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuilder; -import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockRenderContext; -import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockRenderer; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -/** - * Allows vertex AO to be optionally passed in the alpha channel of the vertex color instead of being multiplied - * through into the RGB values. - */ -@Mixin(BlockRenderer.class) -public class MixinBlockRenderer { - @Unique - private boolean useSeparateAo; -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBufferBuilder_IntrinsicSeparateAo.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBufferBuilder_IntrinsicSeparateAo.java deleted file mode 100644 index 18bd0163bd..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinBufferBuilder_IntrinsicSeparateAo.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.separate_ao; - -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.DefaultedVertexConsumer; -import com.mojang.blaze3d.vertex.PoseStack; -import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.minecraft.client.renderer.block.model.BakedQuad; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; -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.ModifyVariable; - -import java.util.Arrays; - -@Mixin(value = BufferBuilder.class, priority = 1010) -public abstract class MixinBufferBuilder_IntrinsicSeparateAo extends DefaultedVertexConsumer { - @Shadow - private boolean fastFormat; - private float[] brightnessTable; - private int brightnessIndex; - - /*@Overwrite - public void putBulkData(PoseStack.Pose matrices, BakedQuad quad, float[] brightnessTable, float red, float green, - float blue, int[] lights, int overlay, boolean useQuadColorData) { - if (!this.fastFormat) { - if (BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { - this.brightnessTable = brightnessTable; - this.brightnessIndex = 0; - - brightnessTable = new float[brightnessTable.length]; - Arrays.fill(brightnessTable, 1.0f); - } - - super.putBulkData(matrices, quad, brightnessTable, red, green, blue, lights, overlay, useQuadColorData); - - return; - } - - if (this.defaultColorSet) { - throw new IllegalStateException(); - } - - ModelQuadView quadView = (ModelQuadView) quad; - - Matrix4f positionMatrix = matrices.pose(); - Matrix3f normalMatrix = matrices.normal(); - - int norm = MatrixUtil.computeNormal(normalMatrix, quad.getDirection()); - - QuadVertexSink drain = VertexDrain.of(this) - .createSink(VanillaVertexTypes.QUADS); - drain.ensureCapacity(4); - - for (int i = 0; i < 4; i++) { - float x = quadView.getX(i); - float y = quadView.getY(i); - float z = quadView.getZ(i); - - float fR; - float fG; - float fB; - - float brightness = brightnessTable[i]; - float alpha = 1.0F; - - if (BlockRenderingSettings.INSTANCE.shouldUseSeparateAo()) { - alpha = brightness; - if (useQuadColorData) { - int color = quadView.getColor(i); - - float oR = ColorU8.normalize(ColorABGR.unpackRed(color)); - float oG = ColorU8.normalize(ColorABGR.unpackGreen(color)); - float oB = ColorU8.normalize(ColorABGR.unpackBlue(color)); - - fR = oR * red; - fG = oG * green; - fB = oB * blue; - } else { - fR = red; - fG = green; - fB = blue; - } - } else { - if (useQuadColorData) { - int color = quadView.getColor(i); - - float oR = ColorU8.normalize(ColorABGR.unpackRed(color)); - float oG = ColorU8.normalize(ColorABGR.unpackGreen(color)); - float oB = ColorU8.normalize(ColorABGR.unpackBlue(color)); - - fR = oR * brightness * red; - fG = oG * brightness * green; - fB = oB * brightness * blue; - } else { - fR = brightness * red; - fG = brightness * green; - fB = brightness * blue; - } - } - - float u = quadView.getTexU(i); - float v = quadView.getTexV(i); - - int color = ColorABGR.pack(fR, fG, fB, alpha); - - Vector4f pos = new Vector4f(x, y, z, 1.0F); - pos.transform(positionMatrix); - - drain.writeQuad(pos.x(), pos.y(), pos.z(), color, u, v, lights[i], overlay, norm); - } - - drain.flush(); - }*/ -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinFluidRenderer.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinFluidRenderer.java deleted file mode 100644 index 564c1d2f3c..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/separate_ao/MixinFluidRenderer.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.separate_ao; - -import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; -import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing; -import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; -import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuilder; -import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.FluidRenderer; -import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.DefaultMaterials; -import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.Material; -import me.jellysquid.mods.sodium.client.render.chunk.vertex.builder.ChunkMeshBufferBuilder; -import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder; -import me.jellysquid.mods.sodium.client.world.WorldSlice; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.material.FluidState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -/** - * Basically the same as {@link MixinBlockRenderer}, but for fluid rendering. - */ -@Mixin(FluidRenderer.class) -public abstract class MixinFluidRenderer { - private boolean flipNormal; - - @Shadow - protected abstract void writeQuad(ChunkModelBuilder builder, Material material, BlockPos offset, ModelQuadView quad, ModelQuadFacing facing, boolean flip); - - @Unique - private boolean useSeparateAo; -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinBlockRenderPass.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinBlockRenderPass.java deleted file mode 100644 index 48d95ec9b6..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinBlockRenderPass.java +++ /dev/null @@ -1,15 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; - -import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; -import net.minecraft.client.renderer.RenderType; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(TerrainRenderPass.class) -public class MixinBlockRenderPass { -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinChunkBuilderMeshingTask.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinChunkBuilderMeshingTask.java deleted file mode 100644 index 304eb70c38..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinChunkBuilderMeshingTask.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; - -import me.jellysquid.mods.sodium.client.render.chunk.compile.tasks.ChunkBuilderMeshingTask; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Holder; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.registries.ForgeRegistries; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Map; - -@Mixin(ChunkBuilderMeshingTask.class) -public class MixinChunkBuilderMeshingTask { - /** - * @author embeddedt - * @reason On Forge, render types are not intended to be driven by a central registry like in vanilla; instead, they - * get queried from the block model during meshing. Only the default baked models defer to the vanilla registry; - * specifying a render type in the model JSON or using a custom model will return its own value. Thus, we need - * to redirect the access at a higher level. - */ - @Redirect(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", - at = @At(value = "INVOKE", target = "Lnet/minecraft/client/resources/model/BakedModel;getRenderTypes(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;)Lnet/minecraftforge/client/ChunkRenderTypeSet;"), - remap = false) - private ChunkRenderTypeSet oculus$overrideRenderTypes(BakedModel instance, BlockState blockState, RandomSource randomSource, ModelData modelData) { - Map, ChunkRenderTypeSet> idMap = BlockRenderingSettings.INSTANCE.getBlockTypeIds(); - if (idMap != null) { - ChunkRenderTypeSet type = idMap.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(blockState.getBlock())); - if (type != null) { - return type; - } - } - - return instance.getRenderTypes(blockState, randomSource, modelData); - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java deleted file mode 100644 index 22cdc988a1..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map; - -import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; -import me.jellysquid.mods.sodium.client.render.chunk.DefaultChunkRenderer; -import net.coderbot.iris.shadows.ShadowRenderingState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(DefaultChunkRenderer.class) -public class MixinDefaultChunkRenderer { - @Redirect(method = "render", at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/gui/SodiumGameOptions$PerformanceSettings;useBlockFaceCulling:Z"), remap = false) - private boolean iris$disableBlockFaceCullingInShadowPass(SodiumGameOptions.PerformanceSettings instance) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) return false; - return instance.useBlockFaceCulling; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java deleted file mode 100644 index 6517120f9a..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java +++ /dev/null @@ -1,53 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map; - -import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; -import me.jellysquid.mods.sodium.client.render.chunk.lists.SortedRenderLists; -import me.jellysquid.mods.sodium.client.render.viewport.Viewport; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.minecraft.client.Camera; -import org.jetbrains.annotations.NotNull; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(RenderSectionManager.class) -public class MixinRenderSectionManager { - @Shadow private @NotNull SortedRenderLists renderLists; - @Unique - private @NotNull SortedRenderLists shadowRenderLists = SortedRenderLists.empty(); - - @Redirect(method = "createTerrainRenderList", at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;"), remap = false) - private void useShadowRenderList(RenderSectionManager instance, SortedRenderLists value) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { - shadowRenderLists = value; - } else { - renderLists = value; - } - } - - @Inject(method = "update", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;createTerrainRenderList(Lnet/minecraft/client/Camera;Lme/jellysquid/mods/sodium/client/render/viewport/Viewport;IZ)V", shift = At.Shift.AFTER), cancellable = true, remap = false) - private void cancelIfShadow(Camera camera, Viewport viewport, int frame, boolean spectator, CallbackInfo ci) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) ci.cancel(); - } - - @Redirect(method = { - "getRenderLists", - "getVisibleChunkCount", - "renderLayer" - }, at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;"), remap = false) - private SortedRenderLists useShadowRenderList2(RenderSectionManager instance) { - return ShadowRenderingState.areShadowsCurrentlyBeingRendered() ? shadowRenderLists : renderLists; - } - - @Redirect(method = { - "resetRenderLists" - }, at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;"), remap = false) - private void useShadowRenderList3(RenderSectionManager instance, SortedRenderLists value) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) shadowRenderLists = value; - else renderLists = value; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java deleted file mode 100644 index 89ad894fd7..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map; - -import com.mojang.blaze3d.vertex.PoseStack; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectMaps; -import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; -import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; -import me.jellysquid.mods.sodium.client.render.viewport.Viewport; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.minecraft.client.Camera; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderBuffers; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; -import net.minecraft.server.level.BlockDestructionProgress; -import net.minecraft.world.entity.Entity; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.SortedSet; - -/** - * Ensures that the state of the chunk render visibility graph gets properly swapped when in the shadow map pass, - * because we must maintain one visibility graph for the shadow camera and one visibility graph for the player camera. - * - * Also ensures that the visibility graph is always rebuilt in the shadow pass, since the shadow camera is generally - * always moving. - */ -@Mixin(SodiumWorldRenderer.class) -public class MixinSodiumWorldRenderer { - @Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;)V", at = @At("HEAD"), remap = false) - private void resetEntityList(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, float tickDelta, MultiBufferSource.BufferSource immediate, double x, double y, double z, BlockEntityRenderDispatcher blockEntityRenderer, CallbackInfo ci) { - beList = 0; - } - - @Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;)V", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/SodiumWorldRenderer;renderBlockEntity(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;Lnet/minecraft/world/level/block/entity/BlockEntity;)V"), remap = false) - private void addToList(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, float tickDelta, MultiBufferSource.BufferSource immediate, double x, double y, double z, BlockEntityRenderDispatcher blockEntityRenderer, CallbackInfo ci) { - beList++; - } - - @Inject(method = "renderGlobalBlockEntities", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/SodiumWorldRenderer;renderBlockEntity(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;Lnet/minecraft/world/level/block/entity/BlockEntity;)V"), remap = false) - private void addToList2(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, float tickDelta, MultiBufferSource.BufferSource immediate, double x, double y, double z, BlockEntityRenderDispatcher blockEntityRenderer, CallbackInfo ci) { - beList++; - } - - @Inject(method = "isEntityVisible", at = @At("HEAD"), cancellable = true, remap = false) - private void iris$overrideEntityCulling(Entity entity, CallbackInfoReturnable cir) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) cir.setReturnValue(true); - } - - private static int beList = 0; - - static { - ShadowRenderingState.setBlockEntityRenderFunction((shadowRenderer, bufferSource, modelView, camera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum) -> { - ((SodiumWorldRendererAccessor) SodiumWorldRenderer.instance()).invokeRenderBlockEntities(modelView, Minecraft.getInstance().renderBuffers(), Long2ObjectMaps.emptyMap(), tickDelta, bufferSource, cameraX, cameraY, cameraZ, Minecraft.getInstance().getBlockEntityRenderDispatcher()); - ((SodiumWorldRendererAccessor) SodiumWorldRenderer.instance()).invokeRenderGlobalBlockEntities(modelView, Minecraft.getInstance().renderBuffers(), Long2ObjectMaps.emptyMap(), tickDelta, bufferSource, cameraX, cameraY, cameraZ, Minecraft.getInstance().getBlockEntityRenderDispatcher()); - return beList; - }); - } - - @Redirect(method = "setupTerrain", remap = false, - at = @At(value = "INVOKE", - target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;needsUpdate()Z", - remap = false)) - private boolean iris$forceChunkGraphRebuildInShadowPass(RenderSectionManager instance) { - if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { - // TODO: Detect when the sun/moon isn't moving - return true; - } else { - return instance.needsUpdate(); - } - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java deleted file mode 100644 index 4742e86d88..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; - -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; -import net.caffeinemc.mods.sodium.api.vertex.attributes.CommonVertexAttribute; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisCommonVertexAttributes; -import net.coderbot.iris.vertices.IrisVertexFormats; -import org.apache.commons.lang3.ArrayUtils; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - -/** - * Uses some rather hacky shenanigans to add a few new enum values to {@link CommonVertexAttribute} corresponding to our - * extended vertex attributes. - * - * Credit goes to Nuclearfarts for the trick. - */ -@Mixin(CommonVertexAttribute.class) -public class MixinCommonVertexAttributes { - @SuppressWarnings("target") - @Shadow(remap = false) - @Final - @Mutable - private static CommonVertexAttribute[] $VALUES; - - @Mutable - @Shadow - @Final - public static int COUNT; - - static { - int baseOrdinal = $VALUES.length; - - IrisCommonVertexAttributes.TANGENT - = CommonVertexAttributeAccessor.createCommonVertexElement("TANGENT", baseOrdinal, IrisVertexFormats.TANGENT_ELEMENT); - IrisCommonVertexAttributes.MID_TEX_COORD - = CommonVertexAttributeAccessor.createCommonVertexElement("MID_TEX_COORD", baseOrdinal + 1, IrisVertexFormats.MID_TEXTURE_ELEMENT); - IrisCommonVertexAttributes.BLOCK_ID - = CommonVertexAttributeAccessor.createCommonVertexElement("BLOCK_ID", baseOrdinal + 2, IrisVertexFormats.ENTITY_ELEMENT); - IrisCommonVertexAttributes.ENTITY_ID - = CommonVertexAttributeAccessor.createCommonVertexElement("ENTITY_ID", baseOrdinal + 3, IrisVertexFormats.ENTITY_ID_ELEMENT); - IrisCommonVertexAttributes.MID_BLOCK - = CommonVertexAttributeAccessor.createCommonVertexElement("MID_BLOCK", baseOrdinal + 4, IrisVertexFormats.MID_BLOCK_ELEMENT); - - $VALUES = ArrayUtils.addAll($VALUES, - IrisCommonVertexAttributes.TANGENT, - IrisCommonVertexAttributes.MID_TEX_COORD, - IrisCommonVertexAttributes.BLOCK_ID, - IrisCommonVertexAttributes.ENTITY_ID, - IrisCommonVertexAttributes.MID_BLOCK); - - COUNT = $VALUES.length; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinModelVertexType.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinModelVertexType.java deleted file mode 100644 index e37b2bad7b..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinModelVertexType.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; - -import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyVariable; - -/** - * A ridiculous solution to an impossible problem - * - *

    It is possible for a texture coordinate to equal 1.0 or be very close to 1.0 when - * a sprite is located on the very edge of the texture atlas. However, when presented - * with a value very close to 1.0, Sodium's code for encoding texture coordinates - * returns a value of 0.0 instead of 1.0 due to integer overflow. This code ensures - * that the incoming texture coordinate is clamped such that it will not get close - * enough to 1.0 to trigger the overflow.

    - * - *

    This flaw was extremely difficult to come across, because it requires a very - * specific set of circumstances to occur. The only two ways this bug can occur - * is either a fluid sprite being placed on the bottom or right of a texture atlas, - * which is a rare occurrence, or a small sprite being placed on to the edge - * of a relatively large atlas, and then that sprite actually showing up in terrain - * rendering. Both of these cases require specific combinations of resource packs or - * mods, often leading to situations where removing a given innocent mod appears to - * fix the issue.

    - * - *

    The release of Iris 1.2.5 introduced atlas stitching optimizations by - * PepperCode1, but also resulted in a peculiar error: some blocks in the Modfest - * modpack would display stripes/corruption on the side. As it turned out, the - * optimized stitching meant that textures were packed far tighter into the atlas, - * substantially increasing the likelihood of textures ending up on the problematic - * edges of the atlas.

    - * - *

    Initially, the blame was placed on the Indium mod, since the issue was only observed - * through some mods using the Fabric Rendering API. However, after investigation - * into Indium's code, nothing came up. The issue sat for months, until a report - * of the issue occurring in an environment containing only Iris and Sodium came in. - * This required a specific combination of resource packs to reproduce. Then, the - * blame fell on the stitching optimizations. This seemed like the clear culprit, - * but we were unable to find a correctness issue in the stitching code.

    - * - *

    Finally, after reaching out to the reporter of that issue, - * it turned out that they had already isolated a single resource pack that would - * trigger the bug. After a few hours in the debugger, the actual issue was uncovered. - *

    - * - *

    So, what's the end goal of all this rambling? Basically, resist the urge to place - * blame on to a mod. Instead, focus on getting a stable set of reproduction steps, - * which might take a while. Then, once those steps are available, use the debugger - * to its fullest extent.

    - */ -@Mixin(ChunkVertexType.class) -public interface MixinModelVertexType { -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java deleted file mode 100644 index b59f9afb66..0000000000 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; - -import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; -import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.Iris; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisModelVertexFormats; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - -@Mixin(RenderSectionManager.class) -public class MixinRenderSectionManager { - @ModifyArg(method = "", remap = false, - at = @At(value = "INVOKE", - target = "Lme/jellysquid/mods/sodium/client/render/chunk/DefaultChunkRenderer;(Lme/jellysquid/mods/sodium/client/gl/device/RenderDevice;Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;)V")) - private ChunkVertexType iris$useExtendedVertexFormat$1(ChunkVertexType vertexType) { - return BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : vertexType; - } - - @ModifyArg(method = "", - at = @At(value = "INVOKE", - target = "Lme/jellysquid/mods/sodium/client/render/chunk/compile/executor/ChunkBuilder;(Lnet/minecraft/client/multiplayer/ClientLevel;Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;)V")) - private ChunkVertexType iris$useExtendedVertexFormat$2(ChunkVertexType vertexType) { - return BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : vertexType; - } -} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java similarity index 92% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java index 43295cbc1e..126bedd69a 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/IrisChunkShaderBindingPoints.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.compat.sodium.impl; +package net.irisshaders.iris.compat.sodium.impl; /** * Defines Iris-specific chunk shader binding points. - * + *

    * NB: Make sure this doesn't collide with anything in {@link me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderBindingPoints} */ public class IrisChunkShaderBindingPoints { diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/BlockContextHolder.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/BlockContextHolder.java similarity index 82% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/BlockContextHolder.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/BlockContextHolder.java index fbd41a2e12..7a9fa6619a 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/BlockContextHolder.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/BlockContextHolder.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.block_context; +package net.irisshaders.iris.compat.sodium.impl.block_context; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntMaps; @@ -14,11 +14,13 @@ public class BlockContextHolder { public short blockId; public short renderType; public boolean ignoreMidBlock; + public byte lightValue; public BlockContextHolder() { this.blockStateIds = Object2IntMaps.emptyMap(); this.blockId = -1; this.renderType = -1; + this.lightValue = 0; } public BlockContextHolder(Object2IntMap idMap) { @@ -33,9 +35,10 @@ public void setLocalPos(int localPosX, int localPosY, int localPosZ) { this.localPosZ = localPosZ; } - public void set(BlockState state, short renderType) { + public void set(BlockState state, short renderType, byte lightValue) { this.blockId = (short) this.blockStateIds.getOrDefault(state, -1); this.renderType = renderType; + this.lightValue = lightValue; } public void reset() { @@ -44,5 +47,6 @@ public void reset() { this.localPosX = 0; this.localPosY = 0; this.localPosZ = 0; + this.lightValue = 0; } } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java similarity index 63% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java index 04082a729d..38d0a66890 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ChunkBuildBuffersExt.java @@ -1,11 +1,11 @@ -package net.coderbot.iris.compat.sodium.impl.block_context; +package net.irisshaders.iris.compat.sodium.impl.block_context; import net.minecraft.world.level.block.state.BlockState; public interface ChunkBuildBuffersExt { void iris$setLocalPos(int localPosX, int localPosY, int localPosZ); - void iris$setMaterialId(BlockState state, short renderType); + void iris$setMaterialId(BlockState state, short renderType, byte lightValue); void iris$resetBlockContext(); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java similarity index 68% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java index 77054d7f1f..cd5f62dcf8 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/block_context/ContextAwareVertexWriter.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.block_context; +package net.irisshaders.iris.compat.sodium.impl.block_context; public interface ContextAwareVertexWriter { void iris$setContextHolder(BlockContextHolder holder); diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/IrisSodiumOptions.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/IrisSodiumOptions.java new file mode 100644 index 0000000000..8bd1176570 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/IrisSodiumOptions.java @@ -0,0 +1,85 @@ +package net.irisshaders.iris.compat.sodium.impl.options; + +import me.jellysquid.mods.sodium.client.gui.options.OptionFlag; +import me.jellysquid.mods.sodium.client.gui.options.OptionImpact; +import me.jellysquid.mods.sodium.client.gui.options.OptionImpl; +import me.jellysquid.mods.sodium.client.gui.options.control.ControlValueFormatter; +import me.jellysquid.mods.sodium.client.gui.options.control.CyclingControl; +import me.jellysquid.mods.sodium.client.gui.options.control.SliderControl; +import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.gui.option.IrisVideoSettings; +import net.irisshaders.iris.pathways.colorspace.ColorSpace; +import net.minecraft.client.Options; +import net.minecraft.network.chat.Component; + +import java.io.IOException; + +public class IrisSodiumOptions { + public static OptionImpl createMaxShadowDistanceSlider(MinecraftOptionsStorage vanillaOpts) { + OptionImpl maxShadowDistanceSlider = OptionImpl.createBuilder(int.class, vanillaOpts) + .setName(Component.translatable("options.iris.shadowDistance")) + .setTooltip(Component.translatable("options.iris.shadowDistance.sodium_tooltip")) + .setControl(option -> new SliderControl(option, 0, 32, 1, translateVariableOrDisabled("options.chunks", "Disabled"))) + .setBinding((options, value) -> { + IrisVideoSettings.shadowDistance = value; + try { + Iris.getIrisConfig().save(); + } catch (IOException e) { + e.printStackTrace(); + } + }, + options -> IrisVideoSettings.getOverriddenShadowDistance(IrisVideoSettings.shadowDistance)) + .setImpact(OptionImpact.HIGH) + .setEnabled(true) + .build(); + + ((OptionImplExtended) maxShadowDistanceSlider).iris$dynamicallyEnable(IrisVideoSettings::isShadowDistanceSliderEnabled); + + return maxShadowDistanceSlider; + } + + public static OptionImpl createColorSpaceButton(MinecraftOptionsStorage vanillaOpts) { + OptionImpl colorSpace = OptionImpl.createBuilder(ColorSpace.class, vanillaOpts) + .setName(Component.translatable("options.iris.colorSpace")) + .setTooltip(Component.translatable("options.iris.colorSpace.sodium_tooltip")) + .setControl(option -> new CyclingControl<>(option, ColorSpace.class, + new Component[]{Component.literal("sRGB"), Component.literal("DCI_P3"), Component.literal("Display P3"), Component.literal("REC2020"), Component.literal("Adobe RGB")})) + .setBinding((options, value) -> { + IrisVideoSettings.colorSpace = value; + try { + Iris.getIrisConfig().save(); + } catch (IOException e) { + e.printStackTrace(); + } + }, + options -> IrisVideoSettings.colorSpace) + .setImpact(OptionImpact.LOW) + .setEnabled(true) + .build(); + + + return colorSpace; + } + + static ControlValueFormatter translateVariableOrDisabled(String key, String disabled) { + return (v) -> { + return v == 0 ? Component.literal(disabled) : (Component.translatable(key, v)); + }; + } + + public static OptionImpl createLimitedVideoSettingsButton(MinecraftOptionsStorage vanillaOpts) { + return OptionImpl.createBuilder(SupportedGraphicsMode.class, vanillaOpts) + .setName(Component.translatable("options.graphics")) + // TODO: State that Fabulous Graphics is incompatible with Shader Packs in the tooltip + .setTooltip(Component.translatable("sodium.options.graphics_quality.tooltip")) + .setControl(option -> new CyclingControl<>(option, SupportedGraphicsMode.class, + new Component[]{Component.translatable("options.graphics.fast"), Component.translatable("options.graphics.fancy")})) + .setBinding( + (opts, value) -> opts.graphicsMode().set(value.toVanilla()), + opts -> SupportedGraphicsMode.fromVanilla(opts.graphicsMode().get())) + .setImpact(OptionImpact.HIGH) + .setFlags(OptionFlag.REQUIRES_RENDERER_RELOAD) + .build(); + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/OptionImplExtended.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/OptionImplExtended.java similarity index 71% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/OptionImplExtended.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/OptionImplExtended.java index 7685c4a118..fff35f76fa 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/OptionImplExtended.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/OptionImplExtended.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.options; +package net.irisshaders.iris.compat.sodium.impl.options; import java.util.function.BooleanSupplier; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/SupportedGraphicsMode.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/SupportedGraphicsMode.java similarity index 87% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/SupportedGraphicsMode.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/SupportedGraphicsMode.java index ae0cd05119..d3bfc6fe12 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/options/SupportedGraphicsMode.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/options/SupportedGraphicsMode.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.options; +package net.irisshaders.iris.compat.sodium.impl.options; import net.minecraft.client.GraphicsStatus; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java similarity index 89% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java index 57ec631e7e..70ac2a9853 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/GlUniformMatrix3f.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniform; import org.joml.Matrix3f; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java new file mode 100644 index 0000000000..572f5fc237 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkProgramOverrides.java @@ -0,0 +1,401 @@ +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; + +import me.jellysquid.mods.sodium.client.gl.GlObject; +import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; +import me.jellysquid.mods.sodium.client.gl.shader.GlShader; +import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; +import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkFogMode; +import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderOptions; +import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; +import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.sodium.impl.IrisChunkShaderBindingPoints; +import net.irisshaders.iris.gl.GLDebug; +import net.irisshaders.iris.gl.blending.AlphaTest; +import net.irisshaders.iris.gl.blending.AlphaTests; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.framebuffer.GlFramebuffer; +import net.irisshaders.iris.pipeline.SodiumTerrainPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.opengl.GL43C; + +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +public class IrisChunkProgramOverrides { + private final EnumMap> programs = new EnumMap<>(IrisTerrainPass.class); + private boolean shadersCreated = false; + private int versionCounterForSodiumShaderReload = -1; + + private GlShader createVertexShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + Optional irisVertexShader; + + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + irisVertexShader = pipeline.getShadowVertexShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + irisVertexShader = pipeline.getTerrainSolidVertexShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + irisVertexShader = pipeline.getTerrainCutoutVertexShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + irisVertexShader = pipeline.getTranslucentVertexShaderSource(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + + String source = irisVertexShader.orElse(null); + + if (source == null) { + return null; + } + + return new GlShader(ShaderType.VERTEX, new ResourceLocation("iris", + "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".vsh"), source); + } + + private GlShader createGeometryShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + Optional irisGeometryShader; + + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + irisGeometryShader = pipeline.getShadowGeometryShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + irisGeometryShader = pipeline.getTerrainSolidGeometryShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + irisGeometryShader = pipeline.getTerrainCutoutGeometryShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + irisGeometryShader = pipeline.getTranslucentGeometryShaderSource(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + + String source = irisGeometryShader.orElse(null); + + if (source == null) { + return null; + } + + return new GlShader(IrisShaderTypes.GEOMETRY, new ResourceLocation("iris", + "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".gsh"), source); + } + + private GlShader createTessControlShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + Optional irisTessControlShader; + + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + irisTessControlShader = pipeline.getShadowTessControlShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + irisTessControlShader = pipeline.getTerrainSolidTessControlShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + irisTessControlShader = pipeline.getTerrainCutoutTessControlShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + irisTessControlShader = pipeline.getTranslucentTessControlShaderSource(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + + String source = irisTessControlShader.orElse(null); + + if (source == null) { + return null; + } + + return new GlShader(IrisShaderTypes.TESS_CONTROL, new ResourceLocation("iris", + "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tcs"), source); + } + + private GlShader createTessEvalShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + Optional irisTessEvalShader; + + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + irisTessEvalShader = pipeline.getShadowTessEvalShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + irisTessEvalShader = pipeline.getTerrainSolidTessEvalShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + irisTessEvalShader = pipeline.getTerrainCutoutTessEvalShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + irisTessEvalShader = pipeline.getTranslucentTessEvalShaderSource(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + + String source = irisTessEvalShader.orElse(null); + + if (source == null) { + return null; + } + + return new GlShader(IrisShaderTypes.TESS_EVAL, new ResourceLocation("iris", + "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".tes"), source); + } + + private GlShader createFragmentShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + Optional irisFragmentShader; + + if (pass == IrisTerrainPass.SHADOW) { + irisFragmentShader = pipeline.getShadowFragmentShaderSource(); + } else if (pass == IrisTerrainPass.SHADOW_CUTOUT) { + irisFragmentShader = pipeline.getShadowCutoutFragmentShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + irisFragmentShader = pipeline.getTerrainSolidFragmentShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + irisFragmentShader = pipeline.getTerrainCutoutFragmentShaderSource(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + irisFragmentShader = pipeline.getTranslucentFragmentShaderSource(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + + String source = irisFragmentShader.orElse(null); + + if (source == null) { + return null; + } + + return new GlShader(ShaderType.FRAGMENT, new ResourceLocation("iris", + "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT) + ".fsh"), source); + } + + private BlendModeOverride getBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + return pipeline.getShadowBlendOverride(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + return pipeline.getTerrainSolidBlendOverride(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + return pipeline.getTerrainCutoutBlendOverride(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + return pipeline.getTranslucentBlendOverride(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + } + + private List getBufferBlendOverride(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + return pipeline.getShadowBufferOverrides(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + return pipeline.getTerrainSolidBufferOverrides(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + return pipeline.getTerrainCutoutBufferOverrides(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + return pipeline.getTranslucentBufferOverrides(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + } + + @Nullable + private GlProgram createShader(IrisTerrainPass pass, SodiumTerrainPipeline pipeline, ChunkVertexType vertexType) { + GlShader vertShader = createVertexShader(pass, pipeline); + GlShader geomShader = createGeometryShader(pass, pipeline); + GlShader tessCShader = createTessControlShader(pass, pipeline); + GlShader tessEShader = createTessEvalShader(pass, pipeline); + GlShader fragShader = createFragmentShader(pass, pipeline); + BlendModeOverride blendOverride = getBlendOverride(pass, pipeline); + List bufferOverrides = getBufferBlendOverride(pass, pipeline); + float alpha = getAlphaReference(pass, pipeline); + + if (vertShader == null || fragShader == null) { + if (vertShader != null) { + vertShader.delete(); + } + + if (geomShader != null) { + geomShader.delete(); + } + + if (tessCShader != null) { + tessCShader.delete(); + } + + if (tessEShader != null) { + tessEShader.delete(); + } + + if (fragShader != null) { + fragShader.delete(); + } + + // TODO: Partial shader programs? + return null; + } + + try { + GlProgram.Builder builder = GlProgram.builder(new ResourceLocation("sodium", "chunk_shader_for_" + + pass.getName())); + + if (geomShader != null) { + builder.attachShader(geomShader); + } + if (tessCShader != null) { + builder.attachShader(tessCShader); + } + if (tessEShader != null) { + builder.attachShader(tessEShader); + } + + return builder.attachShader(vertShader) + .attachShader(fragShader) + // The following 4 attributes are part of Sodium. + .bindAttribute("a_PosId", IrisChunkShaderBindingPoints.ATTRIBUTE_POSITION_ID) + .bindAttribute("a_Color", IrisChunkShaderBindingPoints.ATTRIBUTE_COLOR) + .bindAttribute("a_TexCoord", IrisChunkShaderBindingPoints.ATTRIBUTE_BLOCK_TEXTURE) + .bindAttribute("a_LightCoord", IrisChunkShaderBindingPoints.ATTRIBUTE_LIGHT_TEXTURE) + .bindAttribute("mc_Entity", IrisChunkShaderBindingPoints.BLOCK_ID) + .bindAttribute("mc_midTexCoord", IrisChunkShaderBindingPoints.MID_TEX_COORD) + .bindAttribute("at_tangent", IrisChunkShaderBindingPoints.TANGENT) + .bindAttribute("iris_Normal", IrisChunkShaderBindingPoints.NORMAL) + .bindAttribute("at_midBlock", IrisChunkShaderBindingPoints.MID_BLOCK) + .link((shader) -> { + int handle = ((GlObject) shader).handle(); + ShaderBindingContextExt contextExt = (ShaderBindingContextExt) shader; + GLDebug.nameObject(GL43C.GL_PROGRAM, handle, "sodium-terrain-" + pass.toString().toLowerCase(Locale.ROOT)); + return new IrisChunkShaderInterface(handle, contextExt, pipeline, new ChunkShaderOptions(ChunkFogMode.SMOOTH, pass.toTerrainPass(), vertexType), + tessCShader != null || tessEShader != null, pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT, blendOverride, bufferOverrides, alpha, pipeline.getCustomUniforms()); + }); + } finally { + vertShader.delete(); + if (geomShader != null) { + geomShader.delete(); + } + if (tessCShader != null) { + tessCShader.delete(); + } + if (tessEShader != null) { + tessEShader.delete(); + } + fragShader.delete(); + } + } + + private float getAlphaReference(IrisTerrainPass pass, SodiumTerrainPipeline pipeline) { + if (pass == IrisTerrainPass.SHADOW || pass == IrisTerrainPass.SHADOW_CUTOUT) { + return pipeline.getShadowAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).reference(); + } else if (pass == IrisTerrainPass.GBUFFER_SOLID) { + return AlphaTest.ALWAYS.reference(); + } else if (pass == IrisTerrainPass.GBUFFER_CUTOUT) { + return pipeline.getTerrainCutoutAlpha().orElse(AlphaTests.ONE_TENTH_ALPHA).reference(); + } else if (pass == IrisTerrainPass.GBUFFER_TRANSLUCENT) { + return pipeline.getTranslucentAlpha().orElse(AlphaTest.ALWAYS).reference(); + } else { + throw new IllegalArgumentException("Unknown pass type " + pass); + } + } + + private SodiumTerrainPipeline getSodiumTerrainPipeline() { + WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable(); + + if (worldRenderingPipeline != null) { + return worldRenderingPipeline.getSodiumTerrainPipeline(); + } else { + return null; + } + } + + public void createShaders(SodiumTerrainPipeline pipeline, ChunkVertexType vertexType) { + if (pipeline != null) { + pipeline.patchShaders(vertexType); + for (IrisTerrainPass pass : IrisTerrainPass.values()) { + if (pass.isShadow() && !pipeline.hasShadowPass()) { + this.programs.put(pass, null); + continue; + } + + this.programs.put(pass, createShader(pass, pipeline, vertexType)); + } + } else { + for (GlProgram program : this.programs.values()) { + if (program != null) { + program.delete(); + } + } + this.programs.clear(); + } + + shadersCreated = true; + } + + @Nullable + public GlProgram getProgramOverride(TerrainRenderPass pass, ChunkVertexType vertexType) { + if (versionCounterForSodiumShaderReload != Iris.getPipelineManager().getVersionCounterForSodiumShaderReload()) { + versionCounterForSodiumShaderReload = Iris.getPipelineManager().getVersionCounterForSodiumShaderReload(); + deleteShaders(); + } + + WorldRenderingPipeline worldRenderingPipeline = Iris.getPipelineManager().getPipelineNullable(); + SodiumTerrainPipeline sodiumTerrainPipeline = null; + + if (worldRenderingPipeline != null) { + sodiumTerrainPipeline = worldRenderingPipeline.getSodiumTerrainPipeline(); + } + + if (!shadersCreated) { + createShaders(sodiumTerrainPipeline, vertexType); + } + + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + if (sodiumTerrainPipeline != null && !sodiumTerrainPipeline.hasShadowPass()) { + throw new IllegalStateException("Shadow program requested, but the pack does not have a shadow pass?"); + } + + if (pass.supportsFragmentDiscard()) { + return this.programs.get(IrisTerrainPass.SHADOW_CUTOUT); + } else { + return this.programs.get(IrisTerrainPass.SHADOW); + } + } else { + if (pass.supportsFragmentDiscard()) { + return this.programs.get(IrisTerrainPass.GBUFFER_CUTOUT); + } else if (pass.isReverseOrder()) { + return this.programs.get(IrisTerrainPass.GBUFFER_TRANSLUCENT); + } else { + return this.programs.get(IrisTerrainPass.GBUFFER_SOLID); + } + } + } + + public void bindFramebuffer(TerrainRenderPass pass) { + SodiumTerrainPipeline pipeline = getSodiumTerrainPipeline(); + boolean isShadowPass = ShadowRenderingState.areShadowsCurrentlyBeingRendered(); + + if (pipeline != null) { + GlFramebuffer framebuffer; + + if (isShadowPass) { + framebuffer = pipeline.getShadowFramebuffer(); + } else if (pass.isReverseOrder()) { + framebuffer = pipeline.getTranslucentFramebuffer(); + } else { + framebuffer = pipeline.getTerrainSolidFramebuffer(); + } + + if (framebuffer != null) { + framebuffer.bind(); + } + } + } + + public void unbindFramebuffer() { + SodiumTerrainPipeline pipeline = getSodiumTerrainPipeline(); + + if (pipeline != null) { + Minecraft.getInstance().getMainRenderTarget().bindWrite(false); + } + } + + public void deleteShaders() { + for (GlProgram program : this.programs.values()) { + if (program != null) { + program.delete(); + } + } + + this.programs.clear(); + shadersCreated = false; + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java similarity index 88% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java index 3966b9b4cf..21cf30cee2 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisChunkShaderInterface.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; import me.jellysquid.mods.sodium.client.gl.buffer.GlMutableBuffer; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniform; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniformBlock; @@ -11,19 +10,18 @@ import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderOptions; import me.jellysquid.mods.sodium.client.render.chunk.shader.ShaderBindingContext; import me.jellysquid.mods.sodium.client.util.TextureUtil; -import net.coderbot.iris.Iris; -import net.coderbot.iris.gl.IrisRenderSystem; -import net.coderbot.iris.gl.blending.BlendModeOverride; -import net.coderbot.iris.gl.blending.BufferBlendOverride; -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.gl.texture.TextureType; -import net.coderbot.iris.pipeline.SodiumTerrainPipeline; -import net.coderbot.iris.samplers.IrisSamplers; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.uniforms.custom.CustomUniforms; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.gl.blending.BlendModeOverride; +import net.irisshaders.iris.gl.blending.BufferBlendOverride; +import net.irisshaders.iris.gl.program.ProgramImages; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.gl.texture.TextureType; +import net.irisshaders.iris.pipeline.SodiumTerrainPipeline; +import net.irisshaders.iris.samplers.IrisSamplers; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.uniforms.custom.CustomUniforms; +import net.irisshaders.iris.vertices.ImmediateState; import org.jetbrains.annotations.Nullable; import org.joml.Matrix3f; import org.joml.Matrix4f; @@ -58,7 +56,7 @@ public class IrisChunkShaderInterface extends ChunkShaderInterface { private final List bufferBlendOverrides; private final boolean hasOverrides; private final boolean isTess; - private CustomUniforms customUniforms; + private final CustomUniforms customUniforms; public IrisChunkShaderInterface(int handle, ShaderBindingContextExt contextExt, SodiumTerrainPipeline pipeline, ChunkShaderOptions options, boolean isTess, boolean isShadowPass, BlendModeOverride blendModeOverride, List bufferOverrides, float alpha, CustomUniforms customUniforms) { @@ -94,7 +92,7 @@ public GlUniformBlock bindUniformBlock(String s, int i) { customUniforms.mapholderToPass(builder, this); this.irisProgramUniforms = builder.buildUniforms(); this.irisProgramSamplers - = isShadowPass? pipeline.initShadowSamplers(handle) : pipeline.initTerrainSamplers(handle); + = isShadowPass ? pipeline.initShadowSamplers(handle) : pipeline.initTerrainSamplers(handle); this.irisProgramImages = isShadowPass ? pipeline.initShadowImages(handle) : pipeline.initTerrainImages(handle); } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java similarity index 93% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java index 6d8eff3d18..1918e986f9 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderFogComponent.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import com.mojang.blaze3d.systems.RenderSystem; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniformFloat; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java similarity index 56% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java index 18c8980d2c..18ccf8e15e 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisShaderTypes.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; /** - * Initialized by {@link net.coderbot.iris.compat.sodium.mixin.shader_overrides.MixinShaderType} + * Initialized by {@link net.irisshaders.iris.compat.sodium.mixin.shader_overrides.MixinShaderType} */ public class IrisShaderTypes { public static ShaderType GEOMETRY; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java new file mode 100644 index 0000000000..b0d02eb4cc --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/IrisTerrainPass.java @@ -0,0 +1,39 @@ +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; + +import me.jellysquid.mods.sodium.client.render.chunk.terrain.DefaultTerrainRenderPasses; +import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; + +public enum IrisTerrainPass { + SHADOW("shadow"), + SHADOW_CUTOUT("shadow"), + GBUFFER_SOLID("gbuffers_terrain"), + GBUFFER_CUTOUT("gbuffers_terrain_cutout"), + GBUFFER_TRANSLUCENT("gbuffers_water"); + + private final String name; + + IrisTerrainPass(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public boolean isShadow() { + return this == SHADOW || this == SHADOW_CUTOUT; + } + + public TerrainRenderPass toTerrainPass() { + switch (this) { + case SHADOW, GBUFFER_SOLID: + return DefaultTerrainRenderPasses.SOLID; + case SHADOW_CUTOUT, GBUFFER_CUTOUT: + return DefaultTerrainRenderPasses.CUTOUT; + case GBUFFER_TRANSLUCENT: + return DefaultTerrainRenderPasses.TRANSLUCENT; + default: + return null; + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java similarity index 85% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java index dd818291f5..c83e1a10b0 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderBindingContextExt.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniform; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniformBlock; @@ -7,5 +7,6 @@ public interface ShaderBindingContextExt { > U bindUniformIfPresent(String var1, IntFunction var2); + GlUniformBlock bindUniformBlockIfPresent(String var1, int var2); } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java similarity index 71% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java index b641dbc2b5..ce7cbed57c 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shader_overrides/ShaderChunkRendererExt.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.shader_overrides; +package net.irisshaders.iris.compat.sodium.impl.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java similarity index 64% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java index 546dd3386e..b55a567765 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/RenderSectionExt.java @@ -1,6 +1,7 @@ -package net.coderbot.iris.compat.sodium.impl.shadow_map; +package net.irisshaders.iris.compat.sodium.impl.shadow_map; public interface RenderSectionExt { int getPreviousFrameShadow(); + void setPreviousFrameShadow(int frame); } diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java new file mode 100644 index 0000000000..1d5726cae4 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/shadow_map/SwappableRenderSectionManager.java @@ -0,0 +1,5 @@ +package net.irisshaders.iris.compat.sodium.impl.shadow_map; + +public interface SwappableRenderSectionManager { + void iris$swapVisibilityState(); +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java similarity index 88% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java index 4983d77eca..0c957d8024 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/EntityToTerrainVertexSerializer.java @@ -1,12 +1,11 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import net.caffeinemc.mods.sodium.api.util.NormI8; import net.caffeinemc.mods.sodium.api.vertex.format.common.ModelVertex; import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.GlyphVertexExt; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormalHelper; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormalHelper; import org.lwjgl.system.MemoryUtil; public class EntityToTerrainVertexSerializer implements VertexSerializer { diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java similarity index 83% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java index 85566684ae..8d172daf7d 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/GlyphExtVertexSerializer.java @@ -1,13 +1,12 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.QuadViewEntity; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormI8; -import net.coderbot.iris.vertices.NormalHelper; -import net.minecraft.client.renderer.texture.OverlayTexture; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.QuadViewEntity; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormI8; +import net.irisshaders.iris.vertices.NormalHelper; import org.joml.Vector3f; import org.lwjgl.system.MemoryUtil; @@ -21,32 +20,7 @@ public class GlyphExtVertexSerializer implements VertexSerializer { private static final int OFFSET_TANGENT = 46; private static final QuadViewEntity.QuadViewEntityUnsafe quad = new QuadViewEntity.QuadViewEntityUnsafe(); private static final Vector3f saveNormal = new Vector3f(); - - @Override - public void serialize(long src, long dst, int vertexCount) { - float uSum = 0.0f, vSum = 0.0f; - - for (int i = 0; i < vertexCount; i++) { - float u = MemoryUtil.memGetFloat(src + OFFSET_TEXTURE); - float v = MemoryUtil.memGetFloat(src + OFFSET_TEXTURE + 4); - - uSum += u; - vSum += v; - - MemoryUtil.memCopy(src, dst, 28); - - MemoryUtil.memPutShort(dst + 32, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()); - MemoryUtil.memPutShort(dst + 34, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); - MemoryUtil.memPutShort(dst + 36, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); - - src += DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP.getVertexSize(); - dst += IrisVertexFormats.GLYPH.getVertexSize(); - } - - endQuad(uSum, vSum, src, dst); - } - - private static int STRIDE = IrisVertexFormats.GLYPH.getVertexSize(); + private static final int STRIDE = IrisVertexFormats.GLYPH.getVertexSize(); private static void endQuad(float uSum, float vSum, long src, long dst) { uSum *= 0.25f; @@ -71,4 +45,28 @@ private static void endQuad(float uSum, float vSum, long src, long dst) { MemoryUtil.memPutInt(dst + OFFSET_TANGENT - STRIDE * vertex, tangent); } } + + @Override + public void serialize(long src, long dst, int vertexCount) { + float uSum = 0.0f, vSum = 0.0f; + + for (int i = 0; i < vertexCount; i++) { + float u = MemoryUtil.memGetFloat(src + OFFSET_TEXTURE); + float v = MemoryUtil.memGetFloat(src + OFFSET_TEXTURE + 4); + + uSum += u; + vSum += v; + + MemoryUtil.memCopy(src, dst, 28); + + MemoryUtil.memPutShort(dst + 32, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedEntity()); + MemoryUtil.memPutShort(dst + 34, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity()); + MemoryUtil.memPutShort(dst + 36, (short) CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); + + src += DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP.getVertexSize(); + dst += IrisVertexFormats.GLYPH.getVertexSize(); + } + + endQuad(uSum, vSum, src, dst); + } } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java similarity index 68% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java index e51bcbde08..4b34190dee 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisChunkMeshAttributes.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute; /** - * Initialized by {@link net.coderbot.iris.compat.sodium.mixin.vertex_format.MixinChunkMeshAttribute} + * Initialized by {@link net.irisshaders.iris.compat.sodium.mixin.vertex_format.MixinChunkMeshAttribute} */ public class IrisChunkMeshAttributes { public static ChunkMeshAttribute NORMAL; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java similarity index 69% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java index 020ca51936..7a68de4713 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisCommonVertexAttributes.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import net.caffeinemc.mods.sodium.api.vertex.attributes.CommonVertexAttribute; /** - * Initialized by {@link net.coderbot.iris.compat.sodium.mixin.vertex_format.MixinChunkMeshAttribute} + * Initialized by {@link net.irisshaders.iris.compat.sodium.mixin.vertex_format.MixinChunkMeshAttribute} */ public class IrisCommonVertexAttributes { public static CommonVertexAttribute TANGENT; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java new file mode 100644 index 0000000000..001b967fe9 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisEntityToTerrainVertexSerializer.java @@ -0,0 +1,30 @@ +package net.irisshaders.iris.compat.sodium.impl.vertex_format; + +import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import org.lwjgl.system.MemoryUtil; + +public class IrisEntityToTerrainVertexSerializer implements VertexSerializer { + @Override + public void serialize(long src, long dst, int vertexCount) { + for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) { + MemoryUtil.memPutFloat(dst, MemoryUtil.memGetFloat(src)); + MemoryUtil.memPutFloat(dst + 4, MemoryUtil.memGetFloat(src + 4L)); + MemoryUtil.memPutFloat(dst + 8, MemoryUtil.memGetFloat(src + 8L)); + MemoryUtil.memPutInt(dst + 12, MemoryUtil.memGetInt(src + 12L)); + MemoryUtil.memPutFloat(dst + 16, MemoryUtil.memGetFloat(src + 16L)); + MemoryUtil.memPutFloat(dst + 20, MemoryUtil.memGetFloat(src + 20L)); + MemoryUtil.memPutInt(dst + 24, MemoryUtil.memGetInt(src + 28L)); + MemoryUtil.memPutInt(dst + 28, MemoryUtil.memGetInt(src + 32L)); + MemoryUtil.memPutInt(dst + 32, 0); + MemoryUtil.memPutInt(dst + 36, MemoryUtil.memGetInt(src + 36L)); + MemoryUtil.memPutInt(dst + 40, MemoryUtil.memGetInt(src + 40L)); + MemoryUtil.memPutInt(dst + 44, MemoryUtil.memGetInt(src + 44L)); + + src += EntityVertex.STRIDE; + dst += IrisVertexFormats.TERRAIN.getVertexSize(); + } + + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java similarity index 58% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java index cdb7028db3..b398471df8 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisGlVertexAttributeFormat.java @@ -1,11 +1,11 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; -import net.coderbot.iris.compat.sodium.mixin.vertex_format.GlVertexAttributeFormatAccessor; +import net.irisshaders.iris.compat.sodium.mixin.vertex_format.GlVertexAttributeFormatAccessor; import org.lwjgl.opengl.GL20C; public class IrisGlVertexAttributeFormat { public static final GlVertexAttributeFormat BYTE = - GlVertexAttributeFormatAccessor.createGlVertexAttributeFormat(GL20C.GL_BYTE, 1); + GlVertexAttributeFormatAccessor.createGlVertexAttributeFormat(GL20C.GL_BYTE, 1); public static final GlVertexAttributeFormat SHORT = GlVertexAttributeFormatAccessor.createGlVertexAttributeFormat(GL20C.GL_SHORT, 2); } diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java new file mode 100644 index 0000000000..b40b991739 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/IrisModelVertexFormats.java @@ -0,0 +1,7 @@ +package net.irisshaders.iris.compat.sodium.impl.vertex_format; + +import net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType; + +public class IrisModelVertexFormats { + public static final XHFPModelVertexType MODEL_VERTEX_XHFP = new XHFPModelVertexType(); +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java similarity index 87% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java index b833dcd0ba..2424b1d65a 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/ModelToEntityVertexSerializer.java @@ -1,13 +1,11 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format; +package net.irisshaders.iris.compat.sodium.impl.vertex_format; import net.caffeinemc.mods.sodium.api.util.NormI8; import net.caffeinemc.mods.sodium.api.vertex.format.common.ModelVertex; import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.QuadViewEntity; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormalHelper; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormalHelper; import org.lwjgl.system.MemoryUtil; public class ModelToEntityVertexSerializer implements VertexSerializer { diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/SodiumBufferBuilderPolygonView.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/SodiumBufferBuilderPolygonView.java new file mode 100644 index 0000000000..babade60c7 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/SodiumBufferBuilderPolygonView.java @@ -0,0 +1,47 @@ +package net.irisshaders.iris.compat.sodium.impl.vertex_format; + +import net.caffeinemc.mods.sodium.api.vertex.attributes.common.PositionAttribute; +import net.caffeinemc.mods.sodium.api.vertex.attributes.common.TextureAttribute; +import net.irisshaders.iris.vertices.views.QuadView; + +public class SodiumBufferBuilderPolygonView implements QuadView { + private long ptr; + private int attributeOffsetPosition; + private int attributeOffsetTexture; + private int stride; + private int vertexAmount; + + public void setup(long ptr, int attributeOffsetPosition, int attributeOffsetTexture, int stride, int vertexAmount) { + this.ptr = ptr; + this.attributeOffsetPosition = attributeOffsetPosition; + this.attributeOffsetTexture = attributeOffsetTexture; + this.stride = stride; + this.vertexAmount = vertexAmount; + } + + @Override + public float x(int index) { + return PositionAttribute.getX(ptr + attributeOffsetPosition - (long) stride * (vertexAmount - index - 1)); + } + + @Override + public float y(int index) { + return PositionAttribute.getY(ptr + attributeOffsetPosition - (long) stride * (vertexAmount - index - 1)); + } + + @Override + public float z(int index) { + return PositionAttribute.getZ(ptr + attributeOffsetPosition - (long) stride * (vertexAmount - index - 1)); + } + + @Override + public float u(int index) { + return TextureAttribute.getU(ptr + attributeOffsetTexture - (long) stride * (vertexAmount - index - 1)); + } + + @Override + public float v(int index) { + return TextureAttribute.getV(ptr + attributeOffsetTexture - (long) stride * (vertexAmount - index - 1)); + } +} + diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java similarity index 85% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java index 7f35724da6..b757297871 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/CloudVertex.java @@ -1,11 +1,11 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp; import net.caffeinemc.mods.sodium.api.math.MatrixHelper; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatRegistry; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormI8; -import net.coderbot.iris.vertices.NormalHelper; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormI8; +import net.irisshaders.iris.vertices.NormalHelper; import org.joml.Matrix4f; import org.joml.Vector3f; import org.lwjgl.system.MemoryUtil; @@ -46,11 +46,11 @@ public static void write(long ptr, Matrix4f matrix, float x, float y, float z, i public static void write(long ptr, float x, float y, float z, int color) { vertexCount++; - MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 0, x); + MemoryUtil.memPutFloat(ptr + OFFSET_POSITION, x); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 4, y); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 8, z); - MemoryUtil.memPutInt(ptr + OFFSET_COLOR + 0, color); + MemoryUtil.memPutInt(ptr + OFFSET_COLOR, color); if (vertexCount == 4) { vertexCount = 0; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java similarity index 88% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java index 581ddda7cf..9642dd6132 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/EntityVertex.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp; import com.mojang.blaze3d.vertex.PoseStack; import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; @@ -9,11 +9,9 @@ import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatRegistry; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormalHelper; -import net.coderbot.iris.vertices.QuadView; -import org.jetbrains.annotations.NotNull; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormalHelper; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; @@ -33,17 +31,18 @@ public final class EntityVertex { private static final int OFFSET_NORMAL = 32; private static final int OFFSET_TANGENT = 50; - private static Vector3f lastNormal = new Vector3f(); + private static final Vector3f lastNormal = new Vector3f(); + private static final QuadViewEntity.QuadViewEntityUnsafe quadView = new QuadViewEntity.QuadViewEntityUnsafe(); public static void write(long ptr, float x, float y, float z, int color, float u, float v, float midU, float midV, int light, int overlay, int normal, int tangent) { - MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 0, x); + MemoryUtil.memPutFloat(ptr + OFFSET_POSITION, x); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 4, y); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 8, z); MemoryUtil.memPutInt(ptr + OFFSET_COLOR, color); - MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 0, u); + MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE, u); MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 4, v); MemoryUtil.memPutInt(ptr + OFFSET_LIGHT, light); @@ -63,14 +62,14 @@ public static void write(long ptr, } public static void write2(long ptr, - float x, float y, float z, int color, float u, float v, float midU, float midV, int light, int overlay, int normal) { - MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 0, x); + float x, float y, float z, int color, float u, float v, float midU, float midV, int light, int overlay, int normal) { + MemoryUtil.memPutFloat(ptr + OFFSET_POSITION, x); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 4, y); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 8, z); MemoryUtil.memPutInt(ptr + OFFSET_COLOR, color); - MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 0, u); + MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE, u); MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 4, v); MemoryUtil.memPutInt(ptr + OFFSET_LIGHT, light); @@ -163,7 +162,6 @@ public static void writeQuadVertices(VertexBufferWriter writer, PoseStack.Pose m writer.push(stack, buffer, 4, FORMAT); } } - private static QuadViewEntity.QuadViewEntityUnsafe quadView = new QuadViewEntity.QuadViewEntityUnsafe(); private static void endQuad(long ptr, float normalX, float normalY, float normalZ) { quadView.setup(ptr, STRIDE); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java similarity index 91% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java index ca438be236..7f04c28949 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/GlyphVertexExt.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp; import com.mojang.blaze3d.vertex.PoseStack; import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; @@ -6,10 +6,9 @@ import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatRegistry; -import net.coderbot.iris.uniforms.CapturedRenderingState; -import net.coderbot.iris.vertices.IrisVertexFormats; -import net.coderbot.iris.vertices.NormalHelper; -import net.minecraft.client.renderer.texture.OverlayTexture; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.vertices.NormalHelper; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.joml.Vector3f; @@ -31,13 +30,12 @@ public final class GlyphVertexExt { private static final QuadViewEntity.QuadViewEntityUnsafe quad = new QuadViewEntity.QuadViewEntityUnsafe(); private static final Vector3f saveNormal = new Vector3f(); - + private static final Vector3f lastNormal = new Vector3f(); + private static final QuadViewEntity.QuadViewEntityUnsafe quadView = new QuadViewEntity.QuadViewEntityUnsafe(); private static int vertexCount; private static float uSum; private static float vSum; - private static Vector3f lastNormal = new Vector3f(); - public static void write(long ptr, float x, float y, float z, int color, float u, float v, int light) { long i = ptr; @@ -45,13 +43,13 @@ public static void write(long ptr, float x, float y, float z, int color, float u uSum += u; vSum += v; - MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 0, x); + MemoryUtil.memPutFloat(ptr + OFFSET_POSITION, x); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 4, y); MemoryUtil.memPutFloat(ptr + OFFSET_POSITION + 8, z); MemoryUtil.memPutInt(ptr + OFFSET_COLOR, color); - MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 0, u); + MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE, u); MemoryUtil.memPutFloat(ptr + OFFSET_TEXTURE + 4, v); MemoryUtil.memPutInt(ptr + OFFSET_LIGHT, light); @@ -93,6 +91,7 @@ private static void endQuad(long ptr) { uSum = 0; vSum = 0; } + public static void writeQuadVertices(VertexBufferWriter writer, PoseStack.Pose matrices, ModelQuadView quad, int light, int color) { Matrix3f matNormal = matrices.normal(); Matrix4f matPosition = matrices.pose(); @@ -135,7 +134,6 @@ public static void writeQuadVertices(VertexBufferWriter writer, PoseStack.Pose m writer.push(stack, buffer, 4, FORMAT); } } - private static QuadViewEntity.QuadViewEntityUnsafe quadView = new QuadViewEntity.QuadViewEntityUnsafe(); private static void endQuad(long ptr, float normalX, float normalY, float normalZ) { quadView.setup(ptr, STRIDE); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java similarity index 90% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java index f216e91de7..00fe6c5929 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewClouds.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp; -import net.coderbot.iris.vertices.QuadView; +import net.irisshaders.iris.vertices.views.QuadView; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java similarity index 91% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java index 4e516a6367..05043aa774 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/entity_xhfp/QuadViewEntity.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp; -import net.coderbot.iris.vertices.QuadView; +import net.irisshaders.iris.vertices.views.QuadView; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java similarity index 81% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java index 3eeed94b06..a790752f04 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/QuadViewTerrain.java @@ -1,6 +1,6 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.terrain_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp; -import net.coderbot.iris.vertices.QuadView; +import net.irisshaders.iris.vertices.views.QuadView; import org.lwjgl.system.MemoryUtil; import java.nio.ByteBuffer; @@ -11,27 +11,27 @@ public abstract class QuadViewTerrain implements QuadView { @Override public float x(int index) { - return XHFPModelVertexType.decodePosition(getShort(writePointer - stride * (3 - index))); + return XHFPModelVertexType.decodePosition(getShort(writePointer - (long) stride * (3 - index))); } @Override public float y(int index) { - return XHFPModelVertexType.decodePosition(getShort(writePointer + 2 - stride * (3 - index))); + return XHFPModelVertexType.decodePosition(getShort(writePointer + 2 - (long) stride * (3 - index))); } @Override public float z(int index) { - return XHFPModelVertexType.decodePosition(getShort(writePointer + 4 - stride * (3 - index))); + return XHFPModelVertexType.decodePosition(getShort(writePointer + 4 - (long) stride * (3 - index))); } @Override public float u(int index) { - return XHFPModelVertexType.decodeBlockTexture(getShort(writePointer + 12 - stride * (3 - index))); + return XHFPModelVertexType.decodeBlockTexture(getShort(writePointer + 12 - (long) stride * (3 - index))); } @Override public float v(int index) { - return XHFPModelVertexType.decodeBlockTexture(getShort(writePointer + 14 - stride * (3 - index))); + return XHFPModelVertexType.decodeBlockTexture(getShort(writePointer + 14 - (long) stride * (3 - index))); } abstract short getShort(long writePointer); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java similarity index 91% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java index c4c282362b..29ab029b2f 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPModelVertexType.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.terrain_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisGlVertexAttributeFormat; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisGlVertexAttributeFormat; /** * Like HFPModelVertexType, but extended to support Iris. The extensions aren't particularly efficient right now. @@ -22,7 +22,7 @@ public class XHFPModelVertexType implements ChunkVertexType { .addElement(IrisChunkMeshAttributes.TANGENT, 24, IrisGlVertexAttributeFormat.BYTE, 4, true, false) .addElement(IrisChunkMeshAttributes.NORMAL, 28, IrisGlVertexAttributeFormat.BYTE, 3, true, false) .addElement(IrisChunkMeshAttributes.BLOCK_ID, 32, IrisGlVertexAttributeFormat.SHORT, 2, false, false) - .addElement(IrisChunkMeshAttributes.MID_BLOCK, 36, IrisGlVertexAttributeFormat.BYTE, 3, false, false) + .addElement(IrisChunkMeshAttributes.MID_BLOCK, 36, IrisGlVertexAttributeFormat.BYTE, 4, false, false) .build(); private static final int POSITION_MAX_VALUE = 65536; @@ -36,6 +36,23 @@ public class XHFPModelVertexType implements ChunkVertexType { private static final float TEXTURE_SCALE = (1.0f / TEXTURE_MAX_VALUE); + public static int encodeTexture(float u, float v) { + return ((Math.round(u * TEXTURE_MAX_VALUE) & 0xFFFF) << 0) | + ((Math.round(v * TEXTURE_MAX_VALUE) & 0xFFFF) << 16); + } + + static float decodeBlockTexture(short raw) { + return (raw & 0xFFFF) * TEXTURE_SCALE; + } + + static short encodePosition(float v) { + return (short) ((MODEL_ORIGIN + v) * MODEL_SCALE_INV); + } + + static float decodePosition(short raw) { + return (raw & 0xFFFF) * MODEL_SCALE - MODEL_ORIGIN; + } + @Override public float getTextureScale() { return TEXTURE_SCALE; @@ -60,21 +77,4 @@ public GlVertexFormat getVertexFormat() { public ChunkVertexEncoder getEncoder() { return new XHFPTerrainVertex(); } - - public static int encodeTexture(float u, float v) { - return ((Math.round(u * TEXTURE_MAX_VALUE) & 0xFFFF) << 0) | - ((Math.round(v * TEXTURE_MAX_VALUE) & 0xFFFF) << 16); - } - - static float decodeBlockTexture(short raw) { - return (raw & 0xFFFF) * TEXTURE_SCALE; - } - - static short encodePosition(float v) { - return (short) ((MODEL_ORIGIN + v) * MODEL_SCALE_INV); - } - - static float decodePosition(short raw) { - return (raw & 0xFFFF) * MODEL_SCALE - MODEL_ORIGIN; - } } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java similarity index 89% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java index a70b2edb81..a8a408f465 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/impl/vertex_format/terrain_xhfp/XHFPTerrainVertex.java @@ -1,16 +1,16 @@ -package net.coderbot.iris.compat.sodium.impl.vertex_format.terrain_xhfp; +package net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp; import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.Material; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder; -import net.coderbot.iris.compat.sodium.impl.block_context.BlockContextHolder; -import net.coderbot.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; -import net.coderbot.iris.vertices.NormI8; +import net.irisshaders.iris.compat.sodium.impl.block_context.BlockContextHolder; +import net.irisshaders.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; +import net.irisshaders.iris.vertices.ExtendedDataHelper; +import net.irisshaders.iris.vertices.NormI8; +import net.irisshaders.iris.vertices.NormalHelper; import org.joml.Vector3f; -import net.coderbot.iris.vertices.ExtendedDataHelper; -import net.coderbot.iris.vertices.NormalHelper; import org.lwjgl.system.MemoryUtil; -import static net.coderbot.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType.STRIDE; +import static net.irisshaders.iris.compat.sodium.impl.vertex_format.terrain_xhfp.XHFPModelVertexType.STRIDE; public class XHFPTerrainVertex implements ChunkVertexEncoder, ContextAwareVertexWriter { private final QuadViewTerrain.QuadViewTerrainUnsafe quad = new QuadViewTerrain.QuadViewTerrainUnsafe(); @@ -66,7 +66,7 @@ public long write(long ptr, vSum += vertex.v; vertexCount++; - MemoryUtil.memPutShort(ptr + 0L, XHFPModelVertexType.encodePosition(vertex.x)); + MemoryUtil.memPutShort(ptr, XHFPModelVertexType.encodePosition(vertex.x)); MemoryUtil.memPutShort(ptr + 2L, XHFPModelVertexType.encodePosition(vertex.y)); MemoryUtil.memPutShort(ptr + 4L, XHFPModelVertexType.encodePosition(vertex.z)); MemoryUtil.memPutByte(ptr + 6L, (byte) material.bits()); @@ -81,6 +81,7 @@ public long write(long ptr, MemoryUtil.memPutShort(ptr + 32, contextHolder.blockId); MemoryUtil.memPutShort(ptr + 34, contextHolder.renderType); MemoryUtil.memPutInt(ptr + 36, contextHolder.ignoreMidBlock ? 0 : ExtendedDataHelper.computeMidBlock(vertex.x, vertex.y, vertex.z, contextHolder.localPosX, contextHolder.localPosY, contextHolder.localPosZ)); + MemoryUtil.memPutByte(ptr + 39, contextHolder.lightValue); if (vertexCount == 4) { vertexCount = 0; @@ -139,7 +140,6 @@ public long write(long ptr, int packedNormal = NormI8.pack(normal); - MemoryUtil.memPutInt(ptr + 28, packedNormal); MemoryUtil.memPutInt(ptr + 28 - STRIDE, packedNormal); MemoryUtil.memPutInt(ptr + 28 - STRIDE * 2, packedNormal); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java similarity index 96% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java index 1042462b47..16ecb7bdef 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/IrisSodiumCompatMixinPlugin.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin; +package net.irisshaders.iris.compat.sodium.mixin; import net.minecraftforge.fml.loading.LoadingModList; import org.objectweb.asm.tree.ClassNode; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java similarity index 79% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java index 468b56f3b3..0ef9d5444f 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinBakedChunkModelBuilder.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.compat.sodium.mixin.block_id; +package net.irisshaders.iris.compat.sodium.mixin.block_id; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.BakedChunkModelBuilder; import me.jellysquid.mods.sodium.client.render.chunk.vertex.builder.ChunkMeshBufferBuilder; -import net.coderbot.iris.compat.sodium.impl.block_context.BlockContextHolder; -import net.coderbot.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; +import net.irisshaders.iris.compat.sodium.impl.block_context.BlockContextHolder; +import net.irisshaders.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java similarity index 82% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java index 7086c55537..a60dd3b2e8 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkBuildBuffers.java @@ -1,16 +1,15 @@ -package net.coderbot.iris.compat.sodium.mixin.block_id; +package net.irisshaders.iris.compat.sodium.mixin.block_id; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Reference2ReferenceOpenHashMap; -import me.jellysquid.mods.sodium.client.SodiumClientMod; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.BakedChunkModelBuilder; import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.block_context.BlockContextHolder; -import net.coderbot.iris.compat.sodium.impl.block_context.ChunkBuildBuffersExt; -import net.coderbot.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; +import net.irisshaders.iris.compat.sodium.impl.block_context.BlockContextHolder; +import net.irisshaders.iris.compat.sodium.impl.block_context.ChunkBuildBuffersExt; +import net.irisshaders.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.world.level.block.state.BlockState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -34,7 +33,7 @@ public class MixinChunkBuildBuffers implements ChunkBuildBuffersExt { @Inject(method = "", at = @At("RETURN"), remap = false) private void iris$onConstruct(ChunkVertexType vertexType, CallbackInfo ci) { - Object2IntMap blockStateIds = BlockRenderingSettings.INSTANCE.getBlockStateIds(); + Object2IntMap blockStateIds = WorldRenderingSettings.INSTANCE.getBlockStateIds(); if (blockStateIds != null) { this.contextHolder = new BlockContextHolder(blockStateIds); @@ -58,8 +57,8 @@ public class MixinChunkBuildBuffers implements ChunkBuildBuffersExt { } @Override - public void iris$setMaterialId(BlockState state, short renderType) { - this.contextHolder.set(state, renderType); + public void iris$setMaterialId(BlockState state, short renderType, byte lightValue) { + this.contextHolder.set(state, renderType, lightValue); } @Override diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java similarity index 84% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java index ffae9d4e86..e34bb66277 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkRenderRebuildTask.java @@ -1,26 +1,22 @@ -package net.coderbot.iris.compat.sodium.mixin.block_id; +package net.irisshaders.iris.compat.sodium.mixin.block_id; import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildBuffers; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildContext; import me.jellysquid.mods.sodium.client.render.chunk.compile.ChunkBuildOutput; +import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuilder; import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockRenderCache; import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.BlockRenderContext; -import me.jellysquid.mods.sodium.client.render.chunk.compile.buffers.ChunkModelBuilder; -import me.jellysquid.mods.sodium.client.render.chunk.compile.pipeline.FluidRenderer; import me.jellysquid.mods.sodium.client.render.chunk.compile.tasks.ChunkBuilderMeshingTask; import me.jellysquid.mods.sodium.client.render.chunk.data.BuiltSectionInfo; import me.jellysquid.mods.sodium.client.render.chunk.terrain.material.DefaultMaterials; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder; import me.jellysquid.mods.sodium.client.util.task.CancellationToken; import me.jellysquid.mods.sodium.client.world.WorldSlice; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.block_context.ChunkBuildBuffersExt; -import net.coderbot.iris.vertices.ExtendedDataHelper; -import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.renderer.block.BlockModelShaper; +import net.irisshaders.iris.compat.sodium.impl.block_context.ChunkBuildBuffersExt; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import net.irisshaders.iris.vertices.ExtendedDataHelper; import net.minecraft.client.renderer.chunk.VisGraph; -import net.minecraft.client.resources.model.BakedModel; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.LightBlock; import net.minecraft.world.level.block.state.BlockState; @@ -36,7 +32,7 @@ */ @Mixin(ChunkBuilderMeshingTask.class) public class MixinChunkRenderRebuildTask { - private ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad(); + private final ChunkVertexEncoder.Vertex[] vertices = ChunkVertexEncoder.Vertex.uninitializedQuad(); @Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", at = @At(value = "INVOKE", target = "net/minecraft/world/level/block/state/BlockState.getRenderShape()" + @@ -49,11 +45,11 @@ public class MixinChunkRenderRebuildTask { WorldSlice slice, int baseX, int baseY, int baseZ, int maxX, int maxY, int maxZ, BlockPos.MutableBlockPos pos, BlockPos.MutableBlockPos renderOffset, BlockRenderContext context2, int relY, int relZ, int relX, BlockState blockState) { - if (BlockRenderingSettings.INSTANCE.shouldVoxelizeLightBlocks() && blockState.getBlock() instanceof LightBlock) { + if (WorldRenderingSettings.INSTANCE.shouldVoxelizeLightBlocks() && blockState.getBlock() instanceof LightBlock) { ChunkModelBuilder buildBuffers = buffers.get(DefaultMaterials.CUTOUT); ((ChunkBuildBuffersExt) buffers).iris$setLocalPos(0, 0, 0); ((ChunkBuildBuffersExt) buffers).iris$ignoreMidBlock(true); - ((ChunkBuildBuffersExt) buffers).iris$setMaterialId(blockState, (short) 0); + ((ChunkBuildBuffersExt) buffers).iris$setMaterialId(blockState, (short) 0, (byte) blockState.getLightEmission()); for (int i = 0; i < 4; i++) { vertices[i].x = (float) ((relX & 15)) + 0.25f; vertices[i].y = (float) ((relY & 15)) + 0.25f; @@ -74,7 +70,7 @@ public class MixinChunkRenderRebuildTask { } @Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", at = @At(value = "INVOKE", - target = "Lnet/minecraft/client/renderer/block/BlockModelShaper;getBlockModel(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/client/resources/model/BakedModel;"), locals = LocalCapture.CAPTURE_FAILHARD) + target = "Lnet/minecraft/client/renderer/block/BlockModelShaper;getBlockModel(Lnet/minecraft/world/level/block/state/BlockState;)Lnet/minecraft/client/resources/model/BakedModel;"), locals = LocalCapture.CAPTURE_FAILHARD) private void iris$wrapGetBlockLayer(ChunkBuildContext context, CancellationToken cancellationSource, CallbackInfoReturnable cir, BuiltSectionInfo.Builder renderData, VisGraph occluder, ChunkBuildBuffers buffers, @@ -83,12 +79,12 @@ public class MixinChunkRenderRebuildTask { BlockPos.MutableBlockPos pos, BlockPos.MutableBlockPos renderOffset, BlockRenderContext context2, int relY, int relZ, int relX, BlockState blockState) { if (context.buffers instanceof ChunkBuildBuffersExt) { - ((ChunkBuildBuffersExt) context.buffers).iris$setMaterialId(blockState, ExtendedDataHelper.BLOCK_RENDER_TYPE); + ((ChunkBuildBuffersExt) context.buffers).iris$setMaterialId(blockState, ExtendedDataHelper.BLOCK_RENDER_TYPE, (byte) blockState.getLightEmission()); } } - @Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", at = @At(value = "INVOKE", - target = "Lme/jellysquid/mods/sodium/client/render/chunk/compile/pipeline/FluidRenderer;render(Lme/jellysquid/mods/sodium/client/world/WorldSlice;Lnet/minecraft/world/level/material/FluidState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildBuffers;)V"), locals = LocalCapture.CAPTURE_FAILHARD, remap = false) + @Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", remap = false, at = @At(value = "INVOKE", + target = "Lme/jellysquid/mods/sodium/client/render/chunk/compile/pipeline/FluidRenderer;render(Lme/jellysquid/mods/sodium/client/world/WorldSlice;Lnet/minecraft/world/level/material/FluidState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildBuffers;)V"), locals = LocalCapture.CAPTURE_FAILHARD) private void iris$wrapGetFluidLayer(ChunkBuildContext context, CancellationToken cancellationSource, CallbackInfoReturnable cir, BuiltSectionInfo.Builder renderData, VisGraph occluder, ChunkBuildBuffers buffers, @@ -97,12 +93,12 @@ public class MixinChunkRenderRebuildTask { BlockPos.MutableBlockPos pos, BlockPos.MutableBlockPos renderOffset, BlockRenderContext context2, int relY, int relZ, int relX, BlockState blockState, FluidState fluidState) { if (context.buffers instanceof ChunkBuildBuffersExt) { - ((ChunkBuildBuffersExt) context.buffers).iris$setMaterialId(fluidState.createLegacyBlock(), ExtendedDataHelper.FLUID_RENDER_TYPE); + ((ChunkBuildBuffersExt) context.buffers).iris$setMaterialId(fluidState.createLegacyBlock(), ExtendedDataHelper.FLUID_RENDER_TYPE, (byte) blockState.getLightEmission()); } } @Inject(method = "execute(Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildContext;Lme/jellysquid/mods/sodium/client/util/task/CancellationToken;)Lme/jellysquid/mods/sodium/client/render/chunk/compile/ChunkBuildOutput;", - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;hasBlockEntity()Z")) + at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;hasBlockEntity()Z")) private void iris$resetContext(ChunkBuildContext buildContext, CancellationToken cancellationSource, CallbackInfoReturnable cir) { if (buildContext.buffers instanceof ChunkBuildBuffersExt) { ((ChunkBuildBuffersExt) buildContext.buffers).iris$resetBlockContext(); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java similarity index 79% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java index 14980c96cf..a022a28893 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/block_id/MixinChunkVertexBufferBuilder.java @@ -1,9 +1,9 @@ -package net.coderbot.iris.compat.sodium.mixin.block_id; +package net.irisshaders.iris.compat.sodium.mixin.block_id; import me.jellysquid.mods.sodium.client.render.chunk.vertex.builder.ChunkMeshBufferBuilder; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexEncoder; -import net.coderbot.iris.compat.sodium.impl.block_context.BlockContextHolder; -import net.coderbot.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; +import net.irisshaders.iris.compat.sodium.impl.block_context.BlockContextHolder; +import net.irisshaders.iris.compat.sodium.impl.block_context.ContextAwareVertexWriter; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java similarity index 81% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java index 8858f2527f..ecd372b7f1 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/clouds/MixinCloudRenderer.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.clouds; +package net.irisshaders.iris.compat.sodium.mixin.clouds; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; @@ -10,14 +10,13 @@ import me.jellysquid.mods.sodium.client.render.immediate.CloudRenderer; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; import net.caffeinemc.mods.sodium.api.vertex.format.common.ColorVertex; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.CloudVertex; -import net.coderbot.iris.pipeline.WorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.CoreWorldRenderingPipeline; -import net.coderbot.iris.pipeline.newshader.ShaderKey; -import net.coderbot.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.Iris; import net.irisshaders.iris.api.v0.IrisApi; -import net.minecraft.client.CloudStatus; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.CloudVertex; +import net.irisshaders.iris.pipeline.ShaderRenderingPipeline; +import net.irisshaders.iris.pipeline.WorldRenderingPipeline; +import net.irisshaders.iris.pipeline.programs.ShaderKey; +import net.irisshaders.iris.vertices.IrisVertexFormats; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; @@ -39,27 +38,31 @@ @Mixin(CloudRenderer.class) public abstract class MixinCloudRenderer { - @Shadow - protected abstract void rebuildGeometry(BufferBuilder bufferBuilder, int cloudDistance, int centerCellX, int centerCellZ); - @Shadow private ShaderInstance shader; - - @Shadow - protected abstract void applyFogModifiers(ClientLevel world, FogRenderer.FogData fogData, LocalPlayer player, int cloudDistance, float tickDelta); - @Shadow @Final private FogRenderer.FogData fogData; - @Shadow - private CloudStatus cloudRenderMode; @Unique private VertexBuffer vertexBufferWithNormals; - @Unique private int prevCenterCellXIris, prevCenterCellYIris, cachedRenderDistanceIris; - @Inject(method = "render", at = @At(value = "HEAD"), cancellable = true, remap = false) + @Inject(method = "writeVertex", at = @At("HEAD"), cancellable = true, remap = false) + private static void writeIrisVertex(long buffer, float x, float y, float z, int color, CallbackInfoReturnable cir) { + if (IrisApi.getInstance().isShaderPackInUse()) { + CloudVertex.write(buffer, x, y, z, color); + cir.setReturnValue(buffer + 20L); + } + } + + @Shadow + protected abstract void rebuildGeometry(BufferBuilder bufferBuilder, int cloudDistance, int centerCellX, int centerCellZ); + + @Shadow + protected abstract void applyFogModifiers(ClientLevel world, FogRenderer.FogData fogData, LocalPlayer player, int cloudDistance, float tickDelta); + + @Inject(method = "render", remap = false, at = @At(value = "HEAD"), cancellable = true) private void buildIrisVertexBuffer(ClientLevel world, LocalPlayer player, PoseStack matrices, Matrix4f projectionMatrix, float ticks, float tickDelta, double cameraX, double cameraY, double cameraZ, CallbackInfo ci) { if (IrisApi.getInstance().isShaderPackInUse()) { ci.cancel(); @@ -72,15 +75,10 @@ public void renderIris(@Nullable ClientLevel world, LocalPlayer player, PoseStac return; } - float cloudHeight = world.effects().getCloudHeight(); - - // Vanilla uses NaN height as a way to disable cloud rendering - if (Float.isNaN(cloudHeight)) { - return; - } - Vec3 color = world.getCloudColor(tickDelta); + float cloudHeight = world.effects().getCloudHeight(); + double cloudTime = (ticks + tickDelta) * 0.03F; double cloudCenterX = (cameraX + cloudTime); double cloudCenterZ = (cameraZ) + 0.33D; @@ -91,10 +89,9 @@ public void renderIris(@Nullable ClientLevel world, LocalPlayer player, PoseStac int centerCellX = (int) (Math.floor(cloudCenterX / 12)); int centerCellZ = (int) (Math.floor(cloudCenterZ / 12)); - if (this.vertexBufferWithNormals == null || this.prevCenterCellXIris != centerCellX || this.prevCenterCellYIris != centerCellZ || this.cachedRenderDistanceIris != renderDistance || this.cloudRenderMode != Minecraft.getInstance().options.getCloudsType()) { + if (this.vertexBufferWithNormals == null || this.prevCenterCellXIris != centerCellX || this.prevCenterCellYIris != centerCellZ || this.cachedRenderDistanceIris != renderDistance) { BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder(); bufferBuilder.begin(VertexFormat.Mode.QUADS, IrisVertexFormats.CLOUDS); - this.cloudRenderMode = Minecraft.getInstance().options.getCloudsType(); // Give some space for shaders this.rebuildGeometry(bufferBuilder, cloudDistance + 4, centerCellX, centerCellZ); @@ -133,7 +130,7 @@ public void renderIris(@Nullable ClientLevel world, LocalPlayer player, PoseStac boolean insideClouds = cameraY < cloudHeight + 4.5f && cameraY > cloudHeight - 0.5f; - if (insideClouds || (cloudRenderMode == CloudStatus.FAST)) { + if (insideClouds) { RenderSystem.disableCull(); } else { RenderSystem.enableCull(); @@ -178,20 +175,12 @@ public void renderIris(@Nullable ClientLevel world, LocalPlayer player, PoseStac RenderSystem.setShaderFogStart(previousStart); } - @ModifyArg(method = "rebuildGeometry", at = @At(value = "INVOKE", target = "Lorg/lwjgl/system/MemoryStack;nmalloc(I)J"), remap = false) + @ModifyArg(method = "rebuildGeometry", remap = false, at = @At(value = "INVOKE", target = "Lorg/lwjgl/system/MemoryStack;nmalloc(I)J")) private int allocateNewSize(int size) { return IrisApi.getInstance().isShaderPackInUse() ? 480 : size; } - @Inject(method = "writeVertex", at = @At("HEAD"), cancellable = true, remap = false) - private static void writeIrisVertex(long buffer, float x, float y, float z, int color, CallbackInfoReturnable cir) { - if (IrisApi.getInstance().isShaderPackInUse()) { - CloudVertex.write(buffer, x, y, z, color); - cir.setReturnValue(buffer + 20L); - } - } - - @ModifyArg(method = "rebuildGeometry", at = @At(value = "INVOKE", target = "Lnet/caffeinemc/mods/sodium/api/vertex/buffer/VertexBufferWriter;push(Lorg/lwjgl/system/MemoryStack;JILnet/caffeinemc/mods/sodium/api/vertex/format/VertexFormatDescription;)V"), index = 3, remap = false) + @ModifyArg(method = "rebuildGeometry", remap = false, at = @At(value = "INVOKE", target = "Lnet/caffeinemc/mods/sodium/api/vertex/buffer/VertexBufferWriter;push(Lorg/lwjgl/system/MemoryStack;JILnet/caffeinemc/mods/sodium/api/vertex/format/VertexFormatDescription;)V"), index = 3) private VertexFormatDescription modifyArgIris(VertexFormatDescription vertexFormatDescription) { if (IrisApi.getInstance().isShaderPackInUse()) { return CloudVertex.FORMAT; @@ -203,8 +192,8 @@ private VertexFormatDescription modifyArgIris(VertexFormatDescription vertexForm private ShaderInstance getClouds() { WorldRenderingPipeline pipeline = Iris.getPipelineManager().getPipelineNullable(); - if (pipeline instanceof CoreWorldRenderingPipeline) { - return ((CoreWorldRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.CLOUDS_SODIUM); + if (pipeline instanceof ShaderRenderingPipeline) { + return ((ShaderRenderingPipeline) pipeline).getShaderMap().getShader(ShaderKey.CLOUDS_SODIUM); } return shader; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java new file mode 100644 index 0000000000..f26634680a --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/CuboidMixin.java @@ -0,0 +1,31 @@ +package net.irisshaders.iris.compat.sodium.mixin.copyEntity; + +import me.jellysquid.mods.sodium.client.model.ModelCuboidAccessor; +import me.jellysquid.mods.sodium.client.render.immediate.model.ModelCuboid; +import net.minecraft.client.model.geom.ModelPart; +import net.minecraft.core.Direction; +import org.objectweb.asm.Opcodes; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.Set; + +@Mixin(ModelPart.Cube.class) +public class CuboidMixin implements ModelCuboidAccessor { + @Unique + private ModelCuboid sodium$cuboid; + + // Inject at the start of the function, so we don't capture modified locals + @Inject(method = "", at = @At(value = "FIELD", opcode = Opcodes.PUTFIELD, target = "Lnet/minecraft/client/model/geom/ModelPart$Cube;polygons:[Lnet/minecraft/client/model/geom/ModelPart$Polygon;", ordinal = 0)) + private void onInit(int u, int v, float x, float y, float z, float sizeX, float sizeY, float sizeZ, float extraX, float extraY, float extraZ, boolean mirror, float textureWidth, float textureHeight, Set renderDirections, CallbackInfo ci) { + this.sodium$cuboid = new ModelCuboid(u, v, x, y, z, sizeX, sizeY, sizeZ, extraX, extraY, extraZ, mirror, textureWidth, textureHeight, renderDirections); + } + + @Override + public ModelCuboid sodium$copy() { + return this.sodium$cuboid; + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java similarity index 92% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java index af28bf8eb6..44d307f491 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/ModelPartMixin.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.copyEntity; +package net.irisshaders.iris.compat.sodium.mixin.copyEntity; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; @@ -11,7 +11,12 @@ import net.caffeinemc.mods.sodium.api.util.ColorABGR; import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.minecraft.client.model.geom.ModelPart; -import org.spongepowered.asm.mixin.*; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Overwrite; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java new file mode 100644 index 0000000000..9eeb616957 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/cull/EntityRendererMixin.java @@ -0,0 +1,27 @@ +package net.irisshaders.iris.compat.sodium.mixin.copyEntity.cull; + +import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; +import net.minecraft.client.renderer.culling.Frustum; +import net.minecraft.client.renderer.entity.EntityRenderer; +import net.minecraft.world.entity.Entity; +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; + +@Mixin(EntityRenderer.class) +public abstract class EntityRendererMixin { + @Inject(method = "shouldRender", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/renderer/culling/Frustum;isVisible(Lnet/minecraft/world/phys/AABB;)Z", shift = At.Shift.AFTER), cancellable = true) + private void preShouldRender(T entity, Frustum frustum, double x, double y, double z, CallbackInfoReturnable cir) { + var renderer = SodiumWorldRenderer.instanceNullable(); + + if (renderer == null) { + return; + } + + // If the entity isn't culled already by other means, try to perform a second pass + if (cir.getReturnValue() && !renderer.isEntityVisible(entity)) { + cir.setReturnValue(false); + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java similarity index 98% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java index 4d78b1de07..6530f58bf3 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/copyEntity/shadows/EntityRenderDispatcherMixin.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.compat.sodium.mixin.copyEntity.shadows; +package net.irisshaders.iris.compat.sodium.mixin.copyEntity.shadows; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import me.jellysquid.mods.sodium.client.render.vertex.VertexConsumerUtils; +import net.caffeinemc.mods.sodium.api.math.MatrixHelper; +import net.caffeinemc.mods.sodium.api.util.ColorABGR; import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.common.ModelVertex; -import net.caffeinemc.mods.sodium.api.util.ColorABGR; -import net.caffeinemc.mods.sodium.api.math.MatrixHelper; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; import net.minecraft.client.renderer.texture.OverlayTexture; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java similarity index 66% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java index 42c73a1156..c487146403 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinFlatLightPipeline.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.directional_shading; +package net.irisshaders.iris.compat.sodium.mixin.directional_shading; import me.jellysquid.mods.sodium.client.model.light.flat.FlatLightPipeline; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockAndTintGetter; import org.spongepowered.asm.mixin.Mixin; @@ -11,9 +11,9 @@ @Mixin(FlatLightPipeline.class) public class MixinFlatLightPipeline { @Redirect(method = "calculate", at = @At(value = "INVOKE", - target = "net/minecraft/world/level/BlockAndTintGetter.getShade (Lnet/minecraft/core/Direction;Z)F")) + target = "net/minecraft/world/level/BlockAndTintGetter.getShade (Lnet/minecraft/core/Direction;Z)F")) private float iris$getBrightness(BlockAndTintGetter level, Direction direction, boolean shaded) { - if (BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { + if (WorldRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { return 1.0F; } else { return level.getShade(direction, shaded); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java similarity index 77% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java index 39ed530a89..0a2d24adc6 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/directional_shading/MixinSmoothLightPipeline.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.compat.sodium.mixin.directional_shading; +package net.irisshaders.iris.compat.sodium.mixin.directional_shading; import me.jellysquid.mods.sodium.client.model.light.data.QuadLightData; import me.jellysquid.mods.sodium.client.model.light.smooth.SmoothLightPipeline; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import net.minecraft.core.Direction; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -13,7 +13,7 @@ public class MixinSmoothLightPipeline { @Inject(method = "applySidedBrightness", at = @At("HEAD"), cancellable = true, remap = false) private void iris$disableDirectionalShading(QuadLightData out, Direction face, boolean shade, CallbackInfo ci) { - if (BlockRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { + if (WorldRenderingSettings.INSTANCE.shouldDisableDirectionalShading()) { ci.cancel(); } } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java similarity index 94% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java index eab6105938..3fd94f4d98 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/font/MixinGlyphRenderer.java @@ -1,13 +1,13 @@ -package net.coderbot.iris.compat.sodium.mixin.font; +package net.irisshaders.iris.compat.sodium.mixin.font; import com.mojang.blaze3d.vertex.VertexConsumer; import me.jellysquid.mods.sodium.client.render.vertex.VertexConsumerUtils; import net.caffeinemc.mods.sodium.api.util.ColorABGR; import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.common.GlyphVertex; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.GlyphVertexExt; -import net.coderbot.iris.vertices.ImmediateState; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.GlyphVertexExt; +import net.irisshaders.iris.vertices.ImmediateState; import net.minecraft.client.gui.font.glyphs.BakedGlyph; import org.joml.Math; import org.joml.Matrix4f; @@ -54,6 +54,19 @@ public class MixinGlyphRenderer { @Final private float u1; + private static void write(boolean ext, long buffer, + Matrix4f matrix, float x, float y, float z, int color, float u, float v, int light) { + float x2 = Math.fma(matrix.m00(), x, Math.fma(matrix.m10(), y, Math.fma(matrix.m20(), z, matrix.m30()))); + float y2 = Math.fma(matrix.m01(), x, Math.fma(matrix.m11(), y, Math.fma(matrix.m21(), z, matrix.m31()))); + float z2 = Math.fma(matrix.m02(), x, Math.fma(matrix.m12(), y, Math.fma(matrix.m22(), z, matrix.m32()))); + + if (ext) { + GlyphVertexExt.write(buffer, x2, y2, z2, color, u, v, light); + } else { + GlyphVertex.put(buffer, x2, y2, z2, color, u, v, light); + } + } + /** * @reason Use intrinsics * @author JellySquid @@ -105,17 +118,4 @@ private boolean extend() { return IrisApi.getInstance().isShaderPackInUse() && ImmediateState.renderWithExtendedVertexFormat; } - private static void write(boolean ext, long buffer, - Matrix4f matrix, float x, float y, float z, int color, float u, float v, int light) { - float x2 = Math.fma(matrix.m00(), x, Math.fma(matrix.m10(), y, Math.fma(matrix.m20(), z, matrix.m30()))); - float y2 = Math.fma(matrix.m01(), x, Math.fma(matrix.m11(), y, Math.fma(matrix.m21(), z, matrix.m31()))); - float z2 = Math.fma(matrix.m02(), x, Math.fma(matrix.m12(), y, Math.fma(matrix.m22(), z, matrix.m32()))); - - if (ext) { - GlyphVertexExt.write(buffer, x2, y2, z2, color, u, v, light); - } else { - GlyphVertex.put(buffer, x2, y2, z2, color, u, v, light); - } - } - } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinOptionImpl.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinOptionImpl.java similarity index 83% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinOptionImpl.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinOptionImpl.java index bf881474bd..d71dafd5ab 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinOptionImpl.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinOptionImpl.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.options; +package net.irisshaders.iris.compat.sodium.mixin.options; import me.jellysquid.mods.sodium.client.gui.options.OptionImpl; -import net.coderbot.iris.compat.sodium.impl.options.OptionImplExtended; +import net.irisshaders.iris.compat.sodium.impl.options.OptionImplExtended; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; @@ -14,7 +14,7 @@ * Allows a slider to be dynamically enabled or disabled based on some external condition. */ @Mixin(OptionImpl.class) -public class MixinOptionImpl implements OptionImplExtended { +public class MixinOptionImpl implements OptionImplExtended { @Unique private BooleanSupplier iris$dynamicallyEnabled; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java new file mode 100644 index 0000000000..2c3fa89d61 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinRenderSectionManager.java @@ -0,0 +1,26 @@ +package net.irisshaders.iris.compat.sodium.mixin.options; + +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; +import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; +import net.irisshaders.iris.Iris; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +/** + * Disables fog occlusion when a shader pack is enabled, since shaders are not guaranteed to actually implement fog. + */ +@Mixin(RenderSectionManager.class) +public class MixinRenderSectionManager { + @Redirect(method = "getSearchDistance", remap = false, + at = @At(value = "FIELD", + target = "Lme/jellysquid/mods/sodium/client/gui/SodiumGameOptions$PerformanceSettings;useFogOcclusion:Z", + remap = false)) + private boolean iris$disableFogOcclusion(SodiumGameOptions.PerformanceSettings settings) { + if (Iris.getCurrentPack().isPresent()) { + return false; + } else { + return settings.useFogOcclusion; + } + } +} diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java new file mode 100644 index 0000000000..434079292b --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptionPages.java @@ -0,0 +1,79 @@ +package net.irisshaders.iris.compat.sodium.mixin.options; + +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptionPages; +import me.jellysquid.mods.sodium.client.gui.options.Option; +import me.jellysquid.mods.sodium.client.gui.options.OptionGroup; +import me.jellysquid.mods.sodium.client.gui.options.storage.MinecraftOptionsStorage; +import net.irisshaders.iris.Iris; +import net.irisshaders.iris.compat.sodium.impl.options.IrisSodiumOptions; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.Slice; + +/** + * Adds the Iris-specific options / option changes to the Sodium game options pages. + */ +@Mixin(SodiumGameOptionPages.class) +public class MixinSodiumGameOptionPages { + @Shadow(remap = false) + @Final + private static MinecraftOptionsStorage vanillaOpts; + + @Redirect(method = "general", remap = false, + slice = @Slice( + from = @At(value = "CONSTANT", args = "stringValue=options.renderDistance"), + to = @At(value = "CONSTANT", args = "stringValue=options.simulationDistance") + ), + at = @At(value = "INVOKE", remap = false, + target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + + "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + + ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), + allow = 1) + private static OptionGroup.Builder iris$addMaxShadowDistanceOption(OptionGroup.Builder builder, + Option candidate) { + builder.add(candidate); + builder.add(IrisSodiumOptions.createMaxShadowDistanceSlider(vanillaOpts)); + + return builder; + } + + @Redirect(method = "quality", remap = false, + slice = @Slice( + from = @At(value = "CONSTANT", args = "stringValue=options.graphics"), + to = @At(value = "CONSTANT", args = "stringValue=options.renderClouds") + ), + at = @At(value = "INVOKE", remap = false, + target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + + "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + + ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), + allow = 1) + private static OptionGroup.Builder iris$addColorSpaceOption(OptionGroup.Builder builder, + Option candidate) { + builder.add(candidate); + builder.add(IrisSodiumOptions.createColorSpaceButton(vanillaOpts)); + + return builder; + } + + @ModifyArg(method = "quality", remap = false, + slice = @Slice( + from = @At(value = "CONSTANT", args = "stringValue=options.graphics"), + to = @At(value = "CONSTANT", args = "stringValue=options.renderClouds") + ), + at = @At(value = "INVOKE", remap = false, + target = "me/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder.add (" + + "Lme/jellysquid/mods/sodium/client/gui/options/Option;" + + ")Lme/jellysquid/mods/sodium/client/gui/options/OptionGroup$Builder;"), + allow = 1) + private static Option iris$replaceGraphicsQualityButton(Option candidate) { + if (!Iris.getIrisConfig().areShadersEnabled()) { + return candidate; + } else { + return IrisSodiumOptions.createLimitedVideoSettingsButton(vanillaOpts); + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java similarity index 89% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java index 8c41771e50..8ad5d27c5e 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumGameOptions.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.options; +package net.irisshaders.iris.compat.sodium.mixin.options; import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java new file mode 100644 index 0000000000..1ca7292f7e --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/options/MixinSodiumOptionsGUI.java @@ -0,0 +1,50 @@ +package net.irisshaders.iris.compat.sodium.mixin.options; + +import com.google.common.collect.ImmutableList; +import me.jellysquid.mods.sodium.client.gui.SodiumOptionsGUI; +import me.jellysquid.mods.sodium.client.gui.options.OptionPage; +import net.irisshaders.iris.gui.screen.ShaderPackScreen; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.network.chat.Component; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +/** + * Adds our Shader Packs button to the Sodium options GUI. + */ +@Mixin(SodiumOptionsGUI.class) +public class MixinSodiumOptionsGUI extends Screen { + @Shadow(remap = false) + @Final + private List pages; + + @Unique + private OptionPage shaderPacks; + + // make compiler happy + protected MixinSodiumOptionsGUI(Component title) { + super(title); + } + + @Inject(method = "", at = @At("RETURN")) + private void iris$onInit(Screen prevScreen, CallbackInfo ci) { + Component shaderPacksTranslated = Component.translatable("options.iris.shaderPackSelection"); + shaderPacks = new OptionPage(shaderPacksTranslated, ImmutableList.of()); + pages.add(shaderPacks); + } + + @Inject(method = "setPage", at = @At("HEAD"), remap = false, cancellable = true) + private void iris$onSetPage(OptionPage page, CallbackInfo ci) { + if (page == shaderPacks) { + minecraft.setScreen(new ShaderPackScreen(this)); + ci.cancel(); + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java similarity index 82% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java index 6e3e933e8a..caeacd18aa 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/pbr_animation/MixinSpriteContents.java @@ -1,8 +1,8 @@ -package net.coderbot.iris.compat.sodium.mixin.pbr_animation; +package net.irisshaders.iris.compat.sodium.mixin.pbr_animation; import me.jellysquid.mods.sodium.client.render.texture.SpriteUtil; -import net.coderbot.iris.texture.pbr.PBRSpriteHolder; -import net.coderbot.iris.texture.pbr.SpriteContentsExtension; +import net.irisshaders.iris.texture.pbr.PBRSpriteHolder; +import net.irisshaders.iris.texture.pbr.SpriteContentsExtension; import net.minecraft.client.renderer.texture.SpriteContents; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import org.spongepowered.asm.mixin.Mixin; @@ -12,6 +12,7 @@ @Mixin(SpriteContents.class) public abstract class MixinSpriteContents { + @SuppressWarnings("all") @Inject(method = "sodium$setActive(Z)V", at = @At("TAIL"), remap = false) private void iris$onTailMarkActive(CallbackInfo ci) { PBRSpriteHolder pbrHolder = ((SpriteContentsExtension) this).getPBRHolder(); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java similarity index 88% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java index 9fdb33ff51..7dca2aab8f 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlProgram.java @@ -1,12 +1,12 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; import com.mojang.blaze3d.platform.GlStateManager; import me.jellysquid.mods.sodium.client.gl.GlObject; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniform; import me.jellysquid.mods.sodium.client.gl.shader.uniform.GlUniformBlock; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.ShaderBindingContextExt; -import net.coderbot.iris.gl.IrisRenderSystem; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.ShaderBindingContextExt; +import net.irisshaders.iris.gl.IrisRenderSystem; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java similarity index 85% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java index ca9dd80f2b..cbbb478459 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinGlRenderDevice.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; import me.jellysquid.mods.sodium.client.gl.tessellation.GlPrimitiveType; -import net.coderbot.iris.vertices.ImmediateState; +import net.irisshaders.iris.vertices.ImmediateState; import org.lwjgl.opengl.GL43C; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java similarity index 55% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java index b6dcea6f34..f930f59f1a 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinRegionChunkRenderer.java @@ -1,12 +1,8 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; -import me.jellysquid.mods.sodium.client.gl.buffer.GlMutableBuffer; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; -import me.jellysquid.mods.sodium.client.render.chunk.ChunkRenderMatrices; import me.jellysquid.mods.sodium.client.render.chunk.DefaultChunkRenderer; -import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderInterface; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.ShaderChunkRendererExt; -import org.joml.Matrix4f; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.ShaderChunkRendererExt; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -14,8 +10,8 @@ @Mixin(DefaultChunkRenderer.class) public abstract class MixinRegionChunkRenderer implements ShaderChunkRendererExt { @Redirect(method = "render", remap = false, - at = @At(value = "INVOKE", - target = "me/jellysquid/mods/sodium/client/gl/shader/GlProgram.getInterface ()Ljava/lang/Object;")) + at = @At(value = "INVOKE", + target = "me/jellysquid/mods/sodium/client/gl/shader/GlProgram.getInterface ()Ljava/lang/Object;")) private Object iris$getInterface(GlProgram program) { if (program == null) { // Iris sentinel null diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java similarity index 51% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java index 08908c5c52..b0e5d75428 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderChunkRenderer.java @@ -1,61 +1,45 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; import com.mojang.blaze3d.systems.RenderSystem; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.shader.GlProgram; -import me.jellysquid.mods.sodium.client.gl.shader.GlShader; -import me.jellysquid.mods.sodium.client.gl.shader.ShaderConstants; -import me.jellysquid.mods.sodium.client.gl.shader.ShaderLoader; -import me.jellysquid.mods.sodium.client.gl.shader.ShaderParser; -import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; import me.jellysquid.mods.sodium.client.render.chunk.ShaderChunkRenderer; import me.jellysquid.mods.sodium.client.render.chunk.shader.ChunkShaderInterface; import me.jellysquid.mods.sodium.client.render.chunk.terrain.TerrainRenderPass; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.Iris; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.IrisChunkShaderInterface; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.ShaderChunkRendererExt; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisModelVertexFormats; -import net.coderbot.iris.gl.program.ProgramSamplers; -import net.coderbot.iris.gl.program.ProgramUniforms; -import net.coderbot.iris.shaderpack.transform.StringTransformations; -import net.coderbot.iris.shaderpack.transform.Transformations; -import net.coderbot.iris.shadows.ShadowRenderingState; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.IrisChunkProgramOverrides; -import net.minecraft.resources.ResourceLocation; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisChunkProgramOverrides; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisChunkShaderInterface; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.ShaderChunkRendererExt; +import net.irisshaders.iris.gl.program.ProgramSamplers; +import net.irisshaders.iris.gl.program.ProgramUniforms; +import net.irisshaders.iris.shadows.ShadowRenderingState; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import java.util.List; - /** * Overrides shaders in {@link ShaderChunkRenderer} with our own as needed. */ @Mixin(ShaderChunkRenderer.class) public class MixinShaderChunkRenderer implements ShaderChunkRendererExt { - @Unique - private IrisChunkProgramOverrides irisChunkProgramOverrides; - - @Unique - private GlProgram override; - - @Shadow(remap = false) - private GlProgram activeProgram; - - @Shadow(remap = false) + @Shadow(remap = false) @Final protected ChunkVertexType vertexType; - - @Inject(method = "", at = @At("RETURN"), remap = false) - private void iris$onInit(RenderDevice device, ChunkVertexType vertexType, CallbackInfo ci) { - irisChunkProgramOverrides = new IrisChunkProgramOverrides(); - } + @Unique + private IrisChunkProgramOverrides irisChunkProgramOverrides; + @Unique + private GlProgram override; + @Shadow(remap = false) + private GlProgram activeProgram; + + @Inject(method = "", at = @At("RETURN"), remap = false) + private void iris$onInit(RenderDevice device, ChunkVertexType vertexType, CallbackInfo ci) { + irisChunkProgramOverrides = new IrisChunkProgramOverrides(); + } @Inject(method = "begin", at = @At("HEAD"), cancellable = true, remap = false) private void iris$begin(TerrainRenderPass pass, CallbackInfo ci) { @@ -85,13 +69,13 @@ public class MixinShaderChunkRenderer implements ShaderChunkRendererExt { override.getInterface().setupState(); } - @Inject(method = "end", at = @At("HEAD"), remap = false, cancellable = true) - private void iris$onEnd(TerrainRenderPass pass, CallbackInfo ci) { - ProgramUniforms.clearActiveUniforms(); + @Inject(method = "end", at = @At("HEAD"), remap = false, cancellable = true) + private void iris$onEnd(TerrainRenderPass pass, CallbackInfo ci) { + ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); irisChunkProgramOverrides.unbindFramebuffer(); - if (override != null) { + if (override != null) { override.getInterface().restore(); override.unbind(); pass.endDrawing(); @@ -99,12 +83,12 @@ public class MixinShaderChunkRenderer implements ShaderChunkRendererExt { override = null; ci.cancel(); } - } + } - @Inject(method = "delete", at = @At("HEAD"), remap = false) - private void iris$onDelete(CallbackInfo ci) { - irisChunkProgramOverrides.deleteShaders(); - } + @Inject(method = "delete", at = @At("HEAD"), remap = false) + private void iris$onDelete(CallbackInfo ci) { + irisChunkProgramOverrides.deleteShaders(); + } @Override public GlProgram iris$getOverride() { diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java similarity index 63% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java index 0b42012993..5550a6aebe 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/MixinShaderType.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; -import net.coderbot.iris.compat.sodium.impl.shader_overrides.IrisShaderTypes; +import net.irisshaders.iris.compat.sodium.impl.shader_overrides.IrisShaderTypes; import org.apache.commons.lang3.ArrayUtils; import org.lwjgl.opengl.GL32C; import org.lwjgl.opengl.GL42C; @@ -22,11 +22,11 @@ public class MixinShaderType { int baseOrdinal = $VALUES.length; IrisShaderTypes.GEOMETRY - = ShaderTypeAccessor.createShaderType("GEOMETRY", baseOrdinal, GL32C.GL_GEOMETRY_SHADER); + = ShaderTypeAccessor.createShaderType("GEOMETRY", baseOrdinal, GL32C.GL_GEOMETRY_SHADER); IrisShaderTypes.TESS_CONTROL - = ShaderTypeAccessor.createShaderType("TESS_CONTROL", baseOrdinal + 1, GL42C.GL_TESS_CONTROL_SHADER); + = ShaderTypeAccessor.createShaderType("TESS_CONTROL", baseOrdinal + 1, GL42C.GL_TESS_CONTROL_SHADER); IrisShaderTypes.TESS_EVAL - = ShaderTypeAccessor.createShaderType("TESS_EVAL", baseOrdinal + 2, GL42C.GL_TESS_EVALUATION_SHADER); + = ShaderTypeAccessor.createShaderType("TESS_EVAL", baseOrdinal + 2, GL42C.GL_TESS_EVALUATION_SHADER); $VALUES = ArrayUtils.addAll($VALUES, IrisShaderTypes.GEOMETRY, IrisShaderTypes.TESS_CONTROL, IrisShaderTypes.TESS_EVAL); } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java similarity index 84% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java index 771bc76ab5..80fa7bb6f8 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shader_overrides/ShaderTypeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.shader_overrides; +package net.irisshaders.iris.compat.sodium.mixin.shader_overrides; import me.jellysquid.mods.sodium.client.gl.shader.ShaderType; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java new file mode 100644 index 0000000000..b3ac651ba4 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinDefaultChunkRenderer.java @@ -0,0 +1,17 @@ +package net.irisshaders.iris.compat.sodium.mixin.shadow_map; + +import me.jellysquid.mods.sodium.client.gui.SodiumGameOptions; +import me.jellysquid.mods.sodium.client.render.chunk.DefaultChunkRenderer; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +@Mixin(DefaultChunkRenderer.class) +public class MixinDefaultChunkRenderer { + @Redirect(method = "render", at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/gui/SodiumGameOptions$PerformanceSettings;useBlockFaceCulling:Z"), remap = false) + private boolean iris$disableBlockFaceCullingInShadowPass(SodiumGameOptions.PerformanceSettings instance) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) return false; + return instance.useBlockFaceCulling; + } +} diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java new file mode 100644 index 0000000000..d2a95bc673 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinRenderSectionManager.java @@ -0,0 +1,54 @@ +package net.irisshaders.iris.compat.sodium.mixin.shadow_map; + +import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; +import me.jellysquid.mods.sodium.client.render.chunk.lists.SortedRenderLists; +import me.jellysquid.mods.sodium.client.render.viewport.Viewport; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.minecraft.client.Camera; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(RenderSectionManager.class) +public class MixinRenderSectionManager { + @Shadow + private @NotNull SortedRenderLists renderLists; + @Unique + private @NotNull SortedRenderLists shadowRenderLists = SortedRenderLists.empty(); + + @Redirect(method = "createTerrainRenderList", at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;")) + private void useShadowRenderList(RenderSectionManager instance, SortedRenderLists value) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + shadowRenderLists = value; + } else { + renderLists = value; + } + } + + @Inject(method = "update", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;createTerrainRenderList(Lnet/minecraft/client/Camera;Lme/jellysquid/mods/sodium/client/render/viewport/Viewport;IZ)V", shift = At.Shift.AFTER), cancellable = true) + private void cancelIfShadow(Camera camera, Viewport viewport, int frame, boolean spectator, CallbackInfo ci) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) ci.cancel(); + } + + @Redirect(method = { + "getRenderLists", + "getVisibleChunkCount", + "renderLayer" + }, at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;"), remap = false) + private SortedRenderLists useShadowRenderList2(RenderSectionManager instance) { + return ShadowRenderingState.areShadowsCurrentlyBeingRendered() ? shadowRenderLists : renderLists; + } + + @Redirect(method = { + "resetRenderLists" + }, at = @At(value = "FIELD", target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;renderLists:Lme/jellysquid/mods/sodium/client/render/chunk/lists/SortedRenderLists;"), remap = false) + private void useShadowRenderList3(RenderSectionManager instance, SortedRenderLists value) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) shadowRenderLists = value; + else renderLists = value; + } +} diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java new file mode 100644 index 0000000000..946fb95051 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/MixinSodiumWorldRenderer.java @@ -0,0 +1,96 @@ +package net.irisshaders.iris.compat.sodium.mixin.shadow_map; + +import com.mojang.blaze3d.vertex.PoseStack; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectMaps; +import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; +import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; +import net.irisshaders.iris.shadows.ShadowRenderingState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderBuffers; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher; +import net.minecraft.server.level.BlockDestructionProgress; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.SortedSet; + +/** + * Ensures that the state of the chunk render visibility graph gets properly swapped when in the shadow map pass, + * because we must maintain one visibility graph for the shadow camera and one visibility graph for the player camera. + *

    + * Also ensures that the visibility graph is always rebuilt in the shadow pass, since the shadow camera is generally + * always moving. + */ +@Mixin(SodiumWorldRenderer.class) +public abstract class MixinSodiumWorldRenderer { + private static int beList = 0; + private static boolean renderLightsOnly; + + static { + ShadowRenderingState.setBlockEntityRenderFunction((shadowRenderer, bufferSource, modelView, camera, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum, lightsOnly) -> { + // This isn't thread safe - too bad! + + renderLightsOnly = lightsOnly; + + ((SodiumWorldRendererAccessor) SodiumWorldRenderer.instance()).invokeRenderBlockEntities(modelView, Minecraft.getInstance().renderBuffers(), Long2ObjectMaps.emptyMap(), tickDelta, bufferSource, cameraX, cameraY, cameraZ, Minecraft.getInstance().getBlockEntityRenderDispatcher()); + ((SodiumWorldRendererAccessor) SodiumWorldRenderer.instance()).invokeRenderGlobalBlockEntities(modelView, Minecraft.getInstance().renderBuffers(), Long2ObjectMaps.emptyMap(), tickDelta, bufferSource, cameraX, cameraY, cameraZ, Minecraft.getInstance().getBlockEntityRenderDispatcher()); + + renderLightsOnly = false; + + return beList; + }); + } + + @Shadow + private static void renderBlockEntity(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, float tickDelta, MultiBufferSource.BufferSource immediate, double x, double y, double z, BlockEntityRenderDispatcher dispatcher, BlockEntity entity) { + throw new IllegalStateException("maybe get Mixin?"); + } + + @Inject(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;)V", at = @At("HEAD")) + private void resetEntityList(PoseStack matrices, RenderBuffers bufferBuilders, Long2ObjectMap> blockBreakingProgressions, float tickDelta, MultiBufferSource.BufferSource immediate, double x, double y, double z, BlockEntityRenderDispatcher blockEntityRenderer, CallbackInfo ci) { + beList = 0; + } + + @Redirect(method = "renderBlockEntities(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;)V", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/SodiumWorldRenderer;renderBlockEntity(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;Lnet/minecraft/world/level/block/entity/BlockEntity;)V")) + private void addToList(PoseStack bufferBuilder, RenderBuffers entry, Long2ObjectMap> transformer, float stage, MultiBufferSource.BufferSource matrices, double bufferBuilders, double blockBreakingProgressions, double tickDelta, BlockEntityRenderDispatcher immediate, BlockEntity x) { + if (!renderLightsOnly || x.getBlockState().getLightEmission() > 0) { + renderBlockEntity(bufferBuilder, entry, transformer, stage, matrices, bufferBuilders, blockBreakingProgressions, tickDelta, immediate, x); + beList++; + } + } + + @Redirect(method = "renderGlobalBlockEntities", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/render/SodiumWorldRenderer;renderBlockEntity(Lcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/RenderBuffers;Lit/unimi/dsi/fastutil/longs/Long2ObjectMap;FLnet/minecraft/client/renderer/MultiBufferSource$BufferSource;DDDLnet/minecraft/client/renderer/blockentity/BlockEntityRenderDispatcher;Lnet/minecraft/world/level/block/entity/BlockEntity;)V")) + private void addToList2(PoseStack bufferBuilder, RenderBuffers entry, Long2ObjectMap> transformer, float stage, MultiBufferSource.BufferSource matrices, double bufferBuilders, double blockBreakingProgressions, double tickDelta, BlockEntityRenderDispatcher immediate, BlockEntity x) { + if (!renderLightsOnly || x.getBlockState().getLightEmission() > 0) { + renderBlockEntity(bufferBuilder, entry, transformer, stage, matrices, bufferBuilders, blockBreakingProgressions, tickDelta, immediate, x); + beList++; + } + } + + @Inject(method = "isEntityVisible", at = @At("HEAD"), cancellable = true) + private void iris$overrideEntityCulling(Entity entity, CallbackInfoReturnable cir) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) cir.setReturnValue(true); + } + + @Redirect(method = "setupTerrain", remap = false, + at = @At(value = "INVOKE", + target = "Lme/jellysquid/mods/sodium/client/render/chunk/RenderSectionManager;needsUpdate()Z", + remap = false)) + private boolean iris$forceChunkGraphRebuildInShadowPass(RenderSectionManager instance) { + if (ShadowRenderingState.areShadowsCurrentlyBeingRendered()) { + // TODO: Detect when the sun/moon isn't moving + return true; + } else { + return instance.needsUpdate(); + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java similarity index 95% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java index 061e6104e1..5d2cf4585b 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/SodiumWorldRendererAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map; +package net.irisshaders.iris.compat.sodium.mixin.shadow_map; import com.mojang.blaze3d.vertex.PoseStack; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java similarity index 81% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java index 541e11d1ba..a050c08783 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinAdvancedShadowCullingFrustum.java @@ -1,11 +1,10 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map.frustum; +package net.irisshaders.iris.compat.sodium.mixin.shadow_map.frustum; import me.jellysquid.mods.sodium.client.render.viewport.Viewport; import me.jellysquid.mods.sodium.client.render.viewport.ViewportProvider; import me.jellysquid.mods.sodium.client.render.viewport.frustum.Frustum; -import net.coderbot.iris.shadows.frustum.BoxCuller; -import net.coderbot.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum; -import org.joml.FrustumIntersection; +import net.irisshaders.iris.shadows.frustum.BoxCuller; +import net.irisshaders.iris.shadows.frustum.advanced.AdvancedShadowCullingFrustum; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -14,30 +13,26 @@ @Mixin(AdvancedShadowCullingFrustum.class) public abstract class MixinAdvancedShadowCullingFrustum implements ViewportProvider, Frustum { - @Shadow(remap = false) - protected abstract int checkCornerVisibility(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); - + @Unique + private final Vector3d position = new Vector3d(); @Shadow public double x; - @Shadow public double y; - @Shadow public double z; - @Shadow @Final protected BoxCuller boxCuller; + @Shadow(remap = false) + protected abstract int checkCornerVisibility(float minX, float minY, float minZ, float maxX, float maxY, float maxZ); + @Override public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { return (boxCuller == null || !boxCuller.isCulledSodium(minX, minY, minZ, maxX, maxY, maxZ)) && this.checkCornerVisibility(minX, minY, minZ, maxX, maxY, maxZ) > 0; } - @Unique - private Vector3d position = new Vector3d(); - @Override public Viewport sodium$createViewport() { return new Viewport(this, position.set(x, y, z)); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java similarity index 74% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java index 4f0be0b80a..6e959f940d 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinBoxCullingFrustum.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map.frustum; +package net.irisshaders.iris.compat.sodium.mixin.shadow_map.frustum; import me.jellysquid.mods.sodium.client.render.viewport.Viewport; import me.jellysquid.mods.sodium.client.render.viewport.ViewportProvider; import me.jellysquid.mods.sodium.client.render.viewport.frustum.Frustum; -import net.coderbot.iris.shadows.frustum.BoxCuller; -import net.coderbot.iris.shadows.frustum.fallback.BoxCullingFrustum; +import net.irisshaders.iris.shadows.frustum.BoxCuller; +import net.irisshaders.iris.shadows.frustum.fallback.BoxCullingFrustum; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -13,19 +13,17 @@ @Mixin(BoxCullingFrustum.class) public class MixinBoxCullingFrustum implements Frustum, ViewportProvider { + @Unique + private final Vector3d position = new Vector3d(); @Shadow(remap = false) @Final private BoxCuller boxCuller; - @Shadow private double x, y, z; - @Unique - private Vector3d position = new Vector3d(); - @Override public Viewport sodium$createViewport() { - return new Viewport(this, position.set(x, y, z)); + return new Viewport(this, position.set(x, y, z)); } @Override diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java similarity index 76% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java index cc8fe4e9ad..8f652a7f15 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinCullEverythingFrustum.java @@ -1,15 +1,15 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map.frustum; +package net.irisshaders.iris.compat.sodium.mixin.shadow_map.frustum; import me.jellysquid.mods.sodium.client.render.viewport.Viewport; import me.jellysquid.mods.sodium.client.render.viewport.ViewportProvider; import me.jellysquid.mods.sodium.client.render.viewport.frustum.Frustum; -import net.coderbot.iris.shadows.frustum.CullEverythingFrustum; +import net.irisshaders.iris.shadows.frustum.CullEverythingFrustum; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Mixin; @Mixin(CullEverythingFrustum.class) public class MixinCullEverythingFrustum implements Frustum, ViewportProvider { - private static Vector3d EMPTY = new Vector3d(); + private static final Vector3d EMPTY = new Vector3d(); @Override public Viewport sodium$createViewport() { diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java similarity index 82% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java index dba7b40dc7..5ab6cab014 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/shadow_map/frustum/MixinNonCullingFrustum.java @@ -1,16 +1,17 @@ -package net.coderbot.iris.compat.sodium.mixin.shadow_map.frustum; +package net.irisshaders.iris.compat.sodium.mixin.shadow_map.frustum; import me.jellysquid.mods.sodium.client.render.viewport.Viewport; import me.jellysquid.mods.sodium.client.render.viewport.ViewportProvider; import me.jellysquid.mods.sodium.client.render.viewport.frustum.Frustum; -import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; +import net.irisshaders.iris.shadows.frustum.fallback.NonCullingFrustum; import net.minecraft.client.Minecraft; import org.joml.Vector3d; import org.spongepowered.asm.mixin.Mixin; @Mixin(NonCullingFrustum.class) public class MixinNonCullingFrustum implements Frustum, ViewportProvider { - private Vector3d pos = new Vector3d(); + private final Vector3d pos = new Vector3d(); + @Override public Viewport sodium$createViewport() { return new Viewport(this, pos.set(Minecraft.getInstance().gameRenderer.getMainCamera().getPosition().x, Minecraft.getInstance().gameRenderer.getMainCamera().getPosition().y, Minecraft.getInstance().gameRenderer.getMainCamera().getPosition().z)); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java similarity index 93% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java index 8f761088c3..e41be0ce4a 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/sky/MixinLevelRenderer.java @@ -1,8 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.sky; +package net.irisshaders.iris.compat.sodium.mixin.sky; import com.mojang.blaze3d.vertex.PoseStack; -import org.joml.Matrix4f; -import net.coderbot.iris.Iris; +import net.irisshaders.iris.Iris; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.FogRenderer; @@ -13,6 +12,7 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.material.FogType; import net.minecraft.world.phys.Vec3; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -53,7 +53,7 @@ private void preRenderSky(PoseStack poseStack, Matrix4f projectionMatrix, float boolean isSubmersed = camera.getFluidInCamera() != FogType.NONE; boolean hasBlindness = cameraEntity instanceof LivingEntity && ((LivingEntity) cameraEntity).hasEffect(MobEffects.BLINDNESS); boolean useThickFog = this.minecraft.level.effects().isFoggyAt(Mth.floor(cameraPosition.x()), - Mth.floor(cameraPosition.y())) || this.minecraft.gui.getBossOverlay().shouldCreateWorldFog(); + Mth.floor(cameraPosition.y())) || this.minecraft.gui.getBossOverlay().shouldCreateWorldFog(); if (isSubmersed || hasBlindness || useThickFog) { ci.cancel(); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java similarity index 86% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java index 8c7a3df1cf..c2bbf27e7b 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/ChunkMeshAttributeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java similarity index 88% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java index 2bc83bc562..92b32f3fb5 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/CommonVertexAttributeAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import com.mojang.blaze3d.vertex.VertexFormatElement; import net.caffeinemc.mods.sodium.api.vertex.attributes.CommonVertexAttribute; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java similarity index 86% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java index 143ad04b65..ee6c1c7f54 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/GlVertexAttributeFormatAccessor.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import org.spongepowered.asm.mixin.Mixin; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java similarity index 55% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java index 1d40f2374a..2a9a6d0552 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinChunkMeshAttribute.java @@ -1,7 +1,7 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; import org.apache.commons.lang3.ArrayUtils; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -11,7 +11,7 @@ /** * Uses some rather hacky shenanigans to add a few new enum values to {@link ChunkMeshAttribute} corresponding to our * extended vertex attributes. - * + *

    * Credit goes to Nuclearfarts for the trick. */ @Mixin(ChunkMeshAttribute.class) @@ -26,21 +26,21 @@ public class MixinChunkMeshAttribute { int baseOrdinal = $VALUES.length; IrisChunkMeshAttributes.NORMAL - = ChunkMeshAttributeAccessor.createChunkMeshAttribute("NORMAL", baseOrdinal); + = ChunkMeshAttributeAccessor.createChunkMeshAttribute("NORMAL", baseOrdinal); IrisChunkMeshAttributes.TANGENT - = ChunkMeshAttributeAccessor.createChunkMeshAttribute("TANGENT", baseOrdinal + 1); + = ChunkMeshAttributeAccessor.createChunkMeshAttribute("TANGENT", baseOrdinal + 1); IrisChunkMeshAttributes.MID_TEX_COORD - = ChunkMeshAttributeAccessor.createChunkMeshAttribute("MID_TEX_COORD", baseOrdinal + 2); + = ChunkMeshAttributeAccessor.createChunkMeshAttribute("MID_TEX_COORD", baseOrdinal + 2); IrisChunkMeshAttributes.BLOCK_ID - = ChunkMeshAttributeAccessor.createChunkMeshAttribute("BLOCK_ID", baseOrdinal + 3); + = ChunkMeshAttributeAccessor.createChunkMeshAttribute("BLOCK_ID", baseOrdinal + 3); IrisChunkMeshAttributes.MID_BLOCK - = ChunkMeshAttributeAccessor.createChunkMeshAttribute("MID_BLOCK", baseOrdinal + 4); + = ChunkMeshAttributeAccessor.createChunkMeshAttribute("MID_BLOCK", baseOrdinal + 4); $VALUES = ArrayUtils.addAll($VALUES, - IrisChunkMeshAttributes.NORMAL, - IrisChunkMeshAttributes.TANGENT, - IrisChunkMeshAttributes.MID_TEX_COORD, - IrisChunkMeshAttributes.BLOCK_ID, - IrisChunkMeshAttributes.MID_BLOCK); + IrisChunkMeshAttributes.NORMAL, + IrisChunkMeshAttributes.TANGENT, + IrisChunkMeshAttributes.MID_TEX_COORD, + IrisChunkMeshAttributes.BLOCK_ID, + IrisChunkMeshAttributes.MID_BLOCK); } } diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java new file mode 100644 index 0000000000..117ee046fa --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinCommonVertexAttributes.java @@ -0,0 +1,53 @@ +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; + +import net.caffeinemc.mods.sodium.api.vertex.attributes.CommonVertexAttribute; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisCommonVertexAttributes; +import net.irisshaders.iris.vertices.IrisVertexFormats; +import org.apache.commons.lang3.ArrayUtils; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; + +/** + * Uses some rather hacky shenanigans to add a few new enum values to {@link CommonVertexAttribute} corresponding to our + * extended vertex attributes. + *

    + * Credit goes to Nuclearfarts for the trick. + */ +@Mixin(CommonVertexAttribute.class) +public class MixinCommonVertexAttributes { + @Mutable + @Shadow + @Final + public static int COUNT; + @SuppressWarnings("target") + @Shadow(remap = false) + @Final + @Mutable + private static CommonVertexAttribute[] $VALUES; + + static { + int baseOrdinal = $VALUES.length; + + IrisCommonVertexAttributes.TANGENT + = CommonVertexAttributeAccessor.createCommonVertexElement("TANGENT", baseOrdinal, IrisVertexFormats.TANGENT_ELEMENT); + IrisCommonVertexAttributes.MID_TEX_COORD + = CommonVertexAttributeAccessor.createCommonVertexElement("MID_TEX_COORD", baseOrdinal + 1, IrisVertexFormats.MID_TEXTURE_ELEMENT); + IrisCommonVertexAttributes.BLOCK_ID + = CommonVertexAttributeAccessor.createCommonVertexElement("BLOCK_ID", baseOrdinal + 2, IrisVertexFormats.ENTITY_ELEMENT); + IrisCommonVertexAttributes.ENTITY_ID + = CommonVertexAttributeAccessor.createCommonVertexElement("ENTITY_ID", baseOrdinal + 3, IrisVertexFormats.ENTITY_ID_ELEMENT); + IrisCommonVertexAttributes.MID_BLOCK + = CommonVertexAttributeAccessor.createCommonVertexElement("MID_BLOCK", baseOrdinal + 4, IrisVertexFormats.MID_BLOCK_ELEMENT); + + $VALUES = ArrayUtils.addAll($VALUES, + IrisCommonVertexAttributes.TANGENT, + IrisCommonVertexAttributes.MID_TEX_COORD, + IrisCommonVertexAttributes.BLOCK_ID, + IrisCommonVertexAttributes.ENTITY_ID, + IrisCommonVertexAttributes.MID_BLOCK); + + COUNT = $VALUES.length; + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java similarity index 80% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java index 0d5214a68e..a4c26a4dec 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinGlVertexFormatBuilder.java @@ -1,9 +1,8 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttribute; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeFormat; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -15,19 +14,19 @@ @Mixin(GlVertexFormat.Builder.class) public class MixinGlVertexFormatBuilder> { + private static final GlVertexAttribute EMPTY + = new GlVertexAttribute(GlVertexAttributeFormat.FLOAT, 0, false, 0, 0, false); @Shadow @Final private int stride; @Shadow @Final private EnumMap attributes; - private static final GlVertexAttribute EMPTY - = new GlVertexAttribute(GlVertexAttributeFormat.FLOAT, 0, false, 0, 0, false); @Redirect(method = "build", - at = @At(value = "INVOKE", - target = "java/util/EnumMap.get (Ljava/lang/Object;)Ljava/lang/Object;"), - remap = false) + at = @At(value = "INVOKE", + target = "java/util/EnumMap.get (Ljava/lang/Object;)Ljava/lang/Object;"), + remap = false) private Object iris$suppressMissingAttributes(EnumMap map, Object key) { Object value = map.get(key); diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java similarity index 82% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java index 739772e823..c00e22683d 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRegionChunkRenderer.java @@ -1,7 +1,6 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexAttributeBinding; -import me.jellysquid.mods.sodium.client.gl.attribute.GlVertexFormat; import me.jellysquid.mods.sodium.client.gl.buffer.GlBuffer; import me.jellysquid.mods.sodium.client.gl.device.RenderDevice; import me.jellysquid.mods.sodium.client.gl.tessellation.TessellationBinding; @@ -9,20 +8,13 @@ import me.jellysquid.mods.sodium.client.render.chunk.ShaderChunkRenderer; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshAttribute; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.IrisChunkShaderBindingPoints; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; -import org.apache.commons.lang3.ArrayUtils; -import org.spongepowered.asm.mixin.Final; +import net.irisshaders.iris.compat.sodium.impl.IrisChunkShaderBindingPoints; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisChunkMeshAttributes; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; -import java.util.Arrays; -import java.util.List; - @Mixin(DefaultChunkRenderer.class) public abstract class MixinRegionChunkRenderer extends ShaderChunkRenderer { public MixinRegionChunkRenderer(RenderDevice device, ChunkVertexType vertexType) { @@ -32,7 +24,7 @@ public MixinRegionChunkRenderer(RenderDevice device, ChunkVertexType vertexType) @Redirect(remap = false, method = "createRegionTessellation", at = @At(value = "INVOKE", target = "Lme/jellysquid/mods/sodium/client/gl/tessellation/TessellationBinding;forVertexBuffer(Lme/jellysquid/mods/sodium/client/gl/buffer/GlBuffer;[Lme/jellysquid/mods/sodium/client/gl/attribute/GlVertexAttributeBinding;)Lme/jellysquid/mods/sodium/client/gl/tessellation/TessellationBinding;")) @SuppressWarnings({"rawtypes", "unchecked"}) private TessellationBinding iris$onInit(GlBuffer buffer, GlVertexAttributeBinding[] attributes) { - if (!BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) { + if (!WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat()) { return TessellationBinding.forVertexBuffer(buffer, attributes); } diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java similarity index 56% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java index 5af9efd746..0c7827d6c0 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderRegionArenas.java @@ -1,10 +1,10 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.render.chunk.region.RenderRegion; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshFormats; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; -import net.coderbot.iris.block_rendering.BlockRenderingSettings; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisModelVertexFormats; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisModelVertexFormats; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -12,10 +12,10 @@ @Mixin(RenderRegion.DeviceResources.class) public class MixinRenderRegionArenas { @Redirect(method = "", remap = false, - at = @At(value = "FIELD", - target = "Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkMeshFormats;COMPACT:Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;", - remap = false)) + at = @At(value = "FIELD", + target = "Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkMeshFormats;COMPACT:Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;", + remap = false)) private ChunkVertexType iris$useExtendedStride() { - return BlockRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : ChunkMeshFormats.COMPACT; + return WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : ChunkMeshFormats.COMPACT; } } diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java new file mode 100644 index 0000000000..77de3e4d4b --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinRenderSectionManager.java @@ -0,0 +1,26 @@ +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; + +import me.jellysquid.mods.sodium.client.render.chunk.RenderSectionManager; +import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkVertexType; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisModelVertexFormats; +import net.irisshaders.iris.shaderpack.materialmap.WorldRenderingSettings; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.ModifyArg; + +@Mixin(RenderSectionManager.class) +public class MixinRenderSectionManager { + @ModifyArg(method = "", remap = false, + at = @At(value = "INVOKE", + target = "Lme/jellysquid/mods/sodium/client/render/chunk/DefaultChunkRenderer;(Lme/jellysquid/mods/sodium/client/gl/device/RenderDevice;Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;)V")) + private ChunkVertexType iris$useExtendedVertexFormat$1(ChunkVertexType vertexType) { + return WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : vertexType; + } + + @ModifyArg(method = "", + at = @At(value = "INVOKE", + target = "Lme/jellysquid/mods/sodium/client/render/chunk/compile/executor/ChunkBuilder;(Lnet/minecraft/client/multiplayer/ClientLevel;Lme/jellysquid/mods/sodium/client/render/chunk/vertex/format/ChunkVertexType;)V")) + private ChunkVertexType iris$useExtendedVertexFormat$2(ChunkVertexType vertexType) { + return WorldRenderingSettings.INSTANCE.shouldUseExtendedVertexFormat() ? IrisModelVertexFormats.MODEL_VERTEX_XHFP : vertexType; + } +} diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinSodiumBufferBuilder.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinSodiumBufferBuilder.java new file mode 100644 index 0000000000..99de6f3eec --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinSodiumBufferBuilder.java @@ -0,0 +1,246 @@ +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; + +import com.mojang.blaze3d.vertex.BufferBuilder; +import com.mojang.blaze3d.vertex.VertexFormat; +import me.jellysquid.mods.sodium.client.render.vertex.buffer.ExtendedBufferBuilder; +import me.jellysquid.mods.sodium.client.render.vertex.buffer.SodiumBufferBuilder; +import net.caffeinemc.mods.sodium.api.vertex.attributes.common.NormalAttribute; +import net.caffeinemc.mods.sodium.api.vertex.attributes.common.PositionAttribute; +import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisCommonVertexAttributes; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.SodiumBufferBuilderPolygonView; +import net.irisshaders.iris.uniforms.CapturedRenderingState; +import net.irisshaders.iris.vertices.BlockSensitiveBufferBuilder; +import net.irisshaders.iris.vertices.ExtendedDataHelper; +import net.irisshaders.iris.vertices.IrisExtendedBufferBuilder; +import net.irisshaders.iris.vertices.NormI8; +import net.irisshaders.iris.vertices.NormalHelper; +import org.joml.Vector3f; +import org.lwjgl.system.MemoryUtil; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +@Mixin(SodiumBufferBuilder.class) +public abstract class MixinSodiumBufferBuilder implements BlockSensitiveBufferBuilder { + @Unique + private static final int + ATTRIBUTE_TANGENT_BIT = 1 << IrisCommonVertexAttributes.TANGENT.ordinal(), + ATTRIBUTE_MID_TEX_COORD_BIT = 1 << IrisCommonVertexAttributes.MID_TEX_COORD.ordinal(), + ATTRIBUTE_BLOCK_ID_BIT = 1 << IrisCommonVertexAttributes.BLOCK_ID.ordinal(), + ATTRIBUTE_ENTITY_ID_BIT = 1 << IrisCommonVertexAttributes.ENTITY_ID.ordinal(), + ATTRIBUTE_MID_BLOCK_BIT = 1 << IrisCommonVertexAttributes.MID_BLOCK.ordinal(); + @Shadow + @Final + private static int ATTRIBUTE_NOT_PRESENT; + @Shadow + @Final + private static int ATTRIBUTE_NORMAL_BIT; + @Unique + private final SodiumBufferBuilderPolygonView polygon = new SodiumBufferBuilderPolygonView(); + @Unique + private final Vector3f normal = new Vector3f(); + @Shadow + @Final + private ExtendedBufferBuilder builder; + @Shadow + private int attributeOffsetPosition; + @Shadow + private int attributeOffsetTexture; + @Shadow + private int attributeOffsetNormal; + @Shadow + private int requiredAttributes, writtenAttributes; + @Unique + private int + attributeOffsetTangent, + attributeOffsetMidTexCoord, + attributeOffsetBlockId, + attributeOffsetEntityId, + attributeOffsetMidBlock; + + @Shadow + public abstract BufferBuilder getOriginalBufferBuilder(); + + @Shadow + abstract void putNormalAttribute(int normal); + + @Unique + private void putBlockIdAttribute(short s0, short s1) { + if (this.attributeOffsetBlockId == ATTRIBUTE_NOT_PRESENT) { + return; + } + + final long offset = MemoryUtil.memAddress(this.builder.sodium$getBuffer(), this.builder.sodium$getElementOffset() + this.attributeOffsetBlockId); + MemoryUtil.memPutShort(offset, s0); + MemoryUtil.memPutShort(offset + 2, s1); + + this.writtenAttributes |= ATTRIBUTE_BLOCK_ID_BIT; + } + + @Unique + private void putEntityIdAttribute(short s0, short s1, short s2) { + if (this.attributeOffsetEntityId == ATTRIBUTE_NOT_PRESENT) { + return; + } + + final long offset = MemoryUtil.memAddress(this.builder.sodium$getBuffer(), this.builder.sodium$getElementOffset() + this.attributeOffsetEntityId); + MemoryUtil.memPutShort(offset, s0); + MemoryUtil.memPutShort(offset + 2, s1); + MemoryUtil.memPutShort(offset + 4, s2); + + this.writtenAttributes |= ATTRIBUTE_ENTITY_ID_BIT; + } + + @Unique + private void putMidBlockAttribute(int midBlock) { + if (this.attributeOffsetMidBlock == ATTRIBUTE_NOT_PRESENT) { + return; + } + + final long offset = MemoryUtil.memAddress(this.builder.sodium$getBuffer(), this.builder.sodium$getElementOffset() + this.attributeOffsetMidBlock); + MemoryUtil.memPutInt(offset, midBlock); + + this.writtenAttributes |= ATTRIBUTE_MID_BLOCK_BIT; + } + + @Override + public void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ) { + ((BlockSensitiveBufferBuilder) getOriginalBufferBuilder()).beginBlock(block, renderType, localPosX, localPosY, localPosZ); + } + + @Override + public void endBlock() { + ((BlockSensitiveBufferBuilder) getOriginalBufferBuilder()).endBlock(); + } + + @Inject(method = "resetAttributeBindings", at = @At("RETURN"), remap = false) + private void onResetAttributeBindings(CallbackInfo ci) { + attributeOffsetTangent = ATTRIBUTE_NOT_PRESENT; + attributeOffsetMidTexCoord = ATTRIBUTE_NOT_PRESENT; + attributeOffsetBlockId = ATTRIBUTE_NOT_PRESENT; + attributeOffsetEntityId = ATTRIBUTE_NOT_PRESENT; + attributeOffsetMidBlock = ATTRIBUTE_NOT_PRESENT; + } + + @Inject(method = "updateAttributeBindings", at = @At("RETURN"), remap = false) + private void onUpdateAttributeBindings(VertexFormatDescription desc, CallbackInfo ci) { + if (desc.containsElement(IrisCommonVertexAttributes.TANGENT)) { + requiredAttributes |= ATTRIBUTE_TANGENT_BIT; + attributeOffsetTangent = desc.getElementOffset(IrisCommonVertexAttributes.TANGENT); + } + + if (desc.containsElement(IrisCommonVertexAttributes.MID_TEX_COORD)) { + requiredAttributes |= ATTRIBUTE_MID_TEX_COORD_BIT; + attributeOffsetMidTexCoord = desc.getElementOffset(IrisCommonVertexAttributes.MID_TEX_COORD); + } + + if (desc.containsElement(IrisCommonVertexAttributes.BLOCK_ID)) { + requiredAttributes |= ATTRIBUTE_BLOCK_ID_BIT; + attributeOffsetBlockId = desc.getElementOffset(IrisCommonVertexAttributes.BLOCK_ID); + } + + if (desc.containsElement(IrisCommonVertexAttributes.ENTITY_ID)) { + requiredAttributes |= ATTRIBUTE_ENTITY_ID_BIT; + attributeOffsetEntityId = desc.getElementOffset(IrisCommonVertexAttributes.ENTITY_ID); + } + + if (desc.containsElement(IrisCommonVertexAttributes.MID_BLOCK)) { + requiredAttributes |= ATTRIBUTE_MID_BLOCK_BIT; + attributeOffsetMidBlock = desc.getElementOffset(IrisCommonVertexAttributes.MID_BLOCK); + } + } + + @Inject(method = "endVertex", at = @At("HEAD")) + private void onEndVertex(CallbackInfo ci) { + IrisExtendedBufferBuilder ext = (IrisExtendedBufferBuilder) builder; + + if (!ext.iris$extending()) { + return; + } + + if (ext.iris$injectNormalAndUV1() && (writtenAttributes & ATTRIBUTE_NORMAL_BIT) == 0) { + putNormalAttribute(0); + } + + if (ext.iris$isTerrain()) { + putBlockIdAttribute(ext.iris$currentBlock(), ext.iris$currentRenderType()); + } else { + putEntityIdAttribute((short) CapturedRenderingState.INSTANCE.getCurrentRenderedEntity(), + (short) CapturedRenderingState.INSTANCE.getCurrentRenderedBlockEntity(), + (short) CapturedRenderingState.INSTANCE.getCurrentRenderedItem()); + } + + this.writtenAttributes |= ATTRIBUTE_MID_TEX_COORD_BIT; + this.writtenAttributes |= ATTRIBUTE_TANGENT_BIT; + + if (ext.iris$isTerrain()) { + final long offset = MemoryUtil.memAddress(this.builder.sodium$getBuffer(), this.builder.sodium$getElementOffset() + this.attributeOffsetPosition); + float x = PositionAttribute.getX(offset); + float y = PositionAttribute.getY(offset); + float z = PositionAttribute.getZ(offset); + putMidBlockAttribute(ExtendedDataHelper.computeMidBlock(x, y, z, ext.iris$currentLocalPosX(), ext.iris$currentLocalPosY(), ext.iris$currentLocalPosZ())); + } + + ext.iris$incrementVertexCount(); + + VertexFormat.Mode mode = ext.iris$mode(); + int vertexCount = ext.iris$vertexCount(); + + if (mode == VertexFormat.Mode.QUADS && vertexCount == 4 || mode == VertexFormat.Mode.TRIANGLES && vertexCount == 3) { + fillExtendedData(vertexCount); + } + } + + @Unique + private void fillExtendedData(int vertexAmount) { + IrisExtendedBufferBuilder ext = (IrisExtendedBufferBuilder) builder; + + ext.iris$resetVertexCount(); + + int stride = ext.iris$format().getVertexSize(); + + long ptr = MemoryUtil.memAddress(builder.sodium$getBuffer(), this.builder.sodium$getElementOffset()); + polygon.setup(ptr, attributeOffsetPosition, attributeOffsetTexture, stride, vertexAmount); + + float midU = 0; + float midV = 0; + + for (int vertex = 0; vertex < vertexAmount; vertex++) { + midU += polygon.u(vertex); + midV += polygon.v(vertex); + } + + midU /= vertexAmount; + midV /= vertexAmount; + + if (vertexAmount == 3) { + // NormalHelper.computeFaceNormalTri(normal, polygon); // Removed to enable smooth shaded triangles. Mods rendering triangles with bad normals need to recalculate their normals manually or otherwise shading might be inconsistent. + + for (int vertex = 0; vertex < vertexAmount; vertex++) { + int packedNormal = NormalAttribute.get(ptr + attributeOffsetNormal - (long) stride * vertex); // retrieve per-vertex normal + + int tangent = NormalHelper.computeTangentSmooth(NormI8.unpackX(packedNormal), NormI8.unpackY(packedNormal), NormI8.unpackZ(packedNormal), polygon); + + MemoryUtil.memPutFloat(ptr + attributeOffsetMidTexCoord - (long) stride * vertex, midU); + MemoryUtil.memPutFloat(ptr + attributeOffsetMidTexCoord + 4 - (long) stride * vertex, midV); + MemoryUtil.memPutInt(ptr + attributeOffsetTangent - (long) stride * vertex, tangent); + } + } else { + NormalHelper.computeFaceNormal(normal, polygon); + int packedNormal = NormI8.pack(normal.x, normal.y, normal.z, 0.0f); + int tangent = NormalHelper.computeTangent(normal.x, normal.y, normal.z, polygon); + + for (int vertex = 0; vertex < vertexAmount; vertex++) { + MemoryUtil.memPutFloat(ptr + attributeOffsetMidTexCoord - (long) stride * vertex, midU); + MemoryUtil.memPutFloat(ptr + attributeOffsetMidTexCoord + 4 - (long) stride * vertex, midV); + MemoryUtil.memPutInt(ptr + attributeOffsetNormal - (long) stride * vertex, packedNormal); + MemoryUtil.memPutInt(ptr + attributeOffsetTangent - (long) stride * vertex, tangent); + } + } + } +} diff --git a/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexFormatDescriptionImpl.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexFormatDescriptionImpl.java new file mode 100644 index 0000000000..38ec05c089 --- /dev/null +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexFormatDescriptionImpl.java @@ -0,0 +1,20 @@ +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; + +import com.mojang.blaze3d.vertex.VertexFormat; +import me.jellysquid.mods.sodium.client.render.vertex.VertexFormatDescriptionImpl; +import net.irisshaders.iris.vertices.IrisVertexFormats; +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; + +@Mixin(VertexFormatDescriptionImpl.class) +public class MixinVertexFormatDescriptionImpl { + // A better fix would be to treat IrisVertexFormats.PADDING_SHORT as padding, but this works too. + @Inject(method = "checkSimple", at = @At("HEAD"), cancellable = true) + private static void iris$forceSimple(VertexFormat format, CallbackInfoReturnable cir) { + if (format == IrisVertexFormats.TERRAIN || format == IrisVertexFormats.ENTITY || format == IrisVertexFormats.GLYPH) { + cir.setReturnValue(true); + } + } +} diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java similarity index 79% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java index 0e21ac1c92..0100efeaa6 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexSerializerCache.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import it.unimi.dsi.fastutil.longs.Long2ReferenceMap; @@ -6,11 +6,11 @@ import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatDescription; import net.caffeinemc.mods.sodium.api.vertex.format.VertexFormatRegistry; import net.caffeinemc.mods.sodium.api.vertex.serializer.VertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.EntityToTerrainVertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.GlyphExtVertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisEntityToTerrainVertexSerializer; -import net.coderbot.iris.compat.sodium.impl.vertex_format.ModelToEntityVertexSerializer; -import net.coderbot.iris.vertices.IrisVertexFormats; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.EntityToTerrainVertexSerializer; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.GlyphExtVertexSerializer; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.IrisEntityToTerrainVertexSerializer; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.ModelToEntityVertexSerializer; +import net.irisshaders.iris.vertices.IrisVertexFormats; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java similarity index 85% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java index 26a1837f18..8a072476cb 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/MixinVertexTransform.java @@ -1,18 +1,15 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format; import me.jellysquid.mods.sodium.client.render.chunk.vertex.format.ChunkMeshFormats; -import net.coderbot.iris.compat.sodium.impl.vertex_format.IrisCommonVertexAttributes; -import net.coderbot.iris.vertices.IrisVertexFormats; -import org.lwjgl.system.MemoryUtil; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; @Mixin(ChunkMeshFormats.class) public class MixinVertexTransform { - /** - * @author IMS + /* + @author IMS * @reason Rewrite to edit midTexCoord too */ + // TODO: Re-add this /*@Overwrite(remap = false) public static void transformSprite(long ptr, int count, VertexFormatDescription format, float minU, float minV, float maxU, float maxV) { diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java similarity index 89% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java index cf7082bbb0..a07d5bed73 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinEntityRenderDispatcher.java @@ -1,23 +1,17 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format.entity; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format.entity; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; import net.caffeinemc.mods.sodium.api.math.MatrixHelper; import net.caffeinemc.mods.sodium.api.util.ColorABGR; -import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.common.ModelVertex; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; -import net.coderbot.iris.vertices.ImmediateState; -import net.coderbot.iris.vertices.NormI8; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; +import net.irisshaders.iris.vertices.ImmediateState; +import net.irisshaders.iris.vertices.NormI8; import net.minecraft.client.renderer.LightTexture; import net.minecraft.client.renderer.entity.EntityRenderDispatcher; import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.core.Direction; import org.joml.Matrix4f; -import org.lwjgl.system.MemoryStack; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Unique; @Mixin(value = EntityRenderDispatcher.class, priority = 1010) diff --git a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java similarity index 92% rename from src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java rename to src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java index 5235aefc7d..54229d4780 100644 --- a/src/sodiumCompatibility/java/net/coderbot/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java +++ b/src/sodiumCompatibility/java/net/irisshaders/iris/compat/sodium/mixin/vertex_format/entity/MixinModelVertex.java @@ -1,4 +1,4 @@ -package net.coderbot.iris.compat.sodium.mixin.vertex_format.entity; +package net.irisshaders.iris.compat.sodium.mixin.vertex_format.entity; import com.mojang.blaze3d.vertex.PoseStack; import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; @@ -9,16 +9,14 @@ import net.caffeinemc.mods.sodium.api.util.ColorU8; import net.caffeinemc.mods.sodium.api.vertex.buffer.VertexBufferWriter; import net.caffeinemc.mods.sodium.api.vertex.format.common.ModelVertex; -import net.coderbot.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; -import net.coderbot.iris.vertices.ImmediateState; import net.irisshaders.iris.api.v0.IrisApi; +import net.irisshaders.iris.compat.sodium.impl.vertex_format.entity_xhfp.EntityVertex; +import net.irisshaders.iris.vertices.ImmediateState; import org.joml.Matrix3f; import org.joml.Matrix4f; import org.lwjgl.system.MemoryStack; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -52,7 +50,7 @@ public static void writeQuadVertices(VertexBufferWriter writer, PoseStack.Pose m long ptr = buffer; int normal = MatrixHelper.transformNormal(matNormal, quad.getLightFace()); - for(int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; ++i) { float x = quad.getX(i); float y = quad.getY(i); float z = quad.getZ(i); diff --git a/src/sodiumCompatibility/resources/mixins.oculus.compat.sodium.json b/src/sodiumCompatibility/resources/mixins.oculus.compat.sodium.json index 78037fd745..a6e9cd7f9a 100644 --- a/src/sodiumCompatibility/resources/mixins.oculus.compat.sodium.json +++ b/src/sodiumCompatibility/resources/mixins.oculus.compat.sodium.json @@ -1,7 +1,7 @@ { "minVersion": "0.8", - "package": "net.coderbot.iris.compat.sodium.mixin", - "plugin": "net.coderbot.iris.compat.sodium.mixin.IrisSodiumCompatMixinPlugin", + "package": "net.irisshaders.iris.compat.sodium.mixin", + "plugin": "net.irisshaders.iris.compat.sodium.mixin.IrisSodiumCompatMixinPlugin", "required": true, "compatibilityLevel": "JAVA_8", "injectors": { @@ -11,30 +11,28 @@ "conformVisibility": true }, "client": [ - "block_id.MixinChunkBuildBuffers", - "block_id.MixinChunkVertexBufferBuilder", "block_id.MixinBakedChunkModelBuilder", + "block_id.MixinChunkBuildBuffers", "block_id.MixinChunkRenderRebuildTask", + "block_id.MixinChunkVertexBufferBuilder", + "clouds.MixinCloudRenderer", + "copyEntity.CuboidMixin", + "copyEntity.ModelPartMixin", + "copyEntity.cull.EntityRendererMixin", + "copyEntity.shadows.EntityRenderDispatcherMixin", "directional_shading.MixinFlatLightPipeline", "directional_shading.MixinSmoothLightPipeline", - "clouds.MixinCloudRenderer", + "font.MixinGlyphRenderer", "options.MixinOptionImpl", "options.MixinRenderSectionManager", "options.MixinSodiumGameOptionPages", "options.MixinSodiumGameOptions", "options.MixinSodiumOptionsGUI", - "copyEntity.CuboidMixin", - "copyEntity.ModelPartMixin", - "copyEntity.cull.EntityRendererMixin", - "copyEntity.shadows.EntityRenderDispatcherMixin", - "font.MixinGlyphRenderer", "pbr_animation.MixinSpriteContents", - "shader_overrides.MixinChunkBuilderMeshingTask", "shader_overrides.MixinGlProgram", "shader_overrides.MixinGlRenderDevice", "shader_overrides.MixinRegionChunkRenderer", "shader_overrides.MixinShaderChunkRenderer", - "shader_overrides.MixinBlockRenderPass", "shader_overrides.MixinShaderType", "shader_overrides.ShaderTypeAccessor", "shadow_map.MixinDefaultChunkRenderer", @@ -46,21 +44,20 @@ "shadow_map.frustum.MixinCullEverythingFrustum", "shadow_map.frustum.MixinNonCullingFrustum", "sky.MixinLevelRenderer", - "vertex_format.entity.MixinEntityRenderDispatcher", - "vertex_format.entity.MixinModelVertex", "vertex_format.ChunkMeshAttributeAccessor", + "vertex_format.CommonVertexAttributeAccessor", "vertex_format.GlVertexAttributeFormatAccessor", "vertex_format.MixinChunkMeshAttribute", + "vertex_format.MixinCommonVertexAttributes", "vertex_format.MixinGlVertexFormatBuilder", - "vertex_format.MixinModelVertexType", "vertex_format.MixinRegionChunkRenderer", "vertex_format.MixinRenderRegionArenas", "vertex_format.MixinRenderSectionManager", - "vertex_format.MixinCommonVertexAttributes", - "vertex_format.CommonVertexAttributeAccessor", + "vertex_format.MixinSodiumBufferBuilder", + "vertex_format.MixinVertexFormatDescriptionImpl", "vertex_format.MixinVertexSerializerCache", "vertex_format.MixinVertexTransform", - "separate_ao.MixinBlockRenderer", - "separate_ao.MixinFluidRenderer" + "vertex_format.entity.MixinEntityRenderDispatcher", + "vertex_format.entity.MixinModelVertex" ] } diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/Digraphs.java b/src/vendored/java/de/odysseus/ithaka/digraph/Digraphs.java index 973d5a3d4b..847001a07e 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/Digraphs.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/Digraphs.java @@ -331,9 +331,9 @@ public static > G copy(Digraph digraph, DigraphFactor * @return subgraph of the supplied de.odysseus.ithaka.digraph containing the specified vertices. */ public static > G subgraph( - Digraph digraph, - Set vertices, - DigraphFactory factory) { + Digraph digraph, + Set vertices, + DigraphFactory factory) { G subgraph = factory.create(); for (V v : vertices) { if (digraph.contains(v)) { diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/DoubledDigraphAdapter.java b/src/vendored/java/de/odysseus/ithaka/digraph/DoubledDigraphAdapter.java index f2c1741c56..dea03148e5 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/DoubledDigraphAdapter.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/DoubledDigraphAdapter.java @@ -26,16 +26,6 @@ * @param vertex type */ public class DoubledDigraphAdapter extends DigraphAdapter implements DoubledDigraph { - /** - * Factory creating DoubledDigraph. - * - * @param factory delegate factory - * @return doubled de.odysseus.ithaka.digraph factory - */ - public static DigraphFactory> getAdapterFactory(final DigraphFactory> factory) { - return () -> new DoubledDigraphAdapter<>(factory); - } - private final DoubledDigraphAdapter reverse; private final DigraphFactory> factory; @@ -55,6 +45,16 @@ protected DoubledDigraphAdapter(DigraphFactory> factory, Do this.reverse = reverse; } + /** + * Factory creating DoubledDigraph. + * + * @param factory delegate factory + * @return doubled de.odysseus.ithaka.digraph factory + */ + public static DigraphFactory> getAdapterFactory(final DigraphFactory> factory) { + return () -> new DoubledDigraphAdapter<>(factory); + } + protected DoubledDigraphAdapter createReverse() { return new DoubledDigraphAdapter<>(factory, this); } diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/MapDigraph.java b/src/vendored/java/de/odysseus/ithaka/digraph/MapDigraph.java index fb18f1e931..7efe598dcd 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/MapDigraph.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/MapDigraph.java @@ -37,41 +37,75 @@ */ public class MapDigraph implements Digraph { private static final int INVALID_WEIGHT = Integer.MIN_VALUE; + private final VertexMapFactory vertexMapFactory; + private final EdgeMapFactory edgeMapFactory; + private final Map> vertexMap; + private int edgeCount; /** - * Factory creating default MapDigraph. + * Create de.odysseus.ithaka.digraph. + * {@link LinkedHashMap}s will be used as vertex/edge maps. + * Vertices and edge targets will be iterated in no particular order. + */ + public MapDigraph() { + this(null); + } + + /** + * Create de.odysseus.ithaka.digraph. + * If a vertex comparator is given, {@link TreeMap}s will be used as vertex/edge maps. + * Vertices and edge targets will be iterated in the order given by the comparator. * - * @return map de.odysseus.ithaka.digraph factory + * @param comparator vertex comparator (may be null) */ - public static DigraphFactory> getDefaultDigraphFactory() { - return getMapDigraphFactory(MapDigraph.getDefaultVertexMapFactory(null), MapDigraph.getDefaultEdgeMapFactory(null)); + public MapDigraph(final Comparator comparator) { + this(comparator, comparator); } /** - * Factory creating MapDigraph. + * Create de.odysseus.ithaka.digraph. + * If a vertex comparator is given, {@link TreeMap}s will be used as vertex maps + * and vertices will be iterated in the order given by the vertex comparator. + * If an edge comparator is given, {@link TreeMap}s will be used as edge maps + * and edge targets will be iterated in the order given by the edge comparator. + */ + public MapDigraph(final Comparator vertexComparator, final Comparator edgeComparator) { + this(MapDigraph.getDefaultVertexMapFactory(vertexComparator), MapDigraph.getDefaultEdgeMapFactory(edgeComparator)); + } + + /** + * Create de.odysseus.ithaka.digraph. * * @param vertexMapFactory factory to create vertex --> edge-map maps * @param edgeMapFactory factory to create edge-target --> edge-value maps - * @return map de.odysseus.ithaka.digraph factory */ - public static DigraphFactory> getMapDigraphFactory( - final VertexMapFactory vertexMapFactory, - final EdgeMapFactory edgeMapFactory) { - return () -> new MapDigraph<>(vertexMapFactory, edgeMapFactory); + public MapDigraph(VertexMapFactory vertexMapFactory, EdgeMapFactory edgeMapFactory) { + this.vertexMapFactory = vertexMapFactory; + this.edgeMapFactory = edgeMapFactory; + + vertexMap = vertexMapFactory.create(); } /** - * Vertex map factory (vertex to edge map). + * Factory creating default MapDigraph. + * + * @return map de.odysseus.ithaka.digraph factory */ - public interface VertexMapFactory { - Map> create(); + public static DigraphFactory> getDefaultDigraphFactory() { + return getMapDigraphFactory(MapDigraph.getDefaultVertexMapFactory(null), MapDigraph.getDefaultEdgeMapFactory(null)); } /** - * Edge map factory (edge target to edge value). + * Factory creating MapDigraph. + * + * @param vertexMapFactory factory to create vertex --> edge-map maps + * @param edgeMapFactory factory to create edge-target --> edge-value maps + * @return map de.odysseus.ithaka.digraph factory */ - public interface EdgeMapFactory { - Object2IntMap create(V source); + public static DigraphFactory> getMapDigraphFactory( + final VertexMapFactory vertexMapFactory, + final EdgeMapFactory edgeMapFactory) { + return () -> new MapDigraph<>(vertexMapFactory, edgeMapFactory); } private static VertexMapFactory getDefaultVertexMapFactory(final Comparator comparator) { @@ -105,61 +139,11 @@ public Object2IntMap create(V ignore) { } }; } - + private static Object2IntMap createEmptyMap() { return Object2IntMaps.emptyMap(); } - private final VertexMapFactory vertexMapFactory; - private final EdgeMapFactory edgeMapFactory; - private final Map> vertexMap; - - private int edgeCount; - - /** - * Create de.odysseus.ithaka.digraph. - * {@link LinkedHashMap}s will be used as vertex/edge maps. - * Vertices and edge targets will be iterated in no particular order. - */ - public MapDigraph() { - this(null); - } - - /** - * Create de.odysseus.ithaka.digraph. - * If a vertex comparator is given, {@link TreeMap}s will be used as vertex/edge maps. - * Vertices and edge targets will be iterated in the order given by the comparator. - * - * @param comparator vertex comparator (may be null) - */ - public MapDigraph(final Comparator comparator) { - this(comparator, comparator); - } - - /** - * Create de.odysseus.ithaka.digraph. - * If a vertex comparator is given, {@link TreeMap}s will be used as vertex maps - * and vertices will be iterated in the order given by the vertex comparator. - * If an edge comparator is given, {@link TreeMap}s will be used as edge maps - * and edge targets will be iterated in the order given by the edge comparator. - */ - public MapDigraph(final Comparator vertexComparator, final Comparator edgeComparator) { - this(MapDigraph.getDefaultVertexMapFactory(vertexComparator), MapDigraph.getDefaultEdgeMapFactory(edgeComparator)); - } - - /** - * Create de.odysseus.ithaka.digraph. - * - * @param vertexMapFactory factory to create vertex --> edge-map maps - * @param edgeMapFactory factory to create edge-target --> edge-value maps - */ - public MapDigraph(VertexMapFactory vertexMapFactory, EdgeMapFactory edgeMapFactory) { - this.vertexMapFactory = vertexMapFactory; - this.edgeMapFactory = edgeMapFactory; - - vertexMap = vertexMapFactory.create(); - } - @Override public boolean add(V vertex) { if (!vertexMap.containsKey(vertex)) { @@ -430,4 +414,18 @@ public String toString() { b.append(")"); return b.toString(); } + + /** + * Vertex map factory (vertex to edge map). + */ + public interface VertexMapFactory { + Map> create(); + } + + /** + * Edge map factory (edge target to edge value). + */ + public interface EdgeMapFactory { + Object2IntMap create(V source); + } } diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotAttribute.java b/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotAttribute.java index 24f081ba30..c0c6137e9d 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotAttribute.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotAttribute.java @@ -20,18 +20,6 @@ import java.io.Writer; public class DotAttribute { - private static boolean isIdentifier(String value) { - if (!Character.isJavaIdentifierStart(value.charAt(0))) { - return false; - } - for (char c : value.substring(1).toCharArray()) { - if (!Character.isJavaIdentifierPart(c)) { - return false; - } - } - return true; - } - private final String name; private final String value; private final boolean quotes; @@ -60,6 +48,18 @@ public DotAttribute(String name, Color value) { this.quotes = true; } + private static boolean isIdentifier(String value) { + if (!Character.isJavaIdentifierStart(value.charAt(0))) { + return false; + } + for (char c : value.substring(1).toCharArray()) { + if (!Character.isJavaIdentifierPart(c)) { + return false; + } + } + return true; + } + public String getName() { return name; } diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotExporter.java b/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotExporter.java index 83e2cbcc15..82343b7868 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotExporter.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/io/dot/DotExporter.java @@ -27,23 +27,6 @@ import java.util.Map; public class DotExporter { - private static class Cluster> { - String id; - G subgraph; - V sample; - DotAttribute tail; - DotAttribute head; - - public Cluster(String id, G subgraph) { - this.id = id; - this.subgraph = subgraph; - this.sample = subgraph.vertices().iterator().next(); - - this.head = new DotAttribute("lhead", id); - this.tail = new DotAttribute("ltail", id); - } - } - private final String indent; private final String lineSpeparator; @@ -133,9 +116,9 @@ private void writeEdge(Writer writer, int level, V source, V target, int edg } private > Map> createClusters( - G digraph, - DotProvider provider, - DigraphProvider subgraphs) { + G digraph, + DotProvider provider, + DigraphProvider subgraphs) { Map> clusters = new HashMap<>(); if (subgraphs != null) { for (V vertex : digraph.vertices()) { @@ -149,10 +132,10 @@ private > Map> createClusters( } public > void export( - DotProvider provider, - G digraph, - DigraphProvider subgraphs, - Writer writer) throws IOException { + DotProvider provider, + G digraph, + DigraphProvider subgraphs, + Writer writer) throws IOException { writer.write("de.odysseus.ithaka.digraph G {"); writer.write(lineSpeparator); @@ -177,12 +160,12 @@ public > void export( } private > void writeNodesAndEdges( - Writer writer, - int level, - DotProvider provider, - G digraph, - Map> clusters, - DigraphProvider subgraphs) throws IOException { + Writer writer, + int level, + DotProvider provider, + G digraph, + Map> clusters, + DigraphProvider subgraphs) throws IOException { for (V vertex : digraph.vertices()) { if (clusters.containsKey(vertex)) { writeCluster(writer, level, provider, vertex, clusters.get(vertex), subgraphs); @@ -193,18 +176,18 @@ private > void writeNodesAndEdges( for (V source : digraph.vertices()) { for (V target : digraph.targets(source)) { writeEdge(writer, level, source, target, digraph.get(source, target).getAsInt(), provider, - clusters.get(source), clusters.get(target)); + clusters.get(source), clusters.get(target)); } } } private > void writeCluster( - Writer writer, - int level, - DotProvider provider, - V subgraphVertex, - Cluster cluster, - DigraphProvider subgraphs) throws IOException { + Writer writer, + int level, + DotProvider provider, + V subgraphVertex, + Cluster cluster, + DigraphProvider subgraphs) throws IOException { indent(writer, level); writer.write("subgraph "); @@ -221,4 +204,21 @@ private > void writeCluster( writer.write("}"); writer.write(lineSpeparator); } + + private static class Cluster> { + String id; + G subgraph; + V sample; + DotAttribute tail; + DotAttribute head; + + public Cluster(String id, G subgraph) { + this.id = id; + this.subgraph = subgraph; + this.sample = subgraph.vertices().iterator().next(); + + this.head = new DotAttribute("lhead", id); + this.tail = new DotAttribute("ltail", id); + } + } } diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/io/tgf/TgfExporter.java b/src/vendored/java/de/odysseus/ithaka/digraph/io/tgf/TgfExporter.java index d381f53389..6cec82bb4d 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/io/tgf/TgfExporter.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/io/tgf/TgfExporter.java @@ -34,9 +34,9 @@ public TgfExporter(String newline) { } public void export( - TgfLabelProvider provider, - Digraph digraph, - Writer writer) throws IOException { + TgfLabelProvider provider, + Digraph digraph, + Writer writer) throws IOException { Map index = new HashMap<>(); int n = 0; diff --git a/src/vendored/java/de/odysseus/ithaka/digraph/util/fas/AbstractFeedbackArcSetProvider.java b/src/vendored/java/de/odysseus/ithaka/digraph/util/fas/AbstractFeedbackArcSetProvider.java index 9fc5640e5d..583fdb9fbd 100644 --- a/src/vendored/java/de/odysseus/ithaka/digraph/util/fas/AbstractFeedbackArcSetProvider.java +++ b/src/vendored/java/de/odysseus/ithaka/digraph/util/fas/AbstractFeedbackArcSetProvider.java @@ -34,34 +34,15 @@ * Abstract feedback arc set provider. */ public abstract class AbstractFeedbackArcSetProvider implements FeedbackArcSetProvider { - class FeedbackTask implements Callable> { - final Digraph digraph; - final EdgeWeights weights; - final FeedbackArcSetPolicy policy; - final Set scc; - - FeedbackTask(Digraph digraph, EdgeWeights weights, FeedbackArcSetPolicy policy, Set scc) { - this.digraph = digraph; - this.weights = weights; - this.policy = policy; - this.scc = scc; - } - - @Override - public FeedbackArcSet call() { - return fas(digraph.subgraph(scc), weights, policy); - } - } - private final ExecutorService executor; /** * Create provider which calculates a feedback arc set on a de.odysseus.ithaka.digraph (in the * current thread). - * + *

    * The provider decomposes a de.odysseus.ithaka.digraph into strongly connected components and computes * feedback arc sets on the components and combines the results. - * + *

    * The {@link #mfas(Digraph, EdgeWeights)} and {@link #lfas(Digraph, EdgeWeights)} * implementation methods do not have to handle arbitrary digraphs for this reason. */ @@ -217,4 +198,23 @@ public FeedbackArcSet getFeedbackArcSet(Digraph digraph, EdgeWeights(result, weight, policy, exact); } + + class FeedbackTask implements Callable> { + final Digraph digraph; + final EdgeWeights weights; + final FeedbackArcSetPolicy policy; + final Set scc; + + FeedbackTask(Digraph digraph, EdgeWeights weights, FeedbackArcSetPolicy policy, Set scc) { + this.digraph = digraph; + this.weights = weights; + this.policy = policy; + this.scc = scc; + } + + @Override + public FeedbackArcSet call() { + return fas(digraph.subgraph(scc), weights, policy); + } + } }