repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Angelica
src\main\java\net\coderbot\iris\parsing\BiomeCategories.java
package net.coderbot.iris.parsing; public enum BiomeCategories { NONE, TAIGA, EXTREME_HILLS, JUNGLE, MESA, PLAINS, SAVANNA, ICY, THE_END, BEACH, FOREST, OCEAN, DESERT, RIVER, SWAMP, MUSHROOM, NETHER, // TODO: This is in Optifine, but undocumented... MOUNTAIN, UNDERGROUND }
Angelica
src\main\java\net\coderbot\iris\parsing\BooleanVectorizedFunction.java
package net.coderbot.iris.parsing; 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 kroppeb.stareval.function.TypedFunction; import java.util.Collection; public class BooleanVectorizedFunction implements TypedFunction { final TypedFunction inner; final int size; final Parameter[] parameters; private final ElementAccessExpression[] vectorAccessors; private int index; public BooleanVectorizedFunction(TypedFunction inner, int size) { this.inner = inner; this.size = size; Parameter[] innerTypes = inner.getParameters(); this.parameters = new Parameter[innerTypes.length]; this.vectorAccessors = new ElementAccessExpression[innerTypes.length]; for (int i = 0; i < innerTypes.length; i++) { this.parameters[i] = new Parameter(VectorType.of((Type.Primitive) innerTypes[i].type(), size)); this.vectorAccessors[i] = new ElementAccessExpression(innerTypes[i].type()); } } @Override public Type getReturnType() { return Type.Boolean; } @Override public Parameter[] getParameters() { return this.parameters; } @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { for (int p = 0; p < params.length; p++) { final Expression param = params[p]; param.evaluateTo(context, functionReturn); this.vectorAccessors[p].vector = functionReturn.objectReturn; } for (int i = 0; i < this.size; i++) { this.index = i; this.inner.evaluateTo(this.vectorAccessors, context, functionReturn); if (!functionReturn.booleanReturn) return; // if false -> return false } // if all true (and thus the last one was true) -> return true } class ElementAccessExpression implements Expression { final Type parameterType; Object vector; ElementAccessExpression(Type parameterType) { this.parameterType = parameterType; } @Override public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { parameterType.getValueFromArray(vector, index, functionReturn); } @Override public void listVariables(Collection<? super VariableExpression> variables) { throw new IllegalStateException(); } } }
Angelica
src\main\java\net\coderbot\iris\parsing\IrisFunctions.java
package net.coderbot.iris.parsing; import kroppeb.stareval.expression.Expression; 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 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.util.Arrays; import java.util.Random; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * # sin(x) * # cos(x) * # asin(x) * # acos(x) * # tan(x) * # atan(x) * # atan2(y, x) * # torad(deg) * # todeg(rad) * # min(x, y ,...) * # max(x, y, ...) * # clamp(x, min, max) Limits a value to be between min and max values * # abs(x) * # floor(x) * # ceil(x) * # exp(x) * # frac(x) * # log(x) * # pow(x) * # random() * # round(x) * # signum(x) * # sqrt(x) * # fmod(x, y) Similar to Math.floorMod() * # if(cond, val, [cond2, val2, ...], val_else) Select a value based one or more conditions * # 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. * <p> * # 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 { public static final FunctionResolver functions; static final FunctionResolver.Builder builder = new FunctionResolver.Builder(); static { { // Unary ops { // negate IrisFunctions.<I2IFunction>addVectorizable("negate", (a) -> -a); IrisFunctions.<F2FFunction>add("negate", (a) -> -a); IrisFunctions.addUnaryOpJOML("negate", VectorType.VEC2, Vector2f::negate); IrisFunctions.addUnaryOpJOML("negate", VectorType.VEC3, Vector3f::negate); IrisFunctions.addUnaryOpJOML("negate", VectorType.VEC4, Vector4f::negate); } } { // binary ops { // add IrisFunctions.<II2IFunction>addVectorizable("add", Integer::sum); IrisFunctions.<FF2FFunction>add("add", Float::sum); IrisFunctions.addBinaryOpJOML("add", VectorType.VEC2, Vector2f::add); IrisFunctions.addBinaryOpJOML("add", VectorType.VEC3, Vector3f::add); IrisFunctions.addBinaryOpJOML("add", VectorType.VEC4, Vector4f::add); } { // subtract IrisFunctions.<II2IFunction>addVectorizable("subtract", (a, b) -> a - b); IrisFunctions.<FF2FFunction>add("subtract", (a, b) -> a - b); IrisFunctions.addBinaryOpJOML("subtract", VectorType.VEC2, Vector2f::sub); IrisFunctions.addBinaryOpJOML("subtract", VectorType.VEC3, Vector3f::sub); IrisFunctions.addBinaryOpJOML("subtract", VectorType.VEC4, Vector4f::sub); } { // multiply IrisFunctions.<II2IFunction>addVectorizable("multiply", (a, b) -> a * b); IrisFunctions.<FF2FFunction>add("multiply", (a, b) -> a * b); IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC2, Vector2f::mul); IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC3, Vector3f::mul); IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC4, Vector4f::mul); } { // divide IrisFunctions.<FF2FFunction>add("divide", (a, b) -> a / b); IrisFunctions.addBinaryOpJOML("divide", VectorType.VEC2, Vector2f::div); IrisFunctions.addBinaryOpJOML("divide", VectorType.VEC3, Vector3f::div); IrisFunctions.addBinaryOpJOML("divide", VectorType.VEC4, Vector4f::div); } { // remainder IrisFunctions.<II2IFunction>addVectorizable("remainder", (a, b) -> a % b); IrisFunctions.<FF2FFunction>add("remainder", (a, b) -> a % b); // IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC2, Vector2f::??); // IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC3, Vector3f::??); // IrisFunctions.addBinaryOpJOML("multiply", VectorType.VEC4, Vector4f::??); } } { IrisFunctions.<II2BFunction>addBooleanVectorizable("equals", (a, b) -> a == b); IrisFunctions.<FF2BFunction>add("equals", (a, b) -> a == b); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC2, false, Vector2f::equals); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC3, false, Vector3f::equals); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC4, false, Vector4f::equals); IrisFunctions.<II2BFunction>addBooleanVectorizable("notEquals", (a, b) -> a != b); IrisFunctions.<FF2BFunction>add("notEquals", (a, b) -> a != b); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC2, true, Vector2f::equals); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC3, true, Vector3f::equals); IrisFunctions.addBinaryToBooleanOpJOML("equal", VectorType.VEC4, true, Vector4f::equals); IrisFunctions.<II2BFunction>add("lessThanOrEquals", (a, b) -> a <= b); IrisFunctions.<FF2BFunction>add("lessThanOrEquals", (a, b) -> a <= b); IrisFunctions.<II2BFunction>add("moreThanOrEquals", (a, b) -> a >= b); IrisFunctions.<FF2BFunction>add("moreThanOrEquals", (a, b) -> a >= b); IrisFunctions.<II2BFunction>add("lessThan", (a, b) -> a < b); IrisFunctions.<FF2BFunction>add("lessThan", (a, b) -> a < b); IrisFunctions.<II2BFunction>add("moreThan", (a, b) -> a > b); IrisFunctions.<FF2BFunction>add("moreThan", (a, b) -> a > b); } { IrisFunctions.<BB2BFunction>addVectorizable("equals", (a, b) -> a == b); IrisFunctions.<BB2BFunction>addVectorizable("notEquals", (a, b) -> a != b); IrisFunctions.<BB2BFunction>addVectorizable("and", (a, b) -> a && b); IrisFunctions.<BB2BFunction>addVectorizable("or", (a, b) -> a || b); IrisFunctions.<B2BFunction>addVectorizable("not", (a) -> !a); } { // these are also vectorizable in glsl // http://learnwebgl.brown37.net/12_shader_language/documents/webgl-reference-card-1_0.pdf // page 4 { // Angle & Trigonometry Functions // optifine IrisFunctions.<F2FFunction>add("torad", (a) -> (float) Math.toRadians(a)); IrisFunctions.<F2FFunction>add("todeg", (a) -> (float) Math.toDegrees(a)); IrisFunctions.<F2FFunction>add("radians", (a) -> (float) Math.toRadians(a)); IrisFunctions.<F2FFunction>add("degrees", (a) -> (float) Math.toDegrees(a)); IrisFunctions.<F2FFunction>add("sin", (a) -> (float) Math.sin(a)); IrisFunctions.<F2FFunction>add("cos", (a) -> (float) Math.cos(a)); IrisFunctions.<F2FFunction>add("tan", (a) -> (float) Math.tan(a)); IrisFunctions.<F2FFunction>add("asin", (a) -> (float) Math.asin(a)); IrisFunctions.<F2FFunction>add("acos", (a) -> (float) Math.acos(a)); IrisFunctions.<F2FFunction>add("atan", (a) -> (float) Math.atan(a)); IrisFunctions.<FF2FFunction>add("atan", (y, x) -> (float) Math.atan2(y, x)); // optifine IrisFunctions.<FF2FFunction>add("atan2", (y, x) -> (float) Math.atan2(y, x)); } { // Exponential Functions IrisFunctions.<FF2FFunction>add("pow", (a, b) -> (float) Math.pow(a, b)); IrisFunctions.<F2FFunction>add("exp", (a) -> (float) Math.exp(a)); IrisFunctions.<F2FFunction>add("log", (a) -> (float) Math.log(a)); // java does not have built ins: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4851627 IrisFunctions.<F2FFunction>add("exp2", (a) -> (float) Math.pow(2, a)); IrisFunctions.<F2FFunction>add("log2", (a) -> (float) (Math.log(a) / Math.log(2))); IrisFunctions.<F2FFunction>add("sqrt", (a) -> (float) Math.sqrt(a)); // IrisFunctions.<F2FFunction>addVectorizable("inversesqrt", (a) -> (float) Math.(a)); // optifine IrisFunctions.<F2FFunction>add("log10", (a) -> (float) Math.log10(a)); // TODO the base may be static so doing `log(2, x)` would be slower than `log(x)/log(2)` IrisFunctions.<FF2FFunction>add("log", (base, value) -> (float) (Math.log(value) / Math.log(base))); // cause I want consistency IrisFunctions.<F2FFunction>add("exp10", (a) -> (float) Math.pow(10, a)); } { // Common Functions IrisFunctions.<I2IFunction>addVectorizable("abs", Math::abs); IrisFunctions.<F2FFunction>add("abs", Math::abs); IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC2, Vector2f::absolute); IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC3, Vector3f::absolute); IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC4, Vector4f::absolute); IrisFunctions.<F2FFunction>add("sign", Math::signum); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC2, Vector2f::??); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC3, Vector3f::??); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC4, Vector4f::??); // optifine IrisFunctions.<F2FFunction>add("signum", Math::signum); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC2, Vector2f::??); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC3, Vector3f::??); // IrisFunctions.addUnaryOpJOML("abs", VectorType.VEC4, Vector4f::??); // because my type checker can handle (float) -> float and (float) -> int, // floor doesn't require a cast to int, but does not cause issues if the float is too big and // casting to float and back would change the result IrisFunctions.<F2FFunction>add("floor", (a) -> (float) Math.floor(a)); IrisFunctions.<F2IFunction>add("floor", (a) -> (int) Math.floor(a)); IrisFunctions.addUnaryOpJOML("floor", VectorType.VEC2, Vector2f::floor); IrisFunctions.addUnaryOpJOML("floor", VectorType.VEC3, Vector3f::floor); IrisFunctions.addUnaryOpJOML("floor", VectorType.VEC4, Vector4f::floor); IrisFunctions.<F2FFunction>add("ceil", (a) -> (float) Math.ceil(a)); IrisFunctions.<F2IFunction>add("ceil", (a) -> (int) Math.ceil(a)); IrisFunctions.addUnaryOpJOML("ceil", VectorType.VEC2, Vector2f::ceil); IrisFunctions.addUnaryOpJOML("ceil", VectorType.VEC3, Vector3f::ceil); IrisFunctions.addUnaryOpJOML("ceil", VectorType.VEC4, Vector4f::ceil); IrisFunctions.<F2FFunction>add("frac", (a) -> (float) (a - Math.floor(a))); // IrisFunctions.addUnaryOpJOML("frac", VectorType.VEC2, Vector2f::??); // IrisFunctions.addUnaryOpJOML("frac", VectorType.VEC3, Vector3f::??); // IrisFunctions.addUnaryOpJOML("frac", VectorType.VEC4, Vector4f::??); // optifine // TODO: why does Math.round give an int? // IrisFunctions.<F2FFunction>addVectorizable("round", (a) -> (float) Math.round(a)); // TODO maybe add round with a specifyable precission? // IrisFunctions.<F2IFunction>addVectorizable("round", (a) -> (int) Math.round(a)); // mod is also already an operator // TODO: min and max require vararg for optifine compat // TODO: glsl has vecn min(vecn a, float b) IrisFunctions.<II2IFunction>addVectorizable("min", Math::min); IrisFunctions.<FF2FFunction>add("min", Math::min); IrisFunctions.addBinaryOpJOML("min", VectorType.VEC2, Vector2f::min); IrisFunctions.addBinaryOpJOML("min", VectorType.VEC3, Vector3f::min); IrisFunctions.addBinaryOpJOML("min", VectorType.VEC4, Vector4f::min); IrisFunctions.<II2IFunction>addVectorizable("max", Math::max); IrisFunctions.<FF2FFunction>add("max", Math::max); IrisFunctions.addBinaryOpJOML("max", VectorType.VEC2, Vector2f::max); IrisFunctions.addBinaryOpJOML("max", VectorType.VEC3, Vector3f::max); IrisFunctions.addBinaryOpJOML("max", VectorType.VEC4, Vector4f::max); { // Fake vararg for (int length = 3; length <= 16; length++) { { // min float Type[] inputs = new Type[length]; Arrays.fill(inputs, Type.Float); IrisFunctions.add("min", new AbstractTypedFunction(Type.Float, inputs) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); float min = functionReturn.floatReturn; for (int i = 1; i < params.length; i++) { params[1].evaluateTo(context, functionReturn); min = Math.min(min, functionReturn.floatReturn); } functionReturn.floatReturn = min; } }); } { // max float Type[] inputs = new Type[length]; Arrays.fill(inputs, Type.Float); IrisFunctions.add("max", new AbstractTypedFunction(Type.Float, inputs) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); float max = functionReturn.floatReturn; for (int i = 1; i < params.length; i++) { params[1].evaluateTo(context, functionReturn); max = Math.max(max, functionReturn.floatReturn); } functionReturn.floatReturn = max; } }); } { // min int Type[] inputs = new Type[length]; Arrays.fill(inputs, Type.Int); IrisFunctions.addVectorizable("min", new AbstractTypedFunction(Type.Int, inputs) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); int min = functionReturn.intReturn; for (int i = 1; i < params.length; i++) { params[1].evaluateTo(context, functionReturn); min = Math.min(min, functionReturn.intReturn); } functionReturn.intReturn = min; } }); } { // max int Type[] inputs = new Type[length]; Arrays.fill(inputs, Type.Int); IrisFunctions.addVectorizable("max", new AbstractTypedFunction(Type.Int, inputs) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); int max = functionReturn.intReturn; for (int i = 1; i < params.length; i++) { params[1].evaluateTo(context, functionReturn); max = Math.max(max, functionReturn.intReturn); } functionReturn.intReturn = max; } }); } } } // if max < min => undefined behaviour // TODO: glsl has vecn mix(vecn x, float min, float max) IrisFunctions.<III2IFunction>addVectorizable("clamp", (val, min, max) -> Math.max(min, Math.min(max, val))); IrisFunctions.<FFF2FFunction>add("clamp", (val, min, max) -> Math.max(min, Math.min(max, val))); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC2, (val, min, max, dest) -> { val.min(max, dest); dest.max(min); }); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC3, (val, min, max, dest) -> { val.min(max, dest); dest.max(min); }); IrisFunctions.addTernaryOpJOML("clamp", VectorType.VEC4, (val, min, max, dest) -> { val.min(max, dest); dest.max(min); }); // TODO: glsl has vecn mix(vecn x, vecn y, float a) IrisFunctions.<FFF2FFunction>add("mix", (x, y, a) -> x + (y - x) * a); // TODO flaot vector lerp // TODO: glsl has vecn step(float edge, vecn x) IrisFunctions.<II2IFunction>addVectorizable("edge", (edge, x) -> (x < edge) ? 0 : 1); IrisFunctions.<FF2FFunction>add("edge", (edge, x) -> (x < edge) ? 0 : 1); // TODO float vector step // TODO: smooth step } { // Geometric Functions // TODO: Geometric Functions } { // Matrix Functions // TODO: Add matrices } { // Vector Relational Functions // TODO: These might clash with the operators // Although we can have multiple return values so } { { // fmod IrisFunctions.<II2IFunction>addVectorizable("fmod", Math::floorMod); IrisFunctions.<FF2FFunction>add("fmod", (a, b) -> (a % b + b) % b); } { Random random = new Random(); // randomInt(), randomInt(int bound), randomInt(int inclusiveMin, int exclusiveMax) IrisFunctions.<V2IFunction>addVectorizable("randomInt", random::nextInt); IrisFunctions.<I2IFunction>addVectorizable("randomInt", random::nextInt); IrisFunctions.<II2IFunction>addVectorizable("randomInt", (a, b) -> random.nextInt(b - a) + a); // random, random(float min, float max) IrisFunctions.<V2FFunction>add("random", random::nextFloat); IrisFunctions.<FF2FFunction>add("random", (min, max) -> min + random.nextFloat() * (max - min)); } { // IF // if(boolean, primitive, primitive) -> primitive // if(boolean, xvec, xvec) -> xvec // TODO: REDO: if(bvec, xvec, xvec) -> xvec // TODO: optifine requires vararg for (Type.Primitive type : Type.AllPrimitives) { add("if", new AbstractTypedFunction(type, new Type[]{Type.Boolean, type, type}) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); params[ functionReturn.booleanReturn ? 1 : 2 ].evaluateTo(context, functionReturn); } }); } for (Type type : VectorType.AllVectorTypes) { add("if", new AbstractTypedFunction(type, new Type[]{Type.Boolean, type, type}) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); params[ functionReturn.booleanReturn ? 1 : 2 ].evaluateTo(context, functionReturn); } }); } { // FAKE vararg for (int length = 2; length <= 16; length++) { for (Type.Primitive type : Type.AllPrimitives) { Type[] params = new Type[length * 2 + 1]; for (int i = 0; i < length * 2; i += 2) { params[i] = Type.Boolean; params[i + 1] = type; } params[length * 2] = type; int finalLength = length * 2; add("if", new AbstractTypedFunction(type, params) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { for (int i = 0; i < finalLength; i += 2) { params[i].evaluateTo(context, functionReturn); if (functionReturn.booleanReturn) { params[i + 1].evaluateTo(context, functionReturn); return; } params[finalLength].evaluateTo(context, functionReturn); } } }); } } } } { // smooth // 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(); @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, () -> new AbstractTypedFunction( Type.Float, new Parameter[]{ new Parameter(Type.Float, true), // id for backward compat with optifine new Parameter(Type.Float, false), // target }, 1, false ) { private final SmoothFloat smoothFloat = new SmoothFloat(); @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[1].evaluateTo(context, functionReturn); float target = functionReturn.floatReturn; functionReturn.floatReturn = smoothFloat.updateAndGet( target, 1, 1 ); } }); // 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(); @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; functionReturn.floatReturn = smoothFloat.updateAndGet( target, fadeTime, fadeTime ); } }); // smooth(id, target, fadeTime) builder.addDynamicFunction("smooth", Type.Float, () -> new AbstractTypedFunction( Type.Float, new Parameter[]{ new Parameter(Type.Float, true), // id for backward compat with optifine new Parameter(Type.Float, false), // target new Parameter(Type.Float, false), // fadeTime }, 1, false ) { private final SmoothFloat smoothFloat = new SmoothFloat(); @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[1].evaluateTo(context, functionReturn); float target = functionReturn.floatReturn; params[2].evaluateTo(context, functionReturn); float fadeTime = functionReturn.floatReturn; functionReturn.floatReturn = smoothFloat.updateAndGet( target, fadeTime, fadeTime ); } }); // 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(); @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, () -> new AbstractTypedFunction( Type.Float, new Parameter[]{ new Parameter(Type.Float, true), // id for backward compat with optifine new Parameter(Type.Float, false), // target new Parameter(Type.Float, false), // fadeUpTime new Parameter(Type.Float, false), // fadeDownTime }, 1, false ) { private final SmoothFloat smoothFloat = new SmoothFloat(); @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[1].evaluateTo(context, functionReturn); float target = functionReturn.floatReturn; params[2].evaluateTo(context, functionReturn); float fadeUpTime = functionReturn.floatReturn; params[3].evaluateTo(context, functionReturn); float fadeDownTime = functionReturn.floatReturn; functionReturn.floatReturn = smoothFloat.updateAndGet( target, fadeUpTime, fadeDownTime ); } }); } } } // casts { addImplicitCast(Type.Int, Type.Float, r -> r.floatReturn = r.intReturn); // this is actually done by round i think addExplicitCast(Type.Float, Type.Int, r -> r.intReturn = (int) r.floatReturn); } // boolean functions { IrisFunctions.<III2BFunction>add("between", (a, min, max) -> a >= min && a <= max); IrisFunctions.<FFF2BFunction>add("between", (a, min, max) -> a >= min && a <= max); IrisFunctions.<FFF2BFunction>add("equals", (a, b, epsilon) -> Math.abs(a - b) <= epsilon); // TODO: varargs // TODO also for other types { // FAKE vararg for (int length = 2; length <= 32; length++) { Type[] params = new Type[length]; Arrays.fill(params, Type.Float); int finalLength = length; IrisFunctions.add("in", new AbstractTypedFunction( Type.Boolean, params ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn 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) { functionReturn.booleanReturn = true; return; } } functionReturn.booleanReturn = false; } }); } } } // create vectors { for (Type.Primitive type : new Type.Primitive[]{Type.Boolean, Type.Int}) { for (int size = 2; size <= 4; size++) { 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); } } add("vec2", new AbstractTypedFunction( VectorType.VEC2, new Type[]{Type.Float, Type.Float} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); float x = functionReturn.floatReturn; 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); } }); add("vec3", new AbstractTypedFunction( 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); float x = functionReturn.floatReturn; params[1].evaluateTo(context, functionReturn); float y = functionReturn.floatReturn; 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); } }); add("vec4", new AbstractTypedFunction( 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); float x = functionReturn.floatReturn; params[1].evaluateTo(context, functionReturn); float y = functionReturn.floatReturn; params[2].evaluateTo(context, functionReturn); float z = functionReturn.floatReturn; 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); } }); } // accessors { // 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"} }; { // access$0 for (String access : accessNames[0]) { IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector2f) functionReturn.objectReturn).x; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector2i) functionReturn.objectReturn).x; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector3f) functionReturn.objectReturn).x; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector3i) functionReturn.objectReturn).x; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector4f) functionReturn.objectReturn).x; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector4i) functionReturn.objectReturn).x; } }); } } { // access$1 for (String access : accessNames[1]) { IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector2f) functionReturn.objectReturn).y; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC2} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector2i) functionReturn.objectReturn).y; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector3f) functionReturn.objectReturn).y; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector3i) functionReturn.objectReturn).y; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector4f) functionReturn.objectReturn).y; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector4i) functionReturn.objectReturn).y; } }); } } { // access$2 for (String access : accessNames[2]) { IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector3f) functionReturn.objectReturn).z; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC3} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector3i) functionReturn.objectReturn).z; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector4f) functionReturn.objectReturn).z; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector4i) functionReturn.objectReturn).z; } }); } } { // access$3 for (String access : accessNames[3]) { IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Float, new Type[]{VectorType.VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.floatReturn = ((Vector4f) functionReturn.objectReturn).w; } }); IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( Type.Int, new Type[]{VectorType.I_VEC4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.intReturn = ((Vector4i) functionReturn.objectReturn).w; } }); } } { // matrix access for (int i = 0; i < 4; i++) { for (String access : accessNames[i]) { int finalI = i; IrisFunctions.add("<access$" + access + ">", new AbstractTypedFunction( VectorType.VEC4, new Type[]{MatrixType.MAT4} ) { @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); functionReturn.objectReturn = ((Matrix4f) functionReturn.objectReturn).getColumn(finalI, new Vector4f()); } }); } } } } functions = builder.build(); } static <T extends TypedFunction> void addVectorized(String name, T function) { if (function.getReturnType() instanceof Type.Primitive) { add(name, new VectorizedFunction(function, 2)); add(name, new VectorizedFunction(function, 3)); add(name, new VectorizedFunction(function, 4)); } else { throw new IllegalArgumentException(name + " is not vectorizable"); } } static <T extends TypedFunction> void addVectorizable(String name, T function) { add(name, function); addVectorized(name, function); } static <T extends TypedFunction> void addBooleanVectorizable(String name, T function) { assert function.getReturnType().equals(Type.Boolean); add(name, function); if (function.getReturnType() instanceof Type.Primitive) { add(name, new BooleanVectorizedFunction(function, 2)); add(name, new BooleanVectorizedFunction(function, 3)); add(name, new BooleanVectorizedFunction(function, 4)); } else { throw new IllegalArgumentException(name + " is not vectorizable"); } } static <T> void addUnaryOpJOML(String name, VectorType.JOMLVector<T> type, BiConsumer<T, T> function) { builder.add(name, new AbstractTypedFunction( type, new Type[]{type} ) { final private T vector = type.create(); @SuppressWarnings("unchecked") @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); T a = (T) functionReturn.objectReturn; function.accept(a, this.vector); functionReturn.objectReturn = this.vector; } }); } static <T> void addBinaryOpJOML(String name, VectorType.JOMLVector<T> type, TriConsumer<T, T, T> function) { builder.add(name, new AbstractTypedFunction( type, new Type[]{type, type} ) { final private T vector = type.create(); @SuppressWarnings("unchecked") @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); T a = (T) functionReturn.objectReturn; params[1].evaluateTo(context, functionReturn); T b = (T) functionReturn.objectReturn; function.accept(a, b, this.vector); functionReturn.objectReturn = this.vector; } }); } static <T> void addTernaryOpJOML(String name, VectorType.JOMLVector<T> type, QuadConsumer<T, T, T, T> function) { builder.add(name, new AbstractTypedFunction( type, new Type[]{type, type, type} ) { final private T vector = type.create(); @SuppressWarnings("unchecked") @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); T a = (T) functionReturn.objectReturn; params[1].evaluateTo(context, functionReturn); T b = (T) functionReturn.objectReturn; params[2].evaluateTo(context, functionReturn); T c = (T) functionReturn.objectReturn; function.accept(a, b, c, this.vector); functionReturn.objectReturn = this.vector; } }); } static <T> void addBinaryToBooleanOpJOML( String name, VectorType.JOMLVector<T> type, boolean inverted, ObjectObject2BooleanFunction<T, T> function) { builder.add(name, new AbstractTypedFunction( type, new Type[]{type, type} ) { @SuppressWarnings("unchecked") @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); T a = (T) functionReturn.objectReturn; params[1].evaluateTo(context, functionReturn); T b = (T) functionReturn.objectReturn; functionReturn.objectReturn = function.apply(a, b) != inverted; } }); } static <T extends TypedFunction> void add(String name, T function) { builder.add(name, function); } static void addCast(final String name, final Type from, final Type to, final Consumer<FunctionReturn> function) { add(name, new TypedFunction() { @Override public Type getReturnType() { return to; } @Override public Parameter[] getParameters() { return new Parameter[]{new Parameter(from)}; } @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { params[0].evaluateTo(context, functionReturn); function.accept(functionReturn); } }); } static void addImplicitCast(final Type from, final Type to, final Consumer<FunctionReturn> function) { addCast("<cast>", from, to, function); addExplicitCast(from, to, function); } static void addExplicitCast(final Type from, final Type to, final Consumer<FunctionReturn> function) { addCast("to" + to.getClass().getSimpleName(), from, to, function); } public static void main(String[] args) { functions.logAllFunctions(); } interface ObjectObject2BooleanFunction<T, U> { boolean apply(T t, U u); } interface TriConsumer<T, U, V> { void accept(T t, U u, V v); } interface QuadConsumer<T, U, V, W> { void accept(T t, U u, V v, W w); } }
Angelica
src\main\java\net\coderbot\iris\parsing\IrisOptions.java
package net.coderbot.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); 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("and", 3); static final BinaryOp Or = new BinaryOp("or", 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("≠", NotEquals); builder.addBinaryOp("≤", LessThanOrEquals); builder.addBinaryOp("≥", MoreThanOrEquals); builder.addBinaryOp("&&", And); builder.addBinaryOp("||", Or); builder.addUnaryOp("!", Not); builder.addUnaryOp("-", Negate); options = builder.build(); } }
Angelica
src\main\java\net\coderbot\iris\parsing\MatrixType.java
package net.coderbot.iris.parsing; import kroppeb.stareval.function.Type; import org.joml.Matrix2f; import org.joml.Matrix3f; import org.joml.Matrix4f; import java.util.function.Supplier; public class MatrixType<T> extends Type.ObjectType { public static final MatrixType<Matrix4f> MAT4 = new MatrixType<>("mat4", Matrix4f::new); public static MatrixType<Matrix2f> MAT2 = new MatrixType<>("mat2", Matrix2f::new); public static MatrixType<Matrix3f> MAT3 = new MatrixType<>("mat3", Matrix3f::new); final String name; public MatrixType(String name, Supplier<T> supplier) { this.name = name; } @Override public String toString() { return name; } }
Angelica
src\main\java\net\coderbot\iris\parsing\SmoothFloat.java
package net.coderbot.iris.parsing; import net.coderbot.iris.uniforms.SystemTimeUniforms; /** * An implementation of basic exponential smoothing that converts a sequence of unsmoothed values into a sequence of * smoothed values. * * @see <a href="https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_(simple)_exponential_smoothing_(Holt_linear)"> * Wikipedia: Basic (simple) exponential smoothing (Holt linear)</a> */ public class SmoothFloat { /** * Natural logarithm of 2, ie. {@code ln(2)} */ private static final double LN_OF_2 = Math.log(2.0); /** * 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; private float cachedHalfLifeUp; private float cachedDecayUp; 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 */ public float updateAndGet(float value, float halfLifeUp, float halfLifeDown) { if (halfLifeUp != cachedHalfLifeUp) { cachedHalfLifeUp = halfLifeUp; if (halfLifeUp == 0.0f) { cachedDecayUp = 0; } else { cachedDecayUp = computeDecay(halfLifeUp * 0.1F); } } if (halfLifeDown != cachedHalfLifeDown) { cachedHalfLifeDown = halfLifeDown; if (halfLifeDown == 0.0f) { cachedDecayDown = 0; } else { cachedDecayDown = computeDecay(halfLifeDown * 0.1F); } } if (!hasInitialValue) { // There is no smoothing on the first value. // This is not an optimal approach to choosing the initial value: // https://en.wikipedia.org/wiki/Exponential_smoothing#Choosing_the_initial_smoothed_value // // However, it works well enough for now. accumulator = value; hasInitialValue = true; return accumulator; } // Implements the basic variant of exponential smoothing // https://en.wikipedia.org/wiki/Exponential_smoothing#Basic_(simple)_exponential_smoothing_(Holt_linear) // 𝚫t float lastFrameTime = SystemTimeUniforms.TIMER.getLastFrameTime(); float decay = value > this.accumulator ? cachedDecayUp : cachedDecayDown; if (decay == 0.0f) { accumulator = value; return accumulator; } // Compute the smoothing factor based on our // α = 1 - e^(-𝚫t/τ) = 1 - e^(-k𝚫t) float smoothingFactor = 1.0f - exponentialDecayFactor(decay, lastFrameTime); // sₜ = αxₜ + (1 - α)sₜ₋₁ accumulator = lerp(accumulator, value, smoothingFactor); return accumulator; } private float computeDecay(float halfLife) { // Compute the decay constant from the half life // https://en.wikipedia.org/wiki/Exponential_decay#Measuring_rates_of_decay // https://en.wikipedia.org/wiki/Exponential_smoothing#Time_constant // k = 1 / τ return (float) (1.0f / (halfLife / LN_OF_2)); } }
Angelica
src\main\java\net\coderbot\iris\parsing\VectorConstructor.java
package net.coderbot.iris.parsing; import kroppeb.stareval.Util; import kroppeb.stareval.expression.Expression; import kroppeb.stareval.function.AbstractTypedFunction; import kroppeb.stareval.function.FunctionContext; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; 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)) ); } @Override public VectorType.ArrayVector getReturnType() { return (VectorType.ArrayVector) super.getReturnType(); } @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { VectorType.ArrayVector vectorType = this.getReturnType(); vectorType.map(params, context, functionReturn, (i, p, ctx, fr) -> p[i].evaluateTo(ctx, fr)); } }
Angelica
src\main\java\net\coderbot\iris\parsing\VectorizedFunction.java
package net.coderbot.iris.parsing; 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 kroppeb.stareval.function.TypedFunction; import java.util.Collection; public class VectorizedFunction implements TypedFunction { final TypedFunction inner; final int size; final VectorType.ArrayVector returnType; final Parameter[] parameters; private final ElementAccessExpression[] vectorAccessors; private int index; private final VectorType.ArrayVector.IntObjectObjectObjectConsumer<VectorizedFunction, FunctionContext, FunctionReturn> mapper = (i, self, ctx, fr) -> { self.index = i; self.inner.evaluateTo(self.vectorAccessors, ctx, fr); }; public VectorizedFunction(TypedFunction inner, int size) { this.inner = inner; this.size = size; this.returnType = new VectorType.ArrayVector(inner.getReturnType(), size); Parameter[] innerTypes = inner.getParameters(); this.parameters = new Parameter[innerTypes.length]; this.vectorAccessors = new ElementAccessExpression[innerTypes.length]; for (int i = 0; i < innerTypes.length; i++) { this.parameters[i] = new Parameter(new VectorType.ArrayVector(innerTypes[i].type(), size)); this.vectorAccessors[i] = new ElementAccessExpression(innerTypes[i].type()); } } @Override public Type getReturnType() { return this.returnType; } @Override public Parameter[] getParameters() { return this.parameters; } @Override public void evaluateTo(Expression[] params, FunctionContext context, FunctionReturn functionReturn) { for (int p = 0; p < params.length; p++) { final Expression param = params[p]; param.evaluateTo(context, functionReturn); this.vectorAccessors[p].vector = functionReturn.objectReturn; } returnType.map(this, context, functionReturn, this.mapper); } class ElementAccessExpression implements Expression { final Type parameterType; Object vector; ElementAccessExpression(Type parameterType) { this.parameterType = parameterType; } @Override public void evaluateTo(FunctionContext context, FunctionReturn functionReturn) { parameterType.getValueFromArray(vector, index, functionReturn); } @Override public void listVariables(Collection<? super VariableExpression> variables) { throw new IllegalStateException(); } } }
Angelica
src\main\java\net\coderbot\iris\parsing\VectorType.java
package net.coderbot.iris.parsing; import kroppeb.stareval.function.FunctionReturn; import kroppeb.stareval.function.Type; 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; import java.util.function.Supplier; import java.util.stream.IntStream; import java.util.stream.Stream; abstract public class VectorType extends Type.ObjectType { public static final JOMLVector<Vector2f> VEC2 = new JOMLVector<>("vec2", Vector2f::new); public static final JOMLVector<Vector3f> VEC3 = new JOMLVector<>("vec3", Vector3f::new); public static final JOMLVector<Vector4f> VEC4 = new JOMLVector<>("vec4", Vector4f::new); public static final JOMLVector<Vector2i> I_VEC2 = new JOMLVector<>("ivec2", Vector2i::new); public static final JOMLVector<Vector3i> I_VEC3 = new JOMLVector<>("ivec3", Vector3i::new); public static final JOMLVector<Vector4i> 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; public ArrayVector(Type inner, int size) { this.inner = inner; this.size = size; } public Object createObject() { return this.inner.createArray(this.size); } public void setValue(Object vector, int index, FunctionReturn functionReturn) { this.inner.setValueFromReturn(vector, index, functionReturn); } public void getValue(Object vector, int index, FunctionReturn functionReturn) { this.inner.getValueFromArray(vector, index, functionReturn); } public <T1, T2> void map(T1 item1, T2 item2, FunctionReturn functionReturn, IntObjectObjectObjectConsumer<T1, T2, FunctionReturn> mapper) { Object array = this.createObject(); for (int i = 0; i < this.size; i++) { mapper.accept(i, item1, item2, functionReturn); this.setValue(array, i, functionReturn); } functionReturn.objectReturn = array; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ArrayVector that)) return false; return size == that.size && inner.equals(that.inner); } @Override public int hashCode() { return Objects.hash(inner, size); } @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<TB, TC, TD> { void accept(int a, TB b, TC c, TD d); } } public static class JOMLVector<T> extends VectorType { private final String name; private final Supplier<T> supplier; public JOMLVector(String name, Supplier<T> supplier) { this.name = name; this.supplier = supplier; } @Override public String toString() { return this.name; } public T create() { return this.supplier.get(); } } }
Angelica
src\main\java\net\coderbot\iris\pipeline\ClearPass.java
package net.coderbot.iris.pipeline; import net.coderbot.iris.gl.framebuffer.GlFramebuffer; import net.minecraft.client.Minecraft; import org.joml.Vector4f; import org.lwjgl.opengl.GL11; import java.util.Objects; import java.util.function.IntSupplier; public class ClearPass { private final Vector4f color; private final IntSupplier viewportX; private final IntSupplier viewportY; private final GlFramebuffer framebuffer; private final int clearFlags; public ClearPass(Vector4f color, IntSupplier viewportX, IntSupplier viewportY, GlFramebuffer framebuffer, int clearFlags) { this.color = color; this.viewportX = viewportX; this.viewportY = viewportY; this.framebuffer = framebuffer; this.clearFlags = clearFlags; } public void execute(Vector4f defaultClearColor) { GL11.glViewport(0, 0, viewportX.getAsInt(), viewportY.getAsInt()); framebuffer.bind(); Vector4f color = Objects.requireNonNull(defaultClearColor); if (this.color != null) { color = this.color; } GL11.glClearColor(color.x, color.y, color.z, color.w); GL11.glClear(clearFlags); if (Minecraft.isRunningOnMac) { GL11.glGetError(); } } public GlFramebuffer getFramebuffer() { return framebuffer; } }
Angelica
src\main\java\net\coderbot\iris\pipeline\ClearPassCreator.java
package net.coderbot.iris.pipeline; import com.google.common.collect.ImmutableList; 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 org.joml.Vector2i; import org.joml.Vector4f; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL20; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ClearPassCreator { public static ImmutableList<ClearPass> createClearPasses(RenderTargets renderTargets, boolean fullClear, PackRenderTargetDirectives renderTargetDirectives) { final int maxDrawBuffers = GL11.glGetInteger(GL20.GL_MAX_DRAW_BUFFERS); // Sort buffers by their clear color so we can group up glClear calls. Map<Vector2i, Map<ClearPassInformation, IntList>> clearByColor = new HashMap<>(); renderTargetDirectives.getRenderTargetSettings().forEach((bufferI, settings) -> { // unboxed final int buffer = bufferI; if (fullClear || settings.shouldClear()) { Vector4f defaultClearColor; if (buffer == 0) { // colortex0 is cleared to the fog color (with 1.0 alpha) by default. defaultClearColor = null; } else if (buffer == 1) { // colortex1 is cleared to solid white (with 1.0 alpha) by default. defaultClearColor = new Vector4f(1.0f, 1.0f, 1.0f, 1.0f); } else { // all other buffers are cleared to solid black (with 0.0 alpha) by default. defaultClearColor = new Vector4f(0.0f, 0.0f, 0.0f, 0.0f); } RenderTarget target = renderTargets.get(buffer); Vector4f clearColor = settings.getClearColor().orElse(defaultClearColor); clearByColor.computeIfAbsent(new Vector2i(target.getWidth(), target.getHeight()), size -> new HashMap<>()).computeIfAbsent(new ClearPassInformation(clearColor, target.getWidth(), target.getHeight()), color -> new IntArrayList()).add(buffer); } }); List<ClearPass> clearPasses = new ArrayList<>(); 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)]; 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), GL11.GL_COLOR_BUFFER_BIT)); clearPasses.add(new ClearPass(clearInfo.getColor(), clearInfo::getWidth, clearInfo::getHeight, renderTargets.createClearFramebuffer(false, clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); } }); }); return ImmutableList.copyOf(clearPasses); } public static ImmutableList<ClearPass> createShadowClearPasses(ShadowRenderTargets renderTargets, boolean fullClear, PackShadowDirectives renderTargetDirectives) { final int maxDrawBuffers = GL11.glGetInteger(GL20.GL_MAX_DRAW_BUFFERS); // Sort buffers by their clear color so we can group up glClear calls. Map<Vector4f, IntList> clearByColor = new HashMap<>(); for (int i = 0; i < renderTargetDirectives.getColorSamplingSettings().size(); i++) { // unboxed PackShadowDirectives.SamplingSettings settings = renderTargetDirectives.getColorSamplingSettings().get(i); if (fullClear || settings.getClear()) { Vector4f clearColor = settings.getClearColor(); clearByColor.computeIfAbsent(clearColor, color -> new IntArrayList()).add(i); } } List<ClearPass> clearPasses = new ArrayList<>(); clearByColor.forEach((clearColor, 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)]; 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(clearColor, renderTargets::getResolution, renderTargets::getResolution, renderTargets.createFramebufferWritingToAlt(clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); clearPasses.add(new ClearPass(clearColor, renderTargets::getResolution, renderTargets::getResolution, renderTargets.createFramebufferWritingToMain(clearBuffers), GL11.GL_COLOR_BUFFER_BIT)); } }); return ImmutableList.copyOf(clearPasses); } }
Angelica
src\main\java\net\coderbot\iris\pipeline\ClearPassInformation.java
package net.coderbot.iris.pipeline; import org.joml.Vector4f; public class ClearPassInformation { private final Vector4f color; private final int width; private final int height; public ClearPassInformation(Vector4f vector4f, int width, int height) { this.color = vector4f; this.width = width; this.height = height; } public Vector4f getColor() { return color; } public int getWidth() { return width; } public int getHeight() { return height; } @Override public boolean equals(Object obj) { if (!(obj instanceof ClearPassInformation)) { return false; } ClearPassInformation information = (ClearPassInformation) obj; return information.color.equals(this.color) && information.height == this.height && information.width == this.width; } }
Angelica
src\main\java\net\coderbot\iris\pipeline\CustomTextureManager.java
package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.glsm.GLStateManager; 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.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.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.FilenameUtils; import org.lwjgl.opengl.GL11; import java.io.IOException; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Optional; import java.util.function.IntSupplier; public class CustomTextureManager { private final EnumMap<TextureStage, Object2ObjectMap<String, IntSupplier>> customTextureIdMap = new EnumMap<>(TextureStage.class); private final IntSupplier noise; /** * List of all OpenGL texture objects owned by this CustomTextureManager that need to be deleted in order to avoid * leaks. * Make sure any textures added to this list call releaseId from the close method. */ private final List<AbstractTexture> ownedTextures = new ArrayList<>(); public CustomTextureManager(PackDirectives packDirectives, EnumMap<TextureStage, Object2ObjectMap<String, CustomTextureData>> customTextureDataMap, Optional<CustomTextureData> customNoiseTextureData) { customTextureDataMap.forEach((textureStage, customTextureStageDataMap) -> { Object2ObjectMap<String, IntSupplier> customTextureIds = new Object2ObjectOpenHashMap<>(); customTextureStageDataMap.forEach((samplerName, textureData) -> { try { customTextureIds.put(samplerName, createCustomTexture(textureData)); } catch (IOException e) { Iris.logger.error("Unable to parse the image data for the custom texture on stage " + textureStage + ", sampler " + samplerName, e); } }); customTextureIdMap.put(textureStage, customTextureIds); }); noise = customNoiseTextureData.flatMap(textureData -> { try { return Optional.of(createCustomTexture(textureData)); } catch (IOException e) { Iris.logger.error("Unable to parse the image data for the custom noise texture", e); return Optional.empty(); } }).orElseGet(() -> { final int noiseTextureResolution = packDirectives.getNoiseTextureResolution(); AbstractTexture texture = new NativeImageBackedNoiseTexture(noiseTextureResolution); ownedTextures.add(texture); return texture::getGlTextureId; }); } private IntSupplier createCustomTexture(CustomTextureData textureData) throws IOException { if (textureData instanceof CustomTextureData.PngData) { AbstractTexture texture = new NativeImageBackedCustomTexture((CustomTextureData.PngData) textureData); ownedTextures.add(texture); return texture::getGlTextureId; } // TODO: Iris // else if (textureData instanceof CustomTextureData.LightmapMarker) { // // Special code path for the light texture. While shader packs hardcode the primary light texture, it's // // possible that a mod will create a different light texture, so this code path is robust to that. // return () -> ((LightTextureAccessor) Minecraft.getMinecraft().gameRenderer.lightTexture()).getLightTexture().getId(); // } else if (textureData instanceof CustomTextureData.ResourceData) { CustomTextureData.ResourceData resourceData = (CustomTextureData.ResourceData) textureData; String namespace = resourceData.getNamespace(); String location = resourceData.getLocation(); String withoutExtension; int extensionIndex = FilenameUtils.indexOfExtension(location); if (extensionIndex != -1) { withoutExtension = location.substring(0, extensionIndex); } else { withoutExtension = location; } PBRType pbrType = PBRType.fromFileLocation(withoutExtension); TextureManager textureManager = Minecraft.getMinecraft().getTextureManager(); if (pbrType == null) { ResourceLocation textureLocation = new ResourceLocation(namespace, location); // NB: We have to re-query the TextureManager for the texture object every time. This is because the // AbstractTexture object could be removed / deleted from the TextureManager on resource reloads, // and we could end up holding on to a deleted texture unless we added special code to handle resource // reloads. Re-fetching the texture from the TextureManager every time is the most robust approach for // now. return () -> { ITextureObject texture = textureManager.getTexture(textureLocation); // TODO: Should we give something else if the texture isn't there? This will need some thought return texture != null ? texture.getGlTextureId() : TextureUtil.missingTexture.getGlTextureId(); }; } else { location = location.substring(0, extensionIndex - pbrType.getSuffix().length()) + location.substring(extensionIndex); ResourceLocation textureLocation = new ResourceLocation(namespace, location); return () -> { ITextureObject texture = textureManager.getTexture(textureLocation); if (texture != null) { int id = texture.getGlTextureId(); PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); AbstractTexture pbrTexture = switch (pbrType) { case NORMAL -> pbrHolder.getNormalTexture(); case SPECULAR -> pbrHolder.getSpecularTexture(); default -> throw new Error("Unknown PBRType '" + pbrType + "'"); }; TextureFormat textureFormat = TextureFormatLoader.getFormat(); if (textureFormat != null) { int previousBinding = GL11.glGetInteger(GL11.GL_TEXTURE_BINDING_2D); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, pbrTexture.getGlTextureId()); textureFormat.setupTextureParameters(pbrType, pbrTexture); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, previousBinding); } return pbrTexture.getGlTextureId(); } // return MissingTextureAtlasSprite.getTexture().getId(); return TextureUtil.missingTexture.getGlTextureId(); }; } } else { throw new IllegalArgumentException("Unable to handle custom texture data " + textureData); } } public EnumMap<TextureStage, Object2ObjectMap<String, IntSupplier>> getCustomTextureIdMap() { return customTextureIdMap; } public Object2ObjectMap<String, IntSupplier> getCustomTextureIdMap(TextureStage stage) { return customTextureIdMap.getOrDefault(stage, Object2ObjectMaps.emptyMap()); } public IntSupplier getNoiseTexture() { return noise; } public void destroy() { // TODO :Iris // ownedTextures.forEach(AbstractTexture::close); } }
Angelica
src\main\java\net\coderbot\iris\pipeline\DeferredWorldRenderingPipeline.java
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.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.rendering.RenderingState; import net.coderbot.iris.Iris; import net.coderbot.iris.block_rendering.BlockMaterialMapping; import net.coderbot.iris.block_rendering.BlockRenderingSettings; 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.AlphaTestOverride; 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.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.texture.DepthBufferFormat; import net.coderbot.iris.layer.GbufferPrograms; 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.postprocess.ProgramBuildContext; import net.coderbot.iris.rendertarget.IRenderTargetExt; 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.IdMap; import net.coderbot.iris.shaderpack.OptionalBoolean; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.shaderpack.PackShadowDirectives; 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.ShadowRenderTargets; 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.CommonUniforms; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.shader.Framebuffer; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.Nullable; import org.joml.Vector3d; import org.joml.Vector4f; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL30; 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.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import java.util.function.Supplier; /** * Encapsulates the compiled shader program objects for the currently loaded shaderpack. */ public class DeferredWorldRenderingPipeline implements WorldRenderingPipeline, RenderTargetStateListener { private final static int SRC_ALPHA = 770; private final static int ONE_MINUS_SRC_ALPHA = 771; private final static int ONE = 1; private final RenderTargets renderTargets; @Nullable private ShadowRenderTargets shadowRenderTargets; @Nullable private ComputeProgram[] shadowComputes; private final Supplier<ShadowRenderTargets> shadowTargetsSupplier; private final ProgramTable<Pass> table; private ImmutableList<ClearPass> clearPassesFull; private ImmutableList<ClearPass> clearPasses; private ImmutableList<ClearPass> shadowClearPasses; private ImmutableList<ClearPass> shadowClearPassesFull; private final CompositeRenderer prepareRenderer; @Nullable private final ShadowRenderer shadowRenderer; private final CustomUniforms customUniforms; 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<Integer> flippedBeforeShadow; private final ImmutableSet<Integer> flippedAfterPrepare; private final ImmutableSet<Integer> flippedAfterTranslucent; private final SodiumTerrainPipeline sodiumTerrainPipeline; private final Map<Pair<String, InputAvailability>, Map<PatchShaderType, String>> attributeTransforms; 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); private SpecialCondition special = null; private boolean shouldBindPBR; private int currentNormalTexture; private int currentSpecularTexture; private PackDirectives packDirectives; public DeferredWorldRenderingPipeline(ProgramSet programs) { Objects.requireNonNull(programs); final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> prepareTransformFutures = submitCompositeTransforms(programs.getPrepare()); final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> deferredTransformFutures = submitCompositeTransforms(programs.getDeferred()); final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> compositeTransformFutures = submitCompositeTransforms(programs.getComposite()); final CompletableFuture<Map<PatchShaderType, String>> finalTransformFuture = programs.getCompositeFinal() .filter(ProgramSource::isValid) .map(DeferredWorldRenderingPipeline::submitCompositeTransform) .orElse(null); final ProgramFallbackResolver resolver = new ProgramFallbackResolver(programs); final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> attributeTransformFutures = submitAttributeTransforms(resolver); final Optional<ProgramSource> terrainSource = first(programs.getGbuffersTerrain(), programs.getGbuffersTexturedLit(), programs.getGbuffersTextured(), programs.getGbuffersBasic()); final Optional<ProgramSource> translucentSource = first(programs.getGbuffersWater(), terrainSource); final Optional<ProgramSource> shadowSource = programs.getShadow(); final CompletableFuture<Map<PatchShaderType, String>> sodiumTerrainFuture = terrainSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); final CompletableFuture<Map<PatchShaderType, String>> sodiumTranslucentFuture = translucentSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); final CompletableFuture<Map<PatchShaderType, String>> sodiumShadowFuture = shadowSource.map(DeferredWorldRenderingPipeline::submitSodiumTerrainTransform).orElse(null); 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 = programs.getPackDirectives().areParticlesBeforeDeferred(); this.allowConcurrentCompute = programs.getPackDirectives().getConcurrentCompute(); this.shouldRenderPrepareBeforeShadow = programs.getPackDirectives().isPrepareBeforeShadow(); this.oldLighting = programs.getPackDirectives().isOldLighting(); this.updateNotifier = new FrameUpdateNotifier(); this.packDirectives = programs.getPackDirectives(); final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); final int depthTextureId = ((IRenderTargetExt)main).iris$getDepthTextureId(); final int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat(); final DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); this.renderTargets = new RenderTargets(main.framebufferWidth, main.framebufferHeight, depthTextureId, ((IRenderTargetExt)main).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(); } this.customUniforms = programs.getPack().customUniforms.build( holder -> CommonUniforms.addNonDynamicUniforms(holder, programs.getPack().getIdMap(), programs.getPackDirectives(), this.updateNotifier) ); // TODO: BlockStateIdMap BlockRenderingSettings.INSTANCE.setBlockMatches(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(GL13.GL_TEXTURE2); customTextureManager = new CustomTextureManager(programs.getPackDirectives(), programs.getPack().getCustomTextureDataMap(), programs.getPack().getCustomNoiseTexture()); whitePixel = new NativeImageBackedSingleColorTexture(255, 255, 255, 255); GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); this.flippedBeforeShadow = ImmutableSet.of(); 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(shadowMapResolution, shadowDirectives); } return shadowRenderTargets; }; PatchedShaderPrinter.resetPrintState(); final ProgramBuildContext prepareBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.PREPARE), customUniforms); final ProgramBuildContext deferredBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.DEFERRED), customUniforms); final ProgramBuildContext compositeBuildContext = new ProgramBuildContext(renderTargets, customTextureManager.getNoiseTexture(), updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureManager.getCustomTextureIdMap(TextureStage.COMPOSITE_AND_FINAL), customUniforms); this.prepareRenderer = new CompositeRenderer(programs.getPrepare(), programs.getPrepareCompute(), flipper, prepareBuildContext, programs.getPackDirectives().getExplicitFlips("prepare_pre"), prepareTransformFutures, "prepare"); flippedAfterPrepare = flipper.snapshot(); this.deferredRenderer = new CompositeRenderer(programs.getDeferred(), programs.getDeferredCompute(), flipper, deferredBuildContext, programs.getPackDirectives().getExplicitFlips("deferred_pre"), deferredTransformFutures, "deferred"); flippedAfterTranslucent = flipper.snapshot(); this.compositeRenderer = new CompositeRenderer(programs.getComposite(), programs.getCompositeCompute(), flipper, compositeBuildContext, programs.getPackDirectives().getExplicitFlips("composite_pre"), compositeTransformFutures, "composite"); this.finalPassRenderer = new FinalPassRenderer(programs, compositeBuildContext, flipper.snapshot(), this.compositeRenderer.getFlippedAtLeastOnceFinal(), finalTransformFuture, "final"); // [(textured=false,lightmap=false), (textured=true,lightmap=false), (textured=true,lightmap=true)] final 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"); } this.attributeTransforms = new HashMap<>(); for (Map.Entry<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> entry : attributeTransformFutures.entrySet()) { try { this.attributeTransforms.put(entry.getKey(), entry.getValue().join()); } catch (Exception e) { Iris.logger.error("Failed to transform shader: {}", entry.getKey().getLeft(), e); throw new RuntimeException("Shader transformation failed for " + entry.getKey().getLeft(), e); } } final Map<Pair<ProgramId, InputAvailability>, Pass> cachedPasses = new HashMap<>(); this.shadowComputes = createShadowComputes(programs.getShadowCompute()); this.table = new ProgramTable<>((condition, availability) -> { final 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]; } final ProgramId finalId = id; return cachedPasses.computeIfAbsent(Pair.of(id, availability), p -> { final ProgramSource source = resolver.resolveNullable(p.getLeft()); 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(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)) { this.shadowRenderer = new ShadowRenderer(programs.getShadow().orElse(null), programs.getPackDirectives(), shadowRenderTargets); Program shadowProgram = table.match(RenderCondition.SHADOW, new InputAvailability(true, true)).getProgram(); shadowRenderer.setUsesImages(shadowProgram != null && shadowProgram.getActiveImages() > 0); } else { shadowRenderer = null; } } else { this.shadowClearPasses = ImmutableList.of(); this.shadowClearPassesFull = ImmutableList.of(); this.shadowRenderer = null; } this.customUniforms.optimise(); this.clearPassesFull = ClearPassCreator.createClearPasses(renderTargets, true, programs.getPackDirectives().getRenderTargetDirectives()); this.clearPasses = ClearPassCreator.createClearPasses(renderTargets, false, programs.getPackDirectives().getRenderTargetDirectives()); // SodiumTerrainPipeline setup follows. Supplier<ImmutableSet<Integer>> flipped = () -> isBeforeTranslucent ? flippedAfterPrepare : flippedAfterTranslucent; IntFunction<ProgramSamplers> 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.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); IrisSamplers.addWorldDepthSamplers(customTextureSamplerInterceptor, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, Objects.requireNonNull(shadowRenderTargets)); } return builder.build(); }; IntFunction<ProgramImages> createTerrainImages = (programId) -> { ProgramImages.Builder builder = ProgramImages.builder(programId); IrisImages.addRenderTargetImages(builder, flipped, renderTargets); if (IrisImages.hasShadowImages(builder)) { IrisImages.addShadowColorImages(builder, Objects.requireNonNull(shadowRenderTargets)); } return builder.build(); }; IntFunction<ProgramSamplers> 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.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); 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)); } return builder.build(); }; IntFunction<ProgramImages> createShadowTerrainImages = (programId) -> { ProgramImages.Builder builder = ProgramImages.builder(programId); IrisImages.addRenderTargetImages(builder, () -> flippedAfterPrepare, renderTargets); if (IrisImages.hasShadowImages(builder)) { IrisImages.addShadowColorImages(builder, Objects.requireNonNull(shadowRenderTargets)); } return builder.build(); }; this.sodiumTerrainPipeline = new SodiumTerrainPipeline(this, programs, createTerrainSamplers, shadowRenderer == null ? null : createShadowTerrainSamplers, createTerrainImages, shadowRenderer == null ? null : createShadowTerrainImages, this.customUniforms, terrainSource.map(ProgramSource::getName).orElse(null), translucentSource.map(ProgramSource::getName).orElse(null), shadowSource.map(ProgramSource::getName).orElse(null), sodiumTerrainFuture, sodiumTranslucentFuture, sodiumShadowFuture); } 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.getMinecraft().theWorld == 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 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 boolean shouldRenderParticlesBeforeDeferred() { return shouldRenderParticlesBeforeDeferred; } @Override public boolean allowConcurrentCompute() { return allowConcurrentCompute; } @Override public float getSunPathRotation() { return sunPathRotation; } 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, OUTLINE, DEBUG, PARTICLES: return RenderCondition.DEFAULT; case SKY, SUNSET, CUSTOM_SKY, SUN, MOON, STARS, VOID: return RenderCondition.SKY; case TERRAIN_SOLID, TERRAIN_CUTOUT, TERRAIN_CUTOUT_MIPPED: return RenderCondition.TERRAIN_OPAQUE; case ENTITIES: if (GLStateManager.getBlendState().getSrcRgb() == SRC_ALPHA && GLStateManager.getBlendState().getSrcAlpha() == ONE_MINUS_SRC_ALPHA && GLStateManager.getBlendState().getDstRgb() == ONE && GLStateManager.getBlendState().getDstAlpha() == ONE_MINUS_SRC_ALPHA) { 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, 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))); 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() { final GlFramebuffer framebufferBeforeTranslucents = renderTargets.createGbufferFramebuffer(flippedAfterPrepare, new int[] {0}); final GlFramebuffer 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) { // Use pre-computed transform if available, otherwise transform synchronously Pair<String, InputAvailability> key = Pair.of(source.getName(), availability); Map<PatchShaderType, String> transformed = attributeTransforms.get(key); if (transformed == null) { // Fallback to synchronous transform if not pre-computed transformed = TransformPatcher.patchAttributes( source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new), availability); } String vertex = transformed.get(PatchShaderType.VERTEX); String geometry = transformed.get(PatchShaderType.GEOMETRY); String fragment = transformed.get(PatchShaderType.FRAGMENT); PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment); ProgramBuilder builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment, IrisSamplers.WORLD_RESERVED_TEXTURE_UNITS); return createPassInner(builder, source.getDirectives(), availability, shadow, id); } private Pass createPassInner(ProgramBuilder builder, ProgramDirectives programDirectives, InputAvailability availability, boolean shadow, ProgramId id) { CommonUniforms.addDynamicUniforms(builder); this.customUniforms.assignTo(builder); Supplier<ImmutableSet<Integer>> 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); 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); IrisImages.addShadowColorImages(builder, shadowRenderTargets); } } 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"); AlphaTestOverride alphaTestOverride = programDirectives.getAlphaTestOverride().orElse(null); List<BufferBlendOverride> 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); 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); } } private final class Pass { @Nullable private final Program program; private final GlFramebuffer framebufferBeforeTranslucents; private final GlFramebuffer framebufferAfterTranslucents; @Nullable private final AlphaTestOverride alphaTestOverride; @Nullable private final BlendModeOverride blendModeOverride; @Nullable private final List<BufferBlendOverride> bufferBlendOverrides; private final boolean shadowViewport; private Pass(@Nullable Program program, GlFramebuffer framebufferBeforeTranslucents, GlFramebuffer framebufferAfterTranslucents, @Nullable AlphaTestOverride alphaTestOverride, @Nullable BlendModeOverride blendModeOverride, @Nullable List<BufferBlendOverride> 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) { GL11.glViewport(0, 0, shadowMapResolution, shadowMapResolution); } else { final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); GL11.glViewport(0, 0, main.framebufferWidth, main.framebufferHeight); } if (program != null && !sodiumTerrainRendering) { program.use(); } DeferredWorldRenderingPipeline.this.customUniforms.push(this); if (alphaTestOverride != null) { alphaTestOverride.apply(); } else { // Previous program on the stack might have applied an override AlphaTestOverride.restore(); } 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) { AlphaTestOverride.restore(); } 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 OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_DRAW_FRAMEBUFFER, 0); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_FRAMEBUFFER, 0); Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(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(); } private static void destroyPasses(ProgramTable<Pass> table) { Set<Pass> 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. GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); final 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(); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); if (Minecraft.isRunningOnMac) { GL11.glGetError(); } ImmutableList<ClearPass> 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); } } } final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); final int depthTextureId = ((IRenderTargetExt)main).iris$getDepthTextureId(); final int internalFormat = TextureInfoCache.INSTANCE.getInfo(depthTextureId).getInternalFormat(); final DepthBufferFormat depthBufferFormat = DepthBufferFormat.fromGlEnumOrDefault(internalFormat); final boolean changed = renderTargets.resizeIfNeeded(((IRenderTargetExt)main).iris$getDepthBufferVersion(), depthTextureId, main.framebufferWidth, main.framebufferHeight, 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<ClearPass> passes; if (renderTargets.isFullClearRequired()) { renderTargets.onFullClear(); passes = clearPassesFull; } else { passes = clearPasses; } final Vector3d fogColor3 = GLStateManager.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. final 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.getMinecraft().getFramebuffer().bindFramebuffer(true); } private ComputeProgram[] createShadowComputes(ComputeSource[] compute) { 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 (RuntimeException e) { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } CommonUniforms.addDynamicUniforms(builder); this.customUniforms.assignTo(builder); Supplier<ImmutableSet<Integer>> flipped; flipped = () -> flippedBeforeShadow; TextureStage textureStage = TextureStage.GBUFFERS_AND_SHADOW; ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureManager.getCustomTextureIdMap(textureStage)); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, flipped, renderTargets, false); IrisImages.addRenderTargetImages(builder, flipped, renderTargets); IrisSamplers.addLevelSamplers(customTextureSamplerInterceptor, this, whitePixel, new InputAvailability(true, true)); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, customTextureManager.getNoiseTexture()); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { if (shadowRenderTargets != null) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowRenderTargets); IrisImages.addShadowColorImages(builder, shadowRenderTargets); } } programs[i] = builder.buildCompute(); 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(); GLStateManager.enableBlend(); GLStateManager.enableAlphaTest(); // 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(EntityRenderer 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<String> messages) { messages.add(""); if (shadowRenderer != null) { shadowRenderer.addDebugText(messages); } else { messages.add("[" + Iris.MODNAME + "] 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 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?"); } updateNotifier.onNewFrame(); this.customUniforms.update(); // Get ready for world rendering prepareRenderTargets(); 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.getMinecraft().theWorld.effects().skyType(); if (true/*skyType == DimensionSpecialEffects.SkyType.NORMAL*/) { GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDepthMask(false); final Vector3d fogColor = GLStateManager.getFogColor(); GL11.glColor4f((float) fogColor.x, (float) fogColor.y, (float) fogColor.z, 1.0F); horizonRenderer.renderHorizon(RenderingState.INSTANCE.getModelViewBuffer()); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_TEXTURE_2D); } } @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 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 onBindTexture(int id) { if (shouldBindPBR && isRenderingWorld) { final PBRTextureHolder pbrHolder = PBRTextureManager.INSTANCE.getOrLoadHolder(id); currentNormalTexture = pbrHolder.getNormalTexture().getGlTextureId(); currentSpecularTexture = pbrHolder.getSpecularTexture().getGlTextureId(); final TextureFormat textureFormat = TextureFormatLoader.getFormat(); if (textureFormat != null) { textureFormat.setupTextureParameters(PBRType.NORMAL, pbrHolder.getNormalTexture()); textureFormat.setupTextureParameters(PBRType.SPECULAR, pbrHolder.getSpecularTexture()); } PBRTextureManager.notifyPBRTexturesChanged(); } } private static final InputAvailability INPUT_NONE = new InputAvailability(false, false); private static final InputAvailability INPUT_TEXTURE = new InputAvailability(true, false); private static final InputAvailability INPUT_TEXTURE_LIGHTMAP = new InputAvailability(true, true); private static final InputAvailability[] INPUT_AVAILABILITIES = { INPUT_NONE, INPUT_TEXTURE, INPUT_TEXTURE_LIGHTMAP }; private static CompletableFuture<Map<PatchShaderType, String>> submitCompositeTransform(ProgramSource source) { return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchComposite(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null))); } private static Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> submitCompositeTransforms(ProgramSource[] sources) { // Count valid sources for initial capacity int count = 0; for (ProgramSource source : sources) { if (source != null && source.isValid()) count++; } final Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>(count); for (int i = 0; i < sources.length; i++) { if (sources[i] != null && sources[i].isValid()) { futures.put(i, submitCompositeTransform(sources[i])); } } return futures; } private static Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> submitAttributeTransforms(ProgramFallbackResolver resolver) { final Map<Pair<String, InputAvailability>, CompletableFuture<Map<PatchShaderType, String>>> futures = new HashMap<>(); final Set<String> processedSourceNames = new HashSet<>(); for (ProgramId id : ProgramId.values()) { ProgramSource source = resolver.resolveNullable(id); if (source != null && !processedSourceNames.contains(source.getName())) { processedSourceNames.add(source.getName()); for (InputAvailability avail : INPUT_AVAILABILITIES) { Pair<String, InputAvailability> key = Pair.of(source.getName(), avail); futures.put(key, Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchAttributes(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null), avail))); } } } return futures; } private static CompletableFuture<Map<PatchShaderType, String>> submitSodiumTerrainTransform(ProgramSource source) { return Iris.ShaderTransformExecutor.submitTracked(() -> TransformPatcher.patchSodiumTerrain(source.getVertexSource().orElse(null), source.getGeometrySource().orElse(null), source.getFragmentSource().orElse(null))); } @SafeVarargs private static <T> Optional<T> first(Optional<T>... candidates) { for (Optional<T> candidate : candidates) { if (candidate.isPresent()) { return candidate; } } return Optional.empty(); } }
Angelica
src\main\java\net\coderbot\iris\pipeline\FixedFunctionWorldRenderingPipeline.java
package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.compat.mojang.Camera; import net.coderbot.iris.block_rendering.BlockRenderingSettings; 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.shaderpack.CloudSetting; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import org.lwjgl.opengl.GL20; import java.util.List; import java.util.OptionalInt; public class FixedFunctionWorldRenderingPipeline implements WorldRenderingPipeline { public FixedFunctionWorldRenderingPipeline() { BlockRenderingSettings.INSTANCE.setDisableDirectionalShading(shouldDisableDirectionalShading()); BlockRenderingSettings.INSTANCE.setUseSeparateAo(false); BlockRenderingSettings.INSTANCE.setAmbientOcclusionLevel(1.0f); BlockRenderingSettings.INSTANCE.setUseExtendedVertexFormat(false); BlockRenderingSettings.INSTANCE.setBlockTypeIds(null); } @Override public void beginLevelRendering() { // Use the default Minecraft framebuffer and ensure that no programs are in use Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); GL20.glUseProgram(0); } @Override public void renderShadows(EntityRenderer levelRenderer, Camera camera) { // stub: nothing to do here } @Override public void addDebugText(List<String> messages) { // stub: nothing to do here } @Override public OptionalInt getForcedShadowRenderDistanceChunksForDisplay() { return OptionalInt.empty(); } @Override 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() { } @Override public RenderTargetStateListener getRenderTargetStateListener() { return RenderTargetStateListener.NOP; } @Override public int getCurrentNormalTexture() { return 0; } @Override public int getCurrentSpecularTexture() { return 0; } @Override public void onBindTexture(int id) { } @Override public void beginHand() { // stub: nothing to do here } @Override public void beginTranslucents() { // stub: nothing to do here } @Override public void finalizeLevelRendering() { // stub: nothing to do here } @Override public void destroy() { // stub: nothing to do here } @Override public SodiumTerrainPipeline getSodiumTerrainPipeline() { // no shaders to override return null; } @Override public FrameUpdateNotifier getFrameUpdateNotifier() { // return a dummy notifier return new FrameUpdateNotifier(); } @Override public boolean shouldDisableVanillaEntityShadows() { return false; } @Override public boolean shouldDisableDirectionalShading() { return false; } @Override public CloudSetting getCloudSetting() { return CloudSetting.DEFAULT; } @Override public boolean shouldRenderUnderwaterOverlay() { return true; } @Override public boolean shouldRenderVignette() { return true; } @Override public boolean shouldRenderSun() { return true; } @Override public boolean shouldRenderMoon() { return true; } @Override public boolean shouldWriteRainAndSnowToDepthBuffer() { return false; } @Override public boolean shouldRenderParticlesBeforeDeferred() { return false; } @Override public boolean allowConcurrentCompute() { return false; } @Override public float getSunPathRotation() { // No sun tilt return 0; } }
Angelica
src\main\java\net\coderbot\iris\pipeline\HandRenderer.java
package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import com.gtnewhorizons.angelica.compat.mojang.InteractionHand; import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.rendering.RenderingState; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.irisshaders.iris.api.v0.IrisApi; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import org.lwjgl.util.glu.Project; import java.util.Map; public class HandRenderer { public static final HandRenderer INSTANCE = new HandRenderer(); private boolean ACTIVE; private boolean renderingSolid; public static final float DEPTH = 0.125F; private void setupGlState(RenderGlobal gameRenderer, Camera camera, float tickDelta) { final Minecraft mc = Minecraft.getMinecraft(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); // We need to scale the matrix by 0.125 so the hand doesn't clip through blocks. GL11.glScalef(1.0F, 1.0F, DEPTH); // TODO: Anaglyph /*if (this.mc.gameSettings.anaglyph) { GL11.glTranslatef((float) (-(anaglyphChannel * 2 - 1)) * 0.07F, 0.0F, 0.0F); }*/ if (mc.entityRenderer.cameraZoom != 1.0D) { GL11.glTranslatef((float) mc.entityRenderer.cameraYaw, (float) (-mc.entityRenderer.cameraPitch), 0.0F); GL11.glScaled(mc.entityRenderer.cameraZoom, mc.entityRenderer.cameraZoom, 1.0D); } Project.gluPerspective(mc.entityRenderer.getFOVModifier(tickDelta, false), (float) mc.displayWidth / (float) mc.displayHeight, 0.05F, mc.entityRenderer.farPlaneDistance * 2.0F); if (mc.playerController.enableEverythingIsScrewedUpMode()) { GL11.glScalef(1.0F, 2 / 3f, 1.0F); } GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); // TODO: Anaglyph /*if (mc.gameSettings.anaglyph) { GL11.glTranslatef((float) (anaglyphChannel * 2 - 1) * 0.1F, 0.0F, 0.0F); }*/ mc.entityRenderer.hurtCameraEffect(tickDelta); if (mc.gameSettings.viewBobbing) { mc.entityRenderer.setupViewBobbing(tickDelta); } } private boolean canRender(Camera camera, RenderGlobal gameRenderer) { Minecraft mc = Minecraft.getMinecraft(); return mc.entityRenderer.debugViewDirection <= 0 && mc.gameSettings.thirdPersonView == 0 && !camera.getEntity().isPlayerSleeping() && !mc.gameSettings.hideGUI && !GameModeUtil.isSpectator() && !mc.playerController.enableEverythingIsScrewedUpMode(); } public boolean isHandTranslucent(InteractionHand hand) { ItemStack heldItem = hand.getItemInHand(Minecraft.getMinecraft().thePlayer); if (heldItem == null) { return false; } Item item = heldItem.getItem(); if (item instanceof ItemBlock itemBlock) { Map<Block, RenderLayer> blockTypeIds = BlockRenderingSettings.INSTANCE.getBlockTypeIds(); return blockTypeIds != null && blockTypeIds.get(itemBlock.field_150939_a) == RenderLayer.translucent(); } return false; } public boolean isAnyHandTranslucent() { return isHandTranslucent(InteractionHand.MAIN_HAND) || isHandTranslucent(InteractionHand.OFF_HAND); } public void renderSolid(float tickDelta, Camera camera, RenderGlobal gameRenderer, WorldRenderingPipeline pipeline) { if (!canRender(camera, gameRenderer) || !IrisApi.getInstance().isShaderPackInUse()) { return; } Minecraft mc = Minecraft.getMinecraft(); ACTIVE = true; pipeline.setPhase(WorldRenderingPhase.HAND_SOLID); GL11.glPushMatrix(); GL11.glDepthMask(true); // actually write to the depth buffer, it's normally disabled at this point mc.mcProfiler.startSection("iris_hand"); setupGlState(gameRenderer, camera, tickDelta); renderingSolid = true; mc.entityRenderer.enableLightmap(tickDelta); mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta); mc.entityRenderer.disableLightmap(tickDelta); GLStateManager.defaultBlendFunc(); GL11.glDepthMask(false); GL11.glPopMatrix(); mc.mcProfiler.endSection(); resetProjectionMatrix(); renderingSolid = false; pipeline.setPhase(WorldRenderingPhase.NONE); ACTIVE = false; } // TODO: RenderType public void renderTranslucent(float tickDelta, Camera camera, RenderGlobal gameRenderer, WorldRenderingPipeline pipeline) { if (!canRender(camera, gameRenderer) || !isAnyHandTranslucent() || !IrisApi.getInstance().isShaderPackInUse()) { return; } Minecraft mc = Minecraft.getMinecraft(); ACTIVE = true; pipeline.setPhase(WorldRenderingPhase.HAND_TRANSLUCENT); GL11.glPushMatrix(); mc.mcProfiler.startSection("iris_hand_translucent"); setupGlState(gameRenderer, camera, tickDelta); mc.entityRenderer.enableLightmap(tickDelta); mc.entityRenderer.itemRenderer.renderItemInFirstPerson(tickDelta); mc.entityRenderer.disableLightmap(tickDelta); GL11.glPopMatrix(); resetProjectionMatrix(); Minecraft.getMinecraft().mcProfiler.endSection(); pipeline.setPhase(WorldRenderingPhase.NONE); ACTIVE = false; } private void resetProjectionMatrix() { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glMultMatrix(RenderingState.INSTANCE.getProjectionBuffer()); GL11.glMatrixMode(GL11.GL_MODELVIEW); } public boolean isActive() { return ACTIVE; } public boolean isRenderingSolid() { return renderingSolid; } }
Angelica
src\main\java\net\coderbot\iris\pipeline\HorizonRenderer.java
package net.coderbot.iris.pipeline; import com.gtnewhorizon.gtnhlib.client.renderer.CapturingTessellator; import com.gtnewhorizon.gtnhlib.client.renderer.TessellatorManager; import com.gtnewhorizon.gtnhlib.client.renderer.vbo.VertexBuffer; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import org.lwjgl.opengl.GL11; import java.nio.FloatBuffer; /** * Renders the sky horizon. Vanilla Minecraft simply uses the "clear color" for its horizon, and then draws a plane * above the player. This class extends the sky rendering so that an octagonal prism is drawn around the player instead, * allowing shaders to perform more advanced sky rendering. * <p> * However, the horizon rendering is designed so that when sky shaders are not being used, it looks almost exactly the * same as vanilla sky rendering, except a few almost entirely imperceptible differences where the walls * of the octagonal prism intersect the top plane. */ public class HorizonRenderer { /** * The Y coordinate of the top skybox plane. Acts as the upper bound for the horizon prism, since the prism lies * between the bottom and top skybox planes. */ private static final float TOP = 16.0F; /** * The Y coordinate of the bottom skybox plane. Acts as the lower bound for the horizon prism, since the prism lies * between the bottom and top skybox planes. */ private static final float BOTTOM = -16.0F; /** * Cosine of 22.5 degrees. */ private static final double COS_22_5 = Math.cos(Math.toRadians(22.5)); /** * Sine of 22.5 degrees. */ private static final double SIN_22_5 = Math.sin(Math.toRadians(22.5)); private VertexBuffer vertexBuffer; private int currentRenderDistance; public HorizonRenderer() { currentRenderDistance = Minecraft.getMinecraft().gameSettings.renderDistanceChunks; rebuildBuffer(); } private void rebuildBuffer() { final CapturingTessellator tessellator = TessellatorManager.startCapturingAndGet(); // Build the horizon quads into a buffer tessellator.startDrawingQuads(); //(GL11.GL_QUADS, DefaultVertexFormat.POSITION); buildHorizon(currentRenderDistance * 16, tessellator); this.vertexBuffer = TessellatorManager.stopCapturingToVAO(vertexBuffer, DefaultVertexFormat.POSITION); } private void buildQuad(Tessellator consumer, double x1, double z1, double x2, double z2) { consumer.addVertex(x1, BOTTOM, z1); consumer.addVertex(x1, TOP, z1); consumer.addVertex(x2, TOP, z2); consumer.addVertex(x2, BOTTOM, z2); } private void buildHalf(Tessellator consumer, double adjacent, double opposite, boolean invert) { if (invert) { adjacent = -adjacent; opposite = -opposite; } // NB: Make sure that these vertices are being specified in counterclockwise order! // Otherwise back face culling will remove your quads, and you'll be wondering why there's a hole in your horizon. // Don't poke holes in the horizon. Specify vertices in counterclockwise order. // +X,-Z face buildQuad(consumer, adjacent, -opposite, opposite, -adjacent); // +X face buildQuad(consumer, adjacent, opposite, adjacent, -opposite); // +X,+Z face buildQuad(consumer, opposite, adjacent, adjacent, opposite); // +Z face buildQuad(consumer, -opposite, adjacent, opposite, adjacent); } /** * @param adjacent the adjacent side length of the a triangle with a hypotenuse extending from the center of the * octagon to a given vertex on the perimeter. * @param opposite the opposite side length of the a triangle with a hypotenuse extending from the center of the * octagon to a given vertex on the perimeter. */ private void buildOctagonalPrism(Tessellator consumer, double adjacent, double opposite) { buildHalf(consumer, adjacent, opposite, false); buildHalf(consumer, adjacent, opposite, true); } private void buildRegularOctagonalPrism(Tessellator consumer, double radius) { buildOctagonalPrism(consumer, radius * COS_22_5, radius * SIN_22_5); } private void buildBottomPlane(Tessellator consumer, int radius) { for (int x = -radius; x <= radius; x += 64) { for (int z = -radius; z <= radius; z += 64) { consumer.addVertex(x + 64, BOTTOM, z); consumer.addVertex(x, BOTTOM, z); consumer.addVertex(x, BOTTOM, z + 64); consumer.addVertex(x + 64, BOTTOM, z + 64); } } } private void buildTopPlane(Tessellator consumer, int radius) { // You might be tempted to try to combine this with buildBottomPlane to avoid code duplication, // but that won't work since the winding order has to be reversed or else one of the planes will be // discarded by back face culling. for (int x = -radius; x <= radius; x += 64) { for (int z = -radius; z <= radius; z += 64) { consumer.addVertex(x + 64, TOP, z); consumer.addVertex(x + 64, TOP, z + 64); consumer.addVertex(x, TOP, z + 64); consumer.addVertex(x, TOP, z); } } } private void buildHorizon(int radius, Tessellator consumer) { if (radius > 256) { // Prevent the prism from getting too large, this causes issues on some shader packs that modify the vanilla // sky if we don't do this. radius = 256; } buildRegularOctagonalPrism(consumer, radius); // Replicate the vanilla top plane since we can't assume that it'll be rendered. // TODO: Remove vanilla top plane buildTopPlane(consumer, 384); // Always make the bottom plane have a radius of 384, to match the top plane. buildBottomPlane(consumer, 384); } public void renderHorizon(FloatBuffer floatBuffer) { if (currentRenderDistance != Minecraft.getMinecraft().gameSettings.renderDistanceChunks) { currentRenderDistance = Minecraft.getMinecraft().gameSettings.renderDistanceChunks; rebuildBuffer(); } vertexBuffer.setupState(); vertexBuffer.draw(floatBuffer); vertexBuffer.cleanupState(); } public void destroy() { vertexBuffer.close(); } }
Angelica
src\main\java\net\coderbot\iris\pipeline\PatchedShaderPrinter.java
package net.coderbot.iris.pipeline; import net.coderbot.iris.Iris; import net.minecraft.client.Minecraft; import net.minecraft.launchwrapper.Launch; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; /** * Static class that deals with printing the patched_shader folder. */ public class PatchedShaderPrinter { private static boolean outputLocationCleared = false; private static int programCounter = 0; // Is this too early? We'll find out! public static final boolean prettyPrintShaders = (boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment") || System.getProperty("iris.prettyPrintShaders", "false").equals("true"); public static void resetPrintState() { outputLocationCleared = false; programCounter = 0; } public static void debugPatchedShaders(String name, String vertex, String geometry, String fragment) { if (prettyPrintShaders) { final Path debugOutDir = Minecraft.getMinecraft().mcDataDir.toPath().resolve("patched_shaders"); if (!outputLocationCleared) { try { if (Files.exists(debugOutDir)) { try (Stream<Path> 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; } try { programCounter++; String prefix = String.format("%03d_", programCounter); if (vertex != null) { Files.write(debugOutDir.resolve(prefix + name + ".vsh"), vertex.getBytes(StandardCharsets.UTF_8)); } if (geometry != null) { Files.write(debugOutDir.resolve(prefix + name + ".gsh"), geometry.getBytes(StandardCharsets.UTF_8)); } if (fragment != null) { Files.write(debugOutDir.resolve(prefix + name + ".fsh"), fragment.getBytes(StandardCharsets.UTF_8)); } } catch (IOException e) { Iris.logger.warn("Failed to write debug patched shader source", e); } } } }
Angelica
src\main\java\net\coderbot\iris\pipeline\PipelineManager.java
package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.glsm.GLStateManager; import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.block_rendering.BlockRenderingSettings; import net.coderbot.iris.shaderpack.DimensionId; import net.coderbot.iris.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Function; public class PipelineManager { private final Function<DimensionId, WorldRenderingPipeline> pipelineFactory; private final Map<DimensionId, WorldRenderingPipeline> pipelinesPerDimension = new HashMap<>(); private WorldRenderingPipeline pipeline = new FixedFunctionWorldRenderingPipeline(); @Getter private int versionCounterForSodiumShaderReload = 0; public PipelineManager(Function<DimensionId, WorldRenderingPipeline> pipelineFactory) { this.pipelineFactory = pipelineFactory; } public WorldRenderingPipeline preparePipeline(DimensionId currentDimension) { if (!pipelinesPerDimension.containsKey(currentDimension)) { SystemTimeUniforms.COUNTER.reset(); SystemTimeUniforms.TIMER.reset(); Iris.logger.info("Creating pipeline for dimension {}", currentDimension); pipeline = pipelineFactory.apply(currentDimension); pipelinesPerDimension.put(currentDimension, pipeline); if (BlockRenderingSettings.INSTANCE.isReloadRequired()) { if (Minecraft.getMinecraft().renderGlobal != null) { Minecraft.getMinecraft().renderGlobal.loadRenderers(); } BlockRenderingSettings.INSTANCE.clearReloadRequired(); } } else { pipeline = pipelinesPerDimension.get(currentDimension); } return pipeline; } @Nullable public WorldRenderingPipeline getPipelineNullable() { return pipeline; } public Optional<WorldRenderingPipeline> getPipeline() { return Optional.ofNullable(pipeline); } /** * Destroys all the current pipelines. * * <p>This method is <b>EXTREMELY DANGEROUS!</b> It is a huge potential source of hard-to-trace inconsistencies * in program state. You must make sure that you <i>immediately</i> re-prepare the pipeline after destroying * it to prevent the program from falling into an inconsistent state.</p> * * <p>In particular, </p> * * @see <a href="https://github.com/IrisShaders/Iris/issues/1330">this GitHub issue</a> */ public void destroyPipeline() { pipelinesPerDimension.forEach((dimensionId, pipeline) -> { Iris.logger.info("Destroying pipeline {}", dimensionId); resetTextureState(); pipeline.destroy(); }); pipelinesPerDimension.clear(); pipeline = null; versionCounterForSodiumShaderReload++; } private void resetTextureState() { // Unbind all textures // // This is necessary because we don't want destroyed render target textures to remain bound to certain texture // units. Vanilla appears to properly rebind all textures as needed, and we do so too, so this does not cause // issues elsewhere. // // Without this code, there will be weird issues when reloading certain shaderpacks. for (int i = 0; i < 16; i++) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } // Set the active texture unit to unit 0 // // This seems to be what most code expects. It's a sane default in any case. GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } }
Angelica
src\main\java\net\coderbot\iris\pipeline\ShadowRenderer.java
package net.coderbot.iris.pipeline; import com.google.common.collect.ImmutableList; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.rendering.RenderingState; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import me.jellysquid.mods.sodium.client.render.SodiumWorldRenderer; import net.coderbot.iris.Iris; import net.coderbot.iris.gui.option.IrisVideoSettings; 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.shadow.ShadowMatrices; import net.coderbot.iris.shadows.CullingDataCache; import net.coderbot.iris.shadows.ShadowRenderTargets; 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.fallback.BoxCullingFrustum; import net.coderbot.iris.shadows.frustum.fallback.NonCullingFrustum; import net.coderbot.iris.uniforms.CameraUniforms; import net.coderbot.iris.uniforms.CapturedRenderingState; import net.coderbot.iris.uniforms.CelestialUniforms; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.culling.Frustrum; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.entity.Entity; import net.minecraft.profiler.Profiler; import net.minecraft.tileentity.TileEntity; import org.joml.Matrix4f; import org.joml.Vector3dc; import org.joml.Vector3f; import org.joml.Vector4f; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.ARBTextureSwizzle; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; public class ShadowRenderer { public static final Matrix4f MODELVIEW = new Matrix4f(); public static final FloatBuffer MODELVIEW_BUFFER = BufferUtils.createFloatBuffer(16); public static final Matrix4f PROJECTION = new Matrix4f(); public static List<TileEntity> visibleTileEntities; public static List<TileEntity> globalTileEntities; public static boolean ACTIVE = false; private final float halfPlaneLength; private final float renderDistanceMultiplier; private final float entityShadowDistanceMultiplier; private final int resolution; private final float intervalSize; private final Float fov; private final ShadowRenderTargets targets; private final OptionalBoolean packCullingState; 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 float sunPathRotation; // private final RenderBuffers buffers; // private final RenderBuffersExt renderBuffersExt; private final List<MipmapPass> mipmapPasses = new ArrayList<>(); private final String debugStringOverall; private FrustumHolder terrainFrustumHolder; private FrustumHolder entityFrustumHolder; private String debugStringTerrain = "(unavailable)"; private int renderedShadowEntities = 0; private int renderedShadowTileEntities = 0; private Profiler profiler; public ShadowRenderer(ProgramSource shadow, PackDirectives directives, ShadowRenderTargets shadowRenderTargets) { this.profiler = Minecraft.getMinecraft().mcProfiler; final PackShadowDirectives shadowDirectives = directives.getShadowDirectives(); this.halfPlaneLength = shadowDirectives.getDistance(); this.renderDistanceMultiplier = shadowDirectives.getDistanceRenderMul(); this.entityShadowDistanceMultiplier = shadowDirectives.getEntityShadowDistanceMul(); this.resolution = shadowDirectives.getResolution(); this.intervalSize = shadowDirectives.getIntervalSize(); this.shouldRenderTerrain = shadowDirectives.shouldRenderTerrain(); this.shouldRenderTranslucent = shadowDirectives.shouldRenderTranslucent(); this.shouldRenderEntities = shadowDirectives.shouldRenderEntities(); this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer(); this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities(); debugStringOverall = "half plane = " + halfPlaneLength + " meters @ " + resolution + "x" + resolution; this.terrainFrustumHolder = new FrustumHolder(); this.entityFrustumHolder = new FrustumHolder(); this.fov = shadowDirectives.getFov(); this.targets = shadowRenderTargets; if (shadow != null) { // Assume that the shader pack is doing voxelization if a geometry shader is detected. // Also assume voxelization if image load / store is detected. this.packHasVoxelization = shadow.getGeometrySource().isPresent(); this.packCullingState = shadowDirectives.getCullingState(); } else { this.packHasVoxelization = false; this.packCullingState = OptionalBoolean.DEFAULT; } this.sunPathRotation = directives.getSunPathRotation(); // this.buffers = new RenderBuffers(); // // if (this.buffers instanceof RenderBuffersExt) { // this.renderBuffersExt = (RenderBuffersExt) buffers; // } else { // this.renderBuffersExt = null; // } configureSamplingSettings(shadowDirectives); } public void setUsesImages(boolean usesImages) { this.packHasVoxelization = packHasVoxelization || usesImages; } public static MatrixStack createShadowModelView(float sunPathRotation, float intervalSize) { // Determine the camera position final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition(); final double cameraX = cameraPos.x(); final double cameraY = cameraPos.y(); final double cameraZ = cameraPos.z(); // Set up our modelview matrix stack final MatrixStack modelView = new MatrixStack(); ShadowMatrices.createModelViewMatrix(modelView, getShadowAngle(), intervalSize, sunPathRotation, cameraX, cameraY, cameraZ); return modelView; } private static WorldClient getLevel() { return Objects.requireNonNull(Minecraft.getMinecraft().theWorld); } private static float getSkyAngle() { return Minecraft.getMinecraft().theWorld.getCelestialAngle(CapturedRenderingState.INSTANCE.getTickDelta()); } private static float getSunAngle() { final float skyAngle = getSkyAngle(); if (skyAngle < 0.75F) { return skyAngle + 0.25F; } else { return skyAngle - 0.75F; } } private static float getShadowAngle() { float shadowAngle = getSunAngle(); if (!CelestialUniforms.isDay()) { shadowAngle -= 0.5F; } return shadowAngle; } private void configureSamplingSettings(PackShadowDirectives shadowDirectives) { final ImmutableList<PackShadowDirectives.DepthSamplingSettings> depthSamplingSettings = shadowDirectives.getDepthSamplingSettings(); final ImmutableList<PackShadowDirectives.SamplingSettings> colorSamplingSettings = shadowDirectives.getColorSamplingSettings(); GLStateManager.glActiveTexture(GL13.GL_TEXTURE4); configureDepthSampler(targets.getDepthTexture().getTextureId(), depthSamplingSettings.get(0)); configureDepthSampler(targets.getDepthTextureNoTranslucents().getTextureId(), depthSamplingSettings.get(1)); for (int i = 0; i < colorSamplingSettings.size(); i++) { int glTextureId = targets.get(i).getMainTexture(); configureSampler(glTextureId, colorSamplingSettings.get(i)); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } private final IntBuffer swizzleBuf = BufferUtils.createIntBuffer(4); private void configureDepthSampler(int glTextureId, PackShadowDirectives.DepthSamplingSettings settings) { if (settings.getHardwareFiltering()) { // We have to do this or else shadow hardware filtering breaks entirely! RenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_COMPARE_MODE, GL30.GL_COMPARE_REF_TO_TEXTURE); } // Workaround for issues with old shader packs like Chocapic v4. // 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. swizzleBuf.rewind(); swizzleBuf.put(new int[] { GL11.GL_RED, GL11.GL_RED, GL11.GL_RED, GL11.GL_ONE }).rewind(); RenderSystem.texParameteriv(glTextureId, GL11.GL_TEXTURE_2D, ARBTextureSwizzle.GL_TEXTURE_SWIZZLE_RGBA, swizzleBuf); configureSampler(glTextureId, settings); } private void configureSampler(int glTextureId, PackShadowDirectives.SamplingSettings settings) { if (settings.getMipmap()) { final int filteringMode = settings.getNearest() ? GL11.GL_NEAREST_MIPMAP_NEAREST : GL11.GL_LINEAR_MIPMAP_LINEAR; mipmapPasses.add(new MipmapPass(glTextureId, filteringMode)); } if (!settings.getNearest()) { // Make sure that things are smoothed RenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); } else { RenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); RenderSystem.texParameteri(glTextureId, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); } } private void generateMipmaps() { GLStateManager.glActiveTexture(GL13.GL_TEXTURE4); for (MipmapPass mipmapPass : mipmapPasses) { setupMipmappingForTexture(mipmapPass.getTexture(), mipmapPass.getTargetFilteringMode()); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } private void setupMipmappingForTexture(int texture, int filteringMode) { RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filteringMode); } private FrustumHolder createShadowFrustum(float renderMultiplier, FrustumHolder holder) { // TODO: Cull entities / block entities with Advanced Frustum Culling even if voxelization is detected. String distanceInfo; String cullingInfo; if ((packCullingState == OptionalBoolean.FALSE || packHasVoxelization) && packCullingState != OptionalBoolean.TRUE) { double distance = halfPlaneLength * renderMultiplier; String reason; if (packCullingState == OptionalBoolean.FALSE) { reason = "(set by shader pack)"; } else /*if (packHasVoxelization)*/ { reason = "(voxelization detected)"; } if (distance <= 0 || distance > Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) { distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16 + " blocks (capped by normal render distance)"; cullingInfo = "disabled " + reason; return holder.setInfo(new NonCullingFrustum(), distanceInfo, cullingInfo); } else { distanceInfo = distance + " blocks (set by shader pack)"; cullingInfo = "distance only " + reason; BoxCuller boxCuller = new BoxCuller(distance); holder.setInfo(new BoxCullingFrustum(boxCuller), distanceInfo, cullingInfo); } } else { BoxCuller boxCuller; double distance = halfPlaneLength * renderMultiplier; String setter = "(set by shader pack)"; if (renderMultiplier < 0) { // TODO: GUI distance = IrisVideoSettings.shadowDistance * 16; // can be zero :( //distance = 32 * 16; setter = "(set by user)"; } if (distance >= Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16) { distanceInfo = Minecraft.getMinecraft().gameSettings.renderDistanceChunks * 16 + " blocks (capped by normal render distance)"; boxCuller = null; } else { distanceInfo = distance + " blocks " + setter; if (distance == 0.0) { cullingInfo = "no shadows rendered"; holder.setInfo(new CullEverythingFrustum(), distanceInfo, cullingInfo); } boxCuller = new BoxCuller(distance); } cullingInfo = "Advanced Frustum Culling enabled"; Vector4f shadowLightPosition = new CelestialUniforms(sunPathRotation).getShadowLightPositionInWorldSpace(); Vector3f shadowLightVectorFromOrigin = new Vector3f(shadowLightPosition.x(), shadowLightPosition.y(), shadowLightPosition.z()); shadowLightVectorFromOrigin.normalize(); return holder.setInfo(new AdvancedShadowCullingFrustum(RenderingState.INSTANCE.getModelViewMatrix(), RenderingState.INSTANCE.getProjectionMatrix(), shadowLightVectorFromOrigin, boxCuller), distanceInfo, cullingInfo); } return holder; } private void setupGlState(Matrix4f projMatrix) { // Set up our projection matrix and load it into the legacy matrix stack RenderSystem.setupProjectionMatrix(projMatrix); // Disable backface culling // This partially works around an issue where if the front face of a mountain isn't visible, it casts no // shadow. // // However, it only partially resolves issues of light leaking into caves. // // TODO: Better way of preventing light from leaking into places where it shouldn't GLStateManager.disableCull(); } private void restoreGlState() { // Restore backface culling GLStateManager.enableCull(); // Make sure to unload the projection matrix RenderSystem.restoreProjectionMatrix(); } private void copyPreTranslucentDepth() { profiler.endStartSection("translucent depth copy"); targets.copyPreTranslucentDepth(); } private void renderEntities(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) { int shadowEntities = 0; profiler.startSection("cull"); List<Entity> renderedEntities = new ArrayList<>(32); // TODO: I'm sure that this can be improved / optimized. // TODO: Entity culling for (Entity entity : getLevel().loadedEntityList) { if (false/*!dispatcher.shouldRender(entity, frustum, cameraX, cameraY, cameraZ) || entity.isSpectator()*/) { continue; } renderedEntities.add(entity); } profiler.endStartSection("sort"); // TODO: Render // Sort the entities by type first in order to allow vanilla's entity batching system to work better. renderedEntities.sort(Comparator.comparingInt(entity -> entity.getClass().hashCode())); profiler.endStartSection("build geometry"); // TODO: Render GL11.glPushMatrix(); MODELVIEW_BUFFER.clear().rewind(); modelView.peek().getModel().get(MODELVIEW_BUFFER); GL11.glLoadMatrix(MODELVIEW_BUFFER); for (Entity entity : renderedEntities) { RenderManager.instance.renderEntitySimple(entity, tickDelta); shadowEntities++; } GL11.glPopMatrix(); renderedShadowEntities = shadowEntities; profiler.endSection(); } private void renderPlayerEntity(EntityRenderer levelRenderer, Frustrum frustum, Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float tickDelta) { profiler.startSection("cull"); Entity player = Minecraft.getMinecraft().thePlayer; // TODO: Entity culling // if (!dispatcher.shouldRender(player, frustum, cameraX, cameraY, cameraZ) || player.isSpectator()) { // return; // } profiler.endStartSection("build geometry"); int shadowEntities = 0; GL11.glPushMatrix(); MODELVIEW_BUFFER.clear().rewind(); modelView.peek().getModel().get(MODELVIEW_BUFFER); GL11.glLoadMatrix(MODELVIEW_BUFFER); if (player.riddenByEntity != null) { RenderManager.instance.renderEntitySimple(player.riddenByEntity, tickDelta); shadowEntities++; } if (player.ridingEntity != null) { RenderManager.instance.renderEntitySimple(player.ridingEntity, tickDelta); shadowEntities++; } RenderManager.instance.renderEntitySimple(player, tickDelta); GL11.glPopMatrix(); shadowEntities++; renderedShadowEntities = shadowEntities; profiler.endSection(); } private void renderTileEntity(TileEntity tile, double cameraX, double cameraY, double cameraZ, float partialTicks) { if (tile.getDistanceFrom(cameraX, cameraY, cameraZ) >= tile.getMaxRenderDistanceSquared()) { return; } int brightness = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord, tile.yCoord, tile.zCoord, 0); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) brightness % 65536, (float) brightness / 65536); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); TileEntityRendererDispatcher.instance.renderTileEntityAt(tile, (double)tile.xCoord - cameraX, (double)tile.yCoord - cameraY, (double)tile.zCoord - cameraZ, partialTicks ); } private void renderTileEntities(Object bufferSource, MatrixStack modelView, double cameraX, double cameraY, double cameraZ, float partialTicks, boolean hasEntityFrustum) { profiler.startSection("build blockentities"); int shadowTileEntities = 0; BoxCuller culler = null; if (hasEntityFrustum) { culler = new BoxCuller(halfPlaneLength * (renderDistanceMultiplier * entityShadowDistanceMultiplier)); culler.setPosition(cameraX, cameraY, cameraZ); } GL11.glPushMatrix(); MODELVIEW_BUFFER.clear().rewind(); modelView.peek().getModel().get(MODELVIEW_BUFFER); GL11.glLoadMatrix(MODELVIEW_BUFFER); for (TileEntity tileEntity : visibleTileEntities) { if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { continue; } renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); shadowTileEntities++; } for (TileEntity tileEntity : globalTileEntities) { if (hasEntityFrustum && (culler.isCulled(tileEntity.xCoord - 1, tileEntity.yCoord - 1, tileEntity.zCoord - 1, tileEntity.xCoord + 1, tileEntity.yCoord + 1, tileEntity.zCoord + 1))) { continue; } renderTileEntity(tileEntity, cameraX, cameraY, cameraZ, partialTicks); shadowTileEntities++; } GLStateManager.glPopMatrix(); renderedShadowTileEntities = shadowTileEntities; profiler.endSection(); } public void renderShadows(EntityRenderer levelRenderer, Camera playerCamera) { final Minecraft mc = Minecraft.getMinecraft(); final RenderGlobal rg = mc.renderGlobal; // We have to re-query this each frame since this changes based on whether the profiler is active // If the profiler is inactive, it will return InactiveProfiler.INSTANCE this.profiler = Minecraft.getMinecraft().mcProfiler; profiler.endStartSection("shadows"); ACTIVE = true; // 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. // TODO: Render // RenderBuffers playerBuffers = levelRenderer.getRenderBuffers(); // levelRenderer.setRenderBuffers(buffers); visibleTileEntities = new ArrayList<>(); globalTileEntities = new ArrayList<>(); // Create our camera final MatrixStack modelView = createShadowModelView(this.sunPathRotation, this.intervalSize); MODELVIEW.set(modelView.peek().getModel()); final Matrix4f shadowProjection; if (this.fov != null) { // 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); } PROJECTION.set(shadowProjection); profiler.startSection("terrain_setup"); if (levelRenderer instanceof CullingDataCache) { ((CullingDataCache) levelRenderer).saveState(); } profiler.startSection("initialize frustum"); terrainFrustumHolder = createShadowFrustum(renderDistanceMultiplier, terrainFrustumHolder); // Determine the player camera position final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition(); final double cameraX = cameraPos.x(); final double cameraY = cameraPos.y(); final double cameraZ = cameraPos.z(); // Center the frustum on the player camera position terrainFrustumHolder.getFrustum().setPosition(cameraX, cameraY, cameraZ); profiler.endSection(); // Always schedule a terrain update // TODO: Only schedule a terrain update if the sun / moon is moving, or the shadow map camera moved. // We have to ensure that we don't regenerate clouds every frame, since that's what needsUpdate ends up doing. // This took up to 10% of the frame time before we applied this fix! That's really bad! // boolean regenerateClouds = levelRenderer.shouldRegenerateClouds(); // ((LevelRenderer) levelRenderer).needsUpdate(); // levelRenderer.setShouldRegenerateClouds(regenerateClouds); // Execute the vanilla terrain setup / culling routines using our shadow frustum. mc.renderGlobal.clipRenderersByFrustum(terrainFrustumHolder.getFrustum(), playerCamera.getPartialTicks()); // Don't forget to increment the frame counter! This variable is arbitrary and only used in terrain setup, // and if it's not incremented, the vanilla culling code will get confused and think that it's already seen // chunks during traversal, and break rendering in concerning ways. // levelRenderer.setFrameId(levelRenderer.getFrameId() + 1); profiler.endStartSection("terrain"); setupGlState(PROJECTION); // Render all opaque terrain unless pack requests not to if (shouldRenderTerrain) { mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); rg.sortAndRender(mc.thePlayer, 0, playerCamera.getPartialTicks()); } profiler.endStartSection("entities"); // Get the current tick delta. Normally this is the same as client.getTickDelta(), but when the game is paused, // it is set to a fixed value. final float tickDelta = CapturedRenderingState.INSTANCE.getTickDelta(); // Create a constrained shadow frustum for entities to avoid rendering faraway entities in the shadow pass, // if the shader pack has requested it. Otherwise, use the same frustum as for terrain. boolean hasEntityFrustum = false; if (entityShadowDistanceMultiplier == 1.0F || entityShadowDistanceMultiplier < 0.0F) { entityFrustumHolder.setInfo(terrainFrustumHolder.getFrustum(), terrainFrustumHolder.getDistanceInfo(), terrainFrustumHolder.getCullingInfo()); } else { hasEntityFrustum = true; entityFrustumHolder = createShadowFrustum(renderDistanceMultiplier * entityShadowDistanceMultiplier, entityFrustumHolder); } Frustrum entityShadowFrustum = entityFrustumHolder.getFrustum(); entityShadowFrustum.setPosition(cameraX, cameraY, cameraZ); // Render nearby entities if (shouldRenderEntities) { renderEntities(levelRenderer, entityShadowFrustum, null, modelView, cameraX, cameraY, cameraZ, tickDelta); } else if (shouldRenderPlayer) { renderPlayerEntity(levelRenderer, entityShadowFrustum, null, modelView, cameraX, cameraY, cameraZ, tickDelta); } if (shouldRenderBlockEntities) { renderTileEntities(null, modelView, cameraX, cameraY, cameraZ, tickDelta, hasEntityFrustum); } profiler.endStartSection("draw entities"); // NB: Don't try to draw the translucent parts of entities afterwards. It'll cause problems since some // shader packs assume that everything drawn afterwards is actually translucent and should cast a colored // shadow... copyPreTranslucentDepth(); profiler.endStartSection("translucent terrain"); // TODO (Iris): Prevent these calls from scheduling translucent sorting... // It doesn't matter a ton, since this just means that they won't be sorted in the getNormal rendering pass. // Just something to watch out for, however... if (shouldRenderTranslucent) { rg.sortAndRender(mc.thePlayer, 1, playerCamera.getPartialTicks()); } // Note: Apparently tripwire isn't rendered in the shadow pass. // worldRenderer.invokeRenderType(RenderType.getTripwire(), modelView, cameraX, cameraY, cameraZ); // if (renderBuffersExt != null) { // renderBuffersExt.endLevelRendering(); // } debugStringTerrain = SodiumWorldRenderer.getInstance().getChunksDebugString(); profiler.endStartSection("generate mipmaps"); generateMipmaps(); profiler.endStartSection("restore gl state"); restoreGlState(); if (levelRenderer instanceof CullingDataCache) { ((CullingDataCache) levelRenderer).restoreState(); } ACTIVE = false; profiler.endSection(); profiler.endStartSection("updatechunks"); } public void addDebugText(List<String> messages) { messages.add("[" + Iris.MODNAME + "] Shadow Maps: " + debugStringOverall); messages.add("[" + Iris.MODNAME + "] Shadow Distance Terrain: " + terrainFrustumHolder.getDistanceInfo() + " Entity: " + entityFrustumHolder.getDistanceInfo()); messages.add("[" + Iris.MODNAME + "] Shadow Culling Terrain: " + terrainFrustumHolder.getCullingInfo() + " Entity: " + entityFrustumHolder.getCullingInfo()); messages.add("[" + Iris.MODNAME + "] Shadow Terrain: " + debugStringTerrain + (shouldRenderTerrain ? "" : " (no terrain) ") + (shouldRenderTranslucent ? "" : "(no translucent)")); messages.add("[" + Iris.MODNAME + "] Shadow Entities: " + getEntitiesDebugString()); messages.add("[" + Iris.MODNAME + "] Shadow Block Entities: " + getTileEntitiesDebugString()); // if (buffers instanceof DrawCallTrackingRenderBuffers drawCallTracker && (shouldRenderEntities || shouldRenderPlayer)) { // messages.add("[" + Iris.MODNAME + "] Shadow Entity Batching: " + BatchingDebugMessageHelper.getDebugMessage(drawCallTracker)); // } } private String getEntitiesDebugString() { return (shouldRenderEntities || shouldRenderPlayer) ? (renderedShadowEntities + "/" + Minecraft.getMinecraft().theWorld.loadedEntityList.size()) : "disabled by pack"; } private String getTileEntitiesDebugString() { return shouldRenderBlockEntities ? (renderedShadowTileEntities + "/" + Minecraft.getMinecraft().theWorld.loadedTileEntityList.size()) : "disabled by pack"; } private static class MipmapPass { private final int texture; private final int targetFilteringMode; public MipmapPass(int texture, int targetFilteringMode) { this.texture = texture; this.targetFilteringMode = targetFilteringMode; } public int getTexture() { return texture; } public int getTargetFilteringMode() { return targetFilteringMode; } } }
Angelica
src\main\java\net\coderbot\iris\pipeline\SodiumTerrainPipeline.java
package net.coderbot.iris.pipeline; import lombok.Getter; 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.transform.PatchShaderType; import net.coderbot.iris.shaderpack.ProgramSet; import net.coderbot.iris.uniforms.CommonUniforms; import net.coderbot.iris.uniforms.ExternallyManagedUniforms; import net.coderbot.iris.uniforms.builtin.BuiltinReplacementUniforms; import net.coderbot.iris.uniforms.custom.CustomUniforms; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.IntFunction; import net.coderbot.iris.Iris; public class SodiumTerrainPipeline { Optional<String> terrainVertex = Optional.empty(); Optional<String> terrainGeometry = Optional.empty(); Optional<String> terrainFragment = Optional.empty(); Optional<String> translucentVertex = Optional.empty(); Optional<String> translucentGeometry = Optional.empty(); Optional<String> translucentFragment = Optional.empty(); Optional<String> shadowVertex = Optional.empty(); Optional<String> shadowGeometry = Optional.empty(); Optional<String> shadowFragment = Optional.empty(); //GlFramebuffer framebuffer; ProgramSet programSet; @Getter private final CustomUniforms customUniforms; private final WorldRenderingPipeline parent; private final IntFunction<ProgramSamplers> createTerrainSamplers; private final IntFunction<ProgramSamplers> createShadowSamplers; private final IntFunction<ProgramImages> createTerrainImages; private final IntFunction<ProgramImages> createShadowImages; public SodiumTerrainPipeline(WorldRenderingPipeline parent, ProgramSet programSet, IntFunction<ProgramSamplers> createTerrainSamplers, IntFunction<ProgramSamplers> createShadowSamplers, IntFunction<ProgramImages> createTerrainImages, IntFunction<ProgramImages> createShadowImages, CustomUniforms customUniforms, String terrainSourceName, String translucentSourceName, String shadowSourceName, CompletableFuture<Map<PatchShaderType, String>> terrainFuture, CompletableFuture<Map<PatchShaderType, String>> translucentFuture, CompletableFuture<Map<PatchShaderType, String>> shadowFuture) { this.parent = Objects.requireNonNull(parent); this.programSet = programSet; this.customUniforms = customUniforms; if (terrainFuture != null) { try { Map<PatchShaderType, String> result = terrainFuture.join(); terrainVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); terrainGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); terrainFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); PatchedShaderPrinter.debugPatchedShaders(terrainSourceName + "_sodium", terrainVertex.orElse(null), terrainGeometry.orElse(null), terrainFragment.orElse(null)); } catch (Exception e) { Iris.logger.error("Failed to transform terrain shader: {}", terrainSourceName, e); throw new RuntimeException("Shader transformation failed for " + terrainSourceName, e); } } if (translucentFuture != null) { try { Map<PatchShaderType, String> result = translucentFuture.join(); translucentVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); translucentGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); translucentFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); PatchedShaderPrinter.debugPatchedShaders(translucentSourceName + "_sodium", translucentVertex.orElse(null), translucentGeometry.orElse(null), translucentFragment.orElse(null)); } catch (Exception e) { Iris.logger.error("Failed to transform translucent shader: {}", translucentSourceName, e); throw new RuntimeException("Shader transformation failed for " + translucentSourceName, e); } } if (shadowFuture != null) { try { Map<PatchShaderType, String> result = shadowFuture.join(); shadowVertex = Optional.ofNullable(result.get(PatchShaderType.VERTEX)); shadowGeometry = Optional.ofNullable(result.get(PatchShaderType.GEOMETRY)); shadowFragment = Optional.ofNullable(result.get(PatchShaderType.FRAGMENT)); PatchedShaderPrinter.debugPatchedShaders(shadowSourceName + "_sodium", shadowVertex.orElse(null), shadowGeometry.orElse(null), shadowFragment.orElse(null)); } catch (Exception e) { Iris.logger.error("Failed to transform shadow shader: {}", shadowSourceName, e); throw new RuntimeException("Shader transformation failed for " + shadowSourceName, e); } } this.createTerrainSamplers = createTerrainSamplers; this.createShadowSamplers = createShadowSamplers; this.createTerrainImages = createTerrainImages; this.createShadowImages = createShadowImages; } public Optional<String> getTerrainVertexShaderSource() { return terrainVertex; } public Optional<String> getTerrainGeometryShaderSource() { return terrainGeometry; } public Optional<String> getTerrainFragmentShaderSource() { return terrainFragment; } public Optional<String> getTranslucentVertexShaderSource() { return translucentVertex; } public Optional<String> getTranslucentGeometryShaderSource() { return translucentGeometry; } public Optional<String> getTranslucentFragmentShaderSource() { return translucentFragment; } public Optional<String> getShadowVertexShaderSource() { return shadowVertex; } public Optional<String> getShadowGeometryShaderSource() { return shadowGeometry; } public Optional<String> getShadowFragmentShaderSource() { return shadowFragment; } public ProgramUniforms.Builder initUniforms(int programId) { ProgramUniforms.Builder uniforms = ProgramUniforms.builder("<sodium shaders>", programId); CommonUniforms.addDynamicUniforms(uniforms); customUniforms.assignTo(uniforms); ExternallyManagedUniforms.addExternallyManagedUniforms116(uniforms); BuiltinReplacementUniforms.addBuiltinReplacementUniforms(uniforms); return uniforms; } public boolean hasShadowPass() { return createShadowSamplers != null; } public ProgramSamplers initTerrainSamplers(int programId) { return createTerrainSamplers.apply(programId); } public ProgramSamplers initShadowSamplers(int programId) { return createShadowSamplers.apply(programId); } public ProgramImages initTerrainImages(int programId) { return createTerrainImages.apply(programId); } public ProgramImages initShadowImages(int programId) { return createShadowImages.apply(programId); } /*public void bindFramebuffer() { this.framebuffer.bind(); } public void unbindFramebuffer() { GlStateManager.bindFramebuffer(GL30.GL_FRAMEBUFFER, 0); }*/ }
Angelica
src\main\java\net\coderbot\iris\pipeline\WorldRenderingPhase.java
package net.coderbot.iris.pipeline; public enum WorldRenderingPhase { NONE, SKY, SUNSET, CUSTOM_SKY, // Unused, just here to match OptiFine ordinals SUN, MOON, STARS, VOID, TERRAIN_SOLID, TERRAIN_CUTOUT_MIPPED, TERRAIN_CUTOUT, ENTITIES, BLOCK_ENTITIES, DESTROY, OUTLINE, DEBUG, HAND_SOLID, TERRAIN_TRANSLUCENT, TRIPWIRE, PARTICLES, CLOUDS, RAIN_SNOW, WORLD_BORDER, HAND_TRANSLUCENT; }
Angelica
src\main\java\net\coderbot\iris\pipeline\WorldRenderingPipeline.java
package net.coderbot.iris.pipeline; import com.gtnewhorizons.angelica.compat.mojang.Camera; 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.shaderpack.CloudSetting; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.minecraft.client.renderer.EntityRenderer; import java.util.List; import java.util.OptionalInt; public interface WorldRenderingPipeline { void beginLevelRendering(); void renderShadows(EntityRenderer levelRenderer, Camera camera); void addDebugText(List<String> messages); OptionalInt getForcedShadowRenderDistanceChunksForDisplay(); WorldRenderingPhase getPhase(); void beginSodiumTerrainRendering(); void endSodiumTerrainRendering(); void setOverridePhase(WorldRenderingPhase phase); void setPhase(WorldRenderingPhase phase); void setInputs(InputAvailability availability); void setSpecialCondition(SpecialCondition special); void syncProgram(); RenderTargetStateListener getRenderTargetStateListener(); int getCurrentNormalTexture(); int getCurrentSpecularTexture(); void onBindTexture(int id); void beginHand(); void beginTranslucents(); void finalizeLevelRendering(); void destroy(); SodiumTerrainPipeline getSodiumTerrainPipeline(); FrameUpdateNotifier getFrameUpdateNotifier(); boolean shouldDisableVanillaEntityShadows(); boolean shouldDisableDirectionalShading(); CloudSetting getCloudSetting(); boolean shouldRenderUnderwaterOverlay(); boolean shouldRenderVignette(); boolean shouldRenderSun(); boolean shouldRenderMoon(); boolean shouldWriteRainAndSnowToDepthBuffer(); boolean shouldRenderParticlesBeforeDeferred(); boolean allowConcurrentCompute(); float getSunPathRotation(); }
Angelica
src\main\java\net\coderbot\iris\postprocess\BufferFlipper.java
package net.coderbot.iris.postprocess; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; public class BufferFlipper { private final IntSet flippedBuffers; public BufferFlipper() { this.flippedBuffers = new IntOpenHashSet(); } public void flip(int target) { if (!flippedBuffers.remove(target)) { // If the target wasn't in the set, add it to the set. flippedBuffers.add(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) { return flippedBuffers.contains(target); } public IntIterator getFlippedBuffers() { return flippedBuffers.iterator(); } public ImmutableSet<Integer> snapshot() { return ImmutableSet.copyOf(flippedBuffers); } }
Angelica
src\main\java\net\coderbot\iris\postprocess\CenterDepthSampler.java
package net.coderbot.iris.postprocess; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; 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.uniforms.SystemTimeUniforms; import net.minecraft.client.Minecraft; import org.apache.commons.io.IOUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.function.IntSupplier; public class CenterDepthSampler { private static final double LN2 = Math.log(2); private boolean hasFirstSample; private boolean everRetrieved; private final Program program; private final GlFramebuffer framebuffer; private final int texture; private final int altTexture; private boolean destroyed; public CenterDepthSampler(IntSupplier depthSupplier, float halfLife) { this.texture = GL11.glGenTextures(); this.altTexture = GL11.glGenTextures(); this.framebuffer = new GlFramebuffer(); // Fall back to a less precise format if the system doesn't support OpenGL 3 InternalTextureFormat format = GLStateManager.capabilities.OpenGL32 ? InternalTextureFormat.R32F : InternalTextureFormat.RGB16; setupColorTexture(texture, format); setupColorTexture(altTexture, format); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); this.framebuffer.addColorAttachment(0, texture); ProgramBuilder builder; try { String fsh = new String(IOUtils.toByteArray(Objects.requireNonNull(getClass().getResourceAsStream("/centerDepth.fsh"))), StandardCharsets.UTF_8); if (GLStateManager.capabilities.OpenGL32) { fsh = fsh.replace("VERSIONPLACEHOLDER", "150 compatibility"); } else { fsh = fsh.replace("#define IS_GL3", ""); fsh = fsh.replace("VERSIONPLACEHOLDER", "120"); } String vsh = new String(IOUtils.toByteArray(Objects.requireNonNull(getClass().getResourceAsStream("/centerDepth.vsh"))), StandardCharsets.UTF_8); builder = ProgramBuilder.begin("centerDepthSmooth", vsh, null, fsh, ImmutableSet.of(0, 1, 2)); } catch (IOException e) { throw new RuntimeException(e); } builder.addDynamicSampler(depthSupplier, "depth"); builder.addDynamicSampler(() -> altTexture, "altDepth"); builder.uniform1f(UniformUpdateFrequency.PER_FRAME, "lastFrameTime", SystemTimeUniforms.TIMER::getLastFrameTime); builder.uniform1f(UniformUpdateFrequency.ONCE, "decay", () -> (1.0f / ((halfLife * 0.1) / LN2))); this.program = builder.build(); } public void sampleCenterDepth() { if ((hasFirstSample && (!everRetrieved)) || destroyed) { // If the shaderpack isn't reading center depth values, don't bother sampling it // This improves performance with most shaderpacks return; } hasFirstSample = true; this.framebuffer.bind(); this.program.use(); GL11.glViewport(0, 0, 1, 1); FullScreenQuadRenderer.INSTANCE.render(); ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); // The API contract of DepthCopyStrategy claims it can only copy depth, however the 2 non-stencil methods used are entirely capable of copying color as of now. DepthCopyStrategy.fastest(false).copy(this.framebuffer, texture, null, altTexture, 1, 1); //Reset viewport Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); } public void setupColorTexture(int texture, InternalTextureFormat format) { RenderSystem.texImage2D(texture, GL11.GL_TEXTURE_2D, 0, format.getGlFormat(), 1, 1, 0, format.getPixelFormat().getGlFormat(), PixelType.FLOAT.getGlFormat(), null); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } public int getCenterDepthTexture() { return altTexture; } public void setUsage(boolean usage) { everRetrieved |= usage; } public void destroy() { GLStateManager.glDeleteTextures(texture); GLStateManager.glDeleteTextures(altTexture); framebuffer.destroy(); program.destroy(); destroyed = true; } }
Angelica
src\main\java\net\coderbot\iris\postprocess\CompositeRenderer.java
package net.coderbot.iris.postprocess; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import lombok.Getter; 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.sampler.SamplerLimits; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.transform.PatchShaderType; import net.coderbot.iris.pipeline.transform.TransformPatcher; 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.PackDirectives; import net.coderbot.iris.shaderpack.ProgramDirectives; import net.coderbot.iris.shaderpack.ProgramSource; 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.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.shader.Framebuffer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.IntSupplier; import java.util.function.Supplier; public class CompositeRenderer { private final RenderTargets renderTargets; private final ImmutableList<Pass> passes; private final IntSupplier noiseTexture; private final FrameUpdateNotifier updateNotifier; private final CenterDepthSampler centerDepthSampler; private final CustomUniforms customUniforms; private final Object2ObjectMap<String, IntSupplier> customTextureIds; @Getter private final ImmutableSet<Integer> flippedAtLeastOnceFinal; public CompositeRenderer(PackDirectives packDirectives, ProgramSource[] sources, ComputeSource[][] computes, RenderTargets renderTargets, IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier, CenterDepthSampler centerDepthSampler, BufferFlipper bufferFlipper, Supplier<ShadowRenderTargets> shadowTargetsSupplier, Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableMap<Integer, Boolean> explicitPreFlips, CustomUniforms customUniforms, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures) { this(sources, computes, bufferFlipper, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), explicitPreFlips, precomputedTransformFutures, "unknown"); } public CompositeRenderer(ProgramSource[] sources, ComputeSource[][] computes, BufferFlipper bufferFlipper, ProgramBuildContext context, ImmutableMap<Integer, Boolean> explicitPreFlips, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> precomputedTransformFutures, String stageName) { this.noiseTexture = context.noiseTexture(); this.updateNotifier = context.updateNotifier(); this.centerDepthSampler = context.centerDepthSampler(); this.renderTargets = context.renderTargets(); this.customTextureIds = context.customTextureIds(); this.customUniforms = context.customUniforms(); final ImmutableList.Builder<Pass> passes = ImmutableList.builder(); final ImmutableSet.Builder<Integer> flippedAtLeastOnce = new ImmutableSet.Builder<>(); Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures = precomputedTransformFutures; explicitPreFlips.forEach((buffer, shouldFlip) -> { if (shouldFlip) { bufferFlipper.flip(buffer); // NB: Flipping deferred_pre or composite_pre does NOT cause the "flippedAtLeastOnce" flag to trigger } }); for (int i = 0; i < sources.length; i++) { final ProgramSource source = sources[i]; ImmutableSet<Integer> flipped = bufferFlipper.snapshot(); ImmutableSet<Integer> flippedAtLeastOnceSnapshot = flippedAtLeastOnce.build(); if (source == null || !source.isValid()) { if (computes[i] != null) { final ComputeOnlyPass pass = new ComputeOnlyPass(); pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); passes.add(pass); } continue; } final Pass pass = new Pass(); final ProgramDirectives directives = source.getDirectives(); Map<PatchShaderType, String> transformed = getTransformed(source, transformFutures, i, stageName); pass.program = createProgramFromTransformed(source, transformed, flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); pass.computes = createComputes(computes[i], flipped, flippedAtLeastOnceSnapshot, context.shadowTargetsSupplier()); final int[] drawBuffers = directives.getDrawBuffers(); final GlFramebuffer framebuffer = renderTargets.createColorFramebuffer(flipped, drawBuffers); int passWidth = 0, passHeight = 0; // Flip the buffers that this shader wrote to, and set pass width and height final ImmutableMap<Integer, Boolean> explicitFlips = directives.getExplicitFlips(); for (int buffer : drawBuffers) { final RenderTarget target = renderTargets.get(buffer); if ((passWidth > 0 && passWidth != target.getWidth()) || (passHeight > 0 && passHeight != target.getHeight())) { throw new IllegalStateException("Pass widths must match"); } passWidth = target.getWidth(); passHeight = target.getHeight(); // compare with boxed Boolean objects to avoid NPEs if (explicitFlips.get(buffer) == Boolean.FALSE) { continue; } bufferFlipper.flip(buffer); flippedAtLeastOnce.add(buffer); } explicitFlips.forEach((buffer, shouldFlip) -> { if (shouldFlip) { bufferFlipper.flip(buffer); flippedAtLeastOnce.add(buffer); } }); pass.drawBuffers = directives.getDrawBuffers(); pass.viewWidth = passWidth; pass.viewHeight = passHeight; pass.stageReadsFromAlt = flipped; pass.framebuffer = framebuffer; pass.viewportScale = directives.getViewportScale(); pass.mipmappedBuffers = directives.getMipmappedBuffers(); passes.add(pass); } this.passes = passes.build(); this.flippedAtLeastOnceFinal = flippedAtLeastOnce.build(); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); } private static Map<PatchShaderType, String> getTransformed(ProgramSource source, Map<Integer, CompletableFuture<Map<PatchShaderType, String>>> transformFutures, int index, String stageName) { if (transformFutures != null) { final CompletableFuture<Map<PatchShaderType, String>> future = transformFutures.get(index); if (future != null) { try { final Map<PatchShaderType, String> result = future.join(); if (result != null) { return result; } } catch (CompletionException e) { throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "' (pass " + index + ")", e.getCause() != null ? e.getCause() : e); } } } // Fallback: transform synchronously return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new)); } public void recalculateSizes() { for (Pass pass : passes) { if (pass instanceof ComputeOnlyPass) { continue; } int passWidth = 0, passHeight = 0; for (int buffer : pass.drawBuffers) { final RenderTarget target = renderTargets.get(buffer); if ((passWidth > 0 && passWidth != target.getWidth()) || (passHeight > 0 && passHeight != target.getHeight())) { throw new IllegalStateException("Pass widths must match"); } passWidth = target.getWidth(); passHeight = target.getHeight(); } renderTargets.destroyFramebuffer(pass.framebuffer); pass.framebuffer = renderTargets.createColorFramebuffer(pass.stageReadsFromAlt, pass.drawBuffers); pass.viewWidth = passWidth; pass.viewHeight = passHeight; } } private static class Pass { int[] drawBuffers; int viewWidth; int viewHeight; Program program; ComputeProgram[] computes; GlFramebuffer framebuffer; ImmutableSet<Integer> stageReadsFromAlt; ImmutableSet<Integer> mipmappedBuffers; float 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() { GLStateManager.disableBlend(); GLStateManager.disableAlphaTest(); FullScreenQuadRenderer.INSTANCE.begin(); for (Pass renderPass : passes) { boolean ranCompute = false; for (ComputeProgram computeProgram : renderPass.computes) { if (computeProgram != null) { ranCompute = true; final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); computeProgram.use(); this.customUniforms.push(computeProgram); computeProgram.dispatch(main.framebufferWidth, main.framebufferHeight); } } if (ranCompute) { RenderSystem.memoryBarrier(40); } Program.unbind(); if (renderPass instanceof ComputeOnlyPass) { continue; } if (!renderPass.mipmappedBuffers.isEmpty()) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); for (int index : renderPass.mipmappedBuffers) { setupMipmapping(CompositeRenderer.this.renderTargets.get(index), renderPass.stageReadsFromAlt.contains(index)); } } final float scaledWidth = renderPass.viewWidth * renderPass.viewportScale; final float scaledHeight = renderPass.viewHeight * renderPass.viewportScale; GL11.glViewport(0, 0, (int) scaledWidth, (int) scaledHeight); renderPass.framebuffer.bind(); renderPass.program.use(); this.customUniforms.push(renderPass.program); FullScreenQuadRenderer.INSTANCE.renderQuad(); } FullScreenQuadRenderer.end(); // Make sure to reset the viewport to how it was before... Otherwise weird issues could occur. // Also bind the "main" framebuffer if it isn't already bound. Minecraft.getMinecraft().getFramebuffer().bindFramebuffer(true); ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); GL20.glUseProgram(0); // NB: Unbinding all of these textures is necessary for proper shaderpack reloading. for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { // Unbind all textures that we may have used. // NB: This is necessary for shader pack reloading to work propely GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } private static void setupMipmapping(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. RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); int filter = GL11.GL_LINEAR_MIPMAP_LINEAR; if (target.getInternalFormat().getPixelFormat().isInteger()) { filter = GL11.GL_NEAREST_MIPMAP_NEAREST; } RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter); } // TODO: Don't just copy this from DeferredWorldRenderingPipeline private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) { String vertex = transformed.get(PatchShaderType.VERTEX); String geometry = transformed.get(PatchShaderType.GEOMETRY); String fragment = transformed.get(PatchShaderType.FRAGMENT); PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment); Objects.requireNonNull(flipped); ProgramBuilder builder; try { builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (RuntimeException e) { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } CommonUniforms.addDynamicUniforms(builder); this.customUniforms.assignTo(builder); ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get()); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get()); } // TODO: Don't duplicate this with FinalPassRenderer centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); Program build = builder.build(); this.customUniforms.mapholderToPass(builder, build); return build; } private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) { 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 { // TODO: Properly handle empty shaders Objects.requireNonNull(flipped); ProgramBuilder builder; try { builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (RuntimeException e) { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); CommonUniforms.addDynamicUniforms(builder); this.customUniforms.assignTo(builder); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get()); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get()); } // TODO: Don't duplicate this with FinalPassRenderer centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); programs[i] = builder.buildCompute(); customUniforms.mapholderToPass(builder, programs[i]); programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups()); } } return programs; } public void destroy() { for (Pass renderPass : passes) { renderPass.destroy(); } } }
Angelica
src\main\java\net\coderbot\iris\postprocess\FinalPassRenderer.java
package net.coderbot.iris.postprocess; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; 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.sampler.SamplerLimits; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.pipeline.transform.PatchShaderType; import net.coderbot.iris.pipeline.transform.TransformPatcher; import net.coderbot.iris.rendertarget.IRenderTargetExt; 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.ProgramDirectives; import net.coderbot.iris.shaderpack.ProgramSet; import net.coderbot.iris.shaderpack.ProgramSource; 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.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.shader.Framebuffer; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import java.util.Map; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.function.IntSupplier; import java.util.function.Supplier; public class FinalPassRenderer { private final RenderTargets renderTargets; @Nullable private final Pass finalPass; private final ImmutableList<SwapPass> swapPasses; private final GlFramebuffer baseline; private final GlFramebuffer colorHolder; private int lastColorTextureId; private int lastColorTextureVersion; private final IntSupplier noiseTexture; private final FrameUpdateNotifier updateNotifier; private final CenterDepthSampler centerDepthSampler; private final Object2ObjectMap<String, IntSupplier> customTextureIds; private final CustomUniforms customUniforms; public FinalPassRenderer(ProgramSet pack, RenderTargets renderTargets, IntSupplier noiseTexture, FrameUpdateNotifier updateNotifier, ImmutableSet<Integer> flippedBuffers, CenterDepthSampler centerDepthSampler, Supplier<ShadowRenderTargets> shadowTargetsSupplier, Object2ObjectMap<String, IntSupplier> customTextureIds, ImmutableSet<Integer> flippedAtLeastOnce, CustomUniforms customUniforms, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture) { this(pack, new ProgramBuildContext(renderTargets, noiseTexture, updateNotifier, centerDepthSampler, shadowTargetsSupplier, customTextureIds, customUniforms), flippedBuffers, flippedAtLeastOnce, precomputedTransformFuture, "final"); } public FinalPassRenderer(ProgramSet pack, ProgramBuildContext context, ImmutableSet<Integer> flippedBuffers, ImmutableSet<Integer> flippedAtLeastOnce, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture, String stageName) { this.updateNotifier = context.updateNotifier(); this.centerDepthSampler = context.centerDepthSampler(); this.customTextureIds = context.customTextureIds(); this.noiseTexture = context.noiseTexture(); this.renderTargets = context.renderTargets(); this.customUniforms = context.customUniforms(); this.finalPass = pack.getCompositeFinal().filter(ProgramSource::isValid).map(source -> { final Pass pass = new Pass(); final ProgramDirectives directives = source.getDirectives(); final Map<PatchShaderType, String> transformed = getTransformed(source, precomputedTransformFuture, stageName); pass.program = createProgramFromTransformed(source, transformed, flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier()); pass.computes = createComputes(pack.getFinalCompute(), flippedBuffers, flippedAtLeastOnce, context.shadowTargetsSupplier()); pass.stageReadsFromAlt = flippedBuffers; pass.mipmappedBuffers = directives.getMipmappedBuffers(); return pass; }).orElse(null); final IntList buffersToBeCleared = pack.getPackDirectives().getRenderTargetDirectives().getBuffersToBeCleared(); // The name of this method might seem a bit odd here, but we want a framebuffer with color attachments that line // 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). final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); this.baseline = renderTargets.createGbufferFramebuffer(flippedBuffers, new int[] {0}); this.colorHolder = new GlFramebuffer(); this.lastColorTextureId = main.framebufferTexture; this.lastColorTextureVersion = ((IRenderTargetExt)main).iris$getColorBufferVersion(); this.colorHolder.addColorAttachment(0, lastColorTextureId); // TODO: We don't actually fully swap the content, we merely copy it from alt to main // This works for the most part, but it's not perfect. A better approach would be creating secondary // framebuffers for every other frame, but that would be a lot more complex... final ImmutableList.Builder<SwapPass> swapPasses = ImmutableList.builder(); flippedBuffers.forEach((i) -> { final int target = i; if (buffersToBeCleared.contains(target)) { return; } final SwapPass swap = new SwapPass(); final RenderTarget target1 = renderTargets.get(target); swap.target = target; swap.width = target1.getWidth(); swap.height = target1.getHeight(); // Non-flipped buffers write to ALT, copy ALT→MAIN to preserve data swap.from = renderTargets.createColorFramebuffer(ImmutableSet.of(), new int[] {target}); swap.targetTexture = renderTargets.get(target).getMainTexture(); swapPasses.add(swap); }); this.swapPasses = swapPasses.build(); OpenGlHelper.func_153171_g/*glBindFramebuffer*/(GL30.GL_READ_FRAMEBUFFER, 0); } private static Map<PatchShaderType, String> getTransformed(ProgramSource source, CompletableFuture<Map<PatchShaderType, String>> precomputedTransformFuture, String stageName) { if (precomputedTransformFuture != null) { try { final Map<PatchShaderType, String> result = precomputedTransformFuture.join(); if (result != null) { return result; } } catch (CompletionException e) { throw new RuntimeException("Shader transformation failed for '" + source.getName() + "' in stage '" + stageName + "'", e.getCause() != null ? e.getCause() : e); } } return TransformPatcher.patchComposite(source.getVertexSource().orElseThrow(NullPointerException::new), source.getGeometrySource().orElse(null), source.getFragmentSource().orElseThrow(NullPointerException::new)); } private static final class Pass { Program program; ComputeProgram[] computes; ImmutableSet<Integer> stageReadsFromAlt; ImmutableSet<Integer> 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; } public void renderFinalPass() { GLStateManager.disableBlend(); GLStateManager.disableAlphaTest(); GLStateManager.glDepthMask(false); final Framebuffer main = Minecraft.getMinecraft().getFramebuffer(); final int baseWidth = main.framebufferWidth; final int baseHeight = main.framebufferHeight; // Note that since DeferredWorldRenderingPipeline uses the depth texture of the main Minecraft framebuffer, // we'll be writing to that depth buffer directly automatically and won't need to futz around with copying // depth buffer content. // // Previously, we had our own depth texture and then copied its content to the main Minecraft framebuffer. // This worked with vanilla, but broke with mods that used the stencil buffer. // // This approach is a fairly succinct solution to the issue of having to deal with the main Minecraft // framebuffer potentially having a depth-stencil buffer or similar - we'll automatically enable that to // work properly since we re-use the depth buffer instead of trying to make our own. // // This is not a concern for depthtex1 / depthtex2 since the copy call extracts the depth values, and the // shader pack only ever uses them to read the depth values. if (((IRenderTargetExt)main).iris$getColorBufferVersion() != lastColorTextureVersion || main.framebufferTexture != lastColorTextureId) { lastColorTextureVersion = ((IRenderTargetExt)main).iris$getColorBufferVersion(); this.lastColorTextureId = main.framebufferTexture; colorHolder.addColorAttachment(0, lastColorTextureId); } if (this.finalPass != null) { // If there is a final pass, we use the shader-based full screen quad rendering pathway instead of just copying the color buffer. colorHolder.bind(); FullScreenQuadRenderer.INSTANCE.begin(); for (ComputeProgram computeProgram : finalPass.computes) { if (computeProgram != null) { computeProgram.use(); this.customUniforms.push(computeProgram); computeProgram.dispatch(baseWidth, baseHeight); } } RenderSystem.memoryBarrier(40); if (!finalPass.mipmappedBuffers.isEmpty()) { GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); for (int index : finalPass.mipmappedBuffers) { setupMipmapping(renderTargets.get(index), finalPass.stageReadsFromAlt.contains(index)); } } finalPass.program.use(); this.customUniforms.push(finalPass.program); FullScreenQuadRenderer.INSTANCE.renderQuad(); FullScreenQuadRenderer.end(); } else { // If there are no passes, we somehow need to transfer the content of the Iris color render targets into // the main Minecraft framebuffer. // // Thus, the following call transfers the content of colortex0 into the main Minecraft framebuffer. // // Note that glCopyTexSubImage2D is not as strict as glBlitFramebuffer, so we don't have to worry about // colortex0 having a weird format. This should just work. // // We could have used a shader here, but it should be about the same performance either way: // https://stackoverflow.com/a/23994979/18166885 this.baseline.bindAsReadBuffer(); RenderSystem.copyTexSubImage2D(main.framebufferTexture, GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, baseWidth, baseHeight); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) { // Reset mipmapping states at the end of the frame. resetRenderTarget(renderTargets.get(i)); } for (SwapPass swapPass : swapPasses) { // NB: We need to use bind(), not bindAsReadBuffer()... Previously we used bindAsReadBuffer() here which // broke TAA on many packs and on many drivers. // // Note that glCopyTexSubImage2D reads from the current GL_READ_BUFFER (given by glReadBuffer()) for the // current framebuffer bound to GL_FRAMEBUFFER, but that is distinct from the current GL_READ_FRAMEBUFFER, // which is what bindAsReadBuffer() binds. // // Also note that RenderTargets already calls readBuffer(0) for us. swapPass.from.bind(); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, swapPass.targetTexture); GL11.glCopyTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, 0, 0, swapPass.width, swapPass.height); } // Make sure to reset the viewport to how it was before... Otherwise weird issues could occur. // Also bind the "main" framebuffer if it isn't already bound. main.bindFramebuffer(true); ProgramUniforms.clearActiveUniforms(); ProgramSamplers.clearActiveSamplers(); GL20.glUseProgram(0); for (int i = 0; i < SamplerLimits.get().getMaxTextureUnits(); i++) { // Unbind all textures that we may have used. // NB: This is necessary for shader pack reloading to work properly GLStateManager.glActiveTexture(GL13.GL_TEXTURE0 + i); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } GLStateManager.glActiveTexture(GL13.GL_TEXTURE0); } public void recalculateSwapPassSize() { for (SwapPass swapPass : swapPasses) { final RenderTarget target = renderTargets.get(swapPass.target); renderTargets.destroyFramebuffer(swapPass.from); // Match constructor logic - swap passes are only for non-flipped buffers // Copy ALT→MAIN to preserve data written to ALT 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) { final 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. RenderSystem.generateMipmaps(texture, GL11.GL_TEXTURE_2D); int filter = GL11.GL_LINEAR_MIPMAP_LINEAR; if (target.getInternalFormat().getPixelFormat().isInteger()) { filter = GL11.GL_NEAREST_MIPMAP_NEAREST; } RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter); } 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 = GL11.GL_LINEAR; if (target.getInternalFormat().getPixelFormat().isInteger()) { filter = GL11.GL_NEAREST; } RenderSystem.texParameteri(target.getMainTexture(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter); RenderSystem.texParameteri(target.getAltTexture(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, filter); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } // TODO: Don't just copy this from DeferredWorldRenderingPipeline private Program createProgramFromTransformed(ProgramSource source, Map<PatchShaderType, String> transformed, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) { final String vertex = transformed.get(PatchShaderType.VERTEX); final String geometry = transformed.get(PatchShaderType.GEOMETRY); final String fragment = transformed.get(PatchShaderType.FRAGMENT); PatchedShaderPrinter.debugPatchedShaders(source.getName(), vertex, geometry, fragment); Objects.requireNonNull(flipped); final ProgramBuilder builder; try { builder = ProgramBuilder.begin(source.getName(), vertex, geometry, fragment, IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (RuntimeException e) { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } this.customUniforms.assignTo(builder); final ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); CommonUniforms.addDynamicUniforms(builder); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get()); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get()); } // TODO: Don't duplicate this with CompositeRenderer centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); Program build = builder.build(); this.customUniforms.mapholderToPass(builder, build); return build; } private ComputeProgram[] createComputes(ComputeSource[] compute, ImmutableSet<Integer> flipped, ImmutableSet<Integer> flippedAtLeastOnceSnapshot, Supplier<ShadowRenderTargets> shadowTargetsSupplier) { final ComputeProgram[] programs = new ComputeProgram[compute.length]; for (int i = 0; i < programs.length; i++) { final ComputeSource source = compute[i]; if (source == null || !source.getSource().isPresent()) { continue; } else { // TODO: Properly handle empty shaders Objects.requireNonNull(flipped); final ProgramBuilder builder; try { builder = ProgramBuilder.beginCompute(source.getName(), source.getSource().orElse(null), IrisSamplers.COMPOSITE_RESERVED_TEXTURE_UNITS); } catch (RuntimeException e) { // TODO: Better error handling throw new RuntimeException("Shader compilation failed!", e); } ProgramSamplers.CustomTextureSamplerInterceptor customTextureSamplerInterceptor = ProgramSamplers.customTextureSamplerInterceptor(builder, customTextureIds, flippedAtLeastOnceSnapshot); customUniforms.assignTo(builder); CommonUniforms.addDynamicUniforms(builder); IrisSamplers.addRenderTargetSamplers(customTextureSamplerInterceptor, () -> flipped, renderTargets, true); IrisImages.addRenderTargetImages(builder, () -> flipped, renderTargets); IrisSamplers.addNoiseSampler(customTextureSamplerInterceptor, noiseTexture); IrisSamplers.addCompositeSamplers(customTextureSamplerInterceptor, renderTargets); if (IrisSamplers.hasShadowSamplers(customTextureSamplerInterceptor)) { IrisSamplers.addShadowSamplers(customTextureSamplerInterceptor, shadowTargetsSupplier.get()); IrisImages.addShadowColorImages(builder, shadowTargetsSupplier.get()); } // TODO: Don't duplicate this with FinalPassRenderer centerDepthSampler.setUsage(builder.addDynamicSampler(centerDepthSampler::getCenterDepthTexture, "iris_centerDepthSmooth")); programs[i] = builder.buildCompute(); this.customUniforms.mapholderToPass(builder, programs[i]); programs[i].setWorkGroupInfo(source.getWorkGroupRelative(), source.getWorkGroups()); } } return programs; } public void destroy() { if (finalPass != null) { finalPass.destroy(); } } }
Angelica
src\main\java\net\coderbot\iris\postprocess\FullScreenQuadRenderer.java
package net.coderbot.iris.postprocess; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import java.nio.FloatBuffer; /** * Renders a full-screen textured quad to the screen. Used in composite / deferred rendering. */ public class FullScreenQuadRenderer { private final int quadBuffer; public static final FullScreenQuadRenderer INSTANCE = new FullScreenQuadRenderer(); private FullScreenQuadRenderer() { this.quadBuffer = createQuad(); } public void render() { begin(); renderQuad(); end(); } public void begin() { GLStateManager.disableDepthTest(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPushMatrix(); GL11.glLoadIdentity(); // scale the quad from [0, 1] to [-1, 1] GL11.glTranslatef(-1.0F, -1.0F, 0.0F); GL11.glScalef(2.0F, 2.0F, 0.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, quadBuffer); DefaultVertexFormat.POSITION_TEXTURE.setupBufferState(0L); } public void renderQuad() { GLStateManager.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, 4); } public static void end() { DefaultVertexFormat.POSITION_TEXTURE.clearBufferState(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GLStateManager.enableDepthTest(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPopMatrix(); } /** * Creates and uploads a vertex buffer containing a single full-screen quad */ private static int createQuad() { final FloatBuffer vertices = BufferUtils.createFloatBuffer(20); vertices.put(new float[] { // Vertex 0: Top right corner 1.0F, 1.0F, 0.0F, 1.0F, 1.0F, // Vertex 1: Top left corner 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, // Vertex 2: Bottom right corner 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, // Vertex 3: Bottom left corner 0.0F, 0.0F, 0.0F, 0.0F, 0.0F }).rewind(); return RenderSystem.bufferStorage(GL15.GL_ARRAY_BUFFER, vertices, GL15.GL_STATIC_DRAW); } }
Angelica
src\main\java\net\coderbot\iris\postprocess\ProgramBuildContext.java
package net.coderbot.iris.postprocess; import com.github.bsideup.jabel.Desugar; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import net.coderbot.iris.rendertarget.RenderTargets; import net.coderbot.iris.shadows.ShadowRenderTargets; import net.coderbot.iris.uniforms.FrameUpdateNotifier; import net.coderbot.iris.uniforms.custom.CustomUniforms; import org.jetbrains.annotations.NotNull; import java.util.function.IntSupplier; import java.util.function.Supplier; @Desugar public record ProgramBuildContext( @NotNull RenderTargets renderTargets, @NotNull IntSupplier noiseTexture, @NotNull FrameUpdateNotifier updateNotifier, @NotNull CenterDepthSampler centerDepthSampler, @NotNull Supplier<ShadowRenderTargets> shadowTargetsSupplier, @NotNull Object2ObjectMap<String, IntSupplier> customTextureIds, @NotNull CustomUniforms customUniforms ) {}
Angelica
src\main\java\net\coderbot\iris\rendertarget\ColorTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.GlResource; import net.coderbot.iris.gl.texture.TextureUploadHelper; import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.nio.ByteBuffer; public class ColorTexture extends GlResource { public ColorTexture(int width, int height) { super(RenderSystem.createTexture(GL11.GL_TEXTURE_2D)); final int texture = getGlId(); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); TextureUploadHelper.resetTextureUploadState(); RenderSystem.texImage2D(texture, GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width, height, 0, GL11.GL_RGBA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, (ByteBuffer) null); EXTFramebufferObject.glFramebufferTexture2DEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_COLOR_ATTACHMENT0_EXT, GL11.GL_TEXTURE_2D, texture, 0); } public int getTextureId() { return getGlId(); } @Override protected void destroyInternal() { GLStateManager.glDeleteTextures(getGlId()); } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\DepthTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.GlResource; import net.coderbot.iris.gl.texture.DepthBufferFormat; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class DepthTexture extends GlResource { public DepthTexture(int width, int height, DepthBufferFormat format) { super(RenderSystem.createTexture(GL11.GL_TEXTURE_2D)); final int texture = getGlId(); resize(width, height, format); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } void resize(int width, int height, DepthBufferFormat format) { RenderSystem.texImage2D(getTextureId(), GL11.GL_TEXTURE_2D, 0, format.getGlInternalFormat(), width, height, 0, format.getGlType(), format.getGlFormat(), null); } public int getTextureId() { return getGlId(); } @Override protected void destroyInternal() { GLStateManager.glDeleteTextures(getGlId()); } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\IRenderTargetExt.java
package net.coderbot.iris.rendertarget; public interface IRenderTargetExt { int iris$getDepthBufferVersion(); int iris$getColorBufferVersion(); int iris$getDepthTextureId(); }
Angelica
src\main\java\net\coderbot\iris\rendertarget\NativeImageBackedCustomTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.compat.mojang.NativeImage; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.shaderpack.texture.CustomTextureData; import net.minecraft.client.renderer.texture.DynamicTexture; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.io.IOException; import java.nio.ByteBuffer; public class NativeImageBackedCustomTexture extends DynamicTexture { public NativeImageBackedCustomTexture(CustomTextureData.PngData textureData) throws IOException { super(create(textureData.getContent())); // By default, images are unblurred and not clamped. if (textureData.getFilteringData().shouldBlur()) { RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); } if (textureData.getFilteringData().shouldClamp()) { RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); RenderSystem.texParameteri(getGlTextureId(), GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } } private static NativeImage create(byte[] content) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(content.length); buffer.put(content); buffer.flip(); return NativeImage.read(buffer); } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\NativeImageBackedNoiseTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.compat.mojang.NativeImage; import net.minecraft.client.renderer.texture.DynamicTexture; import org.lwjgl.opengl.GL11; import java.util.Random; public class NativeImageBackedNoiseTexture extends DynamicTexture { public NativeImageBackedNoiseTexture(int size) { super(create(size)); } private static NativeImage create(int size) { NativeImage image = new NativeImage(NativeImage.Format.RGBA, size, size, false); Random random = new Random(0); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { int color = random.nextInt() | (255 << 24); image.setPixelRGBA(x, y, color); } } return image; } @Override public void updateDynamicTexture() { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); super.updateDynamicTexture(); } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\NativeImageBackedSingleColorTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.compat.mojang.NativeImage; import net.minecraft.client.renderer.texture.DynamicTexture; public class NativeImageBackedSingleColorTexture extends DynamicTexture { public NativeImageBackedSingleColorTexture(int red, int green, int blue, int alpha) { super(create(NativeImage.combine(alpha, blue, green, red))); } public NativeImageBackedSingleColorTexture(int rgba) { this(rgba >> 24 & 0xFF, rgba >> 16 & 0xFF, rgba >> 8 & 0xFF, rgba & 0xFF); } private static NativeImage create(int color) { NativeImage image = new NativeImage(NativeImage.Format.RGBA, 1, 1, false); image.setPixelRGBA(0, 0, color); return image; } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\NoiseTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.GlResource; import net.coderbot.iris.gl.texture.TextureUploadHelper; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL14; import java.nio.ByteBuffer; import java.util.Random; /** * An extremely simple noise texture. Each color channel contains a uniform random value from 0 to 255. Essentially just * dumps an array of random bytes into a texture and calls it a day, literally could not be any simpler than that. */ public class NoiseTexture extends GlResource { int width; int height; public NoiseTexture(int width, int height) { super(RenderSystem.createTexture(GL11.GL_TEXTURE_2D)); int texture = getGlId(); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 0); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MIN_LOD, 0); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LOD,0); RenderSystem.texParameterf(texture, GL11.GL_TEXTURE_2D, GL14.GL_TEXTURE_LOD_BIAS, 0.0F); resize(texture, width, height); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } void resize(int texture, int width, int height) { this.width = width; this.height = height; ByteBuffer pixels = generateNoise(); TextureUploadHelper.resetTextureUploadState(); // Since we're using tightly-packed RGB data, we must use an alignment of 1 byte instead of the usual 4 bytes. GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); RenderSystem.texImage2D(texture, GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, width, height, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, pixels); GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } private ByteBuffer generateNoise() { byte[] pixels = new byte[3 * width * height]; Random random = new Random(0); random.nextBytes(pixels); ByteBuffer buffer = ByteBuffer.allocateDirect(pixels.length); buffer.put(pixels); buffer.flip(); return buffer; } public int getTextureId() { return getGlId(); } @Override protected void destroyInternal() { GLStateManager.glDeleteTextures(getGlId()); } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\RenderTarget.java
package net.coderbot.iris.rendertarget; import static com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack.*; import com.gtnewhorizon.gtnhlib.bytebuf.MemoryStack; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import lombok.Getter; import net.coderbot.iris.gl.texture.InternalTextureFormat; import net.coderbot.iris.gl.texture.PixelFormat; import net.coderbot.iris.gl.texture.PixelType; import org.joml.Vector2i; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import java.nio.ByteBuffer; import java.nio.IntBuffer; public class RenderTarget { @Getter private final InternalTextureFormat internalFormat; private final PixelFormat format; private final PixelType type; @Getter private int width; @Getter 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; this.internalFormat = builder.internalFormat; this.format = builder.format; this.type = builder.type; this.width = builder.width; this.height = builder.height; try (MemoryStack stack = stackPush()) { IntBuffer textures = stack.mallocInt(2); GL11.glGenTextures(textures); this.mainTexture = textures.get(0); this.altTexture = textures.get(1); } boolean isPixelFormatInteger = builder.internalFormat.getPixelFormat().isInteger(); setupTexture(mainTexture, builder.width, builder.height, !isPixelFormatInteger); setupTexture(altTexture, builder.width, builder.height, !isPixelFormatInteger); // Clean up after ourselves // This is strictly defensive to ensure that other buggy code doesn't tamper with our textures GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, 0); } private void setupTexture(int texture, int width, int height, boolean allowsLinear) { resizeTexture(texture, width, height); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, allowsLinear ? GL11.GL_LINEAR : GL11.GL_NEAREST); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, allowsLinear ? GL11.GL_LINEAR : GL11.GL_NEAREST); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); } private void resizeTexture(int texture, int width, int height) { RenderSystem.texImage2D(texture, GL11.GL_TEXTURE_2D, 0, internalFormat.getGlFormat(), width, height, 0, format.getGlFormat(), type.getGlFormat(), NULL_BUFFER); } void resize(Vector2i textureScaleOverride) { this.resize(textureScaleOverride.x, textureScaleOverride.y); } // Package private, call CompositeRenderTargets#resizeIfNeeded instead. void resize(int width, int height) { requireValid(); this.width = width; this.height = height; resizeTexture(mainTexture, width, height); resizeTexture(altTexture, width, height); } public int getMainTexture() { requireValid(); return mainTexture; } public int getAltTexture() { requireValid(); return altTexture; } private final IntBuffer deleteBuffer = BufferUtils.createIntBuffer(2); public void destroy() { requireValid(); isValid = false; deleteBuffer.put(0, mainTexture); deleteBuffer.put(1, altTexture); GLStateManager.glDeleteTextures(deleteBuffer); } private void requireValid() { if (!isValid) { throw new IllegalStateException("Attempted to use a deleted composite render target"); } } 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 Builder() { // No-op } public Builder setInternalFormat(InternalTextureFormat format) { this.internalFormat = format; return this; } public Builder setDimensions(int width, int height) { if (width <= 0) { throw new IllegalArgumentException("Width must be greater than zero"); } if (height <= 0) { throw new IllegalArgumentException("Height must be greater than zero"); } this.width = width; this.height = height; return this; } public Builder setPixelFormat(PixelFormat pixelFormat) { this.format = pixelFormat; return this; } public Builder setPixelType(PixelType pixelType) { this.type = pixelType; return this; } public RenderTarget build() { return new RenderTarget(this); } } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\RenderTargets.java
package net.coderbot.iris.rendertarget; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import lombok.Getter; 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 org.joml.Vector2i; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; import java.util.Map; public class RenderTargets { private final RenderTarget[] targets; private int currentDepthTexture; private DepthBufferFormat currentDepthFormat; @Getter 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<GlFramebuffer> ownedFramebuffers; private int cachedWidth; private int cachedHeight; @Getter private boolean fullClearRequired; private boolean translucentDepthDirty; private boolean handDepthDirty; private int cachedDepthBufferVersion; public RenderTargets(int width, int height, int depthTexture, int depthBufferVersion, DepthBufferFormat depthFormat, Map<Integer, PackRenderTargetDirectives.RenderTargetSettings> renderTargets, PackDirectives packDirectives) { targets = new RenderTarget[renderTargets.size()]; renderTargets.forEach((index, settings) -> { // TODO: Handle mipmapping? Vector2i dimensions = packDirectives.getTextureScaleOverride(index, width, height); targets[index] = RenderTarget.builder().setDimensions(dimensions.x, dimensions.y) .setInternalFormat(settings.getInternalFormat()) .setPixelFormat(settings.getInternalFormat().getPixelFormat()).build(); }); this.currentDepthTexture = depthTexture; this.currentDepthFormat = depthFormat; this.copyStrategy = DepthCopyStrategy.fastest(currentDepthFormat.isCombinedStencil()); this.cachedWidth = width; this.cachedHeight = height; this.cachedDepthBufferVersion = depthBufferVersion; 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.noTranslucents = new DepthTexture(width, height, currentDepthFormat); this.noHand = new DepthTexture(width, height, currentDepthFormat); this.noTranslucentsDestFb = createFramebufferWritingToMain(new int[] {0}); this.noTranslucentsDestFb.addDepthAttachment(this.noTranslucents.getTextureId()); this.noHandDestFb = createFramebufferWritingToMain(new int[] {0}); this.noHandDestFb.addDepthAttachment(this.noHand.getTextureId()); this.translucentDepthDirty = true; this.handDepthDirty = true; } public void destroy() { for (GlFramebuffer owned : ownedFramebuffers) { owned.destroy(); } for (RenderTarget target : targets) { target.destroy(); } noTranslucents.destroy(); noHand.destroy(); } public int getRenderTargetCount() { return targets.length; } public RenderTarget get(int index) { return targets[index]; } public int getDepthTexture() { return currentDepthTexture; } public DepthTexture getDepthTextureNoTranslucents() { return noTranslucents; } public DepthTexture getDepthTextureNoHand() { return noHand; } public boolean resizeIfNeeded(int newDepthBufferVersion, int newDepthTextureId, int newWidth, int newHeight, DepthBufferFormat newDepthFormat, PackDirectives packDirectives) { boolean recreateDepth = false; if (cachedDepthBufferVersion != newDepthBufferVersion) { recreateDepth = true; currentDepthTexture = newDepthTextureId; cachedDepthBufferVersion = newDepthBufferVersion; } boolean sizeChanged = newWidth != cachedWidth || newHeight != cachedHeight; boolean depthFormatChanged = newDepthFormat != currentDepthFormat; if (depthFormatChanged) { currentDepthFormat = newDepthFormat; // Might need a new copy strategy copyStrategy = DepthCopyStrategy.fastest(currentDepthFormat.isCombinedStencil()); } if (recreateDepth) { // Re-attach the depth textures with the new depth texture ID, since Minecraft re-creates // the depth texture when resizing its render targets. // // I'm not sure if our framebuffers holding on to the old depth texture between frames // could be a concern, in the case of resizing and similar. I think it should work // based on what I've seen of the spec, though - it seems like deleting a texture // automatically detaches it from its framebuffers. for (GlFramebuffer framebuffer : ownedFramebuffers) { if (framebuffer == noHandDestFb || framebuffer == noTranslucentsDestFb) { // NB: Do not change the depth attachment of these framebuffers // as it is intentionally different continue; } if (framebuffer.hasDepthAttachment()) { framebuffer.addDepthAttachment(newDepthTextureId); } } } if (depthFormatChanged || sizeChanged) { // Reallocate depth buffers noTranslucents.resize(newWidth, newHeight, newDepthFormat); noHand.resize(newWidth, newHeight, newDepthFormat); this.translucentDepthDirty = true; this.handDepthDirty = true; } if (sizeChanged) { cachedWidth = newWidth; cachedHeight = newHeight; for (int i = 0; i < targets.length; i++) { targets[i].resize(packDirectives.getTextureScaleOverride(i, newWidth, newHeight)); } fullClearRequired = true; } return sizeChanged; } public void copyPreTranslucentDepth() { if (translucentDepthDirty) { translucentDepthDirty = false; GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, noTranslucents.getTextureId()); depthSourceFb.bindAsReadBuffer(); RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, currentDepthFormat.getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); } else { copyStrategy.copy(depthSourceFb, getDepthTexture(), noTranslucentsDestFb, noTranslucents.getTextureId(), getCurrentWidth(), getCurrentHeight()); } } public void copyPreHandDepth() { if (handDepthDirty) { handDepthDirty = false; GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, noHand.getTextureId()); depthSourceFb.bindAsReadBuffer(); RenderSystem.copyTexImage2D(GL11.GL_TEXTURE_2D, 0, currentDepthFormat.getGlInternalFormat(), 0, 0, cachedWidth, cachedHeight, 0); } else { copyStrategy.copy(depthSourceFb, getDepthTexture(), noHandDestFb, noHand.getTextureId(), getCurrentWidth(), getCurrentHeight()); } } public void onFullClear() { fullClearRequired = false; } public GlFramebuffer createFramebufferWritingToMain(int[] drawBuffers) { return createFullFramebuffer(false, drawBuffers); } public GlFramebuffer createFramebufferWritingToAlt(int[] drawBuffers) { return createFullFramebuffer(true, drawBuffers); } public GlFramebuffer createClearFramebuffer(boolean alt, int[] clearBuffers) { ImmutableSet<Integer> stageWritesToMain = ImmutableSet.of(); if (!alt) { stageWritesToMain = invert(ImmutableSet.of(), clearBuffers); } return createColorFramebuffer(stageWritesToMain, clearBuffers); } private ImmutableSet<Integer> invert(ImmutableSet<Integer> base, int[] relevant) { ImmutableSet.Builder<Integer> inverted = ImmutableSet.builder(); for (int i : relevant) { if (!base.contains(i)) { inverted.add(i); } } return inverted.build(); } private GlFramebuffer createEmptyFramebuffer() { GlFramebuffer framebuffer = new GlFramebuffer(); ownedFramebuffers.add(framebuffer); framebuffer.addDepthAttachment(currentDepthTexture); // NB: Before OpenGL 3.0, all framebuffers are required to have a color attachment no matter what. framebuffer.addColorAttachment(0, get(0).getMainTexture()); framebuffer.noDrawBuffers(); return framebuffer; } public GlFramebuffer createGbufferFramebuffer(ImmutableSet<Integer> stageWritesToAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); } ImmutableSet<Integer> stageWritesToMain = invert(stageWritesToAlt, drawBuffers); GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(currentDepthTexture); return framebuffer; } private GlFramebuffer createFullFramebuffer(boolean clearsAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); } ImmutableSet<Integer> stageWritesToMain = ImmutableSet.of(); if (!clearsAlt) { stageWritesToMain = invert(ImmutableSet.of(), drawBuffers); } return createColorFramebufferWithDepth(stageWritesToMain, drawBuffers); } public GlFramebuffer createColorFramebufferWithDepth(ImmutableSet<Integer> stageWritesToMain, int[] drawBuffers) { final GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(currentDepthTexture); return framebuffer; } public GlFramebuffer createColorFramebuffer(ImmutableSet<Integer> stageWritesToMain, int[] drawBuffers) { if (drawBuffers.length == 0) { throw new IllegalArgumentException("Framebuffer must have at least one color buffer"); } final GlFramebuffer framebuffer = new GlFramebuffer(); ownedFramebuffers.add(framebuffer); final int[] actualDrawBuffers = new int[drawBuffers.length]; for (int i = 0; i < drawBuffers.length; i++) { actualDrawBuffers[i] = i; if (drawBuffers[i] >= getRenderTargetCount()) { // TODO: This causes resource leaks, also we should really verify this in the shaderpack parser... throw new IllegalStateException("Render target with index " + drawBuffers[i] + " is not supported, only " + getRenderTargetCount() + " render targets are supported."); } final RenderTarget target = this.get(drawBuffers[i]); final int textureId = stageWritesToMain.contains(drawBuffers[i]) ? target.getMainTexture() : target.getAltTexture(); framebuffer.addColorAttachment(i, textureId); } framebuffer.drawBuffers(actualDrawBuffers); framebuffer.readBuffer(0); if (!framebuffer.isComplete()) { throw new IllegalStateException("Unexpected error while creating framebuffer"); } return framebuffer; } public void destroyFramebuffer(GlFramebuffer framebuffer) { framebuffer.destroy(); ownedFramebuffers.remove(framebuffer); } public int getCurrentWidth() { return cachedWidth; } public int getCurrentHeight() { return cachedHeight; } }
Angelica
src\main\java\net\coderbot\iris\rendertarget\SingleColorTexture.java
package net.coderbot.iris.rendertarget; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.RenderSystem; import net.coderbot.iris.gl.GlResource; import net.coderbot.iris.gl.texture.TextureUploadHelper; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import java.nio.ByteBuffer; public class SingleColorTexture extends GlResource { public SingleColorTexture(int red, int green, int blue, int alpha) { super(RenderSystem.createTexture(GL11.GL_TEXTURE_2D)); ByteBuffer pixel = BufferUtils.createByteBuffer(4); pixel.put((byte) red); pixel.put((byte) green); pixel.put((byte) blue); pixel.put((byte) alpha); pixel.position(0); int texture = getGlId(); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); RenderSystem.texParameteri(texture, GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); TextureUploadHelper.resetTextureUploadState(); RenderSystem.texImage2D(texture, GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, 1, 1, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixel); } public int getTextureId() { return getGlId(); } @Override protected void destroyInternal() { GLStateManager.glDeleteTextures(getGlId()); } }
Angelica
src\main\java\net\coderbot\iris\samplers\IrisImages.java
package net.coderbot.iris.samplers; import com.google.common.collect.ImmutableSet; import net.coderbot.iris.gl.image.ImageHolder; 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 java.util.function.IntSupplier; import java.util.function.Supplier; public class IrisImages { public static void addRenderTargetImages(ImageHolder images, Supplier<ImmutableSet<Integer>> flipped, RenderTargets renderTargets) { for (int i = 0; i < renderTargets.getRenderTargetCount(); i++) { final int index = i; // Note: image bindings *are* impacted by buffer flips. IntSupplier textureID = () -> { ImmutableSet<Integer> flippedBuffers = flipped.get(); RenderTarget target = renderTargets.get(index); if (flippedBuffers.contains(index)) { return target.getAltTexture(); } else { return target.getMainTexture(); } }; final InternalTextureFormat internalFormat = renderTargets.get(i).getInternalFormat(); final String name = "colorimg" + i; images.addTextureImage(textureID, internalFormat, name); } } public static boolean hasShadowImages(ImageHolder images) { // TODO: Generalize return images.hasImage("shadowcolorimg0") || images.hasImage("shadowcolorimg1"); } public static void addShadowColorImages(ImageHolder images, ShadowRenderTargets shadowRenderTargets) { for (int i = 0; i < shadowRenderTargets.getNumColorTextures(); i++) { final int index = i; IntSupplier textureID = () -> shadowRenderTargets.getColorTextureId(index); InternalTextureFormat format = shadowRenderTargets.getColorTextureFormat(index); images.addTextureImage(textureID, format, "shadowcolorimg" + i); } } }
Angelica
src\main\java\net\coderbot\iris\samplers\IrisSamplers.java
package net.coderbot.iris.samplers; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import net.coderbot.iris.gbuffer_overrides.matching.InputAvailability; import net.coderbot.iris.gl.sampler.SamplerHolder; import net.coderbot.iris.gl.state.StateUpdateNotifiers; 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.shadows.ShadowRenderTargets; import net.minecraft.client.renderer.texture.AbstractTexture; import java.util.function.IntSupplier; import java.util.function.Supplier; public class IrisSamplers { public static final int ALBEDO_TEXTURE_UNIT = 0; public static final int LIGHTMAP_TEXTURE_UNIT = 1; public static final ImmutableSet<Integer> WORLD_RESERVED_TEXTURE_UNITS = ImmutableSet.of(0, 1); // TODO: In composite programs, there shouldn't be any reserved textures. // We need a way to restore these texture bindings. public static final ImmutableSet<Integer> COMPOSITE_RESERVED_TEXTURE_UNITS = ImmutableSet.of(1); private IrisSamplers() { // no construction allowed } public static void addRenderTargetSamplers(SamplerHolder samplers, Supplier<ImmutableSet<Integer>> flipped, RenderTargets renderTargets, boolean isFullscreenPass) { // 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; for (int i = startIndex; i < renderTargets.getRenderTargetCount(); i++) { final int index = i; IntSupplier sampler = () -> { ImmutableSet<Integer> flippedBuffers = flipped.get(); RenderTarget target = renderTargets.get(index); if (flippedBuffers.contains(index)) { return target.getAltTexture(); } else { return target.getMainTexture(); } }; final String name = "colortex" + i; // TODO: How do custom textures interact with aliases? if (i < PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.size()) { String legacyName = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.get(i); // colortex0 is the default sampler in fullscreen passes if (i == 0 && isFullscreenPass) { samplers.addDefaultSampler(sampler, name, legacyName); } else { samplers.addDynamicSampler(sampler, name, legacyName); } } else { samplers.addDynamicSampler(sampler, name); } } } public static void addNoiseSampler(SamplerHolder samplers, IntSupplier sampler) { samplers.addDynamicSampler(sampler, "noisetex"); } 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<String> shadowSamplers = ImmutableList.of("shadowtex0", "shadowtex0HW", "shadowtex1", "shadowtex1HW", "shadow", "watershadow", "shadowcolor", "shadowcolor0", "shadowcolor1", "shadowcolorimg0", "shadowcolorimg1"); for (String samplerName : shadowSamplers) { if (samplers.hasSampler(samplerName)) { return true; } } return false; } public static boolean addShadowSamplers(SamplerHolder samplers, ShadowRenderTargets shadowRenderTargets) { boolean usesShadows; // TODO: figure this out from parsing the shader source code to be 100% compatible with the legacy // shader packs that rely on this behavior. boolean waterShadowEnabled = samplers.hasSampler("watershadow"); if (waterShadowEnabled) { usesShadows = true; samplers.addDynamicSampler(shadowRenderTargets.getDepthTexture()::getTextureId, "shadowtex0", "watershadow"); samplers.addDynamicSampler(shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, "shadowtex1", "shadow"); } else { usesShadows = samplers.addDynamicSampler(shadowRenderTargets.getDepthTexture()::getTextureId, "shadowtex0", "shadow"); usesShadows |= samplers.addDynamicSampler(shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, "shadowtex1"); } samplers.addDynamicSampler(() -> shadowRenderTargets.getColorTextureId(0), "shadowcolor", "shadowcolor0"); samplers.addDynamicSampler(() -> shadowRenderTargets.getColorTextureId(1), "shadowcolor1"); if (shadowRenderTargets.isHardwareFiltered(0)) { samplers.addDynamicSampler(shadowRenderTargets.getDepthTexture()::getTextureId, "shadowtex0HW"); } if (shadowRenderTargets.isHardwareFiltered(1)) { samplers.addDynamicSampler(shadowRenderTargets.getDepthTextureNoTranslucents()::getTextureId, "shadowtex1HW"); } return usesShadows; } 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) { samplers.addExternalSampler(ALBEDO_TEXTURE_UNIT, "tex", "texture", "gtexture"); } else { // TODO: Rebind unbound sampler IDs instead of hardcoding a list... samplers.addDynamicSampler(whitePixel::getGlTextureId, "tex", "texture", "gtexture", "gcolor", "colortex0"); } if (availability.lightmap) { samplers.addExternalSampler(LIGHTMAP_TEXTURE_UNIT, "lightmap"); } else { samplers.addDynamicSampler(whitePixel::getGlTextureId, "lightmap"); } samplers.addDynamicSampler(pipeline::getCurrentNormalTexture, StateUpdateNotifiers.normalTextureChangeNotifier, "normals"); samplers.addDynamicSampler(pipeline::getCurrentSpecularTexture, StateUpdateNotifiers.specularTextureChangeNotifier, "specular"); } public static void addWorldDepthSamplers(SamplerHolder samplers, RenderTargets renderTargets) { samplers.addDynamicSampler(renderTargets::getDepthTexture, "depthtex0"); // TODO: Should depthtex2 be made available to gbuffer / shadow programs? samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1"); } public static void addCompositeSamplers(SamplerHolder samplers, RenderTargets renderTargets) { samplers.addDynamicSampler(renderTargets::getDepthTexture, "gdepthtex", "depthtex0"); samplers.addDynamicSampler(renderTargets.getDepthTextureNoTranslucents()::getTextureId, "depthtex1"); samplers.addDynamicSampler(renderTargets.getDepthTextureNoHand()::getTextureId, "depthtex2"); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\CloudSetting.java
package net.coderbot.iris.shaderpack; public enum CloudSetting { DEFAULT, FAST, FANCY, OFF }
Angelica
src\main\java\net\coderbot\iris\shaderpack\CommentDirective.java
package net.coderbot.iris.shaderpack; public class CommentDirective { public enum Type { DRAWBUFFERS, RENDERTARGETS } private final Type type; private final String directive; private final int location; CommentDirective(Type type, String directive, int location) { this.type = type; this.directive = directive; this.location = location; } public Type getType() { return type; } /** * @return The directive without {@literal /}* or *{@literal /} */ public String getDirective() { return directive; } /** * @return The starting position of the directive in a multi-line string. <br> * This is necessary to check if either the drawbuffer or the rendertarget directive should be applied * when there are multiple in the same shader file, based on which one is defined last. */ public int getLocation() { return location; } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\CommentDirectiveParser.java
package net.coderbot.iris.shaderpack; import java.util.Optional; import java.util.function.Supplier; /** * Parses comment-based directives found in shader source files of the form: * * <pre>/* KEY:VALUE *<i></i>/</pre> * <p> * A common example is draw buffer directives: * * <pre>/* DRAWBUFFERS:157 *<i></i>/</pre> * <p> * A given directive should only occur once in a shader file. If there are multiple occurrences of a directive with a * given key, the last occurrence is used. */ public class CommentDirectiveParser { // Directives take the following form: // /* KEY:VALUE */ private CommentDirectiveParser() { // cannot be constructed } public static Optional<CommentDirective> findDirective(String haystack, CommentDirective.Type type) { String needle = type.name(); String prefix = needle + ":"; String suffix = "*/"; // Search for the last occurrence of the directive within the text, since those take precedence. int indexOfPrefix = haystack.lastIndexOf(prefix); if (indexOfPrefix == -1) { return Optional.empty(); } String before = haystack.substring(0, indexOfPrefix).trim(); if (!before.endsWith("/*")) { // Reject a match if it doesn't actually start with a comment marker // TODO: If a line has two directives, one valid, and the other invalid, then this might not work properly return Optional.empty(); } // Remove everything up to and including the prefix haystack = haystack.substring(indexOfPrefix + prefix.length()); int indexOfSuffix = haystack.indexOf(suffix); // If there isn't a proper suffix, this directive is malformed and should be discarded. if (indexOfSuffix == -1) { return Optional.empty(); } // Remove the suffix and everything afterwards, also trim any whitespace haystack = haystack.substring(0, indexOfSuffix).trim(); return Optional.of(new CommentDirective(CommentDirective.Type.valueOf(needle), haystack, indexOfPrefix)); } // Test code for directive parsing. It's a bit homegrown but it works. @SuppressWarnings("unused") private static class Tests { private static <T> void test(String name, T expected, Supplier<T> testCase) { T actual; try { actual = testCase.get(); } catch (Exception e) { System.err.println("Test \"" + name + "\" failed with an exception:"); e.printStackTrace(); return; } if (!expected.equals(actual)) { System.err.println("Test \"" + name + "\" failed: Expected " + expected + ", got " + actual); } else { System.out.println("Test \"" + name + "\" passed"); } } public static void main(String[] args) { test("normal text", Optional.empty(), () -> { String line = "Some normal text that doesn't contain a DRAWBUFFERS directive of any sort"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("partial directive", Optional.empty(), () -> { String line = "Some normal text that doesn't contain a /* DRAWBUFFERS: directive of any sort"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("bad spacing", Optional.of("321"), () -> { String line = "/*DRAWBUFFERS:321*/ OptiFine will detect this directive, but ShadersMod will not..."; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("matchAtEnd", Optional.of("321"), () -> { String line = "A line containing a drawbuffers directive: /* DRAWBUFFERS:321 */"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("matchAtStart", Optional.of("31"), () -> { String line = "/* DRAWBUFFERS:31 */ This is a line containing a drawbuffers directive"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("matchInMiddle", Optional.of("31"), () -> { String line = "This is a line /* DRAWBUFFERS:31 */ containing a drawbuffers directive"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("emptyMatch", Optional.of(""), () -> { String line = "/* DRAWBUFFERS: */ This is a line containing an invalid but still matching drawbuffers directive"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); test("duplicates", Optional.of("3"), () -> { String line = "/* TEST:2 */ This line contains multiple directives, the last one should be used /* TEST:3 */"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); 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"; return CommentDirectiveParser.findDirective(lines, CommentDirective.Type.RENDERTARGETS).map(CommentDirective::getDirective); }); // OptiFine finds this directive, but ShadersMod does not... test("bad spacing from BSL composite6", Optional.of("12"), () -> { String line = " /*DRAWBUFFERS:12*/"; return CommentDirectiveParser.findDirective(line, CommentDirective.Type.DRAWBUFFERS).map(CommentDirective::getDirective); }); } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ComputeDirectiveParser.java
package net.coderbot.iris.shaderpack; import net.coderbot.iris.Iris; import org.joml.Vector2f; import org.joml.Vector3i; public class ComputeDirectiveParser { public static void setComputeWorkGroups(ComputeSource source, ConstDirectiveParser.ConstDirective directive) { if (!directive.getValue().startsWith("ivec3")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); } String ivec3Args = directive.getValue().substring("ivec3".length()).trim(); if (!ivec3Args.startsWith("(") || !ivec3Args.endsWith(")")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); } ivec3Args = ivec3Args.substring(1, ivec3Args.length() - 1); String[] parts = ivec3Args.split(","); for (int i = 0; i < parts.length; i++) { parts[i] = parts[i].trim(); } if (parts.length != 3) { Iris.logger.error("Failed to process " + directive + ": expected 3 arguments to a ivec3 constructor, got " + parts.length); } try { source.setWorkGroups(new Vector3i( Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]))); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } } public static void setComputeWorkGroupsRelative(ComputeSource source, ConstDirectiveParser.ConstDirective directive) { if (!directive.getValue().startsWith("vec2")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); } String vec2Args = directive.getValue().substring("vec2".length()).trim(); if (!vec2Args.startsWith("(") || !vec2Args.endsWith(")")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); } vec2Args = vec2Args.substring(1, vec2Args.length() - 1); String[] parts = vec2Args.split(","); for (int i = 0; i < parts.length; i++) { parts[i] = parts[i].trim(); } if (parts.length != 2) { Iris.logger.error("Failed to process " + directive + ": expected 2 arguments to a vec2 constructor, got " + parts.length); } try { source.setWorkGroupRelative(new Vector2f( Float.parseFloat(parts[0]), Float.parseFloat(parts[1]) )); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ComputeSource.java
package net.coderbot.iris.shaderpack; import org.joml.Vector2f; import org.joml.Vector3i; import java.util.Optional; public class ComputeSource { private final String name; private final String source; private final ProgramSet parent; private Vector3i workGroups; private Vector2f workGroupRelative; public ComputeSource(String name, String source, ProgramSet parent) { this.name = name; this.source = source; this.parent = parent; } public String getName() { return name; } public Optional<String> getSource() { return Optional.ofNullable(source); } public ProgramSet getParent() { return parent; } public boolean isValid() { return source != null; } public void setWorkGroups(Vector3i workGroups) { this.workGroups = workGroups; } public void setWorkGroupRelative(Vector2f workGroupRelative) { this.workGroupRelative = workGroupRelative; } public Vector2f getWorkGroupRelative() { return workGroupRelative; } public Vector3i getWorkGroups() { return workGroups; } public Optional<ComputeSource> requireValid() { if (this.isValid()) { return Optional.of(this); } else { return Optional.empty(); } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ConstDirectiveParser.java
package net.coderbot.iris.shaderpack; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class ConstDirectiveParser { public static List<ConstDirective> findDirectives(String source) { List<ConstDirective> directives = new ArrayList<>(); // Match any valid newline sequence // https://stackoverflow.com/a/31060125 for (String line : source.split("\\R")) { findDirectiveInLine(line).ifPresent(directives::add); } return directives; } public static Optional<ConstDirective> findDirectiveInLine(String line) { // Valid const directives contain the following elements: // * Zero or more whitespace characters // * A "const" literal // * At least one whitespace character // * A type literal (int, float, vec4, or bool) // * At least one whitespace character // * The name / key of the const directive (alphanumeric & underscore characters) // * Zero or more whitespace characters // * An equals sign // * Zero or more whitespace characters // * The value of the const directive (alphanumeric & underscore characters) // * A semicolon // * (any content) // Bail-out early without doing any processing if required components are not found // A const directive must contain at the very least a const keyword, then an equals // sign, then a semicolon. if (!line.contains("const") || !line.contains("=") || !line.contains(";")) { return Optional.empty(); } // Trim any surrounding whitespace (such as indentation) from the line before processing it. line = line.trim(); // A valid declaration must have a trimmed line starting with const if (!line.startsWith("const")) { return Optional.empty(); } // Remove the const part from the string line = line.substring("const".length()); // There must be at least one whitespace character between the "const" keyword and the type keyword if (!startsWithWhitespace(line)) { return Optional.empty(); } // Trim all whitespace between the const keyword and the type keyword line = line.trim(); // Valid const declarations have a type that is either an int, a float, a vec4, or a bool. Type type; if (line.startsWith("int")) { type = Type.INT; line = line.substring("int".length()); } else if (line.startsWith("float")) { type = Type.FLOAT; line = line.substring("float".length()); } else if (line.startsWith("vec2")) { type = Type.VEC2; line = line.substring("vec2".length()); } else if (line.startsWith("ivec3")) { type = Type.IVEC3; line = line.substring("ivec3".length()); } else if (line.startsWith("vec4")) { type = Type.VEC4; line = line.substring("vec4".length()); } else if (line.startsWith("bool")) { type = Type.BOOL; line = line.substring("bool".length()); } else { return Optional.empty(); } // There must be at least one whitespace character between the type keyword and the key of the const declaration if (!startsWithWhitespace(line)) { return Optional.empty(); } // Split the declaration at the equals sign int equalsIndex = line.indexOf('='); if (equalsIndex == -1) { // No equals sign found, not a valid const declaration return Optional.empty(); } // The key comes before the equals sign String key = line.substring(0, equalsIndex).trim(); // The key must be a "word" (alphanumeric & underscore characters) if (!isWord(key)) { return Optional.empty(); } // Everything after the equals sign but before the semicolon is the value String remaining = line.substring(equalsIndex + 1); int semicolonIndex = remaining.indexOf(';'); if (semicolonIndex == -1) { // No semicolon found, not a valid const declaration return Optional.empty(); } String value = remaining.substring(0, semicolonIndex).trim(); // We make no attempt to properly parse / verify the value here, that responsibility lies with whatever code // is working with the directives. return Optional.of(new ConstDirective(type, key, value)); } private static boolean startsWithWhitespace(String text) { return !text.isEmpty() && Character.isWhitespace(text.charAt(0)); } private static boolean isWord(String text) { if (text.isEmpty()) { return false; } for (char character : text.toCharArray()) { if (!Character.isDigit(character) && !Character.isAlphabetic(character) && character != '_') { return false; } } return true; } public static class ConstDirective { private final Type type; private final String key; private final String value; ConstDirective(Type type, String key, String value) { this.type = type; this.key = key; this.value = value; } public Type getType() { return type; } public String getKey() { return key; } public String getValue() { return value; } @Override public String toString() { return "ConstDirective { " + type + " " + key + " = " + value + "; }"; } } public enum Type { INT, FLOAT, VEC2, IVEC3, VEC4, BOOL } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\DimensionId.java
package net.coderbot.iris.shaderpack; public enum DimensionId { OVERWORLD, NETHER, END }
Angelica
src\main\java\net\coderbot\iris\shaderpack\DirectiveHolder.java
package net.coderbot.iris.shaderpack; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import it.unimi.dsi.fastutil.floats.FloatConsumer; import org.joml.Vector2f; import org.joml.Vector3i; import org.joml.Vector4f; import java.util.function.Consumer; import java.util.function.IntConsumer; public interface DirectiveHolder { void acceptUniformDirective(String name, Runnable onDetected); void acceptCommentStringDirective(String name, Consumer<String> consumer); void acceptCommentIntDirective(String name, IntConsumer consumer); void acceptCommentFloatDirective(String name, FloatConsumer consumer); void acceptConstBooleanDirective(String name, BooleanConsumer consumer); void acceptConstStringDirective(String name, Consumer<String> consumer); void acceptConstIntDirective(String name, IntConsumer consumer); void acceptConstFloatDirective(String name, FloatConsumer consumer); void acceptConstVec2Directive(String name, Consumer<Vector2f> consumer); void acceptConstIVec3Directive(String name, Consumer<Vector3i> consumer); void acceptConstVec4Directive(String name, Consumer<Vector4f> consumer); }
Angelica
src\main\java\net\coderbot\iris\shaderpack\DispatchingDirectiveHolder.java
package net.coderbot.iris.shaderpack; 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 org.joml.Vector2f; import org.joml.Vector3i; import org.joml.Vector4f; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.IntConsumer; public class DispatchingDirectiveHolder implements DirectiveHolder { private final Map<String, BooleanConsumer> booleanConstVariables; private final Map<String, Consumer<String>> stringConstVariables; private final Map<String, IntConsumer> intConstVariables; private final Map<String, FloatConsumer> floatConstVariables; private final Map<String, Consumer<Vector2f>> vec2ConstVariables; private final Map<String, Consumer<Vector3i>> ivec3ConstVariables; private final Map<String, Consumer<Vector4f>> vec4ConstVariables; public DispatchingDirectiveHolder() { booleanConstVariables = new HashMap<>(); stringConstVariables = new HashMap<>(); intConstVariables = new HashMap<>(); floatConstVariables = new HashMap<>(); vec2ConstVariables = new HashMap<>(); ivec3ConstVariables = new HashMap<>(); vec4ConstVariables = new HashMap<>(); } public void processDirective(ConstDirectiveParser.ConstDirective directive) { final ConstDirectiveParser.Type type = directive.getType(); final String key = directive.getKey(); final String value = directive.getValue(); if (type == ConstDirectiveParser.Type.BOOL) { BooleanConsumer consumer = booleanConstVariables.get(key); if (consumer != null) { if ("true".equals(value)) { consumer.accept(true); } else if ("false".equals(value)) { consumer.accept(false); } else { Iris.logger.error("Failed to process " + directive + ": " + value + " is not a valid boolean value"); } return; } if (IrisLogging.ENABLE_SPAM) { // Only logspam in dev Iris.logger.info("Found potential unhandled directive: " + directive); } typeCheckHelper("int", intConstVariables, directive); typeCheckHelper("int", stringConstVariables, directive); typeCheckHelper("float", floatConstVariables, directive); typeCheckHelper("vec4", vec4ConstVariables, directive); } else if (type == ConstDirectiveParser.Type.INT) { // GLSL does not actually have a string type, so string constant directives use "const int" instead. Consumer<String> stringConsumer = stringConstVariables.get(key); if (stringConsumer != null) { stringConsumer.accept(value); return; } IntConsumer intConsumer = intConstVariables.get(key); if (intConsumer != null) { try { intConsumer.accept(Integer.parseInt(value)); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } return; } if (IrisLogging.ENABLE_SPAM) { // Only logspam in dev Iris.logger.info("Found potential unhandled directive: " + directive); } typeCheckHelper("bool", booleanConstVariables, directive); typeCheckHelper("float", floatConstVariables, directive); typeCheckHelper("vec4", vec4ConstVariables, directive); } else if (type == ConstDirectiveParser.Type.FLOAT) { FloatConsumer consumer = floatConstVariables.get(key); if (consumer != null) { try { consumer.accept(Float.parseFloat(value)); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } return; } if (IrisLogging.ENABLE_SPAM) { // Only logspam in dev Iris.logger.info("Found potential unhandled directive: " + directive); } typeCheckHelper("bool", booleanConstVariables, directive); typeCheckHelper("int", intConstVariables, directive); typeCheckHelper("int", stringConstVariables, directive); typeCheckHelper("vec4", vec4ConstVariables, directive); } else if (type == ConstDirectiveParser.Type.VEC2) { Consumer<Vector2f> consumer = vec2ConstVariables.get(key); if (consumer != null) { if (!value.startsWith("vec2")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); } String vec2Args = value.substring("vec2".length()).trim(); if (!vec2Args.startsWith("(") || !vec2Args.endsWith(")")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec2 constructor"); } vec2Args = vec2Args.substring(1, vec2Args.length() - 1); String[] parts = vec2Args.split(","); for (int i = 0; i < parts.length; i++) { parts[i] = parts[i].trim(); } if (parts.length != 2) { Iris.logger.error("Failed to process " + directive + ": expected 2 arguments to a vec2 constructor, got " + parts.length); } try { consumer.accept(new Vector2f( Float.parseFloat(parts[0]), Float.parseFloat(parts[1]) )); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } return; } typeCheckHelper("bool", booleanConstVariables, directive); typeCheckHelper("int", intConstVariables, directive); typeCheckHelper("int", stringConstVariables, directive); typeCheckHelper("float", floatConstVariables, directive); } else if (type == ConstDirectiveParser.Type.IVEC3) { Consumer<Vector3i> consumer = ivec3ConstVariables.get(key); if (consumer != null) { if (!value.startsWith("ivec3")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); } String ivec3Args = value.substring("ivec3".length()).trim(); if (!ivec3Args.startsWith("(") || !ivec3Args.endsWith(")")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid ivec3 constructor"); } ivec3Args = ivec3Args.substring(1, ivec3Args.length() - 1); String[] parts = ivec3Args.split(","); for (int i = 0; i < parts.length; i++) { parts[i] = parts[i].trim(); } if (parts.length != 3) { Iris.logger.error("Failed to process " + directive + ": expected 3 arguments to a ivec3 constructor, got " + parts.length); } try { consumer.accept(new Vector3i( Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2]) )); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } return; } typeCheckHelper("bool", booleanConstVariables, directive); typeCheckHelper("int", intConstVariables, directive); typeCheckHelper("int", stringConstVariables, directive); typeCheckHelper("float", floatConstVariables, directive); } else if (type == ConstDirectiveParser.Type.VEC4) { Consumer<Vector4f> consumer = vec4ConstVariables.get(key); if (consumer != null) { if (!value.startsWith("vec4")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec4 constructor"); } String vec4Args = value.substring("vec4".length()).trim(); if (!vec4Args.startsWith("(") || !vec4Args.endsWith(")")) { Iris.logger.error("Failed to process " + directive + ": value was not a valid vec4 constructor"); } vec4Args = vec4Args.substring(1, vec4Args.length() - 1); String[] parts = vec4Args.split(","); for (int i = 0; i < parts.length; i++) { parts[i] = parts[i].trim(); } if (parts.length != 4) { Iris.logger.error("Failed to process " + directive + ": expected 4 arguments to a vec4 constructor, got " + parts.length); } try { consumer.accept(new Vector4f( Float.parseFloat(parts[0]), Float.parseFloat(parts[1]), Float.parseFloat(parts[2]), Float.parseFloat(parts[3]) )); } catch (NumberFormatException e) { Iris.logger.error("Failed to process " + directive, e); } return; } typeCheckHelper("bool", booleanConstVariables, directive); typeCheckHelper("int", intConstVariables, directive); typeCheckHelper("int", stringConstVariables, directive); typeCheckHelper("float", floatConstVariables, directive); } } private void typeCheckHelper(String expected, Map<String, ? extends Object> 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."); } } @Override public void acceptUniformDirective(String name, Runnable onDetected) { // TODO if (IrisLogging.ENABLE_SPAM) { Iris.logger.warn("Not looking for a uniform directive with the name " + name + " since this type of directive is not currently supported."); } } @Override public void acceptCommentStringDirective(String name, Consumer<String> consumer) { // TODO if (IrisLogging.ENABLE_SPAM) { Iris.logger.warn("Not looking for a comment string directive with the name " + name + " since this type of directive is not currently supported."); } } @Override public void acceptCommentIntDirective(String name, IntConsumer consumer) { // TODO if (IrisLogging.ENABLE_SPAM) { Iris.logger.warn("Not looking for a comment int directive with the name " + name + " since this type of directive is not currently supported."); } } @Override public void acceptCommentFloatDirective(String name, FloatConsumer consumer) { // TODO if (IrisLogging.ENABLE_SPAM) { Iris.logger.warn("Not looking for a comment float directive with the name " + name + " since this type of directive is not currently supported."); } } @Override public void acceptConstBooleanDirective(String name, BooleanConsumer consumer) { booleanConstVariables.put(name, consumer); } @Override public void acceptConstStringDirective(String name, Consumer<String> consumer) { stringConstVariables.put(name, consumer); } @Override public void acceptConstIntDirective(String name, IntConsumer consumer) { intConstVariables.put(name, consumer); } @Override public void acceptConstFloatDirective(String name, FloatConsumer consumer) { floatConstVariables.put(name, consumer); } @Override public void acceptConstVec2Directive(String name, Consumer<Vector2f> consumer) { vec2ConstVariables.put(name, consumer); } @Override public void acceptConstIVec3Directive(String name, Consumer<Vector3i> consumer) { ivec3ConstVariables.put(name, consumer); } @Override public void acceptConstVec4Directive(String name, Consumer<Vector4f> consumer) { vec4ConstVariables.put(name, consumer); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\IdMap.java
package net.coderbot.iris.shaderpack; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; import it.unimi.dsi.fastutil.ints.Int2ObjectMaps; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntMaps; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; 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.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; /** * A utility class for parsing entries in item.properties, block.properties, and entities.properties files in shaderpacks */ public class IdMap { /** * Maps a given item ID to an integer ID */ private final Object2IntMap<NamespacedId> itemIdMap; /** * Maps a given entity ID to an integer ID */ private final Object2IntMap<NamespacedId> entityIdMap; /** * Maps block states to block ids defined in block.properties */ private Int2ObjectMap<List<BlockEntry>> blockPropertiesMap; /** * A set of render type overrides for specific blocks. Allows shader packs to move blocks to different render types. */ private Map<NamespacedId, BlockRenderType> blockRenderTypeMap; IdMap(Path shaderPath, ShaderPackOptions shaderPackOptions, Iterable<StringPair> environmentDefines) { itemIdMap = loadProperties(shaderPath, "item.properties", shaderPackOptions, environmentDefines).map(IdMap::parseItemIdMap).orElse(Object2IntMaps.emptyMap()); entityIdMap = loadProperties(shaderPath, "entity.properties", shaderPackOptions, environmentDefines).map(IdMap::parseEntityIdMap).orElse(Object2IntMaps.emptyMap()); loadProperties(shaderPath, "block.properties", shaderPackOptions, environmentDefines).ifPresent(blockProperties -> { blockPropertiesMap = parseBlockMap(blockProperties, "block.", "block.properties"); blockRenderTypeMap = parseRenderTypeMap(blockProperties, "layer.", "block.properties"); }); // TODO: Properly override block render layers if (blockPropertiesMap == null) { // Fill in with default values... blockPropertiesMap = new Int2ObjectOpenHashMap<>(); LegacyIdMap.addLegacyValues(blockPropertiesMap); } if (blockRenderTypeMap == null) { blockRenderTypeMap = Collections.emptyMap(); } } /** * Loads properties from a properties file in a shaderpack path */ private static Optional<Properties> loadProperties(Path shaderPath, String name, ShaderPackOptions shaderPackOptions, Iterable<StringPair> environmentDefines) { String fileContents = readProperties(shaderPath, name); if (fileContents == null) { return Optional.empty(); } String processed = PropertiesPreprocessor.preprocessSource(fileContents, shaderPackOptions, environmentDefines); StringReader propertiesReader = new StringReader(processed); // Note: ordering of properties is significant // See https://github.com/IrisShaders/Iris/issues/1327 and the relevant putIfAbsent calls in // BlockMaterialMapping Properties properties = new OrderBackedProperties(); try { properties.load(propertiesReader); } catch (IOException e) { Iris.logger.error("Error loading " + name + " at " + shaderPath, e); return Optional.empty(); } 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); } 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 static Object2IntMap<NamespacedId> parseItemIdMap(Properties properties) { return parseIdMap(properties, "item.", "item.properties"); } private static Object2IntMap<NamespacedId> parseEntityIdMap(Properties properties) { return parseIdMap(properties, "entity.", "entity.properties"); } /** * Parses a NamespacedId map in OptiFine format */ private static Object2IntMap<NamespacedId> parseIdMap(Properties properties, String keyPrefix, String fileName) { Object2IntMap<NamespacedId> idMap = new Object2IntOpenHashMap<>(); idMap.defaultReturnValue(-1); properties.forEach((keyObject, valueObject) -> { String key = (String) keyObject; String value = (String) valueObject; if (!key.startsWith(keyPrefix)) { // Not a valid line, ignore it return; } int intId; try { intId = Integer.parseInt(key.substring(keyPrefix.length())); } catch (NumberFormatException e) { // Not a valid property line Iris.logger.warn("Failed to parse line in " + fileName + ": invalid key " + key); return; } // Split on any whitespace for (String part : value.split("\\s+")) { if (part.contains("=")) { // Avoid tons of logspam for now Iris.logger.warn("Failed to parse an ResourceLocation in " + fileName + " for the key " + key + ": state properties are currently not supported: " + part); continue; } // Note: NamespacedId performs no validation on the content. That will need to be done by whatever is // converting these things to ResourceLocations. idMap.put(new NamespacedId(part), intId); } }); return Object2IntMaps.unmodifiable(idMap); } private static Int2ObjectMap<List<BlockEntry>> parseBlockMap(Properties properties, String keyPrefix, String fileName) { Int2ObjectMap<List<BlockEntry>> entriesById = new Int2ObjectOpenHashMap<>(); properties.forEach((keyObject, valueObject) -> { final String key = (String) keyObject; StringBuilder value = new StringBuilder((String) valueObject); if (!key.startsWith(keyPrefix)) { // Not a valid line, ignore it return; } final int intId; try { intId = Integer.parseInt(key.substring(keyPrefix.length())); } catch (NumberFormatException e) { // Not a valid property line Iris.logger.warn("Failed to parse line in " + fileName + ": invalid key " + key); return; } final List<BlockEntry> entries = new ArrayList<>(); if (value.toString().contains("minecraft:leaves")) { ArrayList<ItemStack> leaves = OreDictionary.getOres("treeLeaves"); for (ItemStack leaf : leaves) { if (leaf.getItem() instanceof ItemBlock) { Iris.logger.warn("Found leaf " + Item.itemRegistry.getNameForObject(leaf.getItem())); value.append(" ").append(Item.itemRegistry.getNameForObject(leaf.getItem())); } } } // Split on whitespace groups, not just single spaces for (String part : value.toString().split("\\s+")) { if (part.isEmpty()) { continue; } try { entries.add(BlockEntry.parse(part)); } catch (Exception e) { Iris.logger.warn("Unexpected error while parsing an entry from " + fileName + " for the key " + key + ":", e); } } entriesById.put(intId, Collections.unmodifiableList(entries)); }); return Int2ObjectMaps.unmodifiable(entriesById); } /** * 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<NamespacedId, BlockRenderType> parseRenderTypeMap(Properties properties, String keyPrefix, String fileName) { Map<NamespacedId, BlockRenderType> overrides = new HashMap<>(); properties.forEach((keyObject, valueObject) -> { String key = (String) keyObject; String value = (String) valueObject; if (!key.startsWith(keyPrefix)) { // Not a valid line, ignore it return; } // Note: We have to remove the prefix "layer." because fromString expects "cutout", not "layer.cutout". String keyWithoutPrefix = key.substring(keyPrefix.length()); BlockRenderType renderType = BlockRenderType.fromString(keyWithoutPrefix).orElse(null); if (renderType == null) { Iris.logger.warn("Failed to parse line in " + fileName + ": invalid block render type: " + key); return; } for (String part : value.split("\\s+")) { // Note: NamespacedId performs no validation on the content. That will need to be done by whatever is // converting these things to ResourceLocations. overrides.put(new NamespacedId(part), renderType); } }); return overrides; } public Int2ObjectMap<List<BlockEntry>> getBlockProperties() { return blockPropertiesMap; } public Object2IntFunction<NamespacedId> getItemIdMap() { return itemIdMap; } public Object2IntFunction<NamespacedId> getEntityIdMap() { return entityIdMap; } public Map<NamespacedId, BlockRenderType> getBlockRenderTypeMap() { return blockRenderTypeMap; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } 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); } @Override public int hashCode() { return Objects.hash(itemIdMap, entityIdMap, blockPropertiesMap, blockRenderTypeMap); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\IrisLimits.java
package net.coderbot.iris.shaderpack; 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. */ public static final int MAX_COLOR_BUFFERS = 16; }
Angelica
src\main\java\net\coderbot\iris\shaderpack\LanguageMap.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableMap; import net.coderbot.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.Map; import java.util.Properties; import java.util.Set; import java.util.stream.Stream; public class LanguageMap { private final Map<String, Map<String, String>> translationMaps; public LanguageMap(Path root) throws IOException { this.translationMaps = new HashMap<>(); if (!Files.exists(root)) { return; } // We are using a max depth of one to ensure we only get the surface level *files* without going deeper // we also want to avoid any directories while filtering // Basically, we want the immediate files nested in the path for the langFolder // There is also Files.list which can be used for similar behavior try (Stream<Path> stream = Files.list(root)) { stream.filter(path -> !Files.isDirectory(path)).forEach(path -> { // Also note that OptiFine uses a property scheme for loading language entries to keep parity with other // OptiFine features final String currentFileName = path.getFileName().toString(); if (!currentFileName.endsWith(".lang")) { // This file lacks a .lang file extension and should be ignored. return; } final String currentLangCode = currentFileName.substring(0, currentFileName.lastIndexOf(".")); final Properties properties = new Properties(); // Use InputStreamReader to avoid the default charset of ISO-8859-1. // This is needed since shader language files are specified to be in UTF-8. try (InputStreamReader isr = new InputStreamReader(Files.newInputStream(path), StandardCharsets.UTF_8)) { properties.load(isr); } catch (IOException e) { Iris.logger.error("Failed to parse shader pack language file " + path, e); } final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); properties.forEach((key, value) -> builder.put(key.toString(), value.toString())); translationMaps.put(currentLangCode, builder.build()); }); } } public Set<String> getLanguages() { // Ensure that the caller can't mess with the language map. return Collections.unmodifiableSet(translationMaps.keySet()); } public Map<String, String> getTranslations(String language) { // We're returning an immutable map, so the caller can't modify it. return translationMaps.get(language); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\LegacyIdMap.java
package net.coderbot.iris.shaderpack; 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; import java.util.Collections; import java.util.List; public class LegacyIdMap { private static final ImmutableList<String> COLORS = ImmutableList.of("white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black"); private static final ImmutableList<String> WOOD_TYPES = ImmutableList.of("oak", "birch", "jungle", "spruce", "acacia", "dark_oak"); public static void addLegacyValues(Int2ObjectMap<List<BlockEntry>> blockIdMap) { add(blockIdMap, 1, block("stone"), block("granite"), block("diorite"), block("andesite")); add(blockIdMap, 2, block("grass_block")); add(blockIdMap, 4, block("cobblestone")); add(blockIdMap, 50, block("torch")); add(blockIdMap, 89, block("glowstone")); // TODO: what about inactive redstone lamps? add(blockIdMap, 124, block("redstone_lamp")); add(blockIdMap, 12, block("sand")); add(blockIdMap, 24, block("sandstone")); add(blockIdMap, 41, block("gold_block")); add(blockIdMap, 42, block("iron_block")); add(blockIdMap, 57, block("diamond_block")); // Apparently this is what SEUS v11 expects? Maybe old shadersmod was buggy. add(blockIdMap, -123, block("emerald_block")); addMany(blockIdMap, 35, COLORS, color -> block(color + "_wool")); // NB: Use the "still" IDs for water and lava, since some shader packs don't properly support the "flowing" // versions: https://github.com/IrisShaders/Iris/issues/1462 add(blockIdMap, 9, block("water")); add(blockIdMap, 11, block("lava")); add(blockIdMap, 79, block("ice")); addMany(blockIdMap, 18, WOOD_TYPES, woodType -> block(woodType + "_leaves")); addMany(blockIdMap, 95, COLORS, color -> block(color + "_stained_glass")); addMany(blockIdMap, 160, COLORS, color -> block(color + "_stained_glass_pane")); // Short grass / bush add(blockIdMap, 31, block("grass"), block("seagrass"), block("sweet_berry_bush")); // Crops (59 = wheat), but we include carrots and potatoes too. add(blockIdMap, 59, block("wheat"), block("carrots"), block("potatoes")); // 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")); // 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")); // Fire add(blockIdMap, 51, block("fire")); // Lily pad add(blockIdMap, 111, block("lily_pad")); // TODO: 76 -> redstone_torch (on) } private static BlockEntry block(String name) { return new BlockEntry(new NamespacedId("minecraft", name), Collections.emptySet()); } private static void addMany(Int2ObjectMap<List<BlockEntry>> blockIdMap, int id, List<String> prefixes, Function<String, BlockEntry> toId) { List<BlockEntry> entries = new ArrayList<>(); for (String prefix : prefixes) { entries.add(toId.apply(prefix)); } blockIdMap.put(id, entries); } private static void add(Int2ObjectMap<List<BlockEntry>> blockIdMap, int id, BlockEntry... entries) { blockIdMap.put(id, Arrays.asList(entries)); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\OptionalBoolean.java
package net.coderbot.iris.shaderpack; import java.util.function.BooleanSupplier; public enum OptionalBoolean { DEFAULT, FALSE, TRUE; public boolean orElse(boolean defaultValue) { if (this == DEFAULT) { return defaultValue; } return this == TRUE; } public boolean orElseGet(BooleanSupplier defaultValue) { if (this == DEFAULT) { return defaultValue.getAsBoolean(); } return this == TRUE; } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\OrderBackedProperties.java
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 static final long serialVersionUID = 1555967254721760731L; private transient final Map<Object, Object> 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<? super Object, ? super Object> action) { this.backing.forEach(action); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\PackDirectives.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableMap; 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 lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.texture.TextureScaleOverride; import org.joml.Vector2i; import java.util.Set; public class PackDirectives { @Getter private int noiseTextureResolution; @Getter private float sunPathRotation; @Getter private float ambientOcclusionLevel; @Getter private float wetnessHalfLife; @Getter private float drynessHalfLife; @Getter private float eyeBrightnessHalfLife; @Getter private float centerDepthHalfLife; @Getter private CloudSetting cloudSetting; private boolean underwaterOverlay; private boolean vignette; private boolean sun; private boolean moon; private boolean rainDepth; private boolean separateAo; @Getter private boolean oldLighting; private boolean concurrentCompute; @Getter private boolean oldHandLight; private boolean particlesBeforeDeferred; @Getter private boolean prepareBeforeShadow; private Object2ObjectMap<String, Object2BooleanMap<String>> explicitFlips = new Object2ObjectOpenHashMap<>(); private Object2ObjectMap<String, TextureScaleOverride> scaleOverrides = new Object2ObjectOpenHashMap<>(); @Getter private final PackRenderTargetDirectives renderTargetDirectives; @Getter private final PackShadowDirectives shadowDirectives; private PackDirectives(Set<Integer> supportedRenderTargets, PackShadowDirectives packShadowDirectives) { noiseTextureResolution = 256; sunPathRotation = 0.0F; ambientOcclusionLevel = 1.0F; wetnessHalfLife = 600.0f; drynessHalfLife = 200.0f; eyeBrightnessHalfLife = 10.0f; centerDepthHalfLife = 1.0F; renderTargetDirectives = new PackRenderTargetDirectives(supportedRenderTargets); shadowDirectives = packShadowDirectives; } PackDirectives(Set<Integer> supportedRenderTargets, ShaderProperties properties) { this(supportedRenderTargets, new PackShadowDirectives(properties)); cloudSetting = properties.getCloudSetting(); underwaterOverlay = properties.getUnderwaterOverlay().orElse(false); vignette = properties.getVignette().orElse(false); sun = properties.getSun().orElse(true); moon = properties.getMoon().orElse(true); rainDepth = properties.getRainDepth().orElse(false); separateAo = false; //properties.getSeparateAo().orElse(false); oldLighting = properties.getOldLighting().orElse(false); concurrentCompute = properties.getConcurrentCompute().orElse(false); oldHandLight = properties.getOldHandLight().orElse(true); explicitFlips = properties.getExplicitFlips(); scaleOverrides = properties.getTextureScaleOverrides(); particlesBeforeDeferred = properties.getParticlesBeforeDeferred().orElse(false); prepareBeforeShadow = properties.getPrepareBeforeShadow().orElse(false); } PackDirectives(Set<Integer> supportedRenderTargets, PackDirectives directives) { this(supportedRenderTargets, new PackShadowDirectives(directives.getShadowDirectives())); cloudSetting = directives.cloudSetting; separateAo = directives.separateAo; oldLighting = directives.oldLighting; concurrentCompute = directives.concurrentCompute; explicitFlips = directives.explicitFlips; scaleOverrides = directives.scaleOverrides; particlesBeforeDeferred = directives.particlesBeforeDeferred; prepareBeforeShadow = directives.prepareBeforeShadow; } public boolean underwaterOverlay() { return underwaterOverlay; } public boolean vignette() { return vignette; } public boolean shouldRenderSun() { return sun; } public boolean shouldRenderMoon() { return moon; } public boolean rainDepth() { return rainDepth; } public boolean shouldUseSeparateAo() { return separateAo; } public boolean areParticlesBeforeDeferred() { return particlesBeforeDeferred; } public boolean getConcurrentCompute() { return concurrentCompute; } 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); directives.acceptConstFloatDirective("sunPathRotation", sunPathRotation -> this.sunPathRotation = sunPathRotation); directives.acceptConstFloatDirective("ambientOcclusionLevel", ambientOcclusionLevel -> this.ambientOcclusionLevel = clamp(ambientOcclusionLevel, 0.0f, 1.0f)); directives.acceptConstFloatDirective("wetnessHalflife", wetnessHalfLife -> this.wetnessHalfLife = wetnessHalfLife); directives.acceptConstFloatDirective("drynessHalflife", wetnessHalfLife -> this.wetnessHalfLife = wetnessHalfLife); directives.acceptConstFloatDirective("eyeBrightnessHalflife", eyeBrightnessHalfLife -> this.eyeBrightnessHalfLife = eyeBrightnessHalfLife); directives.acceptConstFloatDirective("centerDepthHalflife", centerDepthHalfLife -> this.centerDepthHalfLife = centerDepthHalfLife); } public ImmutableMap<Integer, Boolean> getExplicitFlips(String pass) { ImmutableMap.Builder<Integer, Boolean> explicitFlips = ImmutableMap.builder(); Object2BooleanMap<String> explicitFlipsStr = this.explicitFlips.get(pass); if (explicitFlipsStr == null) { explicitFlipsStr = Object2BooleanMaps.emptyMap(); } explicitFlipsStr.forEach((buffer, shouldFlip) -> { int index = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.indexOf(buffer); if (index == -1 && buffer.startsWith("colortex")) { final String id = buffer.substring("colortex".length()); try { index = Integer.parseInt(id); } catch (NumberFormatException e) { // fall through to index == null check for unknown buffer. } } if (index != -1) { explicitFlips.put(index, shouldFlip); } else { Iris.logger.warn("Unknown buffer with ID " + buffer + " specified in flip directive for pass " + pass); } }); return explicitFlips.build(); } public Vector2i getTextureScaleOverride(int index, int dimensionX, int dimensionY) { final String name = "colortex" + index; // TODO: How do custom textures interact with aliases? final Vector2i scale = new Vector2i(); if (index < PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.size()) { final String legacyName = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.get(index); if (scaleOverrides.containsKey(legacyName)) { scale.set(scaleOverrides.get(legacyName).getX(dimensionX), scaleOverrides.get(legacyName).getY(dimensionY)); } else if (scaleOverrides.containsKey(name)) { scale.set(scaleOverrides.get(name).getX(dimensionX), scaleOverrides.get(name).getY(dimensionY)); } else { scale.set(dimensionX, dimensionY); } } else if (scaleOverrides.containsKey(name)) { scale.set(scaleOverrides.get(name).getX(dimensionX), scaleOverrides.get(name).getY(dimensionY)); } else { scale.set(dimensionX, dimensionY); } return scale; } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\PackRenderTargetDirectives.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.ints.Int2ObjectMap; 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 org.joml.Vector4f; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Set; public class PackRenderTargetDirectives { public static final ImmutableList<String> LEGACY_RENDER_TARGETS = ImmutableList.of( "gcolor", "gdepth", "gnormal", "composite", "gaux1", "gaux2", "gaux3", "gaux4" ); // TODO: Instead of just passing this, the shader pack loader should try to figure out what color buffers are in // use. public static final Set<Integer> BASELINE_SUPPORTED_RENDER_TARGETS; static { ImmutableSet.Builder<Integer> builder = ImmutableSet.builder(); for (int i = 0; i < IrisLimits.MAX_COLOR_BUFFERS; i++) { builder.add(i); } BASELINE_SUPPORTED_RENDER_TARGETS = builder.build(); } private final Int2ObjectMap<RenderTargetSettings> renderTargetSettings; PackRenderTargetDirectives(Set<Integer> supportedRenderTargets) { this.renderTargetSettings = new Int2ObjectOpenHashMap<>(); supportedRenderTargets.forEach( (index) -> renderTargetSettings.put(index.intValue(), new RenderTargetSettings())); } public IntList getBuffersToBeCleared() { IntList buffersToBeCleared = new IntArrayList(); renderTargetSettings.forEach((index, settings) -> { if (settings.shouldClear()) { buffersToBeCleared.add(index.intValue()); } }); return buffersToBeCleared; } public Map<Integer, RenderTargetSettings> getRenderTargetSettings() { return Collections.unmodifiableMap(renderTargetSettings); } public void acceptDirectives(DirectiveHolder directives) { Optional.ofNullable(renderTargetSettings.get(7)).ifPresent(colortex7 -> { // Handle legacy GAUX4FORMAT directives directives.acceptCommentStringDirective("GAUX4FORMAT", format -> { if ("RGBA32F".equals(format)) { colortex7.requestedFormat = InternalTextureFormat.RGBA32F; } else if ("RGB32F".equals(format)) { colortex7.requestedFormat = InternalTextureFormat.RGB32F; } else if ("RGB16".equals(format)) { colortex7.requestedFormat = InternalTextureFormat.RGB16; } else { Iris.logger.warn("Ignoring GAUX4FORMAT directive /* GAUX4FORMAT:" + format + "*/ because " + format + " must be RGBA32F, RGB32F, or RGB16. Use `const int colortex7Format = " + format + ";` + instead."); } }); }); // If a shaderpack declares a gdepth uniform (even if it is not actually sampled or even of the correct type), // we upgrade the format of gdepth / colortex1 to RGBA32F if it is currently RGBA. Optional.ofNullable(renderTargetSettings.get(1)).ifPresent(gdepth -> { directives.acceptUniformDirective("gdepth", () -> { if (gdepth.requestedFormat == InternalTextureFormat.RGBA) { gdepth.requestedFormat = InternalTextureFormat.RGBA32F; } }); }); renderTargetSettings.forEach((index, settings) -> { acceptBufferDirectives(directives, settings, "colortex" + index); if (index < LEGACY_RENDER_TARGETS.size()) { acceptBufferDirectives(directives, settings, LEGACY_RENDER_TARGETS.get(index)); } }); } private void acceptBufferDirectives(DirectiveHolder directives, RenderTargetSettings settings, String bufferName) { directives.acceptConstStringDirective(bufferName + "Format", format -> { Optional<InternalTextureFormat> internalFormat = InternalTextureFormat.fromString(format); if (internalFormat.isPresent()) { settings.requestedFormat = internalFormat.get(); } else { Iris.logger.warn("Unrecognized internal texture format " + format + " specified for " + bufferName + "Format, ignoring."); } }); // TODO: Only for composite and deferred directives.acceptConstBooleanDirective(bufferName + "Clear", 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); } public static final class RenderTargetSettings { private InternalTextureFormat requestedFormat; private boolean clear; private Vector4f clearColor; public RenderTargetSettings() { this.requestedFormat = InternalTextureFormat.RGBA; this.clear = true; this.clearColor = null; } public InternalTextureFormat getInternalFormat() { return requestedFormat; } public boolean shouldClear() { return clear; } public Optional<Vector4f> getClearColor() { return Optional.ofNullable(clearColor); } @Override public String toString() { return "RenderTargetSettings{" + "requestedFormat=" + requestedFormat + ", clear=" + clear + ", clearColor=" + clearColor + '}'; } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\PackShadowDirectives.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableList; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.texture.InternalTextureFormat; import org.joml.Vector4f; import java.util.Optional; public class PackShadowDirectives { // Bump this up if you want more shadow color buffers! // This is currently set at 2 for ShadersMod / OptiFine parity but can theoretically be bumped up to 8. // TODO: Make this configurable? public static final int MAX_SHADOW_COLOR_BUFFERS = 2; private final OptionalBoolean shadowEnabled; 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 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 OptionalBoolean cullingState; private final ImmutableList<DepthSamplingSettings> depthSamplingSettings; private final ImmutableList<SamplingSettings> colorSamplingSettings; public PackShadowDirectives(ShaderProperties properties) { // By default, the shadow map has a resolution of 1024x1024. It's recommended to increase this for better // quality. this.resolution = 1024; // By default, shadows do not use FOV, and instead use an orthographic projection controlled by shadowDistance // // If FOV is defined, shadows will use a perspective projection controlled by the FOV, and shadowDistance will // be disregarded for the purposes of creating the projection matrix. However, it will still be used to figure // out the render distance for shadows if shadowRenderDistanceMul is greater than zero. this.fov = null; // By default, an orthographic projection with a half plane of 160 meters is used, corresponding to a render // distance of 10 chunks. // // It's recommended for shader pack authors to lower this setting to meet their needs in addition to setting // shadowRenderDistanceMul to a nonzero value, since having a high shadow render distance will impact // performance quite heavily on most systems. this.distance = 160.0f; // By default, shadows are not culled based on distance from the player. However, pack authors may // enable this by setting shadowRenderDistanceMul to a nonzero value. // // Culling shadows based on the shadow matrices is often infeasible because shader packs frequently // employ non-linear transformations that end up fitting more far away chunks into the shadow map, // as well as giving higher detail to close up chunks. // // However, Iris does still does cull shadows whenever it can - but, it does so by analyzing // whether or not shadows can possibly be cast into the player's view, instead of just checking // the shadow matrices. this.distanceRenderMul = -1.0f; this.entityShadowDistanceMul = 1.0f; this.explicitRenderDistance = false; // By default, a shadow interval size of 2 meters is used. This means that the shadow camera will be snapped to // a grid where each grid cell is 2 meters by 2 meters by 2 meters, and it will only move either when the sun / // moon move, or when the player camera moves into a different grid cell. this.intervalSize = 2.0f; this.shouldRenderTerrain = properties.getShadowTerrain().orElse(true); this.shouldRenderTranslucent = properties.getShadowTranslucent().orElse(true); this.shouldRenderEntities = properties.getShadowEntities().orElse(true); this.shouldRenderPlayer = properties.getShadowPlayer().orElse(false); this.shouldRenderBlockEntities = properties.getShadowBlockEntities().orElse(true); this.cullingState = properties.getShadowCulling(); this.shadowEnabled = properties.getShadowEnabled(); this.depthSamplingSettings = ImmutableList.of(new DepthSamplingSettings(), new DepthSamplingSettings()); ImmutableList.Builder<SamplingSettings> colorSamplingSettings = ImmutableList.builder(); for (int i = 0; i < MAX_SHADOW_COLOR_BUFFERS; i++) { colorSamplingSettings.add(new SamplingSettings()); } this.colorSamplingSettings = colorSamplingSettings.build(); } public PackShadowDirectives(PackShadowDirectives shadowDirectives) { this.resolution = shadowDirectives.resolution; this.fov = shadowDirectives.fov; this.distance = shadowDirectives.distance; this.distanceRenderMul = shadowDirectives.distanceRenderMul; this.entityShadowDistanceMul = shadowDirectives.entityShadowDistanceMul; this.explicitRenderDistance = shadowDirectives.explicitRenderDistance; this.intervalSize = shadowDirectives.intervalSize; this.shouldRenderTerrain = shadowDirectives.shouldRenderTerrain; this.shouldRenderTranslucent = shadowDirectives.shouldRenderTranslucent; this.shouldRenderEntities = shadowDirectives.shouldRenderEntities; this.shouldRenderPlayer = shadowDirectives.shouldRenderPlayer; this.shouldRenderBlockEntities = shadowDirectives.shouldRenderBlockEntities; this.cullingState = shadowDirectives.cullingState; this.depthSamplingSettings = shadowDirectives.depthSamplingSettings; this.colorSamplingSettings = shadowDirectives.colorSamplingSettings; this.shadowEnabled = shadowDirectives.shadowEnabled; } public int getResolution() { return resolution; } public Float getFov() { return fov; } public float getDistance() { return distance; } public float getDistanceRenderMul() { return distanceRenderMul; } public float getEntityShadowDistanceMul() { return entityShadowDistanceMul; } public boolean isDistanceRenderMulExplicit() { return explicitRenderDistance; } public float getIntervalSize() { return intervalSize; } public boolean shouldRenderTerrain() { return shouldRenderTerrain; } public boolean shouldRenderTranslucent() { return shouldRenderTranslucent; } public boolean shouldRenderEntities() { return shouldRenderEntities; } public boolean shouldRenderPlayer() { return shouldRenderPlayer; } public boolean shouldRenderBlockEntities() { return shouldRenderBlockEntities; } public OptionalBoolean getCullingState() { return cullingState; } public OptionalBoolean isShadowEnabled() { return shadowEnabled; } public ImmutableList<DepthSamplingSettings> getDepthSamplingSettings() { return depthSamplingSettings; } public ImmutableList<SamplingSettings> getColorSamplingSettings() { return colorSamplingSettings; } public void acceptDirectives(DirectiveHolder directives) { directives.acceptCommentIntDirective("SHADOWRES", resolution -> this.resolution = resolution); directives.acceptConstIntDirective("shadowMapResolution", resolution -> this.resolution = resolution); directives.acceptCommentFloatDirective("SHADOWFOV", fov -> this.fov = fov); directives.acceptConstFloatDirective("shadowMapFov", fov -> this.fov = fov); directives.acceptCommentFloatDirective("SHADOWHPL", distance -> this.distance = distance); directives.acceptConstFloatDirective("shadowDistance", distance -> this.distance = distance); directives.acceptConstFloatDirective("entityShadowDistanceMul", distance -> this.entityShadowDistanceMul = distance); directives.acceptConstFloatDirective("shadowDistanceRenderMul", distanceRenderMul -> { this.distanceRenderMul = distanceRenderMul; this.explicitRenderDistance = true; }); directives.acceptConstFloatDirective("shadowIntervalSize", intervalSize -> this.intervalSize = intervalSize); acceptHardwareFilteringSettings(directives, depthSamplingSettings); acceptDepthMipmapSettings(directives, depthSamplingSettings); acceptColorMipmapSettings(directives, colorSamplingSettings); acceptDepthFilteringSettings(directives, depthSamplingSettings); acceptColorFilteringSettings(directives, colorSamplingSettings); acceptBufferDirectives(directives, colorSamplingSettings); } /** * Handles shadowHardwareFiltering* directives */ private static void acceptHardwareFilteringSettings(DirectiveHolder directives, ImmutableList<DepthSamplingSettings> 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<DepthSamplingSettings> 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, ImmutableList<SamplingSettings> samplers) { // Get the default base value for the shadow depth mipmap setting directives.acceptConstBooleanDirective("generateShadowColorMipmap", mipmap -> { for (SamplingSettings samplerSettings : samplers) { samplerSettings.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.get(i)::setMipmap); name = "shadowColor" + i + "Mipmap"; directives.acceptConstBooleanDirective(name, samplers.get(i)::setMipmap); } } private static void acceptDepthFilteringSettings(DirectiveHolder directives, ImmutableList<DepthSamplingSettings> 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, ImmutableList<SamplingSettings> samplers) { for (int i = 0; i < samplers.size(); i++) { String name = "shadowcolor" + i + "Nearest"; directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); name = "shadowColor" + i + "Nearest"; directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); name = "shadowColor" + i + "MinMagNearest"; directives.acceptConstBooleanDirective(name, samplers.get(i)::setNearest); } } private void acceptBufferDirectives(DirectiveHolder directives, ImmutableList<SamplingSettings> settings) { for (int i = 0; i < settings.size(); i++) { String bufferName = "shadowcolor" + i; int finalI = i; directives.acceptConstStringDirective(bufferName + "Format", format -> { Optional<InternalTextureFormat> internalFormat = InternalTextureFormat.fromString(format); if (internalFormat.isPresent()) { settings.get(finalI).setFormat(internalFormat.get()); } else { Iris.logger.warn("Unrecognized internal texture format " + format + " specified for " + bufferName + "Format, ignoring."); } }); // TODO: Only for composite and deferred directives.acceptConstBooleanDirective(bufferName + "Clear", shouldClear -> settings.get(finalI).setClear(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.get(finalI).setClearColor(clearColor)); } } @Override public String toString() { return "PackShadowDirectives{" + "resolution=" + resolution + ", fov=" + fov + ", distance=" + distance + ", distanceRenderMul=" + distanceRenderMul + ", entityDistanceRenderMul=" + entityShadowDistanceMul + ", intervalSize=" + intervalSize + ", depthSamplingSettings=" + depthSamplingSettings + ", colorSamplingSettings=" + colorSamplingSettings + '}'; } public static class SamplingSettings { /** * Whether mipmaps should be generated before sampling. Disabled by default. */ private boolean mipmap; /** * Whether nearest texture filtering should be used in place of linear filtering. By default, linear filtering * is used, which applies some blur, but if this is not desired behavior, nearest filtering can be used. */ private boolean nearest; /** * Whether to clear the buffer every frame. */ private boolean clear; /** * The color to clear the buffer to. If {@code clear} is false, this has no effect. */ private Vector4f clearColor; /** * The internal format to use for the color buffer. */ private InternalTextureFormat format; public SamplingSettings() { mipmap = false; nearest = false; clear = true; clearColor = new Vector4f(1.0F); format = InternalTextureFormat.RGBA; } protected void setMipmap(boolean mipmap) { this.mipmap = mipmap; } protected void setNearest(boolean nearest) { this.nearest = nearest; } protected void setClear(boolean clear) { this.clear = clear; } protected void setClearColor(Vector4f clearColor) { this.clearColor = clearColor; } protected void setFormat(InternalTextureFormat format) { this.format = format; } public boolean getMipmap() { return this.mipmap; } public boolean getNearest() { return this.nearest; } public boolean getClear() { return clear; } public Vector4f getClearColor() { return clearColor; } public InternalTextureFormat getFormat() { return this.format; } @Override public String toString() { return "SamplingSettings{" + "mipmap=" + mipmap + ", nearest=" + nearest + ", clear=" + clear + ", clearColor=" + clearColor + ", format=" + format.name() + '}'; } } public static class DepthSamplingSettings extends SamplingSettings { private boolean hardwareFiltering; public DepthSamplingSettings() { hardwareFiltering = false; } private void setHardwareFiltering(boolean hardwareFiltering) { this.hardwareFiltering = hardwareFiltering; } public boolean getHardwareFiltering() { return hardwareFiltering; } @Override public String toString() { return "DepthSamplingSettings{" + "mipmap=" + getMipmap() + ", nearest=" + getNearest() + ", hardwareFiltering=" + hardwareFiltering + '}'; } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ProgramDirectives.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import net.coderbot.iris.gl.blending.AlphaTestOverride; import net.coderbot.iris.gl.blending.BlendModeOverride; import net.coderbot.iris.gl.blending.BufferBlendInformation; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; public class ProgramDirectives { private static final ImmutableList<String> LEGACY_RENDER_TARGETS = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS; private final int[] drawBuffers; private final float viewportScale; @Nullable private final AlphaTestOverride alphaTestOverride; private final Optional<BlendModeOverride> blendModeOverride; private final List<BufferBlendInformation> bufferBlendInformations; private final ImmutableSet<Integer> mipmappedBuffers; private final ImmutableMap<Integer, Boolean> explicitFlips; private ProgramDirectives(int[] drawBuffers, float viewportScale, @Nullable AlphaTestOverride alphaTestOverride, Optional<BlendModeOverride> blendModeOverride, List<BufferBlendInformation> bufferBlendInformations, ImmutableSet<Integer> mipmappedBuffers, ImmutableMap<Integer, Boolean> explicitFlips) { this.drawBuffers = drawBuffers; this.viewportScale = viewportScale; this.alphaTestOverride = alphaTestOverride; this.blendModeOverride = blendModeOverride; this.bufferBlendInformations = bufferBlendInformations; this.mipmappedBuffers = mipmappedBuffers; this.explicitFlips = explicitFlips; } ProgramDirectives(ProgramSource source, ShaderProperties properties, Set<Integer> supportedRenderTargets, @Nullable BlendModeOverride defaultBlendOverride) { // DRAWBUFFERS is only detected in the fragment shader source code (.fsh). // If there's no explicit declaration, then by default /* DRAWBUFFERS:0 */ is inferred. // For SEUS v08 and SEUS v10 to work, this will need to be set to 01234567. However, doing this causes // TAA to break on Sildur's Vibrant Shaders, since gbuffers_skybasic lacks a DRAWBUFFERS directive, causing // undefined data to be written to colortex7. // // TODO: Figure out how to infer the DRAWBUFFERS directive when it is missing. Optional<CommentDirective> optionalDrawbuffersDirective = findDrawbuffersDirective(source.getFragmentSource()); Optional<CommentDirective> optionalRendertargetsDirective = findRendertargetsDirective(source.getFragmentSource()); Optional<CommentDirective> optionalCommentDirective = getAppliedDirective(optionalDrawbuffersDirective, optionalRendertargetsDirective); drawBuffers = optionalCommentDirective.map(commentDirective -> { if (commentDirective.getType() == CommentDirective.Type.DRAWBUFFERS) { return parseDigits(commentDirective.getDirective().toCharArray()); } else if (commentDirective.getType() == CommentDirective.Type.RENDERTARGETS) { return parseDigitList(commentDirective.getDirective()); } else { throw new IllegalStateException("Unhandled comment directive type!"); } }).orElse(new int[] { 0 }); if (properties != null) { viewportScale = properties.getViewportScaleOverrides().getOrDefault(source.getName(), 1.0f); alphaTestOverride = properties.getAlphaTestOverrides().get(source.getName()); BlendModeOverride blendModeOverride = properties.getBlendModeOverrides().get(source.getName()); List<BufferBlendInformation> bufferBlendInformations = properties.getBufferBlendOverrides().get(source.getName()); this.blendModeOverride = Optional.ofNullable(blendModeOverride != null ? blendModeOverride : defaultBlendOverride); this.bufferBlendInformations = bufferBlendInformations != null ? bufferBlendInformations : Collections.emptyList(); explicitFlips = source.getParent().getPackDirectives().getExplicitFlips(source.getName()); } else { viewportScale = 1.0f; alphaTestOverride = null; blendModeOverride = Optional.ofNullable(defaultBlendOverride); bufferBlendInformations = Collections.emptyList(); explicitFlips = ImmutableMap.of(); } HashSet<Integer> mipmappedBuffers = new HashSet<>(); DispatchingDirectiveHolder directiveHolder = new DispatchingDirectiveHolder(); supportedRenderTargets.forEach(index -> { BooleanConsumer mipmapHandler = shouldMipmap -> { if (shouldMipmap) { mipmappedBuffers.add(index); } else { mipmappedBuffers.remove(index); } }; directiveHolder.acceptConstBooleanDirective("colortex" + index + "MipmapEnabled", mipmapHandler); if (index < LEGACY_RENDER_TARGETS.size()) { directiveHolder.acceptConstBooleanDirective(LEGACY_RENDER_TARGETS.get(index) + "MipmapEnabled", mipmapHandler); } }); source.getFragmentSource().map(ConstDirectiveParser::findDirectives).ifPresent(directives -> { for (ConstDirectiveParser.ConstDirective directive : directives) { directiveHolder.processDirective(directive); } }); this.mipmappedBuffers = ImmutableSet.copyOf(mipmappedBuffers); } public ProgramDirectives withOverriddenDrawBuffers(int[] drawBuffersOverride) { return new ProgramDirectives(drawBuffersOverride, viewportScale, alphaTestOverride, blendModeOverride, bufferBlendInformations, mipmappedBuffers, explicitFlips); } private static Optional<CommentDirective> findDrawbuffersDirective(Optional<String> stageSource) { return stageSource.flatMap(fragment -> CommentDirectiveParser.findDirective(fragment, CommentDirective.Type.DRAWBUFFERS)); } private static Optional<CommentDirective> findRendertargetsDirective(Optional<String> stageSource) { return stageSource.flatMap(fragment -> CommentDirectiveParser.findDirective(fragment, CommentDirective.Type.RENDERTARGETS)); } private static int[] parseDigits(char[] directiveChars) { int[] buffers = new int[directiveChars.length]; int index = 0; for (char buffer : directiveChars) { buffers[index++] = Character.digit(buffer, 10); } return buffers; } private static int[] parseDigitList(String digitListString) { return Arrays.stream(digitListString.split(",")) .mapToInt(Integer::parseInt) .toArray(); } private static Optional<CommentDirective> getAppliedDirective(Optional<CommentDirective> optionalDrawbuffersDirective, Optional<CommentDirective> optionalRendertargetsDirective) { if (optionalDrawbuffersDirective.isPresent() && optionalRendertargetsDirective.isPresent()) { if (optionalDrawbuffersDirective.get().getLocation() > optionalRendertargetsDirective.get().getLocation()) { return optionalDrawbuffersDirective; } else { return optionalRendertargetsDirective; } } else if (optionalDrawbuffersDirective.isPresent()) { return optionalDrawbuffersDirective; } else if (optionalRendertargetsDirective.isPresent()) { return optionalRendertargetsDirective; } else { return Optional.empty(); } } public int[] getDrawBuffers() { return drawBuffers; } public float getViewportScale() { return viewportScale; } public Optional<AlphaTestOverride> getAlphaTestOverride() { return Optional.ofNullable(alphaTestOverride); } public Optional<BlendModeOverride> getBlendModeOverride() { return blendModeOverride; } public List<BufferBlendInformation> getBufferBlendOverrides() { return bufferBlendInformations; } public ImmutableSet<Integer> getMipmappedBuffers() { return mipmappedBuffers; } public ImmutableMap<Integer, Boolean> getExplicitFlips() { return explicitFlips; } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ProgramFallbackResolver.java
package net.coderbot.iris.shaderpack; import net.coderbot.iris.shaderpack.loading.ProgramId; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class ProgramFallbackResolver { private final ProgramSet programs; private final Map<ProgramId, ProgramSource> cache; public ProgramFallbackResolver(ProgramSet programs) { this.programs = programs; this.cache = new HashMap<>(); } public Optional<ProgramSource> resolve(ProgramId id) { return Optional.ofNullable(resolveNullable(id)); } @Nullable public ProgramSource resolveNullable(ProgramId id) { if (cache.containsKey(id)) { return cache.get(id); } ProgramSource source = programs.get(id).orElse(null); if (source == null) { ProgramId fallback = id.getFallback().orElse(null); if (fallback != null) { source = resolveNullable(fallback); } } cache.put(id, source); return source; } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ProgramSet.java
package net.coderbot.iris.shaderpack; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.blending.BlendModeOverride; import net.coderbot.iris.shaderpack.include.AbsolutePackPath; import net.coderbot.iris.shaderpack.loading.ProgramId; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; public class ProgramSet { private final PackDirectives packDirectives; private final ProgramSource shadow; private final ComputeSource[] shadowCompute; private final ProgramSource[] shadowcomp; private final ComputeSource[][] shadowCompCompute; private final ProgramSource[] prepare; private final ComputeSource[][] prepareCompute; private final ProgramSource gbuffersBasic; private final ProgramSource gbuffersLine; private final ProgramSource gbuffersBeaconBeam; private final ProgramSource gbuffersTextured; private final ProgramSource gbuffersTexturedLit; private final ProgramSource gbuffersTerrain; private ProgramSource gbuffersDamagedBlock; private final ProgramSource gbuffersSkyBasic; private final ProgramSource gbuffersSkyTextured; private final ProgramSource gbuffersClouds; private final ProgramSource gbuffersWeather; private final ProgramSource gbuffersEntities; private final ProgramSource gbuffersEntitiesTrans; private final ProgramSource gbuffersEntitiesGlowing; private final ProgramSource gbuffersGlint; private final ProgramSource gbuffersEntityEyes; private final ProgramSource gbuffersBlock; 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 ShaderPack pack; public ProgramSet(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, ShaderProperties shaderProperties, ShaderPack pack) { this.packDirectives = new PackDirectives(PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, shaderProperties); this.pack = pack; // Note: Ensure that blending is properly overridden during the shadow pass. By default, blending is disabled // in the shadow pass. Shader packs expect this for colored shadows from stained glass and nether portals // to work properly. // // Note: Enabling blending in the shadow pass results in weird results since translucency sorting happens // relative to the player camera, not the shadow camera, so we can't rely on chunks being properly // sorted in the shadow pass. // // - https://github.com/IrisShaders/Iris/issues/483 // - https://github.com/IrisShaders/Iris/issues/987 this.shadow = readProgramSource(directory, sourceProvider, "shadow", this, shaderProperties, BlendModeOverride.OFF); this.shadowCompute = readComputeArray(directory, sourceProvider, "shadow"); this.shadowcomp = readProgramArray(directory, sourceProvider, "shadowcomp", shaderProperties); 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.prepare = readProgramArray(directory, sourceProvider, "prepare", shaderProperties); 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.gbuffersBasic = readProgramSource(directory, sourceProvider, "gbuffers_basic", this, shaderProperties); this.gbuffersLine = readProgramSource(directory, sourceProvider, "gbuffers_line", this, shaderProperties); this.gbuffersBeaconBeam = readProgramSource(directory, sourceProvider, "gbuffers_beaconbeam", this, shaderProperties); this.gbuffersTextured = readProgramSource(directory, sourceProvider, "gbuffers_textured", this, shaderProperties); this.gbuffersTexturedLit = readProgramSource(directory, sourceProvider, "gbuffers_textured_lit", this, shaderProperties); this.gbuffersTerrain = readProgramSource(directory, sourceProvider, "gbuffers_terrain", this, shaderProperties); this.gbuffersDamagedBlock = readProgramSource(directory, sourceProvider, "gbuffers_damagedblock", this, shaderProperties); this.gbuffersSkyBasic = readProgramSource(directory, sourceProvider, "gbuffers_skybasic", this, shaderProperties); this.gbuffersSkyTextured = readProgramSource(directory, sourceProvider, "gbuffers_skytextured", this, shaderProperties); this.gbuffersClouds = readProgramSource(directory, sourceProvider, "gbuffers_clouds", this, shaderProperties); this.gbuffersWeather = readProgramSource(directory, sourceProvider, "gbuffers_weather", this, shaderProperties); this.gbuffersEntities = readProgramSource(directory, sourceProvider, "gbuffers_entities", this, shaderProperties); this.gbuffersEntitiesTrans = readProgramSource(directory, sourceProvider, "gbuffers_entities_translucent", this, shaderProperties); this.gbuffersEntitiesGlowing = readProgramSource(directory, sourceProvider, "gbuffers_entities_glowing", this, shaderProperties); this.gbuffersGlint = readProgramSource(directory, sourceProvider, "gbuffers_armor_glint", this, shaderProperties); this.gbuffersEntityEyes = readProgramSource(directory, sourceProvider, "gbuffers_spidereyes", this, shaderProperties); this.gbuffersBlock = readProgramSource(directory, sourceProvider, "gbuffers_block", this, shaderProperties); this.gbuffersHand = readProgramSource(directory, sourceProvider, "gbuffers_hand", this, shaderProperties); this.deferred = readProgramArray(directory, sourceProvider, "deferred", shaderProperties); 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.gbuffersWater = readProgramSource(directory, sourceProvider, "gbuffers_water", this, shaderProperties); this.gbuffersHandWater = readProgramSource(directory, sourceProvider, "gbuffers_hand_water", this, shaderProperties); this.composite = readProgramArray(directory, sourceProvider, "composite", shaderProperties); 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.compositeFinal = readProgramSource(directory, sourceProvider, "final", this, shaderProperties); this.finalCompute = readComputeArray(directory, sourceProvider, "final"); 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 private static <T> Optional<T> first(Optional<T>... candidates) { for (Optional<T> candidate : candidates) { if (candidate.isPresent()) { return candidate; } } return Optional.empty(); } private ProgramSource[] readProgramArray(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, String name, ShaderProperties shaderProperties) { ProgramSource[] programs = new ProgramSource[99]; for (int i = 0; i < programs.length; i++) { String suffix = i == 0 ? "" : Integer.toString(i); programs[i] = readProgramSource(directory, sourceProvider, name + suffix, this, shaderProperties); } return programs; } private ComputeSource[] readComputeArray(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, String name) { ComputeSource[] programs = new ComputeSource[27]; programs[0] = readComputeSource(directory, sourceProvider, name, this); for (char c = 'a'; c <= 'z'; ++c) { String suffix = "_" + c; programs[c - 96] = readComputeSource(directory, sourceProvider, name + suffix, this); if (programs[c - 96] == null) { break; } } return programs; } private void locateDirectives() { List<ProgramSource> programs = new ArrayList<>(); List<ComputeSource> computes = new ArrayList<>(); programs.add(shadow); programs.addAll(Arrays.asList(shadowcomp)); programs.addAll(Arrays.asList(prepare)); programs.addAll (Arrays.asList( gbuffersBasic, gbuffersBeaconBeam, gbuffersTextured, gbuffersTexturedLit, gbuffersTerrain, gbuffersDamagedBlock, gbuffersSkyBasic, gbuffersSkyTextured, gbuffersClouds, gbuffersWeather, gbuffersEntities, gbuffersEntitiesTrans, gbuffersEntitiesGlowing, gbuffersGlint, gbuffersEntityEyes, gbuffersBlock, gbuffersHand )); for (ComputeSource[] computeSources : compositeCompute) { computes.addAll(Arrays.asList(computeSources)); } for (ComputeSource[] computeSources : deferredCompute) { computes.addAll(Arrays.asList(computeSources)); } for (ComputeSource[] computeSources : prepareCompute) { computes.addAll(Arrays.asList(computeSources)); } for (ComputeSource[] computeSources : shadowCompCompute) { computes.addAll(Arrays.asList(computeSources)); } Collections.addAll(computes, finalCompute); Collections.addAll(computes, shadowCompute); for (ComputeSource source : computes) { if (source != null) { source.getSource().map(ConstDirectiveParser::findDirectives).ifPresent(constDirectives -> { for (ConstDirectiveParser.ConstDirective directive : constDirectives) { if (directive.getType() == ConstDirectiveParser.Type.IVEC3 && directive.getKey().equals("workGroups")) { ComputeDirectiveParser.setComputeWorkGroups(source, directive); } else if (directive.getType() == ConstDirectiveParser.Type.VEC2 && directive.getKey().equals("workGroupsRender")) { ComputeDirectiveParser.setComputeWorkGroupsRelative(source, directive); } } }); } } programs.addAll(Arrays.asList(deferred)); programs.add(gbuffersWater); programs.add(gbuffersHandWater); programs.addAll(Arrays.asList(composite)); programs.add(compositeFinal); DispatchingDirectiveHolder packDirectiveHolder = new DispatchingDirectiveHolder(); packDirectives.acceptDirectivesFrom(packDirectiveHolder); for (ProgramSource source : programs) { if (source == null) { continue; } source.getFragmentSource().map(ConstDirectiveParser::findDirectives).ifPresent(directives -> { for (ConstDirectiveParser.ConstDirective directive : directives) { packDirectiveHolder.processDirective(directive); } }); } packDirectives.getRenderTargetDirectives().getRenderTargetSettings().forEach((index, settings) -> Iris.logger.debug("Render target settings for colortex" + index + ": " + settings)); } public Optional<ProgramSource> getShadow() { return shadow.requireValid(); } public ProgramSource[] getShadowComposite() { return shadowcomp; } public ProgramSource[] getPrepare() { return prepare; } public Optional<ProgramSource> getGbuffersBasic() { return gbuffersBasic.requireValid(); } public Optional<ProgramSource> getGbuffersBeaconBeam() { return gbuffersBeaconBeam.requireValid(); } public Optional<ProgramSource> getGbuffersTextured() { return gbuffersTextured.requireValid(); } public Optional<ProgramSource> getGbuffersTexturedLit() { return gbuffersTexturedLit.requireValid(); } public Optional<ProgramSource> getGbuffersTerrain() { return gbuffersTerrain.requireValid(); } public Optional<ProgramSource> getGbuffersDamagedBlock() { return gbuffersDamagedBlock.requireValid(); } public Optional<ProgramSource> getGbuffersSkyBasic() { return gbuffersSkyBasic.requireValid(); } public Optional<ProgramSource> getGbuffersSkyTextured() { return gbuffersSkyTextured.requireValid(); } public Optional<ProgramSource> getGbuffersClouds() { return gbuffersClouds.requireValid(); } public Optional<ProgramSource> getGbuffersWeather() { return gbuffersWeather.requireValid(); } public Optional<ProgramSource> getGbuffersEntities() { return gbuffersEntities.requireValid(); } public Optional<ProgramSource> getGbuffersEntitiesTrans() { return gbuffersEntitiesTrans.requireValid(); } public Optional<ProgramSource> getGbuffersEntitiesGlowing() { return gbuffersEntitiesGlowing.requireValid(); } public Optional<ProgramSource> getGbuffersGlint() { return gbuffersGlint.requireValid(); } public Optional<ProgramSource> getGbuffersEntityEyes() { return gbuffersEntityEyes.requireValid(); } public Optional<ProgramSource> getGbuffersBlock() { return gbuffersBlock.requireValid(); } public Optional<ProgramSource> getGbuffersHand() { return gbuffersHand.requireValid(); } public Optional<ProgramSource> get(ProgramId programId) { 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 DamagedBlock -> getGbuffersDamagedBlock(); case Block -> getGbuffersBlock(); case BeaconBeam -> getGbuffersBeaconBeam(); case Entities -> getGbuffersEntities(); case EntitiesTrans -> getGbuffersEntitiesTrans(); case EntitiesGlowing -> getGbuffersEntitiesGlowing(); case ArmorGlint -> getGbuffersGlint(); case SpiderEyes -> getGbuffersEntityEyes(); case Hand -> getGbuffersHand(); case Weather -> getGbuffersWeather(); case Water -> getGbuffersWater(); case HandWater -> getGbuffersHandWater(); case Final -> getCompositeFinal(); default -> Optional.empty(); }; } public ProgramSource[] getDeferred() { return deferred; } public Optional<ProgramSource> getGbuffersWater() { return gbuffersWater.requireValid(); } public Optional<ProgramSource> getGbuffersHandWater() { return gbuffersHandWater.requireValid(); } public ProgramSource[] getComposite() { return composite; } public Optional<ProgramSource> getCompositeFinal() { return compositeFinal.requireValid(); } public ComputeSource[] getShadowCompute() { return shadowCompute; } public ComputeSource[][] getShadowCompCompute() { return shadowCompCompute; } public ComputeSource[][] getPrepareCompute() { return prepareCompute; } public ComputeSource[][] getDeferredCompute() { return deferredCompute; } public ComputeSource[][] getCompositeCompute() { return compositeCompute; } public ComputeSource[] getFinalCompute() { return finalCompute; } public PackDirectives getPackDirectives() { return packDirectives; } public ShaderPack getPack() { return pack; } private static ProgramSource readProgramSource(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, String program, ProgramSet programSet, ShaderProperties properties) { return readProgramSource(directory, sourceProvider, program, programSet, properties, null); } private static ProgramSource readProgramSource(AbsolutePackPath directory, Function<AbsolutePackPath, String> sourceProvider, String program, ProgramSet programSet, ShaderProperties properties, BlendModeOverride defaultBlendModeOverride) { AbsolutePackPath vertexPath = directory.resolve(program + ".vsh"); String vertexSource = sourceProvider.apply(vertexPath); AbsolutePackPath geometryPath = directory.resolve(program + ".gsh"); String geometrySource = sourceProvider.apply(geometryPath); AbsolutePackPath fragmentPath = directory.resolve(program + ".fsh"); String fragmentSource = sourceProvider.apply(fragmentPath); return new ProgramSource(program, vertexSource, geometrySource, fragmentSource, programSet, properties, defaultBlendModeOverride); } private static ComputeSource readComputeSource(AbsolutePackPath directory, Function<AbsolutePackPath, String> 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); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ProgramSource.java
package net.coderbot.iris.shaderpack; import net.coderbot.iris.gl.blending.BlendModeOverride; import java.util.Optional; public class ProgramSource { private final String name; private final String vertexSource; private final String geometrySource; private final String fragmentSource; private final ProgramDirectives directives; private final ProgramSet parent; private ProgramSource(String name, String vertexSource, String geometrySource, String fragmentSource, ProgramDirectives directives, ProgramSet parent) { this.name = name; this.vertexSource = vertexSource; this.geometrySource = geometrySource; this.fragmentSource = fragmentSource; this.directives = directives; this.parent = parent; } public ProgramSource(String name, String vertexSource, String geometrySource, String fragmentSource, ProgramSet parent, ShaderProperties properties, BlendModeOverride defaultBlendModeOverride) { this.name = name; this.vertexSource = vertexSource; this.geometrySource = geometrySource; this.fragmentSource = fragmentSource; this.parent = parent; this.directives = new ProgramDirectives(this, properties, PackRenderTargetDirectives.BASELINE_SUPPORTED_RENDER_TARGETS, defaultBlendModeOverride); } public ProgramSource withDirectiveOverride(ProgramDirectives overrideDirectives) { return new ProgramSource(name, vertexSource, geometrySource, fragmentSource, overrideDirectives, parent); } public String getName() { return name; } public Optional<String> getVertexSource() { return Optional.ofNullable(vertexSource); } public Optional<String> getGeometrySource() { return Optional.ofNullable(geometrySource); } public Optional<String> getFragmentSource() { return Optional.ofNullable(fragmentSource); } public ProgramDirectives getDirectives() { return this.directives; } public ProgramSet getParent() { return parent; } public boolean isValid() { return vertexSource != null && fragmentSource != null; } public Optional<ProgramSource> requireValid() { if (this.isValid()) { return Optional.of(this); } else { return Optional.empty(); } } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ShaderPack.java
package net.coderbot.iris.shaderpack; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.stream.JsonReader; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.features.FeatureFlags; 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.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.texture.CustomTextureData; import net.coderbot.iris.shaderpack.texture.TextureFilteringData; import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.irisshaders.iris.api.v0.IrisApi; import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; public class ShaderPack { private static final Gson GSON = new Gson(); public final CustomUniforms.Builder customUniforms; private final ProgramSet base; @Nullable private final ProgramSet overworld; private final ProgramSet nether; private final ProgramSet end; @Getter private final IdMap idMap; @Getter private final LanguageMap languageMap; @Getter private final EnumMap<TextureStage, Object2ObjectMap<String, CustomTextureData>> customTextureDataMap = new EnumMap<>(TextureStage.class); private final CustomTextureData customNoiseTexture; @Getter private final ShaderPackOptions shaderPackOptions; @Getter private final OptionMenuContainer menuContainer; private final ProfileSet.ProfileResult profile; private final String profileInfo; public ShaderPack(Path root, Iterable<StringPair> environmentDefines) throws IOException, IllegalStateException { this(root, Collections.emptyMap(), environmentDefines); } /** * Reads a shader pack from the disk. * * @param root The path to the "shaders" directory within the shader pack. The created ShaderPack will not retain * this path in any form; once the constructor exits, all disk I/O needed to load this shader pack will * have completed, and there is no need to hold on to the path for that reason. * @throws IOException if there are any IO errors during shader pack loading. */ public ShaderPack(Path root, Map<String, String> changedConfigs, Iterable<StringPair> environmentDefines) throws IOException, IllegalStateException { // A null path is not allowed. Objects.requireNonNull(root); ImmutableList.Builder<AbsolutePackPath> starts = ImmutableList.builder(); ImmutableList<String> potentialFileNames = ShaderPackSourceNames.POTENTIAL_STARTS; ShaderPackSourceNames.findPresentSources(starts, root, AbsolutePackPath.fromAbsolutePath("/"), potentialFileNames); boolean hasWorld0 = ShaderPackSourceNames.findPresentSources(starts, root, AbsolutePackPath.fromAbsolutePath("/world0"), potentialFileNames); boolean hasNether = ShaderPackSourceNames.findPresentSources(starts, root, AbsolutePackPath.fromAbsolutePath("/world-1"), potentialFileNames); boolean hasEnd = ShaderPackSourceNames.findPresentSources(starts, root, AbsolutePackPath.fromAbsolutePath("/world1"), potentialFileNames); // Read all files and included files recursively IncludeGraph graph = new IncludeGraph(root, starts.build()); if (!graph.getFailures().isEmpty()) { graph.getFailures().forEach((path, error) -> { Iris.logger.error("{}", error.toString()); }); throw new IOException("Failed to resolve some #include directives, see previous messages for details"); } this.languageMap = new LanguageMap(root.resolve("lang")); // Discover, merge, and apply shader pack options this.shaderPackOptions = new ShaderPackOptions(graph, changedConfigs); graph = this.shaderPackOptions.getIncludes(); Iterable<StringPair> finalEnvironmentDefines = environmentDefines; ShaderProperties shaderProperties = loadProperties(root, "shaders.properties") .map(source -> new ShaderProperties(source, shaderPackOptions, finalEnvironmentDefines)) .orElseGet(ShaderProperties::empty); List<FeatureFlags> invalidFlagList = shaderProperties.getRequiredFeatureFlags().stream().filter(FeatureFlags::isInvalid).map(FeatureFlags::getValue).collect(Collectors.toList()); List<String> invalidFeatureFlags = invalidFlagList.stream().map(FeatureFlags::getHumanReadableName).collect(Collectors.toList()); if (!invalidFeatureFlags.isEmpty()) { // TODO: GUI // if (Minecraft.getMinecraft().screen instanceof ShaderPackScreen) { // Minecraft.getMinecraft().setScreen(new FeatureMissingErrorScreen(Minecraft.getMinecraft().screen, I18n.format("iris.unsupported.pack"), I18n.format("iris.unsupported.pack.description", FeatureFlags.getInvalidStatus(invalidFlagList), invalidFeatureFlags.stream() // .collect(Collectors.joining(", ", ": ", "."))))); // } IrisApi.getInstance().getConfig().setShadersEnabledAndApply(false); } List<String> optionalFeatureFlags = shaderProperties.getOptionalFeatureFlags().stream().filter(flag -> !FeatureFlags.isInvalid(flag)).collect(Collectors.toList()); if (!optionalFeatureFlags.isEmpty()) { List<StringPair> newEnvDefines = new ArrayList<>(); environmentDefines.forEach(newEnvDefines::add); optionalFeatureFlags.forEach(flag -> newEnvDefines.add(new StringPair("IRIS_FEATURE_" + flag, ""))); environmentDefines = ImmutableList.copyOf(newEnvDefines); } ProfileSet profiles = ProfileSet.fromTree(shaderProperties.getProfiles(), this.shaderPackOptions.getOptionSet()); this.profile = profiles.scan(this.shaderPackOptions.getOptionSet(), this.shaderPackOptions.getOptionValues()); // Get programs that should be disabled from the detected profile List<String> disabledPrograms = new ArrayList<>(); this.profile.current.ifPresent(profile -> disabledPrograms.addAll(profile.disabledPrograms)); // Add programs that are disabled by shader options shaderProperties.getConditionallyEnabledPrograms().forEach((program, shaderOption) -> { if ("true".equals(shaderOption)) return; if ("false".equals(shaderOption) || !this.shaderPackOptions.getOptionValues().getBooleanValueOrDefault(shaderOption)) { disabledPrograms.add(program); } }); this.menuContainer = new OptionMenuContainer(shaderProperties, this.shaderPackOptions, profiles); { String profileName = getCurrentProfileName(); OptionValues profileOptions = new MutableOptionValues( this.shaderPackOptions.getOptionSet(), this.profile.current.map(p -> p.optionValues).orElse(new HashMap<>())); int userOptionsChanged = this.shaderPackOptions.getOptionValues().getOptionsChanged() - profileOptions.getOptionsChanged(); this.profileInfo = "Profile: " + profileName + " (+" + userOptionsChanged + " option" + (userOptionsChanged == 1 ? "" : "s") + " changed by user)"; } Iris.logger.info(this.profileInfo); // Prepare our include processor IncludeProcessor includeProcessor = new IncludeProcessor(graph); // Set up our source provider for creating ProgramSets Iterable<StringPair> finalEnvironmentDefines1 = environmentDefines; Function<AbsolutePackPath, String> sourceProvider = (path) -> { String pathString = path.getPathString(); // Removes the first "/" in the path if present, and the file // extension in order to represent the path as its program name String programString = pathString.substring(pathString.indexOf("/") == 0 ? 1 : 0, pathString.lastIndexOf(".")); // Return an empty program source if the program is disabled by the current profile if (disabledPrograms.contains(programString)) { return null; } ImmutableList<String> lines = includeProcessor.getIncludedFile(path); if (lines == null) { return null; } StringBuilder builder = new StringBuilder(); for (String line : lines) { builder.append(line); builder.append('\n'); } // Apply GLSL preprocessor to source, while making environment defines available. // // This uses similar techniques to the *.properties preprocessor to avoid actually putting // #define statements in the actual source - instead, we tell the preprocessor about them // directly. This removes one obstacle to accurate reporting of line numbers for errors, // though there exist many more (such as relocating all #extension directives and similar things) String source = builder.toString(); source = JcppProcessor.glslPreprocessSource(source, finalEnvironmentDefines1); return source; }; this.base = new ProgramSet(AbsolutePackPath.fromAbsolutePath("/"), sourceProvider, shaderProperties, this); this.overworld = loadOverrides(hasWorld0, AbsolutePackPath.fromAbsolutePath("/world0"), sourceProvider, shaderProperties, this); this.nether = loadOverrides(hasNether, AbsolutePackPath.fromAbsolutePath("/world-1"), sourceProvider, shaderProperties, this); this.end = loadOverrides(hasEnd, AbsolutePackPath.fromAbsolutePath("/world1"), sourceProvider, shaderProperties, this); this.idMap = new IdMap(root, shaderPackOptions, environmentDefines); customNoiseTexture = shaderProperties.getNoiseTexturePath().map(path -> { try { return readTexture(root, path); } catch (IOException e) { Iris.logger.error("Unable to read the custom noise texture at " + path, e); return null; } }).orElse(null); shaderProperties.getCustomTextures().forEach((textureStage, customTexturePropertiesMap) -> { Object2ObjectMap<String, CustomTextureData> innerCustomTextureDataMap = new Object2ObjectOpenHashMap<>(); customTexturePropertiesMap.forEach((samplerName, path) -> { try { innerCustomTextureDataMap.put(samplerName, readTexture(root, path)); } catch (IOException e) { Iris.logger.error("Unable to read the custom texture at " + path, e); } }); customTextureDataMap.put(textureStage, innerCustomTextureDataMap); }); this.customUniforms = shaderProperties.getCustomUniforms(); } 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<AbsolutePackPath, String> sourceProvider, ShaderProperties shaderProperties, ShaderPack pack) { if (has) { return new ProgramSet(path, sourceProvider, shaderProperties, pack); } return null; } // TODO: Copy-paste from IdMap, find a way to deduplicate this private static Optional<String> loadProperties(Path shaderPath, String name) { String fileContents = readProperties(shaderPath, name); if (fileContents == null) { return Optional.empty(); } return Optional.of(fileContents); } // TODO: Implement raw texture data types public CustomTextureData readTexture(Path root, String path) throws IOException { CustomTextureData customTextureData; if (path.contains(":")) { String[] parts = path.split(":"); if (parts.length > 2) { Iris.logger.warn("Resource location " + path + " contained more than two parts?"); } if (parts[0].equals("minecraft") && (parts[1].equals("dynamic/lightmap_1") || parts[1].equals("dynamic/light_map_1"))) { customTextureData = new CustomTextureData.LightmapMarker(); } else { customTextureData = new CustomTextureData.ResourceData(parts[0], parts[1]); } } else { // TODO: Make sure the resulting path is within the shaderpack? if (path.startsWith("/")) { // NB: This does not guarantee the resulting path is in the shaderpack as a double slash could be used, // this just fixes shaderpacks like Continuum 2.0.4 that use a leading slash in texture paths path = path.substring(1); } boolean blur = false; boolean clamp = false; String mcMetaPath = path + ".mcmeta"; Path mcMetaResolvedPath = root.resolve(mcMetaPath); if (Files.exists(mcMetaResolvedPath)) { try { JsonObject meta = loadMcMeta(mcMetaResolvedPath); if (meta.get("texture") != null) { if (meta.get("texture").getAsJsonObject().get("blur") != null) { blur = meta.get("texture").getAsJsonObject().get("blur").getAsBoolean(); } if (meta.get("texture").getAsJsonObject().get("clamp") != null) { clamp = meta.get("texture").getAsJsonObject().get("clamp").getAsBoolean(); } } } catch (IOException e) { Iris.logger.error("Unable to read the custom texture mcmeta at " + mcMetaPath + ", ignoring: " + e); } } byte[] content = Files.readAllBytes(root.resolve(path)); customTextureData = new CustomTextureData.PngData(new TextureFilteringData(blur, clamp), content); } return customTextureData; } private JsonObject loadMcMeta(Path mcMetaPath) throws IOException, JsonParseException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(mcMetaPath), StandardCharsets.UTF_8))) { JsonReader jsonReader = new JsonReader(reader); return GSON.getAdapter(JsonObject.class).read(jsonReader); } } 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(DimensionId dimension) { ProgramSet overrides = switch (dimension) { case OVERWORLD -> overworld; case NETHER -> nether; case END -> end; default -> throw new IllegalArgumentException("Unknown dimension " + dimension); }; // NB: If a dimension overrides directory is present, none of the files from the parent directory are "merged" // into the override. Rather, we act as if the overrides directory contains a completely different set of // shader programs unrelated to that of the base shader pack. // // This makes sense because if base defined a composite pass and the override didn't, it would make it // impossible to "un-define" the composite pass. It also removes a lot of complexity related to "merging" // program sets. At the same time, this might be desired behavior by shader pack authors. It could make // sense to bring it back as a configurable option, and have a more maintainable set of code backing it. if (overrides != null) { return overrides; } else { return base; } } public Optional<CustomTextureData> getCustomNoiseTexture() { return Optional.ofNullable(customNoiseTexture); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\ShaderProperties.java
package net.coderbot.iris.shaderpack; import com.gtnewhorizons.angelica.glsm.RenderSystem; import com.gtnewhorizons.angelica.glsm.states.BlendState; import it.unimi.dsi.fastutil.booleans.BooleanConsumer; import it.unimi.dsi.fastutil.objects.Object2BooleanMap; import it.unimi.dsi.fastutil.objects.Object2BooleanOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2FloatMap; import it.unimi.dsi.fastutil.objects.Object2FloatOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import lombok.Getter; import net.coderbot.iris.Iris; import net.coderbot.iris.gl.blending.AlphaTest; import net.coderbot.iris.gl.blending.AlphaTestFunction; import net.coderbot.iris.gl.blending.AlphaTestOverride; import net.coderbot.iris.gl.blending.BlendModeFunction; import net.coderbot.iris.gl.blending.BlendModeOverride; import net.coderbot.iris.gl.blending.BufferBlendInformation; import net.coderbot.iris.gl.texture.TextureScaleOverride; import net.coderbot.iris.pipeline.PatchedShaderPrinter; import net.coderbot.iris.shaderpack.option.ShaderPackOptions; import net.coderbot.iris.shaderpack.preprocessor.PropertiesPreprocessor; import net.coderbot.iris.shaderpack.texture.TextureStage; import net.coderbot.iris.uniforms.custom.CustomUniforms; import net.minecraft.client.Minecraft; import java.io.IOException; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * The parsed representation of the shaders.properties file. This class is not meant to be stored permanently, rather * it merely exists as an intermediate step until we build up PackDirectives and ProgramDirectives objects from the * values in here & the values parsed from shader source code. */ public class ShaderProperties { @Getter private final CustomUniforms.Builder customUniforms = new CustomUniforms.Builder(); @Getter private CloudSetting cloudSetting = CloudSetting.DEFAULT; @Getter private OptionalBoolean oldHandLight = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean dynamicHandLight = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean oldLighting = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowTerrain = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowTranslucent = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowEntities = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowPlayer = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowBlockEntities = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean underwaterOverlay = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean sun = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean moon = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean vignette = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean backFaceSolid = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean backFaceCutout = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean backFaceCutoutMipped = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean backFaceTranslucent = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean rainDepth = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean concurrentCompute = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean beaconBeamDepth = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean separateAo = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean frustumCulling = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowCulling = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean shadowEnabled = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean particlesBeforeDeferred = OptionalBoolean.DEFAULT; @Getter private OptionalBoolean prepareBeforeShadow = OptionalBoolean.DEFAULT; @Getter private List<String> sliderOptions = new ArrayList<>(); @Getter private final Map<String, List<String>> profiles = new LinkedHashMap<>(); private List<String> mainScreenOptions = null; @Getter private final Map<String, List<String>> subScreenOptions = new HashMap<>(); private Integer mainScreenColumnCount = null; @Getter private final Map<String, Integer> subScreenColumnCount = new HashMap<>(); // TODO: private Map<String, String> optifineVersionRequirements; // TODO: Parse custom uniforms / variables @Getter private final Object2ObjectMap<String, AlphaTestOverride> alphaTestOverrides = new Object2ObjectOpenHashMap<>(); @Getter private final Object2FloatMap<String> viewportScaleOverrides = new Object2FloatOpenHashMap<>(); @Getter private final Object2ObjectMap<String, TextureScaleOverride> textureScaleOverrides = new Object2ObjectOpenHashMap<>(); @Getter private final Object2ObjectMap<String, BlendModeOverride> blendModeOverrides = new Object2ObjectOpenHashMap<>(); @Getter private final Object2ObjectMap<String, ArrayList<BufferBlendInformation>> bufferBlendOverrides = new Object2ObjectOpenHashMap<>(); @Getter private final EnumMap<TextureStage, Object2ObjectMap<String, String>> customTextures = new EnumMap<>(TextureStage.class); @Getter private final Object2ObjectMap<String, Object2BooleanMap<String>> explicitFlips = new Object2ObjectOpenHashMap<>(); private String noiseTexturePath = null; @Getter private Object2ObjectMap<String, String> conditionallyEnabledPrograms = new Object2ObjectOpenHashMap<>(); @Getter private List<String> requiredFeatureFlags = new ArrayList<>(); @Getter private List<String> optionalFeatureFlags = new ArrayList<>(); private ShaderProperties() { // empty } // TODO: Is there a better solution than having ShaderPack pass a root path to ShaderProperties to be able to read textures? public ShaderProperties(String contents, ShaderPackOptions shaderPackOptions, Iterable<StringPair> environmentDefines) { final String preprocessedContents = PropertiesPreprocessor.preprocessSource(contents, shaderPackOptions, environmentDefines); if (PatchedShaderPrinter.prettyPrintShaders) { try { Files.write(Minecraft.getMinecraft().mcDataDir.toPath().resolve("preprocessed.properties"), preprocessedContents.getBytes(StandardCharsets.UTF_8)); Files.write(Minecraft.getMinecraft().mcDataDir.toPath().resolve("original.properties"), contents.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } final Properties preprocessed = new OrderBackedProperties(); final Properties original = new OrderBackedProperties(); try { preprocessed.load(new StringReader(preprocessedContents)); original.load(new StringReader(contents)); } catch (IOException e) { Iris.logger.error("Error loading shaders.properties!", e); } preprocessed.forEach((keyObject, valueObject) -> { final String key = (String) keyObject; final String value = (String) valueObject; if ("texture.noise".equals(key)) { noiseTexturePath = value; return; } if ("clouds".equals(key)) { if ("off".equals(value)) { cloudSetting = CloudSetting.OFF; } else if ("fast".equals(value)) { cloudSetting = CloudSetting.FAST; } else if ("fancy".equals(value)) { cloudSetting = CloudSetting.FANCY; } else { Iris.logger.error("Unrecognized clouds setting: " + value); } } handleBooleanDirective(key, value, "oldHandLight", bool -> oldHandLight = bool); handleBooleanDirective(key, value, "dynamicHandLight", bool -> dynamicHandLight = bool); handleBooleanDirective(key, value, "oldLighting", bool -> oldLighting = bool); handleBooleanDirective(key, value, "shadowTerrain", bool -> shadowTerrain = bool); handleBooleanDirective(key, value, "shadowTranslucent", bool -> shadowTranslucent = bool); handleBooleanDirective(key, value, "shadowEntities", bool -> shadowEntities = bool); handleBooleanDirective(key, value, "shadowPlayer", bool -> shadowPlayer = bool); handleBooleanDirective(key, value, "shadowBlockEntities", bool -> shadowBlockEntities = bool); handleBooleanDirective(key, value, "underwaterOverlay", bool -> underwaterOverlay = bool); handleBooleanDirective(key, value, "sun", bool -> sun = bool); handleBooleanDirective(key, value, "moon", bool -> moon = bool); handleBooleanDirective(key, value, "vignette", bool -> vignette = bool); handleBooleanDirective(key, value, "backFace.solid", bool -> backFaceSolid = bool); handleBooleanDirective(key, value, "backFace.cutout", bool -> backFaceCutout = bool); handleBooleanDirective(key, value, "backFace.cutoutMipped", bool -> backFaceCutoutMipped = bool); handleBooleanDirective(key, value, "backFace.translucent", bool -> backFaceTranslucent = bool); handleBooleanDirective(key, value, "rain.depth", bool -> rainDepth = bool); handleBooleanDirective(key, value, "allowConcurrentCompute", bool -> concurrentCompute = bool); handleBooleanDirective(key, value, "beacon.beam.depth", bool -> beaconBeamDepth = bool); handleBooleanDirective(key, value, "separateAo", bool -> separateAo = bool); handleBooleanDirective(key, value, "frustum.culling", bool -> frustumCulling = bool); handleBooleanDirective(key, value, "shadow.culling", bool -> shadowCulling = bool); handleBooleanDirective(key, value, "particles.before.deferred", bool -> particlesBeforeDeferred = bool); handleBooleanDirective(key, value, "prepareBeforeShadow", bool -> prepareBeforeShadow = bool); // TODO: Min optifine versions, shader options layout / appearance / profiles // TODO: Custom uniforms handlePassDirective("scale.", key, value, pass -> { final float scale; try { scale = Float.parseFloat(value); } catch (NumberFormatException e) { Iris.logger.error("Unable to parse scale directive for " + pass + ": " + value, e); return; } viewportScaleOverrides.put(pass, scale); }); handlePassDirective("size.buffer.", key, value, pass -> { final String[] parts = value.split(" "); if (parts.length != 2) { Iris.logger.error("Unable to parse size.buffer directive for " + pass + ": " + value); return; } textureScaleOverrides.put(pass, new TextureScaleOverride(parts[0], parts[1])); }); handlePassDirective("alphaTest.", key, value, pass -> { if ("off".equals(value) || "false".equals(value)) { alphaTestOverrides.put(pass, AlphaTestOverride.OFF); return; } final String[] parts = value.split(" "); if (parts.length > 2) { Iris.logger.warn("Weird alpha test directive for " + pass + " contains more parts than we expected: " + value); } else if (parts.length < 2) { Iris.logger.error("Invalid alpha test directive for " + pass + ": " + value); return; } final Optional<AlphaTestFunction> function = AlphaTestFunction.fromString(parts[0]); if (!function.isPresent()) { Iris.logger.error("Unable to parse alpha test directive for " + pass + ", unknown alpha test function " + parts[0] + ": " + value); return; } final float reference; try { reference = Float.parseFloat(parts[1]); } catch (NumberFormatException e) { Iris.logger.error("Unable to parse alpha test directive for " + pass + ": " + value, e); return; } alphaTestOverrides.put(pass, new AlphaTestOverride(new AlphaTest(function.get(), reference))); }); handlePassDirective("blend.", key, value, pass -> { if (pass.contains(".")) { if (!RenderSystem.supportsBufferBlending()) { throw new RuntimeException("Buffer blending is not supported on this platform, however it was attempted to be used!"); } final String[] parts = pass.split("\\."); int index = PackRenderTargetDirectives.LEGACY_RENDER_TARGETS.indexOf(parts[1]); if (index == -1 && parts[1].startsWith("colortex")) { final String id = parts[1].substring("colortex".length()); try { index = Integer.parseInt(id); } catch (NumberFormatException e) { throw new RuntimeException("Failed to parse buffer blend!", e); } } if (index == -1) { throw new RuntimeException("Failed to parse buffer blend! index = " + index); } if ("off".equals(value)) { bufferBlendOverrides.computeIfAbsent(parts[0], list -> new ArrayList<>()).add(new BufferBlendInformation(index, null)); return; } final String[] modeArray = value.split(" "); final int[] modes = new int[modeArray.length]; int i = 0; for (String modeName : modeArray) { modes[i] = BlendModeFunction.fromString(modeName).get().getGlId(); i++; } bufferBlendOverrides.computeIfAbsent(parts[0], list -> new ArrayList<>()).add(new BufferBlendInformation(index, new BlendState(modes[0], modes[1], modes[2], modes[3]))); return; } if ("off".equals(value)) { blendModeOverrides.put(pass, BlendModeOverride.OFF); return; } final String[] modeArray = value.split(" "); final int[] modes = new int[modeArray.length]; int i = 0; for (String modeName : modeArray) { modes[i] = BlendModeFunction.fromString(modeName).get().getGlId(); i++; } blendModeOverrides.put(pass, new BlendModeOverride(new BlendState(modes[0], modes[1], modes[2], modes[3]))); }); handleProgramEnabledDirective("program.", key, value, program -> { conditionallyEnabledPrograms.put(program, value); }); handleTwoArgDirective("texture.", key, value, (stageName, samplerName) -> { final String[] parts = value.split(" "); // TODO: Support raw textures if (parts.length > 1) { Iris.logger.warn("Custom texture directive for stage " + stageName + ", sampler " + samplerName + " contains more parts than we expected: " + value); return; } final Optional<TextureStage> optionalTextureStage = TextureStage.parse(stageName); if (!optionalTextureStage.isPresent()) { Iris.logger.warn("Unknown texture stage " + "\"" + stageName + "\"," + " ignoring custom texture directive for " + key); return; } final TextureStage stage = optionalTextureStage.get(); customTextures.computeIfAbsent(stage, _stage -> new Object2ObjectOpenHashMap<>()) .put(samplerName, value); }); handleTwoArgDirective("flip.", key, value, (pass, buffer) -> { handleBooleanValue(key, value, shouldFlip -> { explicitFlips.computeIfAbsent(pass, _pass -> new Object2BooleanOpenHashMap<>()) .put(buffer, shouldFlip); }); }); handleWhitespacedListDirective(key, value, "iris.features.required", options -> requiredFeatureFlags = options); handleWhitespacedListDirective(key, value, "iris.features.optional", options -> optionalFeatureFlags = options); handlePassDirective("variable.", key, value, pass -> { String[] parts = pass.split("\\."); if (parts.length != 2) { Iris.logger.warn("Custom variables should take the form of `variable.<type>.<name> = <expression>. Ignoring " + key); return; } customUniforms.addVariable(parts[0], parts[1], value, false); }); handlePassDirective("uniform.", key, value, pass -> { String[] parts = pass.split("\\."); if (parts.length != 2) { Iris.logger.warn("Custom uniforms sould take the form of `uniform.<type>.<name> = <expression>. Ignoring " + key); return; } customUniforms.addVariable(parts[0], parts[1], value, true); }); // TODO: Buffer size directives // TODO: Conditional program enabling directives }); // We need to use a non-preprocessed property file here since we don't want any weird preprocessor changes to be applied to the screen/value layout. original.forEach((keyObject, valueObject) -> { final String key = (String) keyObject; final String value = (String) valueObject; // Defining "sliders" multiple times in the properties file will only result in // the last definition being used, should be tested if behavior matches OptiFine handleWhitespacedListDirective(key, value, "sliders", sliders -> sliderOptions = sliders); handlePrefixedWhitespacedListDirective("profile.", key, value, profiles::put); if (handleIntDirective(key, value, "screen.columns", columns -> mainScreenColumnCount = columns)) { return; } if (handleAffixedIntDirective("screen.", ".columns", key, value, subScreenColumnCount::put)) { return; } handleWhitespacedListDirective(key, value, "screen", options -> mainScreenOptions = options); handlePrefixedWhitespacedListDirective("screen.", key, value, subScreenOptions::put); }); } private static void handleBooleanValue(String key, String value, BooleanConsumer handler) { if ("true".equals(value)) { handler.accept(true); } else if ("false".equals(value)) { handler.accept(false); } else { Iris.logger.warn("Unexpected value for boolean key " + key + " in shaders.properties: got " + value + ", but expected either true or false"); } } private static void handleBooleanDirective(String key, String value, String expectedKey, Consumer<OptionalBoolean> handler) { if (!expectedKey.equals(key)) { return; } if ("true".equals(value)) { handler.accept(OptionalBoolean.TRUE); } else if ("false".equals(value)) { handler.accept(OptionalBoolean.FALSE); } else { Iris.logger.warn("Unexpected value for boolean key " + key + " in shaders.properties: got " + value + ", but expected either true or false"); } } private static boolean handleIntDirective(String key, String value, String expectedKey, Consumer<Integer> handler) { if (!expectedKey.equals(key)) { return false; } try { final int result = Integer.parseInt(value); handler.accept(result); } catch (NumberFormatException nex) { Iris.logger.warn("Unexpected value for integer key " + key + " in shaders.properties: got " + value + ", but expected an integer"); } return true; } private static boolean handleAffixedIntDirective(String prefix, String suffix, String key, String value, BiConsumer<String, Integer> handler) { if (key.startsWith(prefix) && key.endsWith(suffix)) { final int substrBegin = prefix.length(); final int substrEnd = key.length() - suffix.length(); if (substrEnd <= substrBegin) { return false; } final String affixStrippedKey = key.substring(substrBegin, substrEnd); try { final int result = Integer.parseInt(value); handler.accept(affixStrippedKey, result); } catch (NumberFormatException nex) { Iris.logger.warn("Unexpected value for integer key " + key + " in shaders.properties: got " + value + ", but expected an integer"); } return true; } return false; } private static void handlePassDirective(String prefix, String key, String value, Consumer<String> handler) { if (key.startsWith(prefix)) { final String pass = key.substring(prefix.length()); handler.accept(pass); } } private static void handleProgramEnabledDirective(String prefix, String key, String value, Consumer<String> handler) { if (key.startsWith(prefix)) { final String program = key.substring(prefix.length(), key.indexOf(".", prefix.length())); handler.accept(program); } } private static void handleWhitespacedListDirective(String key, String value, String expectedKey, Consumer<List<String>> handler) { if (!expectedKey.equals(key)) { return; } final String[] elements = value.split(" +"); handler.accept(Arrays.asList(elements)); } private static void handlePrefixedWhitespacedListDirective(String prefix, String key, String value, BiConsumer<String, List<String>> handler) { if (key.startsWith(prefix)) { final String prefixStrippedKey = key.substring(prefix.length()); final String[] elements = value.split(" +"); handler.accept(prefixStrippedKey, Arrays.asList(elements)); } } private static void handleTwoArgDirective(String prefix, String key, String value, BiConsumer<String, String> handler) { if (key.startsWith(prefix)) { final int endOfPassIndex = key.indexOf(".", prefix.length()); final String stage = key.substring(prefix.length(), endOfPassIndex); final String sampler = key.substring(endOfPassIndex + 1); handler.accept(stage, sampler); } } public static ShaderProperties empty() { return new ShaderProperties(); } public Optional<String> getNoiseTexturePath() { return Optional.ofNullable(noiseTexturePath); } public Optional<List<String>> getMainScreenOptions() { return Optional.ofNullable(mainScreenOptions); } public Optional<Integer> getMainScreenColumnCount() { return Optional.ofNullable(mainScreenColumnCount); } }
Angelica
src\main\java\net\coderbot\iris\shaderpack\StringPair.java
package net.coderbot.iris.shaderpack; import org.jetbrains.annotations.NotNull; import java.util.Objects; /** * 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 StringPair(@NotNull String key, @NotNull String value) { this.key = Objects.requireNonNull(key); this.value = Objects.requireNonNull(value); } @NotNull public String getKey() { return key; } @NotNull public String getValue() { return value; } }
Angelica
src\main\java\net\coderbot\iris\shadow\ShadowMatrices.java
package net.coderbot.iris.shadow; import com.gtnewhorizons.angelica.compat.toremove.MatrixStack; import org.joml.Matrix4f; import static com.gtnewhorizons.angelica.compat.mojang.Constants.DEGREES_TO_RADIANS; 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) { 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 ); } public static Matrix4f createPerspectiveMatrix(float fov) { // This converts from degrees to radians. final 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 ); } public static void createBaselineModelViewMatrix(MatrixStack target, float shadowAngle, float sunPathRotation) { final float skyAngle; if (shadowAngle < 0.25f) { skyAngle = shadowAngle + 0.75f; } else { skyAngle = shadowAngle - 0.25f; } target.peek().getNormal().identity(); target.peek().getModel().identity(); target.peek().getModel().translate(0.0f, 0.0f, -100.0f); target.rotateX(90F * DEGREES_TO_RADIANS); target.rotateZ(skyAngle * -360.0f * DEGREES_TO_RADIANS); target.rotateX(sunPathRotation * DEGREES_TO_RADIANS); } public static void snapModelViewToGrid(MatrixStack target, float shadowIntervalSize, double cameraX, double cameraY, double cameraZ) { if (Math.abs(shadowIntervalSize) == 0.0F) { // Avoid a division by zero - semantically, this just means that the snapping does not take place, // if the shadow interval (size of each grid "cell") is zero. return; } // Calculate where we are within each grid "cell" // These values will be in the range of (-shadowIntervalSize, shadowIntervalSize) // // It looks like it's intended for these to be within the range [0, shadowIntervalSize), however since the // expression (-2.0f % 32.0f) returns -2.0f, negative inputs will result in negative outputs. float offsetX = (float) cameraX % shadowIntervalSize; float offsetY = (float) cameraY % shadowIntervalSize; float offsetZ = (float) cameraZ % shadowIntervalSize; // Halve the size of each grid cell in order to move to the center of it. final float halfIntervalSize = shadowIntervalSize / 2.0f; // Shift by -halfIntervalSize // // It's clear that the intent of the algorithm was to place the values into the range: // [-shadowIntervalSize/2, shadowIntervalSize), however due to the previously-mentioned behavior with negatives, // it's possible that values will lie in the range (-3shadowIntervalSize/2, shadowIntervalSize/2). offsetX -= halfIntervalSize; offsetY -= halfIntervalSize; offsetZ -= halfIntervalSize; target.peek().getModel().translate(offsetX, offsetY, offsetZ); } public static void createModelViewMatrix(MatrixStack target, float shadowAngle, float shadowIntervalSize, float sunPathRotation, double cameraX, double cameraY, double cameraZ) { createBaselineModelViewMatrix(target, shadowAngle, sunPathRotation); snapModelViewToGrid(target, shadowIntervalSize, cameraX, cameraY, cameraZ); } private static final class Tests { 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 ); test("ortho projection hpl=32", expected, createOrthoMatrix(32.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 ); test("ortho projection hpl=110", expected110, createOrthoMatrix(110.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 ); 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 ); MatrixStack modelView = new MatrixStack(); // NB: At dawn, the shadow angle is NOT zero. // 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); test("model view at dawn", expectedModelViewAtDawn, modelView.peek().getModel()); } 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.println(" created: "); System.err.print(created.toString()); } else { System.out.println("test " + name + " passed"); } } } }
Angelica
src\main\java\net\coderbot\iris\shadows\CullingDataCache.java
package net.coderbot.iris.shadows; public interface CullingDataCache { void saveState(); void restoreState(); }
Angelica
src\main\java\net\coderbot\iris\shadows\Matrix4fAccess.java
package net.coderbot.iris.shadows; import org.joml.Matrix4f; 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 */ Matrix4f convertToJOML(); }
Angelica
src\main\java\net\coderbot\iris\shadows\ShadowRenderingState.java
package net.coderbot.iris.shadows; import net.coderbot.iris.pipeline.ShadowRenderer; import org.joml.Matrix4f; public class ShadowRenderingState { public static boolean areShadowsCurrentlyBeingRendered() { return ShadowRenderer.ACTIVE; } public static Matrix4f getShadowOrthoMatrix() { return ShadowRenderer.ACTIVE ? new Matrix4f(ShadowRenderer.PROJECTION) : null; } }
Angelica
src\main\java\net\coderbot\iris\shadows\ShadowRenderTargets.java
package net.coderbot.iris.shadows; import com.google.common.collect.ImmutableSet; import com.gtnewhorizons.angelica.glsm.RenderSystem; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; 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.rendertarget.DepthTexture; import net.coderbot.iris.rendertarget.RenderTarget; import net.coderbot.iris.shaderpack.PackShadowDirectives; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; public class ShadowRenderTargets { private final RenderTarget[] targets; private final DepthTexture mainDepth; private final DepthTexture noTranslucents; private final GlFramebuffer depthSourceFb; private final GlFramebuffer noTranslucentsDestFb; private final boolean[] flipped; private final List<GlFramebuffer> ownedFramebuffers; private final int resolution; private boolean fullClearRequired; private boolean translucentDepthDirty; private boolean[] hardwareFiltered; private InternalTextureFormat[] formats; private IntList buffersToBeCleared; public ShadowRenderTargets(int resolution, PackShadowDirectives shadowDirectives) { targets = new RenderTarget[shadowDirectives.getColorSamplingSettings().size()]; formats = new InternalTextureFormat[shadowDirectives.getColorSamplingSettings().size()]; flipped = new boolean[shadowDirectives.getColorSamplingSettings().size()]; hardwareFiltered = new boolean[shadowDirectives.getColorSamplingSettings().size()]; buffersToBeCleared = new IntArrayList(); this.mainDepth = new DepthTexture(resolution, resolution, DepthBufferFormat.DEPTH); this.noTranslucents = new DepthTexture(resolution, resolution, DepthBufferFormat.DEPTH); for (int i = 0; i < shadowDirectives.getColorSamplingSettings().size(); i++) { PackShadowDirectives.SamplingSettings settings = shadowDirectives.getColorSamplingSettings().get(i); targets[i] = RenderTarget.builder().setDimensions(resolution, resolution) .setInternalFormat(settings.getFormat()) .setPixelFormat(settings.getFormat().getPixelFormat()).build(); formats[i] = settings.getFormat(); if (settings.getClear()) { buffersToBeCleared.add(i); } this.hardwareFiltered[i] = shadowDirectives.getDepthSamplingSettings().get(i).getHardwareFiltering(); } 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.noTranslucentsDestFb = createFramebufferWritingToMain(new int[] {0}); this.noTranslucentsDestFb.addDepthAttachment(this.noTranslucents.getTextureId()); this.translucentDepthDirty = true; } // TODO: Actually flip. This is required for shadow composites! public void flip(int target) { flipped[target] = !flipped[target]; } public boolean isFlipped(int target) { return flipped[target]; } public void destroy() { for (GlFramebuffer owned : ownedFramebuffers) { owned.destroy(); } for (RenderTarget target : targets) { target.destroy(); } noTranslucents.destroy(); } public int getRenderTargetCount() { return targets.length; } public RenderTarget get(int index) { return targets[index]; } public int getResolution() { return resolution; } public DepthTexture getDepthTexture() { return mainDepth; } public DepthTexture getDepthTextureNoTranslucents() { return noTranslucents; } public GlFramebuffer getDepthSourceFb() { return depthSourceFb; } public void copyPreTranslucentDepth() { if (translucentDepthDirty) { translucentDepthDirty = false; RenderSystem.blitFramebuffer(depthSourceFb.getId(), noTranslucentsDestFb.getId(), 0, 0, resolution, resolution, 0, 0, resolution, resolution, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); } else { DepthCopyStrategy.fastest(false).copy(depthSourceFb, mainDepth.getTextureId(), noTranslucentsDestFb, noTranslucents.getTextureId(), resolution, resolution); } } public boolean isFullClearRequired() { return fullClearRequired; } public void onFullClear() { fullClearRequired = false; } public GlFramebuffer createFramebufferWritingToMain(int[] drawBuffers) { return createFullFramebuffer(false, drawBuffers); } public GlFramebuffer createFramebufferWritingToAlt(int[] drawBuffers) { return createFullFramebuffer(true, drawBuffers); } private ImmutableSet<Integer> invert(ImmutableSet<Integer> base, int[] relevant) { ImmutableSet.Builder<Integer> inverted = ImmutableSet.builder(); for (int i : relevant) { if (!base.contains(i)) { inverted.add(i); } } return inverted.build(); } private GlFramebuffer createEmptyFramebuffer() { GlFramebuffer framebuffer = new GlFramebuffer(); ownedFramebuffers.add(framebuffer); framebuffer.addDepthAttachment(mainDepth.getTextureId()); // NB: Before OpenGL 3.0, all framebuffers are required to have a color // attachment no matter what. framebuffer.addColorAttachment(0, get(0).getMainTexture()); framebuffer.noDrawBuffers(); return framebuffer; } public GlFramebuffer createShadowFramebuffer(ImmutableSet<Integer> stageWritesToAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); } ImmutableSet<Integer> stageWritesToMain = invert(stageWritesToAlt, drawBuffers); GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(mainDepth.getTextureId()); return framebuffer; } private GlFramebuffer createFullFramebuffer(boolean clearsAlt, int[] drawBuffers) { if (drawBuffers.length == 0) { return createEmptyFramebuffer(); } ImmutableSet<Integer> stageWritesToMain = ImmutableSet.of(); if (!clearsAlt) { stageWritesToMain = invert(ImmutableSet.of(), drawBuffers); } return createColorFramebufferWithDepth(stageWritesToMain, drawBuffers); } public GlFramebuffer createColorFramebufferWithDepth(ImmutableSet<Integer> stageWritesToMain, int[] drawBuffers) { GlFramebuffer framebuffer = createColorFramebuffer(stageWritesToMain, drawBuffers); framebuffer.addDepthAttachment(mainDepth.getTextureId()); return framebuffer; } public GlFramebuffer createColorFramebuffer(ImmutableSet<Integer> stageWritesToMain, int[] drawBuffers) { if (drawBuffers.length == 0) { throw new IllegalArgumentException("Framebuffer must have at least one color buffer"); } GlFramebuffer framebuffer = new GlFramebuffer(); ownedFramebuffers.add(framebuffer); int[] actualDrawBuffers = new int[drawBuffers.length]; for (int i = 0; i < drawBuffers.length; i++) { actualDrawBuffers[i] = i; if (drawBuffers[i] >= getRenderTargetCount()) { // TODO: This causes resource leaks, also we should really verify this in the shaderpack parser... throw new IllegalStateException("Render target with index " + drawBuffers[i] + " is not supported, only " + getRenderTargetCount() + " render targets are supported."); } RenderTarget target = this.get(drawBuffers[i]); int textureId = stageWritesToMain.contains(drawBuffers[i]) ? target.getMainTexture() : target.getAltTexture(); framebuffer.addColorAttachment(i, textureId); } framebuffer.drawBuffers(actualDrawBuffers); framebuffer.readBuffer(0); if (!framebuffer.isComplete()) { throw new IllegalStateException("Unexpected error while creating framebuffer"); } return framebuffer; } public int getColorTextureId(int i) { return isFlipped(i) ? get(i).getAltTexture() : get(i).getMainTexture(); } public boolean isHardwareFiltered(int i) { return hardwareFiltered[i]; } public int getNumColorTextures() { return targets.length; } public InternalTextureFormat getColorTextureFormat(int index) { return formats[index]; } public ImmutableSet<Integer> snapshot() { ImmutableSet.Builder<Integer> builder = ImmutableSet.builder(); for (int i = 0; i < flipped.length; i++) { if (flipped[i]) { builder.add(i); } } return builder.build(); } public IntList getBuffersToBeCleared() { return buffersToBeCleared; } }
Angelica
src\main\java\net\coderbot\iris\sodium\IrisChunkShaderBindingPoints.java
package net.coderbot.iris.sodium; import me.jellysquid.mods.sodium.client.gl.shader.ShaderBindingPoint; /** * 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 { public static final ShaderBindingPoint NORMAL = new ShaderBindingPoint(5); public static final ShaderBindingPoint TANGENT = new ShaderBindingPoint(6); public static final ShaderBindingPoint MID_TEX_COORD = new ShaderBindingPoint(7); public static final ShaderBindingPoint BLOCK_ID = new ShaderBindingPoint(8); public static final ShaderBindingPoint MID_BLOCK = new ShaderBindingPoint(9); }
Angelica
src\main\java\net\coderbot\iris\uniforms\BiomeUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.compat.iris.BiomeCategoryCache; import com.gtnewhorizons.angelica.compat.iris.ModdedBiomeDetector; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.parsing.BiomeCategories; import net.minecraft.client.Minecraft; import net.minecraft.util.MathHelper; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenBeach; import net.minecraft.world.biome.BiomeGenDesert; import net.minecraft.world.biome.BiomeGenEnd; import net.minecraft.world.biome.BiomeGenForest; import net.minecraft.world.biome.BiomeGenHell; import net.minecraft.world.biome.BiomeGenHills; import net.minecraft.world.biome.BiomeGenJungle; import net.minecraft.world.biome.BiomeGenMesa; import net.minecraft.world.biome.BiomeGenMushroomIsland; import net.minecraft.world.biome.BiomeGenMutated; import net.minecraft.world.biome.BiomeGenOcean; import net.minecraft.world.biome.BiomeGenPlains; import net.minecraft.world.biome.BiomeGenRiver; import net.minecraft.world.biome.BiomeGenSavanna; import net.minecraft.world.biome.BiomeGenSnow; import net.minecraft.world.biome.BiomeGenStoneBeach; import net.minecraft.world.biome.BiomeGenSwamp; import net.minecraft.world.biome.BiomeGenTaiga; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.HashMap; import java.util.Map; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; public class BiomeUniforms { private static final Logger LOGGER = LogManager.getLogger("BiomeUniforms"); private static final Minecraft client = Minecraft.getMinecraft(); // Cache to avoid multiple biome lookups per tick private static BiomeGenBase cachedBiome = null; private static long cachedWorldTime = -1; private static int cachedPlayerX = Integer.MIN_VALUE; private static int cachedPlayerZ = Integer.MIN_VALUE; /** * Adds biome-related uniforms that change based on the player's current biome. */ public static void addBiomeUniforms(UniformHolder uniforms) { uniforms.uniform1i(PER_TICK, "biome", BiomeUniforms::getBiomeId) .uniform1i(PER_TICK, "biome_category", BiomeUniforms::getBiomeCategory) .uniform1i(PER_TICK, "biome_precipitation", BiomeUniforms::getBiomePrecipitation) .uniform1f(PER_TICK, "rainfall", BiomeUniforms::getBiomeRainfall) .uniform1f(PER_TICK, "temperature", BiomeUniforms::getBiomeTemperature); } /** * Gets the current biome, with caching to avoid repeated lookups within the same tick. * Returns null if player or world is not available. */ private static BiomeGenBase getCachedBiome() { if (client.thePlayer == null || client.theWorld == null) { return null; } final long worldTime = client.theWorld.getTotalWorldTime(); final int playerX = MathHelper.floor_double(client.thePlayer.posX); final int playerZ = MathHelper.floor_double(client.thePlayer.posZ); // Invalidate cache if time or position changed if (cachedBiome == null || cachedWorldTime != worldTime || cachedPlayerX != playerX || cachedPlayerZ != playerZ) { cachedBiome = client.theWorld.getBiomeGenForCoords(playerX, playerZ); cachedWorldTime = worldTime; cachedPlayerX = playerX; cachedPlayerZ = playerZ; } return cachedBiome; } public static int getBiomePrecipitation() { final BiomeGenBase biome = getCachedBiome(); if (biome == null) { return 0; } if (!biome.enableRain && !biome.enableSnow) { return 0; } final float temp = biome.getFloatTemperature( MathHelper.floor_double(client.thePlayer.posX), MathHelper.floor_double(client.thePlayer.posY), MathHelper.floor_double(client.thePlayer.posZ)); return temp > 0.15F ? 1 : 2; } public static float getBiomeRainfall() { final BiomeGenBase biome = getCachedBiome(); return biome != null ? biome.rainfall : 0.0F; } public static float getBiomeTemperature() { final BiomeGenBase biome = getCachedBiome(); return biome != null ? biome.temperature : 0.0F; } public static int getBiomeId() { final BiomeGenBase biome = getCachedBiome(); return biome != null ? biome.biomeID : 0; } public static int getBiomeCategory() { final BiomeGenBase biome = getCachedBiome(); if (biome == null) { return BiomeCategories.NONE.ordinal(); } // Check cache first if (biome instanceof BiomeCategoryCache cache) { final int cached = cache.iris$getCachedCategory(); if (cached != -1) { return cached; } // Not cached yet, determine and cache it final int category = determineBiomeCategory(biome); cache.iris$setCachedCategory(category); final BiomeCategories[] categories = BiomeCategories.values(); final String categoryName = (category >= 0 && category < categories.length) ? categories[category].name() : "INVALID(" + category + ")"; LOGGER.debug("Cached biome category for '{}': {}", biome.biomeName, categoryName); return category; } // Fallback if mixin didn't apply (shouldn't happen) return determineBiomeCategory(biome); } private static int determineBiomeCategory(BiomeGenBase biome) { // Tier 1: Hardcoded vanilla biome IDs BiomeGenBase lookupBiome = biome; if (biome instanceof BiomeGenMutated mutated && mutated.baseBiome != null) { lookupBiome = mutated.baseBiome; } BiomeCategories category = getVanillaBiomeCategory(lookupBiome.biomeID); if (category != null) { return category.ordinal(); } // Tier 2: Class-based detection for vanilla biome types category = detectVanillaBiomeByClass(biome); if (category != null) { return category.ordinal(); } // Tier 3: Modded biome detection (BiomesOPlenty, Realistic World Gen) category = detectModdedBiome(biome); if (category != null) { return category.ordinal(); } // Tier 4: Name pattern matching category = detectBiomeByName(biome); if (category != null) { return category.ordinal(); } // Tier 5: Temperature/rainfall heuristics category = detectBiomeByProperties(biome); if (category != null) { return category.ordinal(); } // Default: NONE return BiomeCategories.NONE.ordinal(); } private static BiomeCategories getVanillaBiomeCategory(int biomeID) { return switch (biomeID) { // OCEAN case 0, 10, 24 -> BiomeCategories.OCEAN; // ocean, frozenOcean, deepOcean // PLAINS case 1 -> BiomeCategories.PLAINS; // plains // DESERT case 2, 17 -> BiomeCategories.DESERT; // desert, desertHills // EXTREME_HILLS (Vanilla mountains) case 3, 20, 34 -> BiomeCategories.EXTREME_HILLS; // extremeHills, extremeHillsEdge, extremeHillsPlus // FOREST case 4, 18, 27, 28, 29 -> BiomeCategories.FOREST; // forest, forestHills, birchForest, birchForestHills, roofedForest // TAIGA case 5, 19, 30, 31, 32, 33 -> BiomeCategories.TAIGA; // taiga, taigaHills, coldTaiga, coldTaigaHills, megaTaiga, megaTaigaHills // SWAMP case 6 -> BiomeCategories.SWAMP; // swampland // RIVER case 7, 11 -> BiomeCategories.RIVER; // river, frozenRiver // NETHER case 8 -> BiomeCategories.NETHER; // hell // THE_END case 9 -> BiomeCategories.THE_END; // sky // ICY case 12, 13 -> BiomeCategories.ICY; // icePlains, iceMountains // MUSHROOM case 14, 15 -> BiomeCategories.MUSHROOM; // mushroomIsland, mushroomIslandShore // BEACH case 16, 25, 26 -> BiomeCategories.BEACH; // beach, stoneBeach, coldBeach // JUNGLE case 21, 22, 23 -> BiomeCategories.JUNGLE; // jungle, jungleHills, jungleEdge // SAVANNA case 35, 36 -> BiomeCategories.SAVANNA; // savanna, savannaPlateau // MESA case 37, 38, 39 -> BiomeCategories.MESA; // mesa, mesaPlateau_F, mesaPlateau default -> null; // Not a vanilla biome or unknown }; } private static final Map<Class<? extends BiomeGenBase>, BiomeCategories> VANILLA_CLASS_MAP = createVanillaClassMap(); private static Map<Class<? extends BiomeGenBase>, BiomeCategories> createVanillaClassMap() { final Map<Class<? extends BiomeGenBase>, BiomeCategories> map = new HashMap<>(); // Most specific first (subclasses before superclasses) map.put(BiomeGenStoneBeach.class, BiomeCategories.BEACH); map.put(BiomeGenBeach.class, BiomeCategories.BEACH); map.put(BiomeGenMushroomIsland.class, BiomeCategories.MUSHROOM); map.put(BiomeGenOcean.class, BiomeCategories.OCEAN); map.put(BiomeGenPlains.class, BiomeCategories.PLAINS); map.put(BiomeGenDesert.class, BiomeCategories.DESERT); map.put(BiomeGenHills.class, BiomeCategories.EXTREME_HILLS); map.put(BiomeGenForest.class, BiomeCategories.FOREST); map.put(BiomeGenTaiga.class, BiomeCategories.TAIGA); map.put(BiomeGenSwamp.class, BiomeCategories.SWAMP); map.put(BiomeGenRiver.class, BiomeCategories.RIVER); map.put(BiomeGenHell.class, BiomeCategories.NETHER); map.put(BiomeGenEnd.class, BiomeCategories.THE_END); map.put(BiomeGenSnow.class, BiomeCategories.ICY); map.put(BiomeGenJungle.class, BiomeCategories.JUNGLE); map.put(BiomeGenSavanna.class, BiomeCategories.SAVANNA); map.put(BiomeGenMesa.class, BiomeCategories.MESA); return map; } private static BiomeCategories detectVanillaBiomeByClass(BiomeGenBase biome) { // Direct class lookup (O(1) for exact matches) final BiomeCategories direct = VANILLA_CLASS_MAP.get(biome.getClass()); if (direct != null) { return direct; } // Fallback: instanceof checks for subclasses (modded biomes extending vanilla) for (Map.Entry<Class<? extends BiomeGenBase>, BiomeCategories> entry : VANILLA_CLASS_MAP.entrySet()) { if (entry.getKey().isInstance(biome)) { return entry.getValue(); } } return null; } private static BiomeCategories detectModdedBiome(BiomeGenBase biome) { return ModdedBiomeDetector.detectModdedBiome(biome); } private static BiomeCategories detectBiomeByName(BiomeGenBase biome) { if (biome.biomeName == null) return null; final String name = biome.biomeName.toLowerCase(); // Check for keywords in biome names // Priority order matters - check more specific terms first if (name.contains("nether")) return BiomeCategories.NETHER; if (name.contains("end")) return BiomeCategories.THE_END; if (name.contains("ocean") || name.contains("sea")) return BiomeCategories.OCEAN; if (name.contains("river") || name.contains("stream")) return BiomeCategories.RIVER; if (name.contains("beach") || name.contains("shore") || name.contains("coast")) return BiomeCategories.BEACH; if (name.contains("mushroom")) return BiomeCategories.MUSHROOM; if (name.contains("swamp") || name.contains("marsh") || name.contains("bog")) return BiomeCategories.SWAMP; if (name.contains("jungle")) return BiomeCategories.JUNGLE; if (name.contains("savanna") || name.contains("savannah")) return BiomeCategories.SAVANNA; if (name.contains("mesa") || name.contains("badlands")) return BiomeCategories.MESA; if (name.contains("desert")) return BiomeCategories.DESERT; // Mountain detection - for modded biomes if (name.contains("mountain") || name.contains("peak") || name.contains("alpine") || name.contains("cliff") || name.contains("crag")) return BiomeCategories.MOUNTAIN; // Ice/Snow detection if (name.contains("ice") || name.contains("frozen") || name.contains("snow") || name.contains("arctic") || name.contains("tundra") || name.contains("glacier")) return BiomeCategories.ICY; if (name.contains("taiga") || name.contains("boreal") || name.contains("conifer")) return BiomeCategories.TAIGA; if (name.contains("forest") || name.contains("wood") || name.contains("grove") || name.contains("thicket")) return BiomeCategories.FOREST; if (name.contains("plain") || name.contains("field") || name.contains("meadow") || name.contains("grassland") || name.contains("prairie")) return BiomeCategories.PLAINS; return null; } private static BiomeCategories detectBiomeByProperties(BiomeGenBase biome) { final float temp = biome.temperature; final float rain = biome.rainfall; // Very cold biomes with snow if (temp <= 0.0F && biome.enableSnow) { return BiomeCategories.ICY; } // Hot, dry biomes if (temp >= 2.0F && !biome.enableRain) { return BiomeCategories.DESERT; } // Warm, dry biomes (savanna-like) if (temp >= 1.0F && rain <= 0.1F && !biome.enableRain) { return BiomeCategories.SAVANNA; } // Wet biomes with high rainfall if (rain >= 0.85F && temp >= 0.5F && temp <= 1.0F) { return BiomeCategories.SWAMP; } // Cold forested biomes if (temp >= 0.0F && temp <= 0.4F && rain >= 0.4F) { return BiomeCategories.TAIGA; } // Temperate forested biomes if (temp >= 0.4F && temp <= 0.9F && rain >= 0.5F) { return BiomeCategories.FOREST; } // Default to plains for temperate, moderate biomes if (temp >= 0.4F && temp <= 1.0F && rain >= 0.3F && rain <= 0.6F) { return BiomeCategories.PLAINS; } return null; } }
Angelica
src\main\java\net\coderbot\iris\uniforms\CameraUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.rendering.RenderingState; import lombok.Getter; import net.coderbot.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; import org.joml.Vector3d; import org.joml.Vector3dc; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * @see <a href="https://github.com/IrisShaders/ShaderDoc/blob/master/uniforms.md#camera">Uniforms: Camera</a> */ public class CameraUniforms { private static final Minecraft client = Minecraft.getMinecraft(); private CameraUniforms() { } public static void addCameraUniforms(UniformHolder uniforms, FrameUpdateNotifier notifier) { final CameraPositionTracker tracker = new CameraPositionTracker(notifier); uniforms .uniform1f(ONCE, "near", () -> 0.05) .uniform1f(PER_FRAME, "far", CameraUniforms::getRenderDistanceInBlocks) .uniform3d(PER_FRAME, "cameraPosition", tracker::getCurrentCameraPosition) .uniform1f(PER_FRAME, "eyeAltitude", tracker::getCurrentCameraPositionY) .uniform3d(PER_FRAME, "previousCameraPosition", tracker::getPreviousCameraPosition); } private static int getRenderDistanceInBlocks() { // TODO: Should we ask the game renderer for this? return client.gameSettings.renderDistanceChunks * 16; } public static Vector3dc getUnshiftedCameraPosition() { return RenderingState.INSTANCE.getCameraPosition(); } static class CameraPositionTracker { /** * Value range of cameraPosition. We want this to be small enough that precision is maintained when we convert * from a double to a float, but big enough that shifts happen infrequently, since each shift corresponds with * a noticeable change in shader animations and similar. 1000024 is the number used by Optifine for walking (however this is too much, so we choose 30000), * with an extra 1024 check for if the user has teleported between camera positions. */ private static final double WALK_RANGE = 30000; private static final double TP_RANGE = 1000; @Getter private Vector3d previousCameraPosition = new Vector3d(); @Getter private Vector3d currentCameraPosition = new Vector3d(); private final Vector3d shift = new Vector3d(); CameraPositionTracker(FrameUpdateNotifier notifier) { notifier.addListener(this::update); } private void update() { previousCameraPosition.set(currentCameraPosition); currentCameraPosition.set(getUnshiftedCameraPosition()).add(shift); updateShift(); } /** * Updates our shift values to try to keep |x| < 30000 and |z| < 30000, to maintain precision with cameraPosition. * Since our actual range is 60000x60000, this means that we won't excessively move back and forth when moving * around a chunk border. */ private void updateShift() { final double dX = getShift(currentCameraPosition.x, previousCameraPosition.x); final double dZ = getShift(currentCameraPosition.z, previousCameraPosition.z); if (dX != 0.0 || dZ != 0.0) { applyShift(dX, dZ); } } 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 * to the shader for the most part. */ private void applyShift(double dX, double dZ) { shift.x += dX; currentCameraPosition.x += dX; previousCameraPosition.x += dX; shift.z += dZ; currentCameraPosition.z += dZ; previousCameraPosition.z += dZ; } public double getCurrentCameraPositionY() { return currentCameraPosition.y; } } }
Angelica
src\main\java\net\coderbot\iris\uniforms\CapturedRenderingState.java
package net.coderbot.iris.uniforms; import lombok.Getter; import net.coderbot.iris.gl.state.ValueUpdateNotifier; import org.joml.Vector4f; public class CapturedRenderingState { public static final CapturedRenderingState INSTANCE = new CapturedRenderingState(); @Getter private float tickDelta; @Getter private int currentRenderedBlockEntity; private Runnable blockEntityIdListener = null; @Getter private int currentRenderedEntity = -1; private Runnable entityIdListener = null; @Getter private final Vector4f currentEntityColor = new Vector4f(); private Runnable entityColorListener = null; private CapturedRenderingState() { } public void setTickDelta(float tickDelta) { this.tickDelta = tickDelta; } public void setCurrentBlockEntity(int entity) { this.currentRenderedBlockEntity = entity; if (this.blockEntityIdListener != null) { this.blockEntityIdListener.run(); } } public void setCurrentEntity(int entity) { this.currentRenderedEntity = entity; if (this.entityIdListener != null) { this.entityIdListener.run(); } } public void setCurrentEntityColor(float r, float g, float b, float a) { this.currentEntityColor.set(r, g, b, a); if (this.entityColorListener != null) { this.entityColorListener.run(); } } public ValueUpdateNotifier getEntityIdNotifier() { return listener -> this.entityIdListener = listener; } public ValueUpdateNotifier getBlockEntityIdNotifier() { return listener -> this.blockEntityIdListener = listener; } public ValueUpdateNotifier getEntityColorNotifier() { return listener -> this.entityColorListener = listener; } }
Angelica
src\main\java\net\coderbot\iris\uniforms\CelestialUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.compat.mojang.Constants; import com.gtnewhorizons.angelica.rendering.RenderingState; import net.coderbot.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import org.joml.Matrix4f; import org.joml.Vector4f; import java.util.Objects; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * @see <a href="https://github.com/IrisShaders/ShaderDoc/blob/master/uniforms.md#celestial-bodies">Uniforms: Celestial bodies</a> */ public final class CelestialUniforms { private final float sunPathRotation; 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() { final float skyAngle = getSkyAngle(); if (skyAngle < 0.75F) { return skyAngle + 0.25F; } else { return skyAngle - 0.75F; } } private static float getShadowAngle() { float shadowAngle = getSunAngle(); if (!isDay()) { shadowAngle -= 0.5F; } return shadowAngle; } private Vector4f getSunPosition() { return getCelestialPosition(100.0F); } private Vector4f getMoonPosition() { return getCelestialPosition(-100.0F); } public Vector4f getShadowLightPosition() { return isDay() ? getSunPosition() : getMoonPosition(); } public Vector4f getShadowLightPositionInWorldSpace() { return isDay() ? getCelestialPositionInWorldSpace(100.0F) : getCelestialPositionInWorldSpace(-100.0F); } private Vector4f getCelestialPositionInWorldSpace(float y) { final Vector4f position = new Vector4f(0.0F, y, 0.0F, 0.0F); // TODO: Deduplicate / remove this function. final Matrix4f celestial = new Matrix4f().identity(); // This is the same transformation applied by renderSky, however, it's been moved to here. // This is because we need the result of it before it's actually performed in vanilla. celestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS); celestial.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS); celestial.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS); celestial.transform(position); return position; } private Vector4f getCelestialPosition(float y) { Vector4f position = new Vector4f(0.0F, y, 0.0F, 0.0F); final Matrix4f celestial = new Matrix4f(RenderingState.INSTANCE.getModelViewMatrix()); // This is the same transformation applied by renderSky, however, it's been moved to here. // This is because we need the result of it before it's actually performed in vanilla. celestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS); celestial.rotateZ(sunPathRotation * Constants.DEGREES_TO_RADIANS); celestial.rotateX(getSkyAngle() * 360.0F * Constants.DEGREES_TO_RADIANS); position = celestial.transform(position); return position; } private static Vector4f getUpPosition() { Vector4f upVector = new Vector4f(0.0F, 100.0F, 0.0F, 0.0F); // Get the current model view matrix, since that is the basis of the celestial model view matrix final Matrix4f preCelestial = new Matrix4f(RenderingState.INSTANCE.getModelViewMatrix()); // Apply the fixed -90.0F degrees rotation to mirror the same transformation in renderSky. // But, notably, skip the rotation by the skyAngle. preCelestial.rotateY(-90.F * Constants.DEGREES_TO_RADIANS); // 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 WorldClient getWorld() { return Objects.requireNonNull(Minecraft.getMinecraft().theWorld); } private static float getSkyAngle() { return getWorld().getCelestialAngle(CapturedRenderingState.INSTANCE.getTickDelta()); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\CommonUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.glsm.GLStateManager; import com.gtnewhorizons.angelica.glsm.states.BlendState; import com.gtnewhorizons.angelica.glsm.texture.TextureInfo; import com.gtnewhorizons.angelica.glsm.texture.TextureInfoCache; import com.gtnewhorizons.angelica.glsm.texture.TextureTracker; import com.gtnewhorizons.angelica.mixins.interfaces.EntityRendererAccessor; 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.shaderpack.IdMap; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.uniforms.transforms.SmoothedFloat; import net.coderbot.iris.uniforms.transforms.SmoothedVec2f; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.Vec3; import org.joml.Math; import org.joml.Vector2f; import org.joml.Vector2i; import org.joml.Vector3d; import org.joml.Vector4i; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.ONCE; public final class CommonUniforms { private static final Minecraft client = Minecraft.getMinecraft(); private static final Vector2i ZERO_VECTOR_2i = new Vector2i(); private static final Vector4i ZERO_VECTOR_4i = new Vector4i(0, 0, 0, 0); private static final Vector3d ZERO_VECTOR_3d = new Vector3d(); private CommonUniforms() { // no construction allowed } public static void addNonDynamicUniforms(UniformHolder uniforms, IdMap idMap, PackDirectives directives, FrameUpdateNotifier updateNotifier) { CameraUniforms.addCameraUniforms(uniforms, updateNotifier); ViewportUniforms.addViewportUniforms(uniforms); WorldTimeUniforms.addWorldTimeUniforms(uniforms); SystemTimeUniforms.addSystemTimeUniforms(uniforms); BiomeUniforms.addBiomeUniforms(uniforms); new CelestialUniforms(directives.getSunPathRotation()).addCelestialUniforms(uniforms); IrisExclusiveUniforms.addIrisExclusiveUniforms(uniforms); IdMapUniforms.addIdMapUniforms(updateNotifier, uniforms, idMap, directives.isOldHandLight()); MatrixUniforms.addMatrixUniforms(uniforms, directives); if (AngelicaConfig.enableHardcodedCustomUniforms) { HardcodedCustomUniforms.addHardcodedCustomUniforms(uniforms, updateNotifier); } CommonUniforms.generalCommonUniforms(uniforms, updateNotifier, directives); } // Needs to use a LocationalUniformHolder as we need it for the common uniforms public static void addDynamicUniforms(DynamicUniformHolder uniforms) { ExternallyManagedUniforms.addExternallyManagedUniforms116(uniforms); IdMapUniforms.addEntityIdMapUniforms(uniforms); FogUniforms.addFogUniforms(uniforms); // TODO: OptiFine doesn't think that atlasSize is a "dynamic" uniform, // but we do. How will custom uniforms depending on atlasSize work? uniforms.uniform2i("atlasSize", () -> { final int glId = GLStateManager.getBoundTextureForServerState(); final AbstractTexture texture = TextureTracker.INSTANCE.getTexture(glId); if (texture instanceof TextureMap) { final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(glId); return new Vector2i(info.getWidth(), info.getHeight()); } return ZERO_VECTOR_2i; }, StateUpdateNotifiers.bindTextureNotifier); uniforms.uniform2i("gtextureSize", () -> { final int glId = GLStateManager.getBoundTextureForServerState(); final TextureInfo info = TextureInfoCache.INSTANCE.getInfo(glId); return new Vector2i(info.getWidth(), info.getHeight()); }, StateUpdateNotifiers.bindTextureNotifier); uniforms.uniform4i("blendFunc", () -> { if(GLStateManager.getBlendMode().isEnabled()) { final BlendState blend = GLStateManager.getBlendState(); return new Vector4i(blend.getSrcRgb(), blend.getDstRgb(), blend.getSrcAlpha(), blend.getDstAlpha()); } return ZERO_VECTOR_4i; }, StateUpdateNotifiers.blendFuncNotifier); uniforms.uniform1i("renderStage", () -> GbufferPrograms.getCurrentPhase().ordinal(), StateUpdateNotifiers.phaseChangeNotifier); uniforms.uniform4f("entityColor", CapturedRenderingState.INSTANCE::getCurrentEntityColor, CapturedRenderingState.INSTANCE.getEntityColorNotifier()); } public static void generalCommonUniforms(UniformHolder uniforms, FrameUpdateNotifier updateNotifier, PackDirectives directives) { ExternallyManagedUniforms.addExternallyManagedUniforms116(uniforms); final SmoothedVec2f eyeBrightnessSmooth = new SmoothedVec2f(directives.getEyeBrightnessHalfLife(), directives.getEyeBrightnessHalfLife(), CommonUniforms::getEyeBrightness, updateNotifier); uniforms .uniform1f(ONCE, "darknessFactor", () -> 0.0F) // This is PER_FRAME in modern, it is an effect added by The Warden. We're just setting to 0 because 1.7.10 doesn't have it. .uniform1f(ONCE, "darknessLightFactor", () -> 0.0F) // Warden darkness current light factor - 1.7.10 doesn't have it so hardcode to 0 .uniform1b(PER_FRAME, "hideGUI", () -> client.gameSettings.hideGUI) .uniform1i(PER_FRAME, "isEyeInWater", CommonUniforms::isEyeInWater) .uniform1f(PER_FRAME, "blindness", CommonUniforms::getBlindness) .uniform1f(PER_FRAME, "nightVision", CommonUniforms::getNightVision) .uniform1b(PER_FRAME, "is_sneaking", CommonUniforms::isSneaking) .uniform1b(PER_FRAME, "is_sprinting", CommonUniforms::isSprinting) .uniform1b(PER_FRAME, "is_hurt", CommonUniforms::isHurt) .uniform1b(PER_FRAME, "is_invisible", CommonUniforms::isInvisible) .uniform1b(PER_FRAME, "is_burning", CommonUniforms::isBurning) .uniform1b(PER_FRAME, "is_on_ground", CommonUniforms::isOnGround) // TODO: Do we need to clamp this to avoid fullbright breaking shaders? Or should shaders be able to detect // that the player is trying to turn on fullbright? .uniform1f(PER_FRAME, "screenBrightness", () -> client.gameSettings.gammaSetting) // just a dummy value for shaders where entityColor isn't supplied through a vertex attribute (and thus is // not available) - suppresses warnings. See AttributeShaderTransformer for the actual entityColor code. .uniform1f(PER_TICK, "playerMood", CommonUniforms::getPlayerMood) .uniform2i(PER_FRAME, "eyeBrightness", CommonUniforms::getEyeBrightness) .uniform2i(PER_FRAME, "eyeBrightnessSmooth", () -> { final Vector2f smoothed = eyeBrightnessSmooth.get(); 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, "fogColor", GLStateManager::getFogColor); } private static boolean isOnGround() { return client.thePlayer != null && client.thePlayer.onGround; } private static boolean isHurt() { // Do not use isHurt, that's not what we want! return (client.thePlayer != null && client.thePlayer.hurtTime > 0); } private static boolean isInvisible() { return (client.thePlayer != null && client.thePlayer.isInvisible()); } private static boolean isBurning() { return client.thePlayer != null && client.thePlayer.fire > 0 && !client.thePlayer.isImmuneToFire(); } private static boolean isSneaking() { return (client.thePlayer != null && client.thePlayer.isSneaking()); } private static boolean isSprinting() { return (client.thePlayer != null && client.thePlayer.isSprinting()); } private static Vector3d getSkyColor() { if (client.theWorld == null || client.renderViewEntity == null) { return ZERO_VECTOR_3d; } final Vec3 skyColor = client.theWorld.getSkyColor(client.renderViewEntity, CapturedRenderingState.INSTANCE.getTickDelta()); return new Vector3d(skyColor.xCoord, skyColor.yCoord, skyColor.zCoord); } static float getBlindness() { final EntityLivingBase cameraEntity = client.renderViewEntity; if (cameraEntity instanceof EntityPlayer livingEntity && livingEntity.isPotionActive(Potion.blindness)) { final PotionEffect blindness = livingEntity.getActivePotionEffect(Potion.blindness); if (blindness != null) { // Guessing that this is what OF uses, based on how vanilla calculates the fog value in BackgroundRenderer // TODO: Add this to ShaderDoc return Math.clamp(0.0F, 1.0F, blindness.getDuration() / 20.0F); } } return 0.0F; } private static float getPlayerMood() { // TODO: What should this be? return 0.0F; // if (!(client.cameraEntity instanceof LocalPlayer)) { // return 0.0F; // } // // // This should always be 0 to 1 anyways but just making sure // return Math.clamp(0.0F, 1.0F, ((LocalPlayer) client.cameraEntity).getCurrentMood()); } static float getRainStrength() { if (client.theWorld == null) { return 0f; } // Note: Ensure this is in the range of 0 to 1 - some custom servers send out of range values. return Math.clamp(0.0F, 1.0F, client.theWorld.getRainStrength(CapturedRenderingState.INSTANCE.getTickDelta())); } private static Vector2i getEyeBrightness() { if (client.renderViewEntity == null || client.theWorld == null) { return ZERO_VECTOR_2i; } // This is what ShadersMod did in 1.7.10 final int eyeBrightness = client.renderViewEntity.getBrightnessForRender(CapturedRenderingState.INSTANCE.getTickDelta()); return new Vector2i((eyeBrightness & 0xffff), (eyeBrightness >> 16)); // Vec3 feet = client.cameraEntity.position(); // Vec3 eyes = new Vec3(feet.x, client.cameraEntity.getEyeY(), feet.z); // BlockPos eyeBlockPos = new BlockPos(eyes); // // int blockLight = client.level.getBrightness(LightLayer.BLOCK, eyeBlockPos); // int skyLight = client.level.getBrightness(LightLayer.SKY, eyeBlockPos); // // return new Vector2i(blockLight * 16, skyLight * 16); } private static float getNightVision() { Entity cameraEntity = client.renderViewEntity; if (cameraEntity instanceof EntityPlayer entityPlayer) { if (!entityPlayer.isPotionActive(Potion.nightVision)) { return 0.0F; } float nightVisionStrength = ((EntityRendererAccessor)client.entityRenderer).invokeGetNightVisionBrightness(entityPlayer, CapturedRenderingState.INSTANCE.getTickDelta()); try { if (nightVisionStrength > 0) { // Just protecting against potential weird mod behavior return Math.clamp(0.0F, 1.0F, nightVisionStrength); } } catch (NullPointerException e) { return 0.0F; } } return 0.0F; } static int isEyeInWater() { if (client.gameSettings.thirdPersonView == 0 && !client.renderViewEntity.isPlayerSleeping()) { if (client.thePlayer.isInsideOfMaterial(Material.water)) return 1; else if (client.thePlayer.isInsideOfMaterial(Material.lava)) return 2; } return 0; } static { GbufferPrograms.init(); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\ExternallyManagedUniforms.java
package net.coderbot.iris.uniforms; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformType; public class ExternallyManagedUniforms { private ExternallyManagedUniforms() { // no construction allowed } public static void addExternallyManagedUniforms(UniformHolder uniformHolder) { addMat4(uniformHolder, "iris_ModelViewMatrix"); addMat4(uniformHolder, "u_ModelViewProjectionMatrix"); addMat4(uniformHolder, "iris_NormalMatrix"); // 1.21.6+ uniformHolder.externallyManagedUniform("heavyFog", UniformType.BOOL); } public static void addExternallyManagedUniforms116(UniformHolder uniformHolder) { addExternallyManagedUniforms(uniformHolder); uniformHolder.externallyManagedUniform("u_ModelScale", UniformType.VEC3); uniformHolder.externallyManagedUniform("u_TextureScale", UniformType.VEC2); } public static void addExternallyManagedUniforms117(UniformHolder uniformHolder) { addExternallyManagedUniforms(uniformHolder); // Sodium addFloat(uniformHolder, "iris_FogStart"); addFloat(uniformHolder, "iris_FogEnd"); addVec4(uniformHolder, "iris_FogColor"); addMat4(uniformHolder, "iris_ProjectionMatrix"); addFloat(uniformHolder, "u_TextureScale"); addFloat(uniformHolder, "u_ModelScale"); addFloat(uniformHolder, "iris_ModelOffset"); uniformHolder.externallyManagedUniform("iris_CameraTranslation", UniformType.VEC3); // Vanilla uniformHolder.externallyManagedUniform("iris_TextureMat", UniformType.MAT4); uniformHolder.externallyManagedUniform("iris_ModelViewMat", UniformType.MAT4); uniformHolder.externallyManagedUniform("iris_ProjMat", UniformType.MAT4); uniformHolder.externallyManagedUniform("iris_ChunkOffset", UniformType.VEC3); uniformHolder.externallyManagedUniform("iris_ColorModulator", UniformType.VEC4); uniformHolder.externallyManagedUniform("iris_FogStart", UniformType.FLOAT); uniformHolder.externallyManagedUniform("iris_FogEnd", UniformType.FLOAT); uniformHolder.externallyManagedUniform("iris_FogDensity", UniformType.FLOAT); uniformHolder.externallyManagedUniform("iris_LineWidth", UniformType.FLOAT); uniformHolder.externallyManagedUniform("iris_ScreenSize", UniformType.VEC2); uniformHolder.externallyManagedUniform("iris_FogColor", UniformType.VEC4); } private static void addMat4(UniformHolder uniformHolder, String name) { uniformHolder.externallyManagedUniform(name, UniformType.MAT4); } private static void addVec4(UniformHolder uniformHolder, String name) { uniformHolder.externallyManagedUniform(name, UniformType.VEC4); } private static void addFloat(UniformHolder uniformHolder, String name) { uniformHolder.externallyManagedUniform(name, UniformType.FLOAT); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\FogUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.glsm.GLStateManager; import net.coderbot.iris.gl.state.StateUpdateNotifiers; import net.coderbot.iris.gl.uniform.DynamicUniformHolder; public class FogUniforms { private FogUniforms() { // no construction } public static void addFogUniforms(DynamicUniformHolder uniforms) { uniforms.uniform1i("fogMode", () -> { if(!GLStateManager.getFogMode().isEnabled()) return 0; return GLStateManager.getFogState().getFogMode(); }, listener -> { StateUpdateNotifiers.fogToggleNotifier.setListener(listener); StateUpdateNotifiers.fogModeNotifier.setListener(listener); }); uniforms.uniform1f("fogDensity", () -> GLStateManager.getFogState().getDensity(), listener -> { StateUpdateNotifiers.fogToggleNotifier.setListener(listener); StateUpdateNotifiers.fogDensityNotifier.setListener(listener); }); uniforms.uniform1f("fogStart", () -> GLStateManager.getFogState().getStart(), listener -> { StateUpdateNotifiers.fogToggleNotifier.setListener(listener); StateUpdateNotifiers.fogStartNotifier.setListener(listener); }); uniforms.uniform1f("fogEnd", () -> GLStateManager.getFogState().getEnd(), listener -> { StateUpdateNotifiers.fogToggleNotifier.setListener(listener); StateUpdateNotifiers.fogEndNotifier.setListener(listener); }); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\FrameUpdateNotifier.java
package net.coderbot.iris.uniforms; import java.util.ArrayList; import java.util.List; public class FrameUpdateNotifier { private final List<Runnable> listeners; public FrameUpdateNotifier() { listeners = new ArrayList<>(); } public void addListener(Runnable onNewFrame) { listeners.add(onNewFrame); } public void onNewFrame() { listeners.forEach(Runnable::run); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\HardcodedCustomUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.config.AngelicaConfig; import com.gtnewhorizons.angelica.rendering.RenderingState; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.coderbot.iris.uniforms.transforms.SmoothedFloat; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.player.EntityPlayer; import org.joml.Math; import org.joml.Vector3d; // These expressions are copied directly from BSL and Complementary. // TODO: Remove once custom uniforms are actually supported, this is just a temporary thing to get BSL & Complementary // mostly working under Iris. public class HardcodedCustomUniforms { private static final Minecraft client = Minecraft.getMinecraft(); // TODO: Biome // private static Biome storedBiome; public static void addHardcodedCustomUniforms(UniformHolder holder, FrameUpdateNotifier updateNotifier) { updateNotifier.addListener(() -> { // if (Minecraft.getMinecraft().level != null) { // storedBiome = Minecraft.getMinecraft().level.getBiome(Minecraft.getMinecraft().getCameraEntity().blockPosition()); // } else { // storedBiome = null; // } }); CameraUniforms.CameraPositionTracker tracker = new CameraUniforms.CameraPositionTracker(updateNotifier); final SmoothedFloat eyeInCave = new SmoothedFloat(6, 12, HardcodedCustomUniforms::getEyeInCave, updateNotifier); final SmoothedFloat rainStrengthS = rainStrengthS(updateNotifier, 15, 15); final SmoothedFloat rainStrengthShining = rainStrengthS(updateNotifier, 10, 11); final SmoothedFloat rainStrengthS2 = rainStrengthS(updateNotifier, 70, 1); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "timeAngle", HardcodedCustomUniforms::getTimeAngle); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "timeBrightness", HardcodedCustomUniforms::getTimeBrightness); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "moonBrightness", HardcodedCustomUniforms::getMoonBrightness); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "shadowFade", HardcodedCustomUniforms::getShadowFade); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "rainStrengthS", rainStrengthS); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "rainStrengthShiningStars", rainStrengthShining); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "rainStrengthS2", rainStrengthS2); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "blindFactor", HardcodedCustomUniforms::getBlindFactor); // The following uniforms are Complementary specific, used for the biome check and starter/TAA features. holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "isDry", new SmoothedFloat(20, 10, () -> getRawPrecipitation() == 0 ? 1 : 0, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "isRainy", new SmoothedFloat(20, 10, () -> getRawPrecipitation() == 1 ? 1 : 0, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "isSnowy", new SmoothedFloat(20, 10, () -> getRawPrecipitation() == 2 ? 1 : 0, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "isEyeInCave", () -> CommonUniforms.isEyeInWater() == 0 ? eyeInCave.getAsFloat() : 0); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "velocity", () -> getVelocity(tracker)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "starter", getStarter(tracker, updateNotifier)); // The following uniforms are Project Reimagined specific. holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "frameTimeSmooth", new SmoothedFloat(5, 5, SystemTimeUniforms.TIMER::getLastFrameTime, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "eyeBrightnessM", new SmoothedFloat(5, 5, HardcodedCustomUniforms::getEyeBrightnessM, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "rainFactor", rainStrengthS); // The following uniforms are Sildur's specific. holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "inSwamp", new SmoothedFloat(5, 5, () -> { return 0; // if (storedBiome == null) { // return 0; // } else { // return storedBiome.getBiomeCategory() == Biome.BiomeCategory.SWAMP ? 1 : 0; // } }, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "BiomeTemp", () -> { return 0; // if (storedBiome == null) { // return 0; // } else { // return storedBiome.getTemperature(Minecraft.getMinecraft().getCameraEntity().blockPosition()); // } }); // The following uniforms are specific to Super Duper Vanilla Shaders. holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "day", HardcodedCustomUniforms::getDay); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "night", HardcodedCustomUniforms::getNight); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "dawnDusk", HardcodedCustomUniforms::getDawnDusk); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "shdFade", HardcodedCustomUniforms::getShdFade); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "isPrecipitationRain", new SmoothedFloat(6, 6, () -> (getRawPrecipitation() == 1 && tracker.getCurrentCameraPosition().y < 96.0f) ? 1 : 0, updateNotifier)); // The following uniforms are specific to AstralEX, and require an active player. holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "touchmybody", new SmoothedFloat(0f, 0.1f, HardcodedCustomUniforms::getHurtFactor, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "sneakSmooth", new SmoothedFloat(2.0f, 0.9f, HardcodedCustomUniforms::getSneakFactor, updateNotifier)); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "burningSmooth", new SmoothedFloat(1.0f, 2.0f, HardcodedCustomUniforms::getBurnFactor, updateNotifier)); final SmoothedFloat smoothSpeed = new SmoothedFloat(1.0f, 1.5f, () -> getVelocity(tracker) / SystemTimeUniforms.TIMER.getLastFrameTime(), updateNotifier); holder.uniform1f(UniformUpdateFrequency.PER_FRAME, "effectStrength", () -> getHyperSpeedStrength(smoothSpeed)); } private static float getHyperSpeedStrength(SmoothedFloat smoothSpeed) { return (float) (1.0f - Math.exp(-smoothSpeed.getAsFloat() * 0.003906f)); } private static float getBurnFactor() { final EntityPlayer player = Minecraft.getMinecraft().thePlayer; return player.fire > 0 && !player.isImmuneToFire() ? 1.0f : 0f; } private static float getSneakFactor() { return Minecraft.getMinecraft().thePlayer.isSneaking() ? 1.0f : 0f; } private static float getHurtFactor() { final EntityPlayer player = Minecraft.getMinecraft().thePlayer; return player.hurtTime > 0 || player.deathTime > 0 ? 0.4f : 0f; } private static float getEyeInCave() { final Vector3d cameraPosition = RenderingState.INSTANCE.getCameraPosition(); if (cameraPosition.y < 5.0) { return 1.0f - getEyeSkyBrightness() / 240F; } return 0.0f; } private static float getEyeBrightnessM() { return getEyeSkyBrightness() / 240F; } private static float getEyeSkyBrightness() { final int eyeBrightness = client.renderViewEntity.getBrightnessForRender(CapturedRenderingState.INSTANCE.getTickDelta()); return (eyeBrightness & 0xffff); // if (client.cameraEntity == null || client.level == null) { // return 0; // } // Vec3 feet = client.cameraEntity.position(); // Vec3 eyes = new Vec3(feet.x, client.cameraEntity.getEyeY(), feet.z); // BlockPos eyeBlockPos = new BlockPos(eyes); // // int skyLight = client.level.getBrightness(LightLayer.SKY, eyeBlockPos); // // return skyLight * 16; } 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); } private static SmoothedFloat getStarter(CameraUniforms.CameraPositionTracker tracker, FrameUpdateNotifier notifier) { return new SmoothedFloat(20, 20, new SmoothedFloat(0, 31536000, () -> getMoving(tracker), notifier), notifier); } private static float getMoving(CameraUniforms.CameraPositionTracker tracker) { final float difX = (float) (tracker.getCurrentCameraPosition().x - tracker.getPreviousCameraPosition().x); final float difY = (float) (tracker.getCurrentCameraPosition().y - tracker.getPreviousCameraPosition().y); final float difZ = (float) (tracker.getCurrentCameraPosition().z - tracker.getPreviousCameraPosition().z); final float difSum = Math.abs(difX) + Math.abs(difY) + Math.abs(difZ); return (difSum > 0.0F && difSum < 1.0F) ? 1 : 0; } private static float getTimeAngle() { return getWorldDayTime() / 24000F; } private static int getWorldDayTime() { final WorldClient world = Minecraft.getMinecraft().theWorld; return (int) ((AngelicaConfig.useTotalWorldTime ? world.getTotalWorldTime() : world.getWorldTime()) % 24000L); // Level level = Minecraft.getMinecraft().theWorld; // long timeOfDay = level.getDayTime(); // long dayTime = ((DimensionTypeAccessor) level.dimensionType()).getFixedTime().orElse(timeOfDay % 24000L); } private static float getTimeBrightness() { 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); } private static float getShadowFade() { return (float) Math.clamp(0.0, 1.0, 1.0 - (java.lang.Math.abs(java.lang.Math.abs(CelestialUniforms.getSunAngle() - 0.5) - 0.25) - 0.23) * 100.0); } private static SmoothedFloat rainStrengthS(FrameUpdateNotifier updateNotifier, float halfLifeUp, float halfLifeDown) { return new SmoothedFloat(halfLifeUp, halfLifeDown, CommonUniforms::getRainStrength, updateNotifier); } private static float getRawPrecipitation() { // TODO: Biome // if (storedBiome == null) { // return 0; // } return 0; // Biome.Precipitation precipitation = storedBiome.getPrecipitation(); // return switch (precipitation) { // case RAIN -> 1; // case SNOW -> 2; // default -> 0; // }; } private static float getBlindFactor() { float blindFactorSqrt = (float) Math.clamp(0.0, 1.0, CommonUniforms.getBlindness() * 2.0 - 1.0); return blindFactorSqrt * blindFactorSqrt; } private static float getAdjTime() { return Math.abs(((((WorldTimeUniforms.getWorldDayTime()) / 1000.0f) + 6.0f) % 24.0f) - 12.0f); } private static float getDay() { return Math.clamp(0.0f, 1.0f, 5.4f - getAdjTime()); } private static float getNight() { return Math.clamp(0.0f, 1.0f, getAdjTime() - 6.0f); } private static float getDawnDusk() { return (1.0f - getDay()) - getNight(); } private static float getShdFade() { return (float) Math.clamp(0.0, 1.0, 1.0 - (Math.abs(Math.abs(CelestialUniforms.getSunAngle() - 0.5) - 0.25) - 0.225) * 40.0); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\IdMapUniforms.java
package net.coderbot.iris.uniforms; import it.unimi.dsi.fastutil.objects.Object2IntFunction; import com.gtnewhorizons.angelica.compat.mojang.InteractionHand; 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.shaderpack.IdMap; import net.coderbot.iris.shaderpack.materialmap.NamespacedId; import net.irisshaders.iris.api.v0.item.IrisItemLightProvider; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.jetbrains.annotations.NotNull; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public final class IdMapUniforms { private IdMapUniforms() { } public static void addIdMapUniforms(FrameUpdateNotifier notifier, UniformHolder uniforms, IdMap idMap, boolean isOldHandLight) { HeldItemSupplier mainHandSupplier = new HeldItemSupplier(InteractionHand.MAIN_HAND, idMap.getItemIdMap(), isOldHandLight); HeldItemSupplier offHandSupplier = new HeldItemSupplier(InteractionHand.OFF_HAND, idMap.getItemIdMap(), false); notifier.addListener(mainHandSupplier::update); notifier.addListener(offHandSupplier::update); uniforms .uniform1i(UniformUpdateFrequency.PER_FRAME, "heldItemId", mainHandSupplier::getIntID) .uniform1i(UniformUpdateFrequency.PER_FRAME, "heldItemId2", offHandSupplier::getIntID) .uniform1i(PER_FRAME, "heldBlockLightValue", mainHandSupplier::getLightValue) .uniform1i(PER_FRAME, "heldBlockLightValue2", offHandSupplier::getLightValue); // TODO: Figure out API. //.uniformVanilla3f(PER_FRAME, "heldBlockLightColor", mainHandSupplier::getLightColor) //.uniformVanilla3f(PER_FRAME, "heldBlockLightColor2", offHandSupplier::getLightColor); } public static void addEntityIdMapUniforms(DynamicUniformHolder uniforms) { uniforms.uniform1i("entityId", CapturedRenderingState.INSTANCE::getCurrentRenderedEntity, CapturedRenderingState.INSTANCE.getEntityIdNotifier()); uniforms.uniform1i("blockEntityId", CapturedRenderingState.INSTANCE::getCurrentRenderedBlockEntity, CapturedRenderingState.INSTANCE.getBlockEntityIdNotifier()); } /** * Provides the currently held item, and it's light value, in the given hand as a uniform. Uses the item.properties ID map to map the item * to an integer, and the old hand light value to map offhand to main hand. */ private static class HeldItemSupplier { private final InteractionHand hand; private final Object2IntFunction<NamespacedId> itemIdMap; private final boolean applyOldHandLight; private int intID; private int lightValue; HeldItemSupplier(InteractionHand hand, Object2IntFunction<NamespacedId> itemIdMap, boolean shouldApplyOldHandLight) { this.hand = hand; this.itemIdMap = itemIdMap; this.applyOldHandLight = shouldApplyOldHandLight && hand == InteractionHand.MAIN_HAND; } private void invalidate() { intID = -1; lightValue = 0; } public void update() { EntityPlayer player = Minecraft.getMinecraft().thePlayer; if (player == null) { // Not valid when the player doesn't exist invalidate(); return; } ItemStack heldStack = hand.getItemInHand(player); if (heldStack == null) { invalidate(); return; } Item heldItem = heldStack.getItem(); if (heldItem == null) { invalidate(); return; } ResourceLocation heldItemId = new ResourceLocation(Item.itemRegistry.getNameForObject(heldItem)); intID = itemIdMap.applyAsInt(new NamespacedId(heldItemId.getResourceDomain(), heldItemId.getResourcePath())); IrisItemLightProvider lightProvider = (IrisItemLightProvider) heldItem; lightValue = lightProvider.getLightEmission(Minecraft.getMinecraft().thePlayer, heldStack); if (applyOldHandLight) { lightProvider = applyOldHandLighting(player, lightProvider); } } private IrisItemLightProvider applyOldHandLighting(@NotNull EntityPlayer player, IrisItemLightProvider existing) { ItemStack offHandStack = InteractionHand.OFF_HAND.getItemInHand(player); if (offHandStack == null) { return existing; } Item offHandItem = offHandStack.getItem(); if (offHandItem == null) { return existing; } IrisItemLightProvider lightProvider = (IrisItemLightProvider) offHandItem; int newEmission = lightProvider.getLightEmission(Minecraft.getMinecraft().thePlayer, offHandStack); if (lightValue < newEmission) { lightValue = newEmission; return lightProvider; } return existing; } public int getIntID() { return intID; } public int getLightValue() { return lightValue; } } }
Angelica
src\main\java\net\coderbot\iris\uniforms\IrisExclusiveUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.compat.mojang.Camera; import com.gtnewhorizons.angelica.compat.mojang.GameModeUtil; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.effect.EntityLightningBolt; import org.joml.Math; import org.joml.Vector3d; import org.joml.Vector3dc; import org.joml.Vector4f; import java.util.List; public class IrisExclusiveUniforms { // Reusable vectors to avoid allocations every frame private static final Vector3d eyePositionCache = new Vector3d(); private static final Vector3d relativeEyePositionCache = new Vector3d(); private static final Vector4f lightningBoltPositionCache = new Vector4f(); private static final Vector4f ZERO_VECTOR_4f = new Vector4f(0, 0, 0, 0); public static void addIrisExclusiveUniforms(UniformHolder uniforms) { WorldInfoUniforms.addWorldInfoUniforms(uniforms); //All Iris-exclusive uniforms (uniforms which do not exist in either OptiFine or ShadersMod) should be registered here. uniforms.uniform1f(UniformUpdateFrequency.PER_FRAME, "thunderStrength", IrisExclusiveUniforms::getThunderStrength); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "currentPlayerHealth", IrisExclusiveUniforms::getCurrentHealth); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "maxPlayerHealth", IrisExclusiveUniforms::getMaxHealth); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "currentPlayerHunger", IrisExclusiveUniforms::getCurrentHunger); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "maxPlayerHunger", () -> 20); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "currentPlayerAir", IrisExclusiveUniforms::getCurrentAir); uniforms.uniform1f(UniformUpdateFrequency.PER_TICK, "maxPlayerAir", IrisExclusiveUniforms::getMaxAir); uniforms.uniform1b(UniformUpdateFrequency.PER_FRAME, "firstPersonCamera", IrisExclusiveUniforms::isFirstPersonCamera); uniforms.uniform1b(UniformUpdateFrequency.PER_TICK, "isSpectator", IrisExclusiveUniforms::isSpectator); uniforms.uniform1b(UniformUpdateFrequency.PER_TICK, "isRightHanded", () -> true); // 1.7.10 doesn't support left-handed mode uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "eyePosition", IrisExclusiveUniforms::getEyePosition); uniforms.uniform3d(UniformUpdateFrequency.PER_FRAME, "relativeEyePosition", IrisExclusiveUniforms::getRelativeEyePosition); uniforms.uniform4f(UniformUpdateFrequency.PER_TICK, "lightningBoltPosition", IrisExclusiveUniforms::getLightningBoltPosition); } private static float getThunderStrength() { // Note: Ensure this is in the range of 0 to 1 - some custom servers send out of range values. return Math.clamp(0.0F, 1.0F, Minecraft.getMinecraft().theWorld.thunderingStrength); } private static float getCurrentHealth() { if (Minecraft.getMinecraft().thePlayer == null || !Minecraft.getMinecraft().playerController.gameIsSurvivalOrAdventure()) { return -1; } return Minecraft.getMinecraft().thePlayer.getHealth() / Minecraft.getMinecraft().thePlayer.getMaxHealth(); } private static float getCurrentHunger() { if (Minecraft.getMinecraft().thePlayer == null || !Minecraft.getMinecraft().playerController.gameIsSurvivalOrAdventure()) { return -1; } return Minecraft.getMinecraft().thePlayer.getFoodStats().getFoodLevel() / 20f; } private static float getCurrentAir() { if (Minecraft.getMinecraft().thePlayer == null || !Minecraft.getMinecraft().playerController.gameIsSurvivalOrAdventure()) { return -1; } return (float) Minecraft.getMinecraft().thePlayer.getAir() / (float) Minecraft.getMinecraft().thePlayer.getAir(); } private static float getMaxAir() { if (Minecraft.getMinecraft().thePlayer == null || !Minecraft.getMinecraft().playerController.gameIsSurvivalOrAdventure()) { return -1; } // return Minecraft.getMinecraft().thePlayer.getMaxAirSupply(); return 300.0F; } private static float getMaxHealth() { if (Minecraft.getMinecraft().thePlayer == null || !Minecraft.getMinecraft().playerController.gameIsSurvivalOrAdventure()) { return -1; } return Minecraft.getMinecraft().thePlayer.getMaxHealth(); } private static boolean isFirstPersonCamera() { // If camera type is not explicitly third-person, assume it's first-person. return !Camera.INSTANCE.isThirdPerson(); } private static boolean isSpectator() { return GameModeUtil.isSpectator(); } private static Vector3d getEyePosition() { final EntityLivingBase eye = Minecraft.getMinecraft().renderViewEntity; return eyePositionCache.set(eye.posX, eye.posY + eye.getEyeHeight(), eye.posZ); } private static Vector3d getRelativeEyePosition() { final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition(); final Vector3d eyePos = getEyePosition(); return relativeEyePositionCache.set(eyePos).sub(cameraPos); } private static Vector4f getLightningBoltPosition() { if (Minecraft.getMinecraft().theWorld != null) { final List<Entity> weatherEffects = Minecraft.getMinecraft().theWorld.weatherEffects; for (Entity entity : weatherEffects) { if (entity instanceof EntityLightningBolt bolt) { final Vector3dc cameraPos = CameraUniforms.getUnshiftedCameraPosition(); return lightningBoltPositionCache.set( (float)(bolt.posX - cameraPos.x()), (float)(bolt.posY - cameraPos.y()), (float)(bolt.posZ - cameraPos.z()), 1.0f ); } } } return ZERO_VECTOR_4f; } public static class WorldInfoUniforms { public static void addWorldInfoUniforms(UniformHolder uniforms) { final WorldClient level = Minecraft.getMinecraft().theWorld; uniforms.uniform1i(UniformUpdateFrequency.PER_FRAME, "bedrockLevel", () -> 0); uniforms.uniform1f(UniformUpdateFrequency.PER_FRAME, "cloudHeight", () -> { if (level != null && level.provider != null) { return level.provider.getCloudHeight(); } else { return 192.0; } }); uniforms.uniform1i(UniformUpdateFrequency.PER_FRAME, "heightLimit", () -> { if (level != null && level.provider != null) { return level.provider.getHeight(); } else { return 256; } }); uniforms.uniform1b(UniformUpdateFrequency.PER_FRAME, "hasCeiling", () -> { if (level != null && level.provider != null) { return level.provider.hasNoSky; } else { return false; } }); uniforms.uniform1b(UniformUpdateFrequency.PER_FRAME, "hasSkylight", () -> { if (level != null && level.provider != null) { return !level.provider.hasNoSky; } else { return true; } }); uniforms.uniform1f(UniformUpdateFrequency.PER_FRAME, "ambientLight", () -> { if (level != null && level.provider != null) { return level.provider.lightBrightnessTable[0]; } else { return 0f; } }); } } }
Angelica
src\main\java\net\coderbot\iris\uniforms\MatrixUniforms.java
package net.coderbot.iris.uniforms; import com.gtnewhorizons.angelica.rendering.RenderingState; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.pipeline.ShadowRenderer; import net.coderbot.iris.shaderpack.PackDirectives; import net.coderbot.iris.shadow.ShadowMatrices; import org.joml.Matrix4f; import java.util.function.Supplier; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; public final class MatrixUniforms { private MatrixUniforms() { } public static void addMatrixUniforms(UniformHolder uniforms, PackDirectives directives) { addMatrix(uniforms, "ModelView", RenderingState.INSTANCE::getModelViewMatrix); // TODO: In some cases, gbufferProjectionInverse takes on a value much different than OptiFine... // We need to audit Mojang's linear algebra. addMatrix(uniforms, "Projection", RenderingState.INSTANCE::getProjectionMatrix); addShadowMatrix(uniforms, "ModelView", () -> ShadowRenderer.createShadowModelView(directives.getSunPathRotation(), directives.getShadowDirectives().getIntervalSize()).peek().getModel()); addShadowMatrix(uniforms, "Projection", () -> ShadowMatrices.createOrthoMatrix(directives.getShadowDirectives().getDistance())); } private static void addMatrix(UniformHolder uniforms, String name, Supplier<Matrix4f> supplier) { uniforms .uniformMatrix(PER_FRAME, "gbuffer" + name, supplier) .uniformMatrix(PER_FRAME, "gbuffer" + name + "Inverse", new Inverted(supplier)) .uniformMatrix(PER_FRAME, "gbufferPrevious" + name, new Previous(supplier)); } private static void addShadowMatrix(UniformHolder uniforms, String name, Supplier<Matrix4f> supplier) { uniforms .uniformMatrix(PER_FRAME, "shadow" + name, supplier) .uniformMatrix(PER_FRAME, "shadow" + name + "Inverse", new Inverted(supplier)); } private static class Inverted implements Supplier<Matrix4f> { private final Supplier<Matrix4f> parent; Inverted(Supplier<Matrix4f> parent) { this.parent = parent; } @Override public Matrix4f get() { // PERF: Don't copy + allocate this matrix every time? final Matrix4f copy = new Matrix4f(parent.get()); copy.invert(); return copy; } } private static class Previous implements Supplier<Matrix4f> { private final Supplier<Matrix4f> parent; private Matrix4f previous; Previous(Supplier<Matrix4f> parent) { this.parent = parent; this.previous = new Matrix4f(); } @Override public Matrix4f get() { // PERF: Don't copy + allocate these matrices every time? final Matrix4f copy = new Matrix4f(parent.get()); final Matrix4f prev = new Matrix4f(this.previous); this.previous = copy; return prev; } } }
Angelica
src\main\java\net\coderbot\iris\uniforms\SystemTimeUniforms.java
package net.coderbot.iris.uniforms; import lombok.Getter; import net.coderbot.iris.gl.uniform.UniformHolder; import net.coderbot.iris.gl.uniform.UniformUpdateFrequency; import java.util.OptionalLong; import java.util.function.IntSupplier; /** * Implements uniforms relating the system time (as opposed to the world time) * * @see <a href="https://github.com/IrisShaders/ShaderDoc/blob/master/uniforms.md#system-time">Uniforms: System time</a> */ public final class SystemTimeUniforms { public static final Timer TIMER = new Timer(); public static final FrameCounter COUNTER = new FrameCounter(); private SystemTimeUniforms() { } /** * Makes system time uniforms available to the given program * * @param uniforms the program to make the uniforms available to */ public static void addSystemTimeUniforms(UniformHolder uniforms) { uniforms .uniform1i(UniformUpdateFrequency.PER_FRAME, "frameCounter", COUNTER) .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. */ public static class FrameCounter implements IntSupplier { private int count; private FrameCounter() { this.count = 0; } @Override public int getAsInt() { return count; } public void beginFrame() { count = (count + 1) % 720720; } public void reset() { count = 0; } } /** * Keeps track of the time that the last frame took to render as well as the number of milliseconds since the start * of the first frame to the start of the current frame. Updated at the start of each frame. */ public static final class Timer { @Getter private float frameTimeCounter; @Getter private float lastFrameTime; // Disabling this because OptionalLong provides a nice wrapper around (boolean valid, long value) @SuppressWarnings("OptionalUsedAsFieldOrParameterType") private OptionalLong lastStartTime; public Timer() { reset(); } public void beginFrame(long frameStartTime) { // Track how much time passed since the last time we began rendering a frame. // If this is the first frame, then use a value of 0. final long diffNs = frameStartTime - lastStartTime.orElse(frameStartTime); // Convert to milliseconds final long diffMs = (diffNs / 1000) / 1000; // Convert to seconds with a resolution of 1 millisecond, and store as the time taken for the last frame to complete. lastFrameTime = diffMs / 1000.0F; // Advance the current frameTimeCounter by the amount of time the last frame took. frameTimeCounter += lastFrameTime; // Prevent the frameTimeCounter from getting too large, since that causes issues with some shaderpacks // This means that it should reset every hour. if (frameTimeCounter >= 3600.0F) { frameTimeCounter = 0.0F; } // Finally, update the "last start time" value. lastStartTime = OptionalLong.of(frameStartTime); } public void reset() { frameTimeCounter = 0.0F; lastFrameTime = 0.0F; lastStartTime = OptionalLong.empty(); } } }
Angelica
src\main\java\net\coderbot\iris\uniforms\VanillaBiomeList.java
package net.coderbot.iris.uniforms; import net.minecraft.world.biome.BiomeGenBase; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class VanillaBiomeList { public static class BiomeEntry { public final BiomeGenBase biome; public final String name; public BiomeEntry(BiomeGenBase biome, String name) { this.biome = biome; this.name = name; } } private static final List<BiomeEntry> VANILLA_BIOMES = createVanillaBiomeList(); private static List<BiomeEntry> createVanillaBiomeList() { final List<BiomeEntry> biomes = new ArrayList<>(); // Vanilla biomes from BiomeGenBase static fields (IDs 0-39) biomes.add(new BiomeEntry(BiomeGenBase.ocean, "OCEAN")); biomes.add(new BiomeEntry(BiomeGenBase.plains, "PLAINS")); biomes.add(new BiomeEntry(BiomeGenBase.desert, "DESERT")); biomes.add(new BiomeEntry(BiomeGenBase.extremeHills, "EXTREME_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.forest, "FOREST")); biomes.add(new BiomeEntry(BiomeGenBase.taiga, "TAIGA")); biomes.add(new BiomeEntry(BiomeGenBase.swampland, "SWAMPLAND")); biomes.add(new BiomeEntry(BiomeGenBase.river, "RIVER")); biomes.add(new BiomeEntry(BiomeGenBase.hell, "HELL")); biomes.add(new BiomeEntry(BiomeGenBase.sky, "SKY")); biomes.add(new BiomeEntry(BiomeGenBase.frozenOcean, "FROZEN_OCEAN")); biomes.add(new BiomeEntry(BiomeGenBase.frozenRiver, "FROZEN_RIVER")); biomes.add(new BiomeEntry(BiomeGenBase.icePlains, "ICE_PLAINS")); biomes.add(new BiomeEntry(BiomeGenBase.iceMountains, "ICE_MOUNTAINS")); biomes.add(new BiomeEntry(BiomeGenBase.mushroomIsland, "MUSHROOM_ISLAND")); biomes.add(new BiomeEntry(BiomeGenBase.mushroomIslandShore, "MUSHROOM_ISLAND_SHORE")); biomes.add(new BiomeEntry(BiomeGenBase.beach, "BEACH")); biomes.add(new BiomeEntry(BiomeGenBase.desertHills, "DESERT_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.forestHills, "FOREST_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.taigaHills, "TAIGA_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.extremeHillsEdge, "EXTREME_HILLS_EDGE")); biomes.add(new BiomeEntry(BiomeGenBase.jungle, "JUNGLE")); biomes.add(new BiomeEntry(BiomeGenBase.jungleHills, "JUNGLE_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.jungleEdge, "JUNGLE_EDGE")); biomes.add(new BiomeEntry(BiomeGenBase.deepOcean, "DEEP_OCEAN")); biomes.add(new BiomeEntry(BiomeGenBase.stoneBeach, "STONE_BEACH")); biomes.add(new BiomeEntry(BiomeGenBase.coldBeach, "COLD_BEACH")); biomes.add(new BiomeEntry(BiomeGenBase.birchForest, "BIRCH_FOREST")); biomes.add(new BiomeEntry(BiomeGenBase.birchForestHills, "BIRCH_FOREST_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.roofedForest, "ROOFED_FOREST")); biomes.add(new BiomeEntry(BiomeGenBase.coldTaiga, "COLD_TAIGA")); biomes.add(new BiomeEntry(BiomeGenBase.coldTaigaHills, "COLD_TAIGA_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.megaTaiga, "MEGA_TAIGA")); biomes.add(new BiomeEntry(BiomeGenBase.megaTaigaHills, "MEGA_TAIGA_HILLS")); biomes.add(new BiomeEntry(BiomeGenBase.extremeHillsPlus, "EXTREME_HILLS_PLUS")); biomes.add(new BiomeEntry(BiomeGenBase.savanna, "SAVANNA")); biomes.add(new BiomeEntry(BiomeGenBase.savannaPlateau, "SAVANNA_PLATEAU")); biomes.add(new BiomeEntry(BiomeGenBase.mesa, "MESA")); biomes.add(new BiomeEntry(BiomeGenBase.mesaPlateau_F, "MESA_PLATEAU_F")); biomes.add(new BiomeEntry(BiomeGenBase.mesaPlateau, "MESA_PLATEAU")); // Modern End biome variants (1.9+) - all map to the single End biome in 1.7.10 // This allows shaders expecting these constants to work biomes.add(new BiomeEntry(BiomeGenBase.sky, "THE_END")); biomes.add(new BiomeEntry(BiomeGenBase.sky, "SMALL_END_ISLANDS")); biomes.add(new BiomeEntry(BiomeGenBase.sky, "END_MIDLANDS")); biomes.add(new BiomeEntry(BiomeGenBase.sky, "END_HIGHLANDS")); biomes.add(new BiomeEntry(BiomeGenBase.sky, "END_BARRENS")); return Collections.unmodifiableList(biomes); } /** * Returns the cached list of all vanilla biomes with their shader-friendly names. * The list is immutable and created once during class initialization. */ public static List<BiomeEntry> getVanillaBiomes() { return VANILLA_BIOMES; } }
Angelica
src\main\java\net\coderbot\iris\uniforms\ViewportUniforms.java
package net.coderbot.iris.uniforms; import net.coderbot.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_FRAME; /** * Implements uniforms relating the current viewport * * @see <a href="https://github.com/IrisShaders/ShaderDoc/blob/master/uniforms.md#viewport">Uniforms: Viewport</a> */ public final class ViewportUniforms { // cannot be constructed private ViewportUniforms() { } /** * Makes the viewport uniforms available to the given program * * @param uniforms the program to make the uniforms available to */ public static void addViewportUniforms(UniformHolder uniforms) { // TODO: What about the custom scale.composite3 property? // NB: It is not safe to cache the render target due to mods like Resolution Control modifying the render target field. uniforms .uniform1f(PER_FRAME, "viewHeight", () -> Minecraft.getMinecraft().getFramebuffer().framebufferHeight) .uniform1f(PER_FRAME, "viewWidth", () -> Minecraft.getMinecraft().getFramebuffer().framebufferWidth) .uniform1f(PER_FRAME, "aspectRatio", ViewportUniforms::getAspectRatio); } /** * @return the current viewport aspect ratio, calculated from the current Minecraft window size */ private static float getAspectRatio() { return ((float) Minecraft.getMinecraft().getFramebuffer().framebufferWidth) / ((float) Minecraft.getMinecraft().getFramebuffer().framebufferHeight); } }
Angelica
src\main\java\net\coderbot\iris\uniforms\WorldTimeUniforms.java
package net.coderbot.iris.uniforms; import static net.coderbot.iris.gl.uniform.UniformUpdateFrequency.PER_TICK; import com.gtnewhorizons.angelica.config.AngelicaConfig; import java.util.Objects; import net.coderbot.iris.gl.uniform.UniformHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; public final class WorldTimeUniforms { private WorldTimeUniforms() { } /** * Makes world time uniforms available to the given program * * @param uniforms the program to make the uniforms available to */ public static void addWorldTimeUniforms(UniformHolder uniforms) { uniforms .uniform1i(PER_TICK, "worldTime", WorldTimeUniforms::getWorldDayTime) .uniform1i(PER_TICK, "worldDay", WorldTimeUniforms::getWorldDay) .uniform1i(PER_TICK, "moonPhase", () -> getWorld().getMoonPhase()); } static int getWorldDayTime() { final WorldClient world = getWorld(); return (int) ((AngelicaConfig.useTotalWorldTime ? world.getTotalWorldTime() : world.getWorldTime()) % 24000L); // long dayTime = ((DimensionTypeAccessor) getWorld().dimensionType()).getFixedTime().orElse(timeOfDay % 24000L); } private static int getWorldDay() { return (int) (getWorld().getTotalWorldTime() / 24000L); } private static WorldClient getWorld() { return Objects.requireNonNull(Minecraft.getMinecraft().theWorld); } }
Angelica
src\main\java\net\coderbot\iris\vertices\BlockSensitiveBufferBuilder.java
package net.coderbot.iris.vertices; public interface BlockSensitiveBufferBuilder { void beginBlock(short block, short renderType, int localPosX, int localPosY, int localPosZ); void endBlock(); }
Angelica
src\main\java\net\coderbot\iris\vertices\BufferBuilderPolygonView.java
package net.coderbot.iris.vertices; import java.nio.ByteBuffer; public class BufferBuilderPolygonView implements IrisQuadView { private ByteBuffer buffer; private int writePointer; private int stride = 48; private int vertexAmount; public void setup(ByteBuffer buffer, int writePointer, int stride, int vertexAmount) { this.buffer = buffer; this.writePointer = writePointer; this.stride = stride; this.vertexAmount = vertexAmount; } @Override public float x(int index) { return buffer.getFloat(writePointer - stride * (vertexAmount - index)); } @Override public float y(int index) { return buffer.getFloat(writePointer + 4 - stride * (vertexAmount - index)); } @Override public float z(int index) { return buffer.getFloat(writePointer + 8 - stride * (vertexAmount - index)); } @Override public float u(int index) { return buffer.getFloat(writePointer + 16 - stride * (vertexAmount - index)); } @Override public float v(int index) { return buffer.getFloat(writePointer + 20 - stride * (vertexAmount - index)); } }
Angelica
src\main\java\net\coderbot\iris\vertices\ExtendedDataHelper.java
package net.coderbot.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. */ public static final short FLUID_RENDER_TYPE = 1; public static int packMidBlock(float x, float y, float z) { return ((int) (x * 64) & 0xFF) | (((int) (y * 64) & 0xFF) << 8) | (((int) (z * 64) & 0xFF) << 16); } public static int computeMidBlock(float x, float y, float z, int localPosX, int localPosY, int localPosZ) { return packMidBlock( localPosX + 0.5f - x, localPosY + 0.5f - y, localPosZ + 0.5f - z ); } }
Angelica
src\main\java\net\coderbot\iris\vertices\ExtendingBufferBuilder.java
package net.coderbot.iris.vertices; import com.gtnewhorizon.gtnhlib.client.renderer.vertex.VertexFormat; public interface ExtendingBufferBuilder { void iris$beginWithoutExtending(int drawMode, VertexFormat vertexFormat); }
Angelica
src\main\java\net\coderbot\iris\vertices\ImmediateState.java
package net.coderbot.iris.vertices; /** * Some annoying global state needed for the extended vertex format disabling optimization. */ public class ImmediateState { public static boolean isRenderingLevel = false; public static boolean renderWithExtendedVertexFormat = true; }
Angelica
src\main\java\net\coderbot\iris\vertices\IrisQuadView.java
package net.coderbot.iris.vertices; /** * Implementations of this class must support at least four vertices. */ public interface IrisQuadView extends TriView { }
Angelica
src\main\java\net\coderbot\iris\vertices\NormalHelper.java
package net.coderbot.iris.vertices; import org.joml.Vector3f; import org.joml.Math; import org.jetbrains.annotations.NotNull; public abstract class NormalHelper { private NormalHelper() { } /** * Stores a normal plus an extra value as a quartet of signed bytes. * This is the same normal format that vanilla item rendering expects. * The extra value is for use by shaders. */ public static int packNormal(float x, float y, float z, float w) { x = Math.clamp(x, -1, 1); y = Math.clamp(y, -1, 1); z = Math.clamp(z, -1, 1); w = Math.clamp(w, -1, 1); return ((int) (x * 127) & 0xFF) | (((int) (y * 127) & 0xFF) << 8) | (((int) (z * 127) & 0xFF) << 16) | (((int) (w * 127) & 0xFF) << 24); } /** * Version of {@link #packNormal(float, float, float, float)} that accepts a vector type. */ public static int packNormal(Vector3f normal, float w) { return packNormal(normal.x, normal.y, normal.z, w); } /** * Retrieves values packed by {@link #packNormal(float, float, float, float)}. * * <p>Components are x, y, z, w - zero based. */ public static float getPackedNormalComponent(int packedNormal, int component) { return ((byte) (packedNormal >> (8 * component))) / 127f; } /** * Computes the face normal of the given quad and saves it in the provided non-null vector. * * <p>Assumes counter-clockwise winding order, which is the norm. * Expects convex quads with all points co-planar. */ public static void computeFaceNormal(@NotNull Vector3f saveTo, IrisQuadView 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); final float x1 = q.x(1); final float y1 = q.y(1); final float z1 = q.z(1); final float x2 = q.x(2); final float y2 = q.y(2); final float z2 = q.z(2); final float x3 = q.x(3); final float y3 = q.y(3); final float z3 = q.z(3); final float dx0 = x2 - x0; final float dy0 = y2 - y0; final float dz0 = z2 - z0; final float dx1 = x3 - x1; final float dy1 = y3 - y1; final float dz1 = z3 - z1; float normX = dy0 * dz1 - dz0 * dy1; float normY = dz0 * dx1 - dx0 * dz1; float normZ = dx0 * dy1 - dy0 * dx1; float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); if (l != 0) { normX /= l; normY /= l; normZ /= l; } saveTo.set(normX, normY, normZ); } /** * Computes the face normal of the given tri and saves it in the provided non-null vector. * * <p>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); final float x1 = t.x(1); final float y1 = t.y(1); final float z1 = t.z(1); final float x2 = t.x(2); final float y2 = t.y(2); final float z2 = t.z(2); // note: subtraction order is significant here because of how the cross product works. // If we're wrong our calculated normal will be pointing in the opposite direction of how it should. // This current order is similar enough to the order in the quad variant. final float dx0 = x2 - x0; final float dy0 = y2 - y0; final float dz0 = z2 - z0; final float dx1 = x0 - x1; final float dy1 = y0 - y1; final float dz1 = z0 - z1; float normX = dy0 * dz1 - dz0 * dy1; float normY = dz0 * dx1 - dx0 * dz1; float normZ = dx0 * dy1 - dy0 * dx1; float l = (float) Math.sqrt(normX * normX + normY * normY + normZ * normZ); if (l != 0) { normX /= l; normY /= l; normZ /= l; } saveTo.set(normX, normY, normZ); } public static int computeTangentSmooth(float normalX, float normalY, float normalZ, TriView t) { // Capture all of the relevant vertex positions float x0 = t.x(0); float y0 = t.y(0); float z0 = t.z(0); float x1 = t.x(1); float y1 = t.y(1); float z1 = t.z(1); float x2 = t.x(2); float y2 = t.y(2); float z2 = t.z(2); // Project all vertices onto normal plane (for smooth normal support). Optionally skip this step for flat shading. // Procedure: // project v onto normal // offset v by the projection to get the point on the plane // project x0, y0, z0 onto normal float d0 = x0 * normalX + y0 * normalY + z0 * normalZ; float d1 = x1 * normalX + y1 * normalY + z1 * normalZ; float d2 = x2 * normalX + y2 * normalY + z2 * normalZ; // offset x, y, z by the projection to get the projected point on the normal plane x0 -= d0 * normalX; y0 -= d0 * normalY; z0 -= d0 * normalZ; x1 -= d1 * normalX; y1 -= d1 * normalY; z1 -= d1 * normalZ; x2 -= d2 * normalX; y2 -= d2 * normalY; z2 -= d2 * normalZ; float edge1x = x1 - x0; float edge1y = y1 - y0; float edge1z = z1 - z0; float edge2x = x2 - x0; float edge2y = y2 - y0; float edge2z = z2 - z0; float u0 = t.u(0); float v0 = t.v(0); float u1 = t.u(1); float v1 = t.v(1); float u2 = t.u(2); float v2 = t.v(2); float deltaU1 = u1 - u0; float deltaV1 = v1 - v0; float deltaU2 = u2 - u0; float deltaV2 = v2 - v0; float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1; float f; if (fdenom == 0.0) { f = 1.0f; } else { f = 1.0f / fdenom; } float tangentx = f * (deltaV2 * edge1x - deltaV1 * edge2x); float tangenty = f * (deltaV2 * edge1y - deltaV1 * edge2y); float tangentz = f * (deltaV2 * edge1z - deltaV1 * edge2z); float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz); tangentx *= tcoeff; tangenty *= tcoeff; tangentz *= tcoeff; float bitangentx = f * (-deltaU2 * edge1x + deltaU1 * edge2x); float bitangenty = f * (-deltaU2 * edge1y + deltaU1 * edge2y); float bitangentz = f * (-deltaU2 * edge1z + deltaU1 * edge2z); float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz); bitangentx *= bitcoeff; bitangenty *= bitcoeff; bitangentz *= bitcoeff; // predicted bitangent = tangent × normal // Compute the determinant of the following matrix to get the cross product // i j k // tx ty tz // nx ny nz // Be very careful when writing out complex multi-step calculations // such as vector cross products! The calculation for pbitangentz // used to be broken because it multiplied values in the wrong order. float pbitangentx = tangenty * normalZ - tangentz * normalY; float pbitangenty = tangentz * normalX - tangentx * normalZ; float pbitangentz = tangentx * normalY - tangenty * normalX; float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz); float tangentW; if (dot < 0) { tangentW = -1.0F; } else { tangentW = 1.0F; } return NormI8.pack(tangentx, tangenty, tangentz, tangentW); } public static int computeTangent(float normalX, float normalY, float normalZ, TriView t) { // Capture all of the relevant vertex positions float x0 = t.x(0); float y0 = t.y(0); float z0 = t.z(0); float x1 = t.x(1); float y1 = t.y(1); float z1 = t.z(1); float x2 = t.x(2); float y2 = t.y(2); float z2 = t.z(2); float edge1x = x1 - x0; float edge1y = y1 - y0; float edge1z = z1 - z0; float edge2x = x2 - x0; float edge2y = y2 - y0; float edge2z = z2 - z0; float u0 = t.u(0); float v0 = t.v(0); float u1 = t.u(1); float v1 = t.v(1); float u2 = t.u(2); float v2 = t.v(2); float deltaU1 = u1 - u0; float deltaV1 = v1 - v0; float deltaU2 = u2 - u0; float deltaV2 = v2 - v0; float fdenom = deltaU1 * deltaV2 - deltaU2 * deltaV1; float f; if (fdenom == 0.0) { f = 1.0f; } else { f = 1.0f / fdenom; } float tangentx = f * (deltaV2 * edge1x - deltaV1 * edge2x); float tangenty = f * (deltaV2 * edge1y - deltaV1 * edge2y); float tangentz = f * (deltaV2 * edge1z - deltaV1 * edge2z); float tcoeff = rsqrt(tangentx * tangentx + tangenty * tangenty + tangentz * tangentz); tangentx *= tcoeff; tangenty *= tcoeff; tangentz *= tcoeff; float bitangentx = f * (-deltaU2 * edge1x + deltaU1 * edge2x); float bitangenty = f * (-deltaU2 * edge1y + deltaU1 * edge2y); float bitangentz = f * (-deltaU2 * edge1z + deltaU1 * edge2z); float bitcoeff = rsqrt(bitangentx * bitangentx + bitangenty * bitangenty + bitangentz * bitangentz); bitangentx *= bitcoeff; bitangenty *= bitcoeff; bitangentz *= bitcoeff; // predicted bitangent = tangent × normal // Compute the determinant of the following matrix to get the cross product // i j k // tx ty tz // nx ny nz // Be very careful when writing out complex multi-step calculations // such as vector cross products! The calculation for pbitangentz // used to be broken because it multiplied values in the wrong order. float pbitangentx = tangenty * normalZ - tangentz * normalY; float pbitangenty = tangentz * normalX - tangentx * normalZ; float pbitangentz = tangentx * normalY - tangenty * normalX; float dot = (bitangentx * pbitangentx) + (bitangenty * pbitangenty) + (bitangentz * pbitangentz); float tangentW; if (dot < 0) { tangentW = -1.0F; } else { tangentW = 1.0F; } return packNormal(tangentx, tangenty, tangentz, tangentW); } private static float rsqrt(float value) { if (value == 0.0f) { // You heard it here first, folks: 1 divided by 0 equals 1 // In actuality, this is a workaround for normalizing a zero length vector (leaving it as zero length) return 1.0f; } else { return (float) (1.0 / Math.sqrt(value)); } } }
Angelica
src\main\java\net\coderbot\iris\vertices\NormI8.java
package net.coderbot.iris.vertices; import org.joml.Vector3f; /** * 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 | */ public class NormI8 { private static final int X_COMPONENT_OFFSET = 0; private static final int Y_COMPONENT_OFFSET = 8; private static final int Z_COMPONENT_OFFSET = 16; private static final int W_COMPONENT_OFFSET = 24; /** * The maximum value of a normal's vector component. */ private static final float COMPONENT_RANGE = 127.0f; /** * Constant value which can be multiplied with a floating-point vector component to get the normalized value. The * multiplication is slightly faster than a floating point division, and this code is a hot path which justifies it. */ private static final float NORM = 1.0f / COMPONENT_RANGE; public static int pack(Vector3f normal) { return pack(normal.x(), normal.y(), normal.z(), 0); } /** * 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 */ 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 */ public static int packColor(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 & 0xFF) << 24); } /** * 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) { return ((byte) ((norm >> X_COMPONENT_OFFSET) & 0xFF)) * 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) { return ((byte) ((norm >> Y_COMPONENT_OFFSET) & 0xFF)) * 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) { return ((byte) ((norm >> Z_COMPONENT_OFFSET) & 0xFF)) * 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) { return ((byte) ((norm >> W_COMPONENT_OFFSET) & 0xFF)) * NORM; } }
Angelica
src\main\java\net\coderbot\iris\vertices\PolygonView.java
package net.coderbot.iris.vertices; public interface PolygonView { float x(int index); float y(int index); float z(int index); float u(int index); float v(int index); }
Angelica
src\main\java\net\coderbot\iris\vertices\TriView.java
package net.coderbot.iris.vertices; /** * Implementations of this class must support at least three vertices. */ public interface TriView extends PolygonView { }
Angelica
src\main\java\net\coderbot\iris\gbuffer_overrides\matching\InputAvailability.java
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 InputAvailability(boolean texture, boolean lightmap) { this.texture = texture; this.lightmap = lightmap; } public static InputAvailability unpack(int packed) { return new InputAvailability((packed & 1) == 1, (packed & 2) == 2); } public int pack() { int packed = 0; if (lightmap) { packed |= 2; } if (texture) { packed |= 1; } return packed; } @Override public String toString() { return "InputAvailability{" + "texture=" + texture + ", lightmap=" + lightmap + '}'; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (lightmap ? 1231 : 1237); result = prime * result + (texture ? 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 (lightmap != other.lightmap) return false; if (texture != other.texture) return false; return true; } }
Angelica
src\main\java\net\coderbot\iris\gbuffer_overrides\matching\ProgramTable.java
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<T> { private final List<T> table = new ArrayList<>(); public ProgramTable(BiFunction<RenderCondition, InputAvailability, T> 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<T> consumer) { table.forEach(consumer); } }