diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/Axis.java b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/Axis.java index 02dd0d004..8deecd512 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/mojang/Axis.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/mojang/Axis.java @@ -1,6 +1,7 @@ package com.gtnewhorizons.angelica.compat.mojang; import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing; +import net.minecraftforge.common.util.ForgeDirection; public enum Axis { X, @@ -14,7 +15,15 @@ public enum Axis { case WEST, EAST -> X; case UNASSIGNED -> null; }; + } + public static Axis fromDirection(ForgeDirection dir) { + return switch (dir) { + case DOWN, UP -> Y; + case NORTH, SOUTH -> Z; + case WEST, EAST -> X; + case UNKNOWN -> null; + }; } public static Axis fromName(String dir) { @@ -26,4 +35,17 @@ public enum Axis { }; } + + public enum Direction { + POSITIVE, + NEGATIVE; + + public static Direction fromDirection(ForgeDirection dir) { + return switch (dir) { + case DOWN, NORTH, WEST -> NEGATIVE; + case UP, SOUTH, EAST -> POSITIVE; + case UNKNOWN -> null; + }; + } + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/compat/nd/Quad.java b/src/main/java/com/gtnewhorizons/angelica/compat/nd/Quad.java index 854e2ea61..36dd33a9b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/compat/nd/Quad.java +++ b/src/main/java/com/gtnewhorizons/angelica/compat/nd/Quad.java @@ -1,6 +1,8 @@ package com.gtnewhorizons.angelica.compat.nd; import java.util.Locale; + +import lombok.Getter; import me.jellysquid.mods.sodium.client.model.quad.ModelQuadView; import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFacing; import me.jellysquid.mods.sodium.client.model.quad.properties.ModelQuadFlags; @@ -10,6 +12,8 @@ import net.minecraftforge.common.util.ForgeDirection; import org.joml.Vector3f; import org.lwjgl.opengl.GL11; +import javax.annotation.Nullable; + public class Quad implements ModelQuadView { // Adapted from Neodymium @@ -27,36 +31,20 @@ public class Quad implements ModelQuadView { public boolean deleted; - public ModelQuadFacing normal; - private final Vector3f vectorA = new Vector3f(), vectorB = new Vector3f(), vectorC = new Vector3f(); - private boolean hasColor; - private boolean hasShade; - private boolean hasNormals; - + @Getter + private boolean shade; private int cachedFlags; private ForgeDirection face; private int colorIndex = -1; - public boolean hasColor() { - return this.hasColor; - } - public int[] getColors() { return this.cs; } - public boolean hasShade() { - return this.hasShade; - } - - public boolean hasNormals() { - return this.hasNormals; - } - /** Returns the face, forced to take one of 6 directions to mirror the behavior of baked quads in 1.16.5. */ - public ForgeDirection getCoercedFace() { + public ForgeDirection getLightFace() { return this.face != ForgeDirection.UNKNOWN ? this.face : ForgeDirection.UP; } @@ -130,21 +118,41 @@ public class Quad implements ModelQuadView { this.deleted = quad.deleted; - this.normal = quad.normal; - - this.hasColor = quad.hasColor; - this.hasShade = quad.hasShade; - this.hasNormals = quad.hasNormals; - this.cachedFlags = quad.cachedFlags; this.face = quad.face; this.colorIndex = quad.colorIndex; } + public void setRaw(int[] data, boolean shade, @Nullable ForgeDirection face, int colorIndex, int flags) { + + int i = 0; + for(int vi = 0; vi < 4; vi++) { + + xs[vi] = Float.intBitsToFloat(data[i + 0]); + ys[vi] = Float.intBitsToFloat(data[i + 1]); + zs[vi] = Float.intBitsToFloat(data[i + 2]); + + us[vi] = Float.intBitsToFloat(data[i + 3]); + vs[vi] = Float.intBitsToFloat(data[i + 4]); + + cs[vi] = data[i + 5]; + ns[vi] = data[i + 6]; + bs[vi] = data[i + 7]; + + i += 8; + } + + this.shade = shade; + this.deleted = false; + this.face = face; + this.colorIndex = colorIndex; + this.cachedFlags = ModelQuadFlags.getQuadFlags(flags); + } + private void read(int[] rawBuffer, int offset, float offsetX, float offsetY, float offsetZ, int drawMode, BlockRenderer.Flags flags) { final int vertices = drawMode == GL11.GL_TRIANGLES ? 3 : 4; + int i = offset; for(int vi = 0; vi < vertices; vi++) { - int i = offset + vi * 8; xs[vi] = Float.intBitsToFloat(rawBuffer[i + 0]) + offsetX; ys[vi] = Float.intBitsToFloat(rawBuffer[i + 1]) + offsetY; @@ -157,15 +165,14 @@ public class Quad implements ModelQuadView { ns[vi] = flags.hasNormals ? rawBuffer[i + 6] : 0; bs[vi] = flags.hasBrightness ? rawBuffer[i + 7] : DEFAULT_BRIGHTNESS; - this.hasColor = flags.hasColor; - this.hasShade = flags.hasBrightness; - this.hasNormals = flags.hasNormals; - - i += 8; } + // sus + this.shade = flags.hasBrightness; + if(vertices == 3) { + // Quadrangulate! xs[3] = xs[2]; ys[3] = ys[2]; @@ -195,8 +202,7 @@ public class Quad implements ModelQuadView { vectorB.set(xs[2] - xs[1], ys[2] - ys[1], zs[2] - zs[1]); vectorA.cross(vectorB, vectorC); - normal = ModelQuadFacing.fromVector(vectorC); - this.face = ModelQuadFacing.toDirection(normal); + this.face = ModelQuadFacing.toDirection(ModelQuadFacing.fromVector(vectorC)); this.cachedFlags = ModelQuadFlags.getQuadFlags(this); } diff --git a/src/main/java/com/gtnewhorizons/angelica/models/CubeModel.java b/src/main/java/com/gtnewhorizons/angelica/models/CubeModel.java index 6c7feee8d..f1b93ac5b 100644 --- a/src/main/java/com/gtnewhorizons/angelica/models/CubeModel.java +++ b/src/main/java/com/gtnewhorizons/angelica/models/CubeModel.java @@ -6,7 +6,7 @@ import com.gtnewhorizons.angelica.compat.nd.Quad; import com.gtnewhorizons.angelica.utils.ObjectPooler; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectImmutableList; -import java.util.ArrayList; + import java.util.Arrays; import java.util.List; import java.util.Random; @@ -153,6 +153,7 @@ public class CubeModel implements QuadProvider { public static final ThreadLocal INSTANCE = ThreadLocal.withInitial(() -> new CubeModel(false)); + private final NdQuadBuilder builder = new NdQuadBuilder(); private final boolean[] colorized = new boolean[6]; private final BlockRenderer.Flags flags = new BlockRenderer.Flags(true, true, false, false); private static final List EMPTY = ObjectImmutableList.of(); @@ -176,53 +177,14 @@ public class CubeModel implements QuadProvider { if (dir == ForgeDirection.UNKNOWN) return EMPTY; - final Quad face = quadPool.getInstance(); - final int[] buf = Arrays.copyOf(initBufs[dir.ordinal()], 32); // 8 ints per vertex, four vertices per quad. A cube only has one quad per side - // Format: - // x - // y - // z - // u - // v - // color - // normals - // brightness - // repeat - // all are float bits as ints - + this.builder.square(dir, 0, 0, 1, 1, 0); final IIcon tex = block.getIcon(dir.ordinal(), meta); - final int color; - if (this.colorized[dir.ordinal()]) { - final int c = block.colorMultiplier(world, pos.x, pos.y, pos.z); - final int r = (c >> 16) & 0xFF; - final int g = (c >> 8) & 0xFF; - final int b = c & 0xFF; - color = 0xFF << 24 | b << 16 | g << 8 | r; - } else { color = 0xFFFFFFFF; } - this.flags.hasColor = this.colorized[dir.ordinal()]; + this.builder.spriteBake(tex, NdQuadBuilder.BAKE_LOCK_UV); - for (int vi = 0; vi < 4; ++vi) { - final int i = vi * 8; + int color = 0xFF << 24 | block.colorMultiplier(world, pos.x, pos.y, pos.z); + this.builder.color(color, color, color, color); - // UV - buf[i + 3] = Float.floatToIntBits(tex.getInterpolatedU(uv[vi][0] * 16)); - buf[i + 4] = Float.floatToIntBits(tex.getInterpolatedV(uv[vi][1] * 16)); - - // Color - buf[i + 5] = color; - } - - face.setState(buf, 0, this.flags, GL_QUADS, 0, 0, 0); - - // CubeModel is solid all over, and thus doesn't need to do this - // However, you need to drop deleted quads in proper model code - /*if (face.deleted) { - - quadPool.releaseInstance(face); - return EMPTY; - }*/ - - ONE.set(0, face); + ONE.set(0, this.builder.build(quadPool.getInstance())); return ONE; } } diff --git a/src/main/java/com/gtnewhorizons/angelica/models/EncodingFormat.java b/src/main/java/com/gtnewhorizons/angelica/models/EncodingFormat.java index efe9cdfa9..a3a8ad765 100644 --- a/src/main/java/com/gtnewhorizons/angelica/models/EncodingFormat.java +++ b/src/main/java/com/gtnewhorizons/angelica/models/EncodingFormat.java @@ -2,6 +2,7 @@ package com.gtnewhorizons.angelica.models; import com.gtnewhorizons.angelica.compat.mojang.DefaultVertexFormat; import com.gtnewhorizons.angelica.compat.mojang.VertexFormat; +import com.gtnewhorizons.angelica.models.material.RenderMaterialImpl; import net.minecraft.util.MathHelper; import net.minecraftforge.common.util.ForgeDirection; @@ -74,9 +75,9 @@ public abstract class EncodingFormat { private static final int GEOMETRY_MASK = (1 << GeometryHelper.FLAG_BIT_COUNT) - 1; private static final int GEOMETRY_INVERSE_MASK = ~(GEOMETRY_MASK << GEOMETRY_SHIFT); private static final int MATERIAL_SHIFT = GEOMETRY_SHIFT + GeometryHelper.FLAG_BIT_COUNT; - //private static final int MATERIAL_MASK = MathHelper.roundUpToPowerOfTwo(RenderMaterialImpl.VALUE_COUNT) - 1; + private static final int MATERIAL_MASK = MathHelper.roundUpToPowerOfTwo(RenderMaterialImpl.VALUE_COUNT) - 1; //private static final int MATERIAL_BIT_COUNT = Integer.bitCount(MATERIAL_MASK); - //private static final int MATERIAL_INVERSE_MASK = ~(MATERIAL_MASK << MATERIAL_SHIFT); + private static final int MATERIAL_INVERSE_MASK = ~(MATERIAL_MASK << MATERIAL_SHIFT); /*static { Preconditions.checkArgument(MATERIAL_SHIFT + MATERIAL_BIT_COUNT <= 32, "Indigo header encoding bit count (%s) exceeds integer bit length)", TOTAL_STRIDE); @@ -123,11 +124,11 @@ public abstract class EncodingFormat { return (bits & GEOMETRY_INVERSE_MASK) | ((geometryFlags & GEOMETRY_MASK) << GEOMETRY_SHIFT); } - /*static RenderMaterialImpl material(int bits) { + static RenderMaterialImpl material(int bits) { return RenderMaterialImpl.byIndex((bits >>> MATERIAL_SHIFT) & MATERIAL_MASK); } public static int material(int bits, RenderMaterialImpl material) { return (bits & MATERIAL_INVERSE_MASK) | (material.index() << MATERIAL_SHIFT); - }*/ + } } diff --git a/src/main/java/com/gtnewhorizons/angelica/models/GeometryHelper.java b/src/main/java/com/gtnewhorizons/angelica/models/GeometryHelper.java index 7b3a4ede5..8af8e555f 100644 --- a/src/main/java/com/gtnewhorizons/angelica/models/GeometryHelper.java +++ b/src/main/java/com/gtnewhorizons/angelica/models/GeometryHelper.java @@ -1,8 +1,12 @@ package com.gtnewhorizons.angelica.models; import com.gtnewhorizons.angelica.compat.mojang.Axis; +import com.gtnewhorizons.angelica.compat.nd.Quad; +import net.minecraftforge.common.util.ForgeDirection; import org.joml.Vector3f; +import static me.jellysquid.mods.sodium.client.util.MathUtil.fuzzy_eq; + /** * Static routines of general utility for renderer implementations. * Renderers are not required to use these helpers, but they were @@ -14,7 +18,7 @@ public abstract class GeometryHelper { /** set when a quad touches all four corners of a unit cube. */ public static final int CUBIC_FLAG = 1; - /** set when a quad is parallel to (but not necessarily on) a its light face. */ + /** set when a quad is parallel to (but not necessarily on) its light face. */ public static final int AXIS_ALIGNED_FLAG = CUBIC_FLAG << 1; /** set when a quad is coplanar with its light face. Implies {@link #AXIS_ALIGNED_FLAG} */ @@ -26,6 +30,147 @@ public abstract class GeometryHelper { private static final float EPS_MIN = 0.0001f; private static final float EPS_MAX = 1.0f - EPS_MIN; + /** + * Analyzes the quad and returns a value with some combination + * of {@link #AXIS_ALIGNED_FLAG}, {@link #LIGHT_FACE_FLAG} and {@link #CUBIC_FLAG}. + * Intended use is to optimize lighting when the geometry is regular. + * Expects convex quads with all points co-planar. + */ + public static int computeShapeFlags(NdQuadBuilder quad) { + ForgeDirection lightFace = quad.lightFace(); + int bits = 0; + + if (isQuadParallelToFace(lightFace, quad)) { + bits |= AXIS_ALIGNED_FLAG; + + if (isParallelQuadOnFace(lightFace, quad)) { + bits |= LIGHT_FACE_FLAG; + } + } + + if (isQuadCubic(lightFace, quad)) { + bits |= CUBIC_FLAG; + } + + return bits; + } + + /** + * Returns true if quad is parallel to the given face. + * Does not validate quad winding order. + * Expects convex quads with all points co-planar. + */ + public static boolean isQuadParallelToFace(ForgeDirection face, NdQuadBuilder quad) { + int i = Axis.fromDirection(face).ordinal(); + final float val = quad.posByIndex(0, i); + return fuzzy_eq(val, quad.posByIndex(1, i)) && fuzzy_eq(val, quad.posByIndex(2, i)) && fuzzy_eq(val, quad.posByIndex(3, i)); + } + + /** + * True if quad - already known to be parallel to a face - is actually coplanar with it. + * For compatibility with vanilla resource packs, also true if quad is outside the face. + * + *

Test will be unreliable if not already parallel, use {@link #isQuadParallelToFace(ForgeDirection, NdQuadBuilder)} + * for that purpose. Expects convex quads with all points co-planar. + */ + public static boolean isParallelQuadOnFace(ForgeDirection lightFace, NdQuadBuilder quad) { + final float x = quad.posByIndex(0, Axis.fromDirection(lightFace).ordinal()); + return Axis.Direction.fromDirection(lightFace) == Axis.Direction.POSITIVE ? x >= EPS_MAX : x <= EPS_MIN; + } + + /** + * Returns true if quad is truly a quad (not a triangle) and fills a full block cross-section. + * If known to be true, allows use of a simpler/faster AO lighting algorithm. + * + *

Does not check if quad is actually coplanar with the light face, nor does it check that all + * quad vertices are coplanar with each other. + * + *

Expects convex quads with all points co-planar. + */ + public static boolean isQuadCubic(ForgeDirection lightFace, NdQuadBuilder quad) { + int a, b; + + switch (lightFace) { + case EAST: + case WEST: + a = 1; + b = 2; + break; + case UP: + case DOWN: + a = 0; + b = 2; + break; + case SOUTH: + case NORTH: + a = 1; + b = 0; + break; + default: + // handle WTF case + return false; + } + + return confirmSquareCorners(a, b, quad); + } + + /** + * Used by {@link #isQuadCubic(ForgeDirection, NdQuadBuilder)}. + * True if quad touches all four corners of unit square. + * + *

For compatibility with resource packs that contain models with quads exceeding + * block boundaries, considers corners outside the block to be at the corners. + */ + private static boolean confirmSquareCorners(int aCoordinate, int bCoordinate, NdQuadBuilder quad) { + int flags = 0; + + for (int i = 0; i < 4; i++) { + final float a = quad.posByIndex(i, aCoordinate); + final float b = quad.posByIndex(i, bCoordinate); + + if (a <= EPS_MIN) { + if (b <= EPS_MIN) { + flags |= 1; + } else if (b >= EPS_MAX) { + flags |= 2; + } else { + return false; + } + } else if (a >= EPS_MAX) { + if (b <= EPS_MIN) { + flags |= 4; + } else if (b >= EPS_MAX) { + flags |= 8; + } else { + return false; + } + } else { + return false; + } + } + + return flags == 15; + } + + /** + * Identifies the face to which the quad is most closely aligned. + * This mimics the value that {@link Quad#getLightFace()} returns, and is + * used in the vanilla renderer for all diffuse lighting. + * + *

Derived from the quad face normal and expects convex quads with all points co-planar. + */ + public static ForgeDirection lightFace(NdQuadBuilder quad) { + final Vector3f normal = quad.faceNormal; + return switch (GeometryHelper.longestAxis(normal)) { + case X -> normal.x() > 0 ? ForgeDirection.EAST : ForgeDirection.WEST; + case Y -> normal.y() > 0 ? ForgeDirection.UP : ForgeDirection.DOWN; + case Z -> normal.z() > 0 ? ForgeDirection.SOUTH : ForgeDirection.NORTH; + default -> + // handle WTF case + ForgeDirection.UP; + }; + } + /** * Simple 4-way compare, doesn't handle NaN values. */ diff --git a/src/main/java/com/gtnewhorizons/angelica/models/NdQuadBuilder.java b/src/main/java/com/gtnewhorizons/angelica/models/NdQuadBuilder.java index 224c292b5..098df8d17 100644 --- a/src/main/java/com/gtnewhorizons/angelica/models/NdQuadBuilder.java +++ b/src/main/java/com/gtnewhorizons/angelica/models/NdQuadBuilder.java @@ -2,16 +2,26 @@ package com.gtnewhorizons.angelica.models; import com.gtnewhorizons.angelica.compat.nd.Quad; import java.util.Arrays; + +import com.gtnewhorizons.angelica.models.material.RenderMaterial; +import com.gtnewhorizons.angelica.models.material.RenderMaterialImpl; +import com.gtnewhorizons.angelica.models.renderer.IndigoRenderer; import me.jellysquid.mods.sodium.client.render.pipeline.BlockRenderer; import net.minecraft.client.Minecraft; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.joml.Vector3f; import org.lwjgl.opengl.GL11; +import static com.gtnewhorizons.angelica.models.EncodingFormat.*; + public class NdQuadBuilder { + // x, y, z, u, v, color, normal, lightmap public static final int INTS_PER_VERTEX = 8; + public static final int QUAD_STRIDE = INTS_PER_VERTEX * 4; public static final int X_INDEX = 0; public static final int Y_INDEX = 1; public static final int Z_INDEX = 2; @@ -86,20 +96,20 @@ public class NdQuadBuilder { */ public static float CULL_FACE_EPSILON = 0.00001f; - private ForgeDirection cullFace = ForgeDirection.UNKNOWN; private ForgeDirection nominalFace = ForgeDirection.UNKNOWN; - private int[] data = new int[INTS_PER_VERTEX * 4]; - private boolean isGeometryInvalid = false; - private int bitFlags = 0; + // It's called a header, but because I'm lazy it's at the end + private final int[] data = new int[QUAD_STRIDE + HEADER_STRIDE]; + private boolean isGeometryInvalid = true; private int tag = 0; private int colorIndex = -1; + final Vector3f faceNormal = new Vector3f(); /** * Dumps to {@param out} and returns it. */ public Quad build(Quad out) { - out.setState( + /*out.setState( data, 0, new BlockRenderer.Flags(true, false, this.colorIndex != -1, false), @@ -107,7 +117,10 @@ public class NdQuadBuilder { 0, 0, 0 - ); + );*/ + // FRAPI does this late, but we need to do it before baking to Nd quads + this.computeGeometry(); + out.setRaw(this.data, this.hasShade(), this.cullFace(), this.colorIndex, this.data[QUAD_STRIDE + HEADER_BITS]); this.clear(); return out; } @@ -117,11 +130,11 @@ public class NdQuadBuilder { Arrays.fill(this.data, 0); this.isGeometryInvalid = true; this.nominalFace = ForgeDirection.UNKNOWN; - normalFlags(0); - tag(0); - colorIndex(-1); - cullFace(null); - //material(IndigoRenderer.MATERIAL_STANDARD); + this.normalFlags(0); + this.tag(0); + this.colorIndex(-1); + this.cullFace(null); + this.material(IndigoRenderer.MATERIAL_STANDARD); } /** @@ -149,39 +162,87 @@ public class NdQuadBuilder { this.colorIndex = colorIndex; } + private void computeGeometry() { + if (isGeometryInvalid) { + isGeometryInvalid = false; + + NormalHelper.computeFaceNormal(faceNormal, this); + this.data[QUAD_STRIDE + HEADER_FACE_NORMAL] = NormalHelper.packNormal(this.faceNormal); + + // depends on face normal + this.data[QUAD_STRIDE +HEADER_BITS] = EncodingFormat.lightFace(this.data[QUAD_STRIDE +HEADER_BITS], GeometryHelper.lightFace(this)); + + // depends on light face + this.data[QUAD_STRIDE +HEADER_BITS] = EncodingFormat.geometryFlags(this.data[QUAD_STRIDE +HEADER_BITS], GeometryHelper.computeShapeFlags(this)); + } + } + /** - * If not {@link ForgeDirection.UNKNOWN}, quad is coplanar with a block face which, if known, simplifies + * If non-null, quad should not be rendered in-world if the + * opposite face of a neighbor block occludes it. + * + * @see NdQuadBuilder#cullFace(ForgeDirection) + */ + @Nullable + public final ForgeDirection cullFace() { + return EncodingFormat.cullFace(this.data[QUAD_STRIDE + HEADER_BITS]); + } + + /** + * If not {@link ForgeDirection#UNKNOWN}, quad is coplanar with a block face which, if known, simplifies * or shortcuts geometric analysis that might otherwise be needed. - * Set to {@link ForgeDirection.UNKNOWN} if quad is not coplanar or if this is not known. + * Set to {@link ForgeDirection#UNKNOWN} if quad is not coplanar or if this is not known. * Also controls face culling during block rendering. * - *

{@link ForgeDirection.UNKNOWN} by default. + *

{@link ForgeDirection#UNKNOWN} by default. * - *

When called with a non-{@link ForgeDirection.UNKNOWN} value, also sets {@link #nominalFace(ForgeDirection)} + *

When called with a non-{@link ForgeDirection#UNKNOWN} value, also sets {@link #nominalFace(ForgeDirection)} * to the same value. * - *

This is different from the value reported by {@link Quad#getFace()}. That value - * is computed based on face geometry and must be non-{@link ForgeDirection.UNKNOWN} in vanilla quads. + *

This is different from the value reported by {@link Quad#getLightFace()}. That value + * is computed based on face geometry and must be non-{@link ForgeDirection#UNKNOWN} in vanilla quads. * That computed value is returned by {@link #lightFace()}. */ - public void cullFace(ForgeDirection dir) { + public void cullFace(@Nullable ForgeDirection dir) { - this.cullFace = dir; - if (dir != ForgeDirection.UNKNOWN) - this.nominalFace(dir); + this.data[QUAD_STRIDE + HEADER_BITS] = EncodingFormat.cullFace(this.data[QUAD_STRIDE + HEADER_BITS], dir); + this.nominalFace(dir); + } + + private boolean hasShade() { + return !this.material().disableDiffuse(); + } + + /** + * Equivalent to {@link Quad#getLightFace()}. This is the face used for vanilla lighting + * calculations and will be the block face to which the quad is most closely aligned. Always + * the same as cull face for quads that are on a block face, but never + * {@link ForgeDirection#UNKNOWN} or null. + */ + @NotNull + ForgeDirection lightFace() { + this.computeGeometry(); + return EncodingFormat.lightFace(this.data[QUAD_STRIDE + HEADER_BITS]); + } + + /** + * Retrieves the material serialized with the quad. + */ + public final RenderMaterialImpl material() { + return EncodingFormat.material(this.data[QUAD_STRIDE + HEADER_BITS]); } /** * Assigns a different material to this quad. Useful for transformation of * existing meshes because lighting and texture blending are controlled by material. - * / - public void material(RenderMaterial material) { + */ + public final void material(RenderMaterial material) { if (material == null) { material = IndigoRenderer.MATERIAL_STANDARD; } - this.bitFlags = EncodingFormat.material(this.bitFlags, (RenderMaterialImpl) material); - }*/ + this.data[QUAD_STRIDE + HEADER_BITS] = EncodingFormat.material(this.data[QUAD_STRIDE + HEADER_BITS], (RenderMaterialImpl) material); + } /** * Provides a hint to renderer about the facing of this quad. Not required, @@ -196,7 +257,7 @@ public class NdQuadBuilder { *

Note: This value is not persisted independently when the quad is encoded. * When reading encoded quads, this value will always be the same as {@link #lightFace()}. */ - public void nominalFace(ForgeDirection face) { + public void nominalFace(@Nullable ForgeDirection face) { nominalFace = face; } @@ -211,7 +272,7 @@ public class NdQuadBuilder { * Sets the normal flags. */ private void normalFlags(int flags) { - this.bitFlags = EncodingFormat.normalFlags(bitFlags, flags); + this.data[QUAD_STRIDE + HEADER_BITS] = EncodingFormat.normalFlags(this.data[QUAD_STRIDE + HEADER_BITS], flags); } /** @@ -238,6 +299,13 @@ public class NdQuadBuilder { ); } + /** + * Convenience: access x, y, z by index 0-2. + */ + float posByIndex(int vertexIndex, int coordinateIndex) { + return Float.intBitsToFloat(data[vertexIndex * INTS_PER_VERTEX + X_INDEX + coordinateIndex]); + } + /** * Convienence, gets the icon from the block atlas. See {@link #spriteBake(IIcon, int)} */ @@ -370,7 +438,7 @@ public class NdQuadBuilder { } /** - * Modern Minecraft uses magic arrays to do this without breaking AO. Let's copy that. + * Modern Minecraft uses magic arrays to do this without breaking AO. This is the same thing, but without arrays. */ public static Vector3f mapSideToVertex(Vector3f from, Vector3f to, int index, ForgeDirection side) { diff --git a/src/main/java/com/gtnewhorizons/angelica/models/NormalHelper.java b/src/main/java/com/gtnewhorizons/angelica/models/NormalHelper.java new file mode 100644 index 000000000..b9347ffa9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/NormalHelper.java @@ -0,0 +1,85 @@ +package com.gtnewhorizons.angelica.models; + +import net.minecraft.util.MathHelper; +import net.minecraftforge.common.util.ForgeDirection; +import org.jetbrains.annotations.NotNull; +import org.joml.Vector3f; +import org.joml.Vector3i; + +import static me.jellysquid.mods.sodium.common.util.DirectionUtil.STEP; + +public class NormalHelper { + + private static final float PACK = 127.0f; + private static final float UNPACK = 1.0f / PACK; + + /** + * Computes the face normal of the given quad and saves it in the provided non-null vector. + * If {@link NdQuadBuilder#nominalFace()} is set will optimize by confirming quad is parallel to that + * face and, if so, use the standard normal for that face direction. + * + *

Will work with triangles also. Assumes counter-clockwise winding order, which is the norm. + * Expects convex quads with all points co-planar. + */ + public static void computeFaceNormal(@NotNull Vector3f saveTo, NdQuadBuilder q) { + final ForgeDirection nominalFace = q.nominalFace(); + + if (nominalFace != null && GeometryHelper.isQuadParallelToFace(nominalFace, q)) { + Vector3i vec = STEP[nominalFace.ordinal()]; + saveTo.set(vec.x, vec.y, vec.z); + 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); + } + + /** + * Like {@link #packNormal(float, float, float, float)}, but without a {@code w} value. + */ + public static int packNormal(float x, float y, float z) { + x = MathHelper.clamp_float(x, -1, 1); + y = MathHelper.clamp_float(y, -1, 1); + z = MathHelper.clamp_float(z, -1, 1); + + return ((int) (x * PACK) & 0xFF) | (((int) (y * PACK) & 0xFF) << 8) | (((int) (z * PACK) & 0xFF) << 16); + } + + /** + * Like {@link #packNormal(Vector3f, float)}, but without a {@code w} value. + */ + public static int packNormal(Vector3f normal) { + return packNormal(normal.x, normal.y, normal.z); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/fapi/BooleanFunction.java b/src/main/java/com/gtnewhorizons/angelica/models/fapi/BooleanFunction.java new file mode 100644 index 000000000..a00999c5d --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/fapi/BooleanFunction.java @@ -0,0 +1,17 @@ +package com.gtnewhorizons.angelica.models.fapi; + +/** + * Represents a function that accepts a boolean-valued argument and produces a result. + * + *

This is the {@code boolean}-consuming primitive specialization for {@link java.util.function.Function}. + */ +@FunctionalInterface +public interface BooleanFunction { + /** + * Applies this function to the given argument. + * + * @param value the function argument + * @return the function result + */ + R apply(boolean value); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/fapi/TriState.java b/src/main/java/com/gtnewhorizons/angelica/models/fapi/TriState.java new file mode 100644 index 000000000..b215bcd23 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/fapi/TriState.java @@ -0,0 +1,122 @@ +package com.gtnewhorizons.angelica.models.fapi; + +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.Optional; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +/** + * Represents a boolean value which can be true, false or refer to a default value. + */ +public enum TriState { + /** + * Represents the boolean value of {@code false}. + */ + FALSE, + /** + * Represents a value that refers to a "default" value, often as a fallback. + */ + DEFAULT, + /** + * Represents the boolean value of {@code true}. + */ + TRUE; + + /** + * Gets the corresponding tri-state from a boolean value. + * + * @param bool the boolean value + * @return {@link TriState#TRUE} or {@link TriState#FALSE} depending on the value of the boolean. + */ + public static TriState of(boolean bool) { + return bool ? TRUE : FALSE; + } + + /** + * Gets a tri-state from a nullable boxed boolean. + * + * @param bool the boolean value + * @return {@link TriState#DEFAULT} if {@code null}. + * Otherwise {@link TriState#TRUE} or {@link TriState#FALSE} depending on the value of the boolean. + */ + public static TriState of(@Nullable Boolean bool) { + return bool == null ? DEFAULT : of(bool.booleanValue()); + } + + /** + * Gets the value of the tri-state. + * + * @return true if the tri-state is {@link TriState#TRUE}, + * otherwise false. + */ + public boolean get() { + return this == TRUE; + } + + /** + * Gets the value of the tri-state as a boxed, nullable boolean. + * + * @return {@code null} if {@link TriState#DEFAULT}. + * Otherwise {@code true} if {@link TriState#TRUE} or {@code false} if {@link TriState#FALSE}. + */ + @Nullable + public Boolean getBoxed() { + return this == DEFAULT ? null : this.get(); + } + + /** + * Gets the value of this tri-state. + * If the value is {@link TriState#DEFAULT} then use the supplied value. + * + * @param value the value to fall back to + * @return the value of the tri-state or the supplied value if {@link TriState#DEFAULT}. + */ + public boolean orElse(boolean value) { + return this == DEFAULT ? value : this.get(); + } + + /** + * Gets the value of this tri-state. + * If the value is {@link TriState#DEFAULT} then use the supplied value. + * + * @param supplier the supplier used to get the value to fall back to + * @return the value of the tri-state or the value of the supplier if the tri-state is {@link TriState#DEFAULT}. + */ + public boolean orElseGet(BooleanSupplier supplier) { + return this == DEFAULT ? supplier.getAsBoolean() : this.get(); + } + + /** + * Maps the boolean value of this tri-state if it is {@link TriState#TRUE} or {@link TriState#FALSE}. + * + * @param mapper the mapper to use + * @param the type of object being supplier by the mapper + * @return an optional containing the mapped value; {@link Optional#empty()} if the tri-state is {@link TriState#DEFAULT} or the value provided by the mapper is {@code null}. + */ + public Optional map(BooleanFunction mapper) { + Objects.requireNonNull(mapper, "Mapper function cannot be null"); + + if (this == DEFAULT) { + return Optional.empty(); + } + + return Optional.ofNullable(mapper.apply(this.get())); + } + + /** + * Gets the value of this tri-state, or throws an exception if this tri-state's value is {@link TriState#DEFAULT}. + * + * @param exceptionSupplier the supplying function that produces an exception to be thrown + * @param Type of the exception to be thrown + * @return the value + * @throws X if the value is {@link TriState#DEFAULT} + */ + public boolean orElseThrow(Supplier exceptionSupplier) throws X { + if (this != DEFAULT) { + return this.get(); + } + + throw exceptionSupplier.get(); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/json/JsonModel.java b/src/main/java/com/gtnewhorizons/angelica/models/json/JsonModel.java index 65100e200..a0ce566b5 100644 --- a/src/main/java/com/gtnewhorizons/angelica/models/json/JsonModel.java +++ b/src/main/java/com/gtnewhorizons/angelica/models/json/JsonModel.java @@ -11,6 +11,9 @@ import com.gtnewhorizons.angelica.compat.mojang.Axis; import com.gtnewhorizons.angelica.compat.mojang.BlockPos; import com.gtnewhorizons.angelica.compat.nd.Quad; import com.gtnewhorizons.angelica.models.NdQuadBuilder; +import com.gtnewhorizons.angelica.models.fapi.TriState; +import com.gtnewhorizons.angelica.models.material.RenderMaterial; +import com.gtnewhorizons.angelica.models.renderer.IndigoRenderer; import com.gtnewhorizons.angelica.utils.DirUtil; import com.gtnewhorizons.angelica.utils.ObjectPooler; import it.unimi.dsi.fastutil.Function; @@ -22,6 +25,8 @@ import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; + +import lombok.Getter; import net.minecraft.block.Block; import net.minecraft.util.ResourceLocation; import net.minecraft.world.IBlockAccess; @@ -42,10 +47,12 @@ public class JsonModel implements QuadProvider { private final ResourceLocation parentId; @Nullable private JsonModel parent; + @Getter private final boolean useAO; private final Map display; private final Map textures; private List elements; + // TODO: Make a sided list private List bakedQuadStore = new ObjectArrayList<>(); JsonModel(@Nullable ResourceLocation parentId, boolean useAO, Map display, Map textures, List elements) { @@ -74,6 +81,8 @@ public class JsonModel implements QuadProvider { final Matrix4f vRot = v.getAffineMatrix(); final NdQuadBuilder builder = new NdQuadBuilder(); + final RenderMaterial mat = + IndigoRenderer.INSTANCE.materialFinder().ambientOcclusion(TriState.of(this.useAO)).find(); // Append faces from each element for (ModelElement e : this.elements) { @@ -127,6 +136,9 @@ public class JsonModel implements QuadProvider { final int tint = f.getTintIndex(); builder.color(tint, tint, tint, tint); + // Set AO + builder.material(mat); + // Bake and add it this.bakedQuadStore.add(builder.build(new Quad())); } diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/BlendMode.java b/src/main/java/com/gtnewhorizons/angelica/models/material/BlendMode.java new file mode 100644 index 000000000..6194d5210 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/BlendMode.java @@ -0,0 +1,56 @@ +package com.gtnewhorizons.angelica.models.material; + +import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; + +/** + * Defines how sprite pixels will be blended with the scene. + */ +public enum BlendMode { + /** + * Emulate blending behavior of {@code BlockRenderLayer} associated with the block. + */ + DEFAULT(null), + + /** + * Fully opaque with depth test, no blending. Used for most normal blocks. + */ + SOLID(RenderLayer.solid()), + + /** + * Pixels with alpha > 0.5 are rendered as if {@code SOLID}. Other pixels are not rendered. + * Texture mip-map enabled. Used for leaves on modern, unused in 1.7.10. + */ + //CUTOUT_MIPPED(RenderLayer.cutout()), + + /** + * Pixels with alpha > 0.5 are rendered as if {@code SOLID}. Other pixels are not rendered. + * Texture mip-map disabled. Used for iron bars, glass and other cutout sprites with hard edges. + */ + CUTOUT(RenderLayer.cutout()), + + /** + * Pixels are blended with the background according to alpha color values. Some performance cost, + * use in moderation. Texture mip-map enabled. Used for stained glass. + */ + TRANSLUCENT(RenderLayer.translucent()); + + public final RenderLayer blockRenderLayer; + + BlendMode(RenderLayer blockRenderLayer) { + this.blockRenderLayer = blockRenderLayer; + } + + public static BlendMode fromRenderLayer(RenderLayer renderLayer) { + if (renderLayer == RenderLayer.solid()) { + return SOLID; + /*} else if (renderLayer == RenderLayer.getCutoutMipped()) { + return CUTOUT_MIPPED;*/ + } else if (renderLayer == RenderLayer.cutout()) { + return CUTOUT; + } else if (renderLayer == RenderLayer.translucent()) { + return TRANSLUCENT; + } else { + return DEFAULT; + } + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinder.java b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinder.java new file mode 100644 index 000000000..036117b74 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinder.java @@ -0,0 +1,156 @@ +package com.gtnewhorizons.angelica.models.material; + +import com.gtnewhorizons.angelica.compat.toremove.RenderLayer; +import com.gtnewhorizons.angelica.models.renderer.IndigoRenderer; +import com.gtnewhorizons.angelica.models.NdQuadBuilder; +import com.gtnewhorizons.angelica.models.fapi.TriState; +import com.gtnewhorizons.angelica.models.json.JsonModel; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; + +/** + * Finds standard {@link RenderMaterial} instances used to communicate + * quad rendering characteristics to a {@link RenderContext}. + * + *

Must be obtained via {@link IndigoRenderer#materialFinder()}. + */ +public interface MaterialFinder extends MaterialView { + /** + * Defines how sprite pixels will be blended with the scene. + * + *

See {@link BlendMode} for more information. + */ + MaterialFinder blendMode(BlendMode blendMode); + + /** + * Vertex color(s) will be modified for quad color index unless disabled. + */ + MaterialFinder disableColorIndex(boolean disable); + + /** + * When true, sprite texture and color will be rendered at full brightness. + * Lightmap values provided via {@link NdQuadBuilder#lightmap(int)} will be ignored. + * False by default + * + *

This is the preferred method for emissive lighting effects. Some renderers + * with advanced lighting models may not use block lightmaps and this method will + * allow per-sprite emissive lighting in future extensions that support overlay sprites. + * + *

Note that color will still be modified by diffuse shading and ambient occlusion, + * unless disabled via {@link #disableDiffuse(boolean)} and {@link #ambientOcclusion(TriState)}. + */ + MaterialFinder emissive(boolean isEmissive); + + /** + * Vertex color(s) will be modified for diffuse shading unless disabled. + * + *

This property is guaranteed to be respected in block contexts. Some renderers may also respect it in item + * contexts, but this is not guaranteed. + */ + MaterialFinder disableDiffuse(boolean disable); + + /** + * Controls whether vertex color(s) will be modified for ambient occlusion. + * + *

By default, ambient occlusion will be used if {@link JsonModel#isUseAO() the model uses ambient occlusion} + * and the block has {@link Block#getLightValue() a luminance} of 0. + * Set to {@link TriState#TRUE} or {@link TriState#FALSE} to override this behavior. + * + *

This property is respected only in block contexts. It will not have an effect in other contexts. + */ + MaterialFinder ambientOcclusion(TriState mode); + + /** + * Controls whether glint should be applied. + * + *

By default, glint will be applied in item contexts if {@link ItemStack#isItemEnchanted()} the item stack has glint}. + * Set to {@link TriState#TRUE} or {@link TriState#FALSE} to override this behavior. + * + *

This property is guaranteed to be respected in item contexts. Some renderers may also respect it in block + * contexts, but this is not guaranteed. + */ + MaterialFinder glint(TriState mode); + + /** + * Copies all properties from the given {@link MaterialView} to this material finder. + */ + MaterialFinder copyFrom(MaterialView material); + + /** + * Resets this instance to default values. Values will match those + * in effect when an instance is newly obtained via {@link IndigoRenderer#materialFinder()}. + */ + MaterialFinder clear(); + + /** + * Returns the standard material encoding all + * of the current settings in this finder. The settings in + * this finder are not changed. + * + *

Resulting instances can and should be re-used to prevent + * needless memory allocation. {@link IndigoRenderer} implementations + * may or may not cache standard material instances. + */ + RenderMaterial find(); + + /** + * @deprecated Use {@link #blendMode(BlendMode)} instead. + */ + @Deprecated + default MaterialFinder blendMode(int spriteIndex, RenderLayer renderLayer) { + return blendMode(BlendMode.fromRenderLayer(renderLayer)); + } + + /** + * @deprecated Use {@link #blendMode(BlendMode)} instead. + */ + @Deprecated + default MaterialFinder blendMode(int spriteIndex, BlendMode blendMode) { + // Null check is kept for legacy reasons, but the new blendMode method will NPE if passed null! + if (blendMode == null) { + blendMode = BlendMode.DEFAULT; + } + + return blendMode(blendMode); + } + + /** + * @deprecated Use {@link #disableColorIndex(boolean)} instead. + */ + @Deprecated + default MaterialFinder disableColorIndex(int spriteIndex, boolean disable) { + return disableColorIndex(disable); + } + + /** + * @deprecated Use {@link #emissive(boolean)} instead. + */ + @Deprecated + default MaterialFinder emissive(int spriteIndex, boolean isEmissive) { + return emissive(isEmissive); + } + + /** + * @deprecated Use {@link #disableDiffuse(boolean)} instead. + */ + @Deprecated + default MaterialFinder disableDiffuse(int spriteIndex, boolean disable) { + return disableDiffuse(disable); + } + + /** + * @deprecated Use {@link #ambientOcclusion(TriState)} instead. + */ + @Deprecated + default MaterialFinder disableAo(int spriteIndex, boolean disable) { + return ambientOcclusion(disable ? TriState.FALSE : TriState.DEFAULT); + } + + /** + * Do not use. Does nothing. + */ + @Deprecated + default MaterialFinder spriteDepth(int depth) { + return this; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinderImpl.java b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinderImpl.java new file mode 100644 index 000000000..6b005de96 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialFinderImpl.java @@ -0,0 +1,83 @@ +package com.gtnewhorizons.angelica.models.material; + +import com.gtnewhorizons.angelica.models.fapi.TriState; + +import java.util.Objects; + +public class MaterialFinderImpl extends MaterialViewImpl implements MaterialFinder { + private static int defaultBits = 0; + + static { + MaterialFinderImpl finder = new MaterialFinderImpl(); + finder.ambientOcclusion(TriState.DEFAULT); + finder.glint(TriState.DEFAULT); + defaultBits = finder.bits; + + if (!areBitsValid(defaultBits)) { + throw new AssertionError("Default MaterialFinder bits are not valid!"); + } + } + + public MaterialFinderImpl() { + super(defaultBits); + } + + @Override + public MaterialFinder blendMode(BlendMode blendMode) { + Objects.requireNonNull(blendMode, "BlendMode may not be null"); + + bits = (bits & ~BLEND_MODE_MASK) | (blendMode.ordinal() << BLEND_MODE_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder disableColorIndex(boolean disable) { + bits = disable ? (bits | COLOR_DISABLE_FLAG) : (bits & ~COLOR_DISABLE_FLAG); + return this; + } + + @Override + public MaterialFinder emissive(boolean isEmissive) { + bits = isEmissive ? (bits | EMISSIVE_FLAG) : (bits & ~EMISSIVE_FLAG); + return this; + } + + @Override + public MaterialFinder disableDiffuse(boolean disable) { + bits = disable ? (bits | DIFFUSE_FLAG) : (bits & ~DIFFUSE_FLAG); + return this; + } + + @Override + public MaterialFinder ambientOcclusion(TriState mode) { + Objects.requireNonNull(mode, "ambient occlusion TriState may not be null"); + + bits = (bits & ~AO_MASK) | (mode.ordinal() << AO_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder glint(TriState mode) { + Objects.requireNonNull(mode, "glint TriState may not be null"); + + bits = (bits & ~GLINT_MASK) | (mode.ordinal() << GLINT_BIT_OFFSET); + return this; + } + + @Override + public MaterialFinder copyFrom(MaterialView material) { + bits = ((MaterialViewImpl) material).bits; + return this; + } + + @Override + public MaterialFinder clear() { + bits = defaultBits; + return this; + } + + @Override + public RenderMaterial find() { + return RenderMaterialImpl.byIndex(bits); + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialView.java b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialView.java new file mode 100644 index 000000000..f0738f763 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialView.java @@ -0,0 +1,41 @@ +package com.gtnewhorizons.angelica.models.material; + +import com.gtnewhorizons.angelica.models.fapi.TriState; + +/** + * Getter methods for {@link RenderMaterial} (immutable) and {@link MaterialFinder} (mutable). + * + *

Values returned by the getters may not necessarily be identical to those requested in the {@link MaterialFinder}. + * The renderer may choose different values that are sufficiently representative for its own processing. + */ +public interface MaterialView { + /** + * @see MaterialFinder#blendMode(BlendMode) + */ + BlendMode blendMode(); + + /** + * @see MaterialFinder#disableColorIndex(boolean) + */ + boolean disableColorIndex(); + + /** + * @see MaterialFinder#emissive(boolean) + */ + boolean emissive(); + + /** + * @see MaterialFinder#disableDiffuse(boolean) + */ + boolean disableDiffuse(); + + /** + * @see MaterialFinder#ambientOcclusion(TriState) + */ + TriState ambientOcclusion(); + + /** + * @see MaterialFinder#glint(TriState) + */ + TriState glint(); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialViewImpl.java b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialViewImpl.java new file mode 100644 index 000000000..781311fd9 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/MaterialViewImpl.java @@ -0,0 +1,89 @@ +package com.gtnewhorizons.angelica.models.material; + +import com.gtnewhorizons.angelica.models.fapi.TriState; +import net.minecraft.util.MathHelper; + +/** + * Default implementation of the standard render materials. + * The underlying representation is simply an int with bit-wise + * packing of the various material properties. This offers + * easy/fast interning via int/object hashmap. + */ +public class MaterialViewImpl implements MaterialView { + private static final BlendMode[] BLEND_MODES = BlendMode.values(); + private static final int BLEND_MODE_COUNT = BLEND_MODES.length; + private static final TriState[] TRI_STATES = TriState.values(); + private static final int TRI_STATE_COUNT = TRI_STATES.length; + + protected static final int BLEND_MODE_BIT_LENGTH = MathHelper.calculateLogBaseTwoDeBruijn(BLEND_MODE_COUNT); + protected static final int COLOR_DISABLE_BIT_LENGTH = 1; + protected static final int EMISSIVE_BIT_LENGTH = 1; + protected static final int DIFFUSE_BIT_LENGTH = 1; + protected static final int AO_BIT_LENGTH = MathHelper.calculateLogBaseTwoDeBruijn(TRI_STATE_COUNT); + protected static final int GLINT_BIT_LENGTH = MathHelper.calculateLogBaseTwoDeBruijn(TRI_STATE_COUNT); + + protected static final int BLEND_MODE_BIT_OFFSET = 0; + protected static final int COLOR_DISABLE_BIT_OFFSET = BLEND_MODE_BIT_OFFSET + BLEND_MODE_BIT_LENGTH; + protected static final int EMISSIVE_BIT_OFFSET = COLOR_DISABLE_BIT_OFFSET + COLOR_DISABLE_BIT_LENGTH; + protected static final int DIFFUSE_BIT_OFFSET = EMISSIVE_BIT_OFFSET + EMISSIVE_BIT_LENGTH; + protected static final int AO_BIT_OFFSET = DIFFUSE_BIT_OFFSET + DIFFUSE_BIT_LENGTH; + protected static final int GLINT_BIT_OFFSET = AO_BIT_OFFSET + AO_BIT_LENGTH; + protected static final int TOTAL_BIT_LENGTH = GLINT_BIT_OFFSET + GLINT_BIT_LENGTH; + + protected static final int BLEND_MODE_MASK = bitMask(BLEND_MODE_BIT_LENGTH, BLEND_MODE_BIT_OFFSET); + protected static final int COLOR_DISABLE_FLAG = bitMask(COLOR_DISABLE_BIT_LENGTH, COLOR_DISABLE_BIT_OFFSET); + protected static final int EMISSIVE_FLAG = bitMask(EMISSIVE_BIT_LENGTH, EMISSIVE_BIT_OFFSET); + protected static final int DIFFUSE_FLAG = bitMask(DIFFUSE_BIT_LENGTH, DIFFUSE_BIT_OFFSET); + protected static final int AO_MASK = bitMask(AO_BIT_LENGTH, AO_BIT_OFFSET); + protected static final int GLINT_MASK = bitMask(GLINT_BIT_LENGTH, GLINT_BIT_OFFSET); + + protected static int bitMask(int bitLength, int bitOffset) { + return ((1 << bitLength) - 1) << bitOffset; + } + + protected static boolean areBitsValid(int bits) { + int blendMode = (bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET; + int ao = (bits & AO_MASK) >>> AO_BIT_OFFSET; + int glint = (bits & GLINT_MASK) >>> GLINT_BIT_OFFSET; + + return blendMode < BLEND_MODE_COUNT + && ao < TRI_STATE_COUNT + && glint < TRI_STATE_COUNT; + } + + protected int bits; + + protected MaterialViewImpl(int bits) { + this.bits = bits; + } + + @Override + public BlendMode blendMode() { + return BLEND_MODES[(bits & BLEND_MODE_MASK) >>> BLEND_MODE_BIT_OFFSET]; + } + + @Override + public boolean disableColorIndex() { + return (bits & COLOR_DISABLE_FLAG) != 0; + } + + @Override + public boolean emissive() { + return (bits & EMISSIVE_FLAG) != 0; + } + + @Override + public boolean disableDiffuse() { + return (bits & DIFFUSE_FLAG) != 0; + } + + @Override + public TriState ambientOcclusion() { + return TRI_STATES[(bits & AO_MASK) >>> AO_BIT_OFFSET]; + } + + @Override + public TriState glint() { + return TRI_STATES[(bits & GLINT_MASK) >>> GLINT_BIT_OFFSET]; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterial.java b/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterial.java new file mode 100644 index 000000000..a0c103814 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterial.java @@ -0,0 +1,57 @@ +package com.gtnewhorizons.angelica.models.material; + +import net.minecraft.util.ResourceLocation; +import net.minecraft.block.Block; + +/** + * All model quads have an associated render material governing + * how the quad will be rendered. + * + *

A material instance is always immutable and thread-safe. References to a material + * remain valid until the end of the current game session. + * + *

Materials can be registered and shared between mods using {@link Renderer#registerMaterial(net.minecraft.util.Identifier, RenderMaterial)}. + * The registering mod is responsible for creating each registered material at startup. + * + *

Materials are not required to know their registration identity, and two materials + * with the same attributes may or may not satisfy equality and identity tests. Model + * implementations should never attempt to analyze materials or implement control logic based on them. + * They are only tokens for communicating quad attributes to the ModelRenderer. + * + *

There are three classes of materials... + * + *

STANDARD MATERIALS + * + *

Standard materials have "normal" rendering with control over lighting, + * color, and texture blending. In the default renderer, "normal" rendering + * emulates unmodified Minecraft. Other renderers may offer a different aesthetic. + * + *

The number of standard materials is finite, but not necessarily small. + * To find a standard material, use {@link Renderer#materialFinder()}. + * + *

All renderer implementations should support standard materials. + * + *

SPECIAL MATERIALS + * + *

Special materials are implemented directly by the Renderer implementation, typically + * with the aim of providing advanced/extended features. Such materials may offer additional + * vertex attributes via extensions to {@link MeshBuilder} and {@link MutableQuadView}. + * + *

Special materials can be obtained using {@link Renderer#materialById(Identifier)} + * with a known identifier. Renderers may provide other means of access. Popular + * special materials could be implemented by multiple renderers, however there is + * no requirement that special materials be cross-compatible. + */ +public interface RenderMaterial extends MaterialView { + /** + * This will be identical to the material that would be obtained by calling {@link MaterialFinder#find()} + * on a new, unaltered, {@link MaterialFinder} instance. It is defined here for clarity and convenience. + * + *

Quads using this material use {@link Block#getRenderBlockPass()} of + * the associated block to determine texture blending, honor block color index, are non-emissive, and apply both + * diffuse and ambient occlusion shading to vertex colors. + * + *

All standard, non-fluid baked models are rendered using this material. + */ + ResourceLocation MATERIAL_STANDARD = new ResourceLocation("fabric", "standard"); +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterialImpl.java b/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterialImpl.java new file mode 100644 index 000000000..045361aa7 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/material/RenderMaterialImpl.java @@ -0,0 +1,34 @@ +package com.gtnewhorizons.angelica.models.material; + +public class RenderMaterialImpl extends MaterialViewImpl implements RenderMaterial { + public static final int VALUE_COUNT = 1 << TOTAL_BIT_LENGTH; + private static final RenderMaterialImpl[] BY_INDEX = new RenderMaterialImpl[VALUE_COUNT]; + + static { + for (int i = 0; i < VALUE_COUNT; i++) { + if (areBitsValid(i)) { + BY_INDEX[i] = new RenderMaterialImpl(i); + } + } + } + + private RenderMaterialImpl(int bits) { + super(bits); + } + + public int index() { + return bits; + } + + public static RenderMaterialImpl byIndex(int index) { + return BY_INDEX[index]; + } + + public static RenderMaterialImpl setDisableDiffuse(RenderMaterialImpl material, boolean disable) { + if (material.disableDiffuse() != disable) { + return byIndex(disable ? (material.bits | DIFFUSE_FLAG) : (material.bits & ~DIFFUSE_FLAG)); + } + + return material; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/models/renderer/IndigoRenderer.java b/src/main/java/com/gtnewhorizons/angelica/models/renderer/IndigoRenderer.java new file mode 100644 index 000000000..2702ad6e6 --- /dev/null +++ b/src/main/java/com/gtnewhorizons/angelica/models/renderer/IndigoRenderer.java @@ -0,0 +1,61 @@ +package com.gtnewhorizons.angelica.models.renderer; + +import com.gtnewhorizons.angelica.models.material.MaterialFinder; +import com.gtnewhorizons.angelica.models.material.MaterialFinderImpl; +import com.gtnewhorizons.angelica.models.material.RenderMaterial; +import net.minecraft.util.ResourceLocation; + +import java.util.HashMap; + +/** + * The Fabric default renderer implementation. Supports all + * features defined in the API except shaders and offers no special materials. + */ +public class IndigoRenderer { + public static final IndigoRenderer INSTANCE = new IndigoRenderer(); + + public static final RenderMaterial MATERIAL_STANDARD = INSTANCE.materialFinder().find(); + + static { + INSTANCE.registerMaterial(RenderMaterial.MATERIAL_STANDARD, MATERIAL_STANDARD); + } + + private final HashMap materialMap = new HashMap<>(); + + private IndigoRenderer() { } + + /** + * Obtain a new {@link MaterialFinder} instance used to retrieve + * standard {@link RenderMaterial} instances. + * + *

Renderer does not retain a reference to returned instances and they should be re-used for + * multiple materials when possible to avoid memory allocation overhead. + */ + public MaterialFinder materialFinder() { + return new MaterialFinderImpl(); + } + + /** + * Return a material previously registered via {@link #registerMaterial(ResourceLocation, RenderMaterial)}. + * Will return null if no material was found matching the given identifier. + */ + public RenderMaterial materialById(ResourceLocation id) { + return materialMap.get(id); + } + + /** + * Register a material for re-use by other mods or models within a mod. + * The registry does not persist registrations - mods must create and register + * all materials at game initialization. + * + *

Returns false if a material with the given identifier is already present, + * leaving the existing material intact. + */ + public boolean registerMaterial(ResourceLocation id, RenderMaterial material) { + if (materialMap.containsKey(id)) return false; + + // cast to prevent acceptance of impostor implementations + materialMap.put(id, material); + return true; + } +} diff --git a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java index ae50d328f..b31cf713c 100644 --- a/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java +++ b/src/main/java/com/gtnewhorizons/angelica/proxy/ClientProxy.java @@ -9,6 +9,7 @@ import com.gtnewhorizons.angelica.glsm.debug.OpenGLDebugging; import com.gtnewhorizons.angelica.hudcaching.HUDCaching; import com.gtnewhorizons.angelica.models.json.Loader; import com.gtnewhorizons.angelica.render.CloudRenderer; +import com.gtnewhorizons.angelica.rendering.AngelicaBlockSafetyRegistry; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; @@ -17,9 +18,12 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; +import cpw.mods.fml.common.registry.GameData; +import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.ReflectionHelper; import jss.notfine.core.Settings; import java.lang.management.ManagementFactory; +import java.util.Iterator; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import me.jellysquid.mods.sodium.client.SodiumDebugScreenHandler; @@ -68,6 +72,14 @@ public class ClientProxy extends CommonProxy { GLStateManager.setRunningSplash(false); LOGGER.info("World loaded - Enabling GLSM Cache"); } + + // Register all blocks. Because blockids are unique to a world, this must be done each load + GameData.getBlockRegistry().forEach(o -> { + + final Block b = (Block) o; + AngelicaBlockSafetyRegistry.canBlockRenderOffThread(b, true, true); + AngelicaBlockSafetyRegistry.canBlockRenderOffThread(b, false, true); + }); } diff --git a/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaBlockSafetyRegistry.java b/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaBlockSafetyRegistry.java index 9765cd4a7..b0b6ac4e2 100644 --- a/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaBlockSafetyRegistry.java +++ b/src/main/java/com/gtnewhorizons/angelica/rendering/AngelicaBlockSafetyRegistry.java @@ -16,26 +16,16 @@ public class AngelicaBlockSafetyRegistry { private static final Reference2BooleanMap ISBRH_SAFETY_MAP = new Reference2BooleanOpenHashMap<>(); private static final StampedLock LOCK = new StampedLock(); - public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH) { - final long stamp = LOCK.readLock(); + /** + * This method is threadsafe to read, and threadsafe to write, but NOT if both could happen at the same time. + */ + public static boolean canBlockRenderOffThread(Block block, boolean checkISBRH, boolean shouldPopulate) { + final Reference2BooleanMap map = checkISBRH ? ISBRH_SAFETY_MAP : BLOCK_SAFETY_MAP; - boolean isOffThread, shouldPopulate; - try { - isOffThread = map.getBoolean(block); - if (isOffThread) { - return true; // no need to check if 'false' was due to not being populated - } - shouldPopulate = !map.containsKey(block); - } finally { - LOCK.unlock(stamp); - } - - if(shouldPopulate) { - isOffThread = populateCanRenderOffThread(block, map); - } - - return isOffThread; + if (shouldPopulate) + return populateCanRenderOffThread(block, map); + return map.getBoolean(block); } private static boolean populateCanRenderOffThread(Block block, Reference2BooleanMap map) { diff --git a/src/main/java/me/jellysquid/mods/sodium/client/model/quad/properties/ModelQuadFlags.java b/src/main/java/me/jellysquid/mods/sodium/client/model/quad/properties/ModelQuadFlags.java index e1b0a0093..c25087f5b 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/model/quad/properties/ModelQuadFlags.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/model/quad/properties/ModelQuadFlags.java @@ -2,6 +2,7 @@ package me.jellysquid.mods.sodium.client.model.quad.properties; import com.gtnewhorizons.angelica.compat.mojang.Axis; import com.gtnewhorizons.angelica.compat.nd.Quad; +import com.gtnewhorizons.angelica.models.GeometryHelper; import net.minecraftforge.common.util.ForgeDirection; public class ModelQuadFlags { @@ -33,7 +34,7 @@ public class ModelQuadFlags { * certain optimizations. */ public static int getQuadFlags(Quad quad) { - final ForgeDirection face = quad.getCoercedFace(); + final ForgeDirection face = quad.getLightFace(); final Axis axis = Axis.fromDirection(ModelQuadFacing.fromDirection(face)); float minX = 32.0F; @@ -97,4 +98,16 @@ public class ModelQuadFlags { return flags; } + + /** + * See {@link #getQuadFlags(Quad)}. This one converts FRAPI bits to Sodium ones. + */ + public static int getQuadFlags(int bits) { + + int flags = 0; + flags |= ((bits & GeometryHelper.AXIS_ALIGNED_FLAG) == GeometryHelper.AXIS_ALIGNED_FLAG) ? IS_PARALLEL : 0; + flags |= ((bits & GeometryHelper.LIGHT_FACE_FLAG) == GeometryHelper.LIGHT_FACE_FLAG) ? IS_ALIGNED : 0; + flags |= ((bits & GeometryHelper.CUBIC_FLAG) == GeometryHelper.CUBIC_FLAG) ? 0 : IS_PARTIAL; + return flags; + } } diff --git a/src/main/java/me/jellysquid/mods/sodium/client/render/chunk/tasks/ChunkRenderRebuildTask.java b/src/main/java/me/jellysquid/mods/sodium/client/render/chunk/tasks/ChunkRenderRebuildTask.java index 8aaee240a..8f68f6dbf 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/render/chunk/tasks/ChunkRenderRebuildTask.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/render/chunk/tasks/ChunkRenderRebuildTask.java @@ -91,7 +91,7 @@ public class ChunkRenderRebuildTask extends ChunkR private boolean rendersOffThread(Block block) { final int type = block.getRenderType(); - return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true); + return (type < 42 && type != 22 && AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, false, false)) || AngelicaBlockSafetyRegistry.canBlockRenderOffThread(block, true, false); } private void handleRenderBlocksTextures(RenderBlocks rb, ChunkRenderData.Builder builder) { diff --git a/src/main/java/me/jellysquid/mods/sodium/client/render/pipeline/BlockRenderer.java b/src/main/java/me/jellysquid/mods/sodium/client/render/pipeline/BlockRenderer.java index 21adb8efc..eb2c00a2c 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/render/pipeline/BlockRenderer.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/render/pipeline/BlockRenderer.java @@ -66,17 +66,18 @@ public class BlockRenderer { for (ForgeDirection dir : ForgeDirection.values()) { this.random.setSeed(seed); - List quads = qBlock.getQuads(world, pos, block, meta, dir, random, this.quadPool); - - if (quads.isEmpty()) continue; + List quads = null; if (!cull || this.occlusionCache.shouldDrawSide(block, meta, world, pos, dir)) { + quads = qBlock.getQuads(world, pos, block, meta, dir, random, this.quadPool); + if (quads.isEmpty()) continue; this.renderQuadList(pos, lighter, buffers, quads, ModelQuadFacing.fromDirection(dir), true); rendered = true; } - for (Quad q : quads) this.quadPool.releaseInstance(q); + if (quads != null) + for (Quad q : quads) this.quadPool.releaseInstance(q); } } else { @@ -106,10 +107,10 @@ public class BlockRenderer { } private void renderQuadList(BlockPos pos, LightPipeline lighter, ChunkModelBuffers buffers, List quads, ModelQuadFacing facing, boolean useSodiumLight) { + final ForgeDirection cullFace = ModelQuadFacing.toDirection(facing); final ModelVertexSink sink = buffers.getSink(facing); sink.ensureCapacity(quads.size() * 4); - final ForgeDirection cullFace = ModelQuadFacing.toDirection(facing); final ChunkRenderData.Builder renderData = buffers.getRenderData(); @@ -118,13 +119,10 @@ public class BlockRenderer { for (int i = 0, quadsSize = quads.size(); i < quadsSize; i++) { final Quad quad = quads.get(i); - if(quad.normal != facing) - continue; - final QuadLightData light = this.cachedQuadLightData; if (useSodiumLight || this.useSeparateAo) - lighter.calculate(quad, pos, light, cullFace, quad.getCoercedFace(), quad.hasShade()); + lighter.calculate(quad, pos, light, cullFace, quad.getLightFace(), quad.isShade()); this.renderQuad(sink, quad, light, renderData, useSodiumLight); } diff --git a/src/main/java/me/jellysquid/mods/sodium/client/util/MathUtil.java b/src/main/java/me/jellysquid/mods/sodium/client/util/MathUtil.java index 980058068..65cbb3b3e 100644 --- a/src/main/java/me/jellysquid/mods/sodium/client/util/MathUtil.java +++ b/src/main/java/me/jellysquid/mods/sodium/client/util/MathUtil.java @@ -23,4 +23,8 @@ public class MathUtil { private static long cantor(long a, long b) { return (a + b + 1) * (a + b) / 2 + b; } + + public static boolean fuzzy_eq(float a, float b) { + return Math.abs(a - b) < 1e-5; + } } diff --git a/src/main/java/me/jellysquid/mods/sodium/common/util/DirectionUtil.java b/src/main/java/me/jellysquid/mods/sodium/common/util/DirectionUtil.java index be03e7245..f6881102b 100644 --- a/src/main/java/me/jellysquid/mods/sodium/common/util/DirectionUtil.java +++ b/src/main/java/me/jellysquid/mods/sodium/common/util/DirectionUtil.java @@ -1,6 +1,8 @@ package me.jellysquid.mods.sodium.common.util; import net.minecraftforge.common.util.ForgeDirection; +import org.joml.Vector3f; +import org.joml.Vector3i; /** * Contains a number of cached arrays to avoid allocations since calling Enum#values() requires the backing array to @@ -14,4 +16,21 @@ public class DirectionUtil { // Provides the same order as enumerating ForgeDirection and checking the axis of each value public static final ForgeDirection[] HORIZONTAL_DIRECTIONS = new ForgeDirection[] { ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.WEST, ForgeDirection.EAST }; + public static final Vector3i[] STEP = { + + //DOWN + new Vector3i(0, -1, 0), + // UP + new Vector3i(0, 1, 0), + // NORTH + new Vector3i(0, 0, -1), + // SOUTH + new Vector3i(0, 0, 1), + // WEST + new Vector3i(-1, 0, 0), + // EAST + new Vector3i(1, 0, 0), + // UNKNOWN + new Vector3i(0, 0, 0) + }; } diff --git a/src/main/resources/META-INF/angelica_at.cfg b/src/main/resources/META-INF/angelica_at.cfg index d6400b3ce..d8af84cdb 100644 --- a/src/main/resources/META-INF/angelica_at.cfg +++ b/src/main/resources/META-INF/angelica_at.cfg @@ -47,3 +47,5 @@ public net.minecraft.client.gui.GuiSlot field_148165_u # hasListHeader public net.minecraft.client.gui.GuiSlot field_148161_k # mc public net.minecraft.client.gui.GuiSlot func_148121_k()V # void bindAmountScrolled() public net.minecraft.client.gui.GuiSlot func_148136_c(IIII)V # void overlayBackground() + +public net.minecraft.util.MathHelper func_151241_e(I)I # int calculateLogBaseTwoDeBruijn()