diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index be519ea5..a4afe55b 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -11,10 +11,11 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Setup JDK 1.8 - uses: actions/setup-java@v1 + - uses: actions/checkout@v4 + - name: Setup Java + uses: actions/setup-java@v4 with: - java-version: 1.8 + java-version: 21 + distribution: 'temurin' - name: Build - run: ./gradlew build + run: ./gradlew check diff --git a/.gitignore b/.gitignore index 820dad1e..1030c646 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,17 @@ # exclude all /* -# Include important folders - # Gradle stuff !gradle/ !gradlew !gradlew.bat !build.gradle -!build.properties !gradle.properties !settings.gradle # Other Files. !LICENSE !README.md -!.travis.yml # Include git important files !.gitmodules @@ -24,5 +20,3 @@ # Include Important Folders !src/ -!libs/ -!archive diff --git a/archive/codechicken/lib/render/QBImporter.java b/archive/codechicken/lib/render/QBImporter.java deleted file mode 100644 index 03724b64..00000000 --- a/archive/codechicken/lib/render/QBImporter.java +++ /dev/null @@ -1,808 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.texture.TextureDataHolder; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.vec.*; -import codechicken.lib.vec.uv.UV; -import codechicken.lib.vec.uv.UVScale; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.ResourceLocation; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.*; -import java.util.*; - -//TODO, Is this needed anymore? -public class QBImporter { - - private static class ImagePackNode { - - Rectangle4i rect; - ImagePackNode child1; - ImagePackNode child2; - QBImage packed; - - public ImagePackNode(int x, int y, int w, int h) { - rect = new Rectangle4i(x, y, w, h); - } - - public boolean pack(QBImage img) { - if (child1 != null) { - return child1.pack(img) || child2.pack(img); - } - - if (packed != null) { - return false; - } - - int fit = getFit(img.width(), img.height()); - if (fit == 0) { - return false; - } - - if ((fit & 2) != 0) {//exact fit - packed = img; - img.packSlot = rect; - img.packT = new ImageTransform((fit & 1) << 2); - return true; - } - - int w = (fit & 1) == 0 ? img.width() : img.height(); - int h = (fit & 1) == 0 ? img.height() : img.width(); - - if (rect.w - w > rect.h - h) {//create split with biggest leftover space - child1 = new ImagePackNode(rect.x, rect.y, w, rect.h); - child2 = new ImagePackNode(rect.x + w, rect.y, rect.w - w, rect.h); - } else { - child1 = new ImagePackNode(rect.x, rect.y, rect.w, h); - child2 = new ImagePackNode(rect.x, rect.y + h, rect.w, rect.h - h); - } - return child1.pack(img); - } - - private int getFit(int w, int h) { - if (w == rect.w && h == rect.h) { - return 2; - } - if (w == rect.h && h == rect.w) { - return 3; - } - if (rect.w >= w && rect.h >= h) { - return 4; - } - if (rect.w >= h && rect.h >= w) { - return 5; - } - - return 0; - } - - private static void nextSize(Rectangle4i rect, boolean square) { - if (square) { - rect.w <<= 1; - rect.h <<= 1; - } else { - if (rect.w == rect.h) { - rect.w *= 2; - } else { - rect.h *= 2; - } - } - } - - public static ImagePackNode pack(List images, boolean square) { - Collections.sort(images); - - int area = 0; - for (QBImage img : images) { - area += img.area(); - } - - ImagePackNode node = new ImagePackNode(0, 0, 2, 2); - while (node.rect.area() < area) { - nextSize(node.rect, square); - } - - while (true) { - boolean packed = true; - for (QBImage img : images) { - if (!node.pack(img)) { - packed = false; - break; - } - } - - if (packed) { - return node; - } - - node.child1 = node.child2 = null; - nextSize(node.rect, square); - } - } - - public BufferedImage toImage() { - BufferedImage img = new BufferedImage(rect.w, rect.h, BufferedImage.TYPE_INT_ARGB); - write(img); - return img; - } - - private void write(BufferedImage img) { - if (child1 != null) { - child1.write(img); - child2.write(img); - } else if (packed != null) { - ImageTransform t = packed.packT; - for (int u = 0; u < rect.w; u++) { - for (int v = 0; v < rect.h; v++) { - int rgba = t.access(packed, u, v); - img.setRGB(u + rect.x, v + rect.y, rgba >>> 8 | rgba << 24); - } - } - } - } - } - - private static class ImageTransform { - - int transform; - - public ImageTransform(int i) { - transform = i; - } - - public ImageTransform() { - this(0); - } - - public boolean transpose() { - return (transform & 4) != 0; - } - - public boolean flipU() { - return (transform & 1) != 0; - } - - public boolean flipV() { - return (transform & 2) != 0; - } - - public int access(QBImage img, int u, int v) { - if (transpose()) { - int tmp = u; - u = v; - v = tmp; - } - if (flipU()) { - u = img.width() - 1 - u; - } - if (flipV()) { - v = img.height() - 1 - v; - } - - return img.data[u][v]; - } - - public UV transform(UV uv) { - if (transpose()) { - double tmp = uv.u; - uv.u = uv.v; - uv.v = tmp; - } - if (flipU()) { - uv.u = 1 - uv.u; - } - if (flipV()) { - uv.v = 1 - uv.v; - } - - return uv; - } - } - - public static class QBImage implements Comparable { - - int[][] data; - ImageTransform packT; - Rectangle4i packSlot; - - public int width() { - return data.length; - } - - public int height() { - return data[0].length; - } - - public int area() { - return width() * height(); - } - - @Override - public int compareTo(QBImage o) { - int a = area(); - int b = o.area(); - return a > b ? -1 : a == b ? 0 : 1; - } - - public ImageTransform transformTo(QBImage img) { - if (width() == img.width() && height() == img.height()) { - for (int i = 0; i < 4; i++) { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) { - return t; - } - } - } - if (width() == img.height() && height() == img.width()) { - for (int i = 4; i < 8; i++) { - ImageTransform t = new ImageTransform(i); - if (equals(img, t)) { - return t; - } - } - } - return null; - } - - public boolean equals(QBImage img, ImageTransform t) { - for (int u = 0; u < img.width(); u++) { - for (int v = 0; v < img.height(); v++) { - if (t.access(this, u, v) != img.data[u][v]) { - return false; - } - } - } - - return true; - } - - public void transform(UV uv) { - packT.transform(uv); - uv.u *= packSlot.w; - uv.v *= packSlot.h; - uv.u += packSlot.x; - uv.v += packSlot.y; - } - } - - private static final int[][] vertOrder = new int[][] {//clockwise because MC is left handed - { 3, 0 }, { 1, 0 }, { 1, 2 }, { 3, 2 } }; - - public static class QBQuad { - - public Vertex5[] verts = new Vertex5[4]; - public QBImage image = new QBImage(); - public ImageTransform t = new ImageTransform(); - public int side; - - public QBQuad(int side) { - this.side = side; - } - - public void applyImageT() { - for (Vertex5 vert : verts) { - t.transform(vert.uv); - image.transform(vert.uv); - } - } - - public static QBQuad restore(Rectangle4i flat, int side, double d, QBImage img) { - QBQuad quad = new QBQuad(side); - quad.image = img; - - Transformation t = new Scale(-1, 1, -1).with(Rotation.sideOrientation(side, 0)).with(new Translation(new Vector3().setSide(side, d))); - quad.verts[0] = new Vertex5(flat.x, 0, flat.y, 0, 0); - quad.verts[1] = new Vertex5(flat.x + flat.w, 0, flat.y, 1, 0); - quad.verts[2] = new Vertex5(flat.x + flat.w, 0, flat.y + flat.h, 1, 1); - quad.verts[3] = new Vertex5(flat.x, 0, flat.y + flat.h, 0, 1); - for (Vertex5 vert : quad.verts) { - vert.apply(t); - } - - return quad; - } - - public Rectangle4i flatten() { - Transformation t = Rotation.sideOrientation(side, 0).inverse().with(new Scale(-1, 0, -1)); - Vector3 vmin = verts[0].vec.copy().apply(t); - Vector3 vmax = verts[2].vec.copy().apply(t); - return new Rectangle4i((int) vmin.x, (int) vmin.z, (int) (vmax.x - vmin.x), (int) (vmax.z - vmin.z)); - } - } - - public static class QBCuboid { - - public QBMatrix mat; - public CuboidCoord c; - public int sides; - - public QBCuboid(QBMatrix mat, CuboidCoord c) { - this.mat = mat; - this.c = c; - sides = 0; - } - - public static boolean intersects(QBCuboid a, QBCuboid b) { - CuboidCoord c = a.c; - CuboidCoord d = b.c; - return c.min.x <= d.max.x && d.min.x <= c.max.x && c.min.y <= d.max.y && d.min.y <= c.max.y && c.min.z <= d.max.z && d.min.z <= c.max.z; - } - - public static void clip(QBCuboid a, QBCuboid b) { - if (intersects(a, b)) { - a.clip(b); - b.clip(a); - } - } - - public void clip(QBCuboid o) { - CuboidCoord d = o.c; - for (int a = 0; a < 6; a += 2) { - int a1 = (a + 2) % 6; - int a2 = (a + 4) % 6; - if (c.getSide(a1 + 1) <= d.getSide(a1 + 1) && c.getSide(a1) >= d.getSide(a1) && c.getSide(a2 + 1) <= d.getSide(a2 + 1) && c.getSide(a2) >= d.getSide(a2)) { - - if (c.getSide(a) <= d.getSide(a + 1) && c.getSide(a) >= d.getSide(a)) { - c.setSide(a, d.getSide(a + 1) + 1); - sides |= 1 << a; - } - if (c.getSide(a + 1) >= d.getSide(a) && c.getSide(a + 1) <= d.getSide(a + 1)) { - c.setSide(a + 1, d.getSide(a) - 1); - sides |= 2 << a; - } - } - } - } - - public void extractQuads(List quads) { - Cuboid6 box = c.bounds(); - for (int s = 0; s < 6; s++) { - if ((sides & 1 << s) == 0) { - quads.add(extractQuad(s, box)); - } - } - } - - private QBQuad extractQuad(int side, Cuboid6 box) { - double[] da = new double[3]; - da[side >> 1] = box.getSide(side); - - QBQuad quad = new QBQuad(side); - for (int i = 0; i < 4; i++) { - int rU = vertOrder[i][0]; - int rV = vertOrder[i][1]; - int sideU = Rotation.rotateSide(side, rU); - int sideV = Rotation.rotateSide(side, rV); - da[sideU >> 1] = box.getSide(sideU); - da[sideV >> 1] = box.getSide(sideV); - quad.verts[i] = new Vertex5(Vector3.fromAxes(da), (3 - rU) / 2, rV / 2); - } - - int sideU = Rotation.rotateSide(side, 1); - int sideV = Rotation.rotateSide(side, 2); - quad.image.data = new int[c.size(sideU)][c.size(sideV)]; - QBImage image = quad.image; - - int[] ia = new int[3]; - ia[side >> 1] = c.getSide(side); - ia[sideU >> 1] = c.getSide(sideU ^ 1); - ia[sideV >> 1] = c.getSide(sideV ^ 1); - BlockCoord b = BlockCoord.fromAxes(ia); - BlockCoord bU = BlockCoord.sideOffsets[sideU]; - BlockCoord bV = BlockCoord.sideOffsets[sideV]; - for (int u = 0; u < image.width(); u++) { - for (int v = 0; v < image.height(); v++) { - image.data[u][v] = mat.matrix[b.x + bU.x * u + bV.x * v][b.y + bU.y * u + bV.y * v][b.z + bU.z * u + bV.z * v]; - } - } - - return quad; - } - } - - public static class QBMatrix { - - public String name; - public BlockCoord pos; - public BlockCoord size; - public int[][][] matrix; - - public void readMatrix(DataInputStream din, boolean compressed) throws IOException { - if (compressed) { - int z = 0; - while (z < size.z) { - int index = 0; - - while (true) { - int data = din.readInt(); - - if (data == NEXTSLICEFLAG) { - break; - } - - if (data == CODEFLAG) { - int count = readTni(din); - data = din.readInt(); - - for (int j = 0; j < count; j++, index++) { - matrix[index % size.x][index / size.x][z] = data; - } - } else { - matrix[index % size.x][index / size.x][z] = data; - index++; - } - } - z++; - } - } else { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - matrix[x][y][z] = din.readInt(); - } - } - } - } - } - - public void convertBGRAtoRGBA() { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - int i = matrix[x][y][z]; - matrix[x][y][z] = Integer.reverseBytes(i >>> 8) | i & 0xFF; - } - } - } - } - - private boolean voxelFull(boolean[][][] solid, CuboidCoord c) { - for (BlockCoord b : c) { - if (matrix[b.x][b.y][b.z] == 0) { - return false; - } - } - for (BlockCoord b : c) { - solid[b.x][b.y][b.z] = false; - } - return true; - } - - private QBCuboid expand(boolean[][][] solid, BlockCoord b) { - CuboidCoord c = new CuboidCoord(b); - solid[b.x][b.y][b.z] = false; - - for (int s = 0; s < 6; s++) { - CuboidCoord slice = c.copy(); - slice.expand(s ^ 1, -(slice.size(s) - 1)); - slice.expand(s, 1); - - while (slice.getSide(s) >= 0 && slice.getSide(s) < size.getSide(s)) { - if (!voxelFull(solid, slice)) { - break; - } - slice.expand(s ^ 1, -1); - slice.expand(s, 1); - c.expand(s, 1); - } - } - return new QBCuboid(this, c); - } - - public List rectangulate() { - List list = new ArrayList<>(); - boolean[][][] solid = new boolean[size.x][size.y][size.z]; - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - for (int x = 0; x < size.x; x++) { - solid[x][y][z] = matrix[x][y][z] != 0; - } - } - } - - for (int x = 0; x < size.x; x++) { - for (int z = 0; z < size.z; z++) { - for (int y = 0; y < size.y; y++) { - if (solid[x][y][z]) { - list.add(expand(solid, new BlockCoord(x, y, z))); - } - } - } - } - - for (int i = 0; i < list.size(); i++) { - for (int j = i + 1; j < list.size(); j++) { - QBCuboid.clip(list.get(i), list.get(j)); - } - } - - return list; - } - - public List extractQuads(boolean texturePlanes) { - List quads = new LinkedList<>(); - for (QBCuboid c : rectangulate()) { - c.extractQuads(quads); - } - - if (texturePlanes) { - optimisePlanes(quads); - } - - return quads; - } - - private void optimisePlanes(List quads) { - Multimap map = HashMultimap.create(); - for (QBQuad quad : quads) { - map.put(quad.side | ((int) quad.verts[0].vec.getSide(quad.side)) << 3, quad); - } - - quads.clear(); - for (Integer key : map.keySet()) { - Collection plane = map.get(key); - if (plane.size() == 1) { - quads.add(plane.iterator().next()); - continue; - } - - int side = key & 7; - Rectangle4i rect = null; - for (QBQuad q : plane) { - if (rect == null) { - rect = q.flatten(); - } else { - rect.include(q.flatten()); - } - } - - QBImage img = new QBImage(); - img.data = new int[rect.w][rect.h]; - for (QBQuad q : plane) { - QBImage from = q.image; - Rectangle4i r = q.flatten(); - int du = r.x - rect.x; - int dv = r.y - rect.y; - for (int u = 0; u < from.width(); u++) { - for (int v = 0; v < from.height(); v++) { - img.data[du + u][dv + v] = from.data[u][v]; - } - } - } - - quads.add(QBQuad.restore(rect, side, key >> 3, img)); - } - } - - public CCModel buildModel(List quads, BufferedImage img, boolean scaleMC) { - CCModel m = CCModel.quadModel(quads.size() * 4); - int i = 0; - for (QBQuad quad : quads) { - quad.applyImageT(); - m.verts[i++] = quad.verts[0]; - m.verts[i++] = quad.verts[1]; - m.verts[i++] = quad.verts[2]; - m.verts[i++] = quad.verts[3]; - } - m.apply(new UVScale(1D / img.getWidth(), 1D / img.getHeight())); - m.apply(new Translation(pos.x, pos.y, pos.z)); - if (scaleMC) { - m.apply(new Scale(1 / 16D)); - } - m.computeNormals(); - return m; - } - - private static void addImages(List quads, List images) { - for (QBQuad q : quads) { - QBImage img = q.image; - boolean matched = false; - for (QBImage img2 : images) { - ImageTransform t = img.transformTo(img2); - if (t != null) { - q.t = t; - q.image = img2; - matched = true; - break; - } - } - if (!matched) { - images.add(img); - } - } - } - } - - public static final int TEXTUREPLANES = 1; - public static final int SQUARETEXTURE = 2; - public static final int MERGETEXTURES = 4; - public static final int SCALEMC = 8; - - public static class QBModel { - - public QBMatrix[] matrices; - public boolean rightHanded; - - public RasterisedModel toRasterisedModel(int flags) { - List qbImages = new ArrayList<>(); - List> modelQuads = new ArrayList<>(); - List images = new ArrayList<>(); - - boolean texturePlanes = (flags & TEXTUREPLANES) != 0; - boolean squareTextures = (flags & SQUARETEXTURE) != 0; - boolean mergeTextures = (flags & MERGETEXTURES) != 0; - boolean scaleMC = (flags & SCALEMC) != 0; - - for (QBMatrix mat : matrices) { - List quads = mat.extractQuads(texturePlanes); - modelQuads.add(quads); - QBMatrix.addImages(quads, qbImages); - if (!mergeTextures) { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - qbImages.clear(); - } - } - - if (mergeTextures) { - images.add(ImagePackNode.pack(qbImages, squareTextures).toImage()); - } - - RasterisedModel m = new RasterisedModel(images); - for (int i = 0; i < matrices.length; i++) { - QBMatrix mat = matrices[i]; - BufferedImage img = images.get(mergeTextures ? 0 : i); - m.add(mat.name, mat.buildModel(modelQuads.get(i), img, scaleMC)); - } - return m; - } - } - - public static class RasterisedModel { - - private class Holder { - - CCModel m; - int img; - - public Holder(CCModel m, int img) { - this.m = m; - this.img = img; - } - } - - private Map map = new HashMap<>(); - private List images; - - public RasterisedModel(List images) { - this.images = images; - } - - public void add(String name, CCModel m) { - map.put(name, new Holder(m, Math.min(map.size(), images.size() - 1))); - } - - public CCModel getModel(String key) { - return map.get(key).m; - } - - public TextureAtlasSprite getIcon(String key, TextureMap textureMap) { - int img = map.get(key).img; - String iconName = "QBModel" + hashCode() + "_img"; - TextureAtlasSprite icon = textureMap.getTextureExtry(iconName); - if (icon != null) { - return icon; - } - - return TextureUtils.getTextureSpecial(textureMap, iconName).addTexture(new TextureDataHolder(images.get(img))); - } - - private void exportImg(BufferedImage img, File imgFile) throws IOException { - if (!imgFile.exists()) { - imgFile.createNewFile(); - } - ImageIO.write(img, "PNG", imgFile); - } - - public void export(File objFile, File imgDir) { - try { - if (!objFile.exists()) { - objFile.createNewFile(); - } - if (!imgDir.exists()) { - imgDir.mkdirs(); - } - - Map modelMap = new HashMap<>(); - for (Map.Entry e : map.entrySet()) { - modelMap.put(e.getKey(), e.getValue().m); - } - - PrintWriter p = new PrintWriter(objFile); - CCOBJParser.exportObj(modelMap, p); - p.close(); - - if (images.size() < map.size()) { - exportImg(images.get(0), new File(imgDir, objFile.getName().replaceAll("(.+)\\..+", "$1.png"))); - } else { - for (Map.Entry e : map.entrySet()) { - exportImg(images.get(e.getValue().img), new File(imgDir, e.getKey() + ".png")); - } - } - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - private static String readAsciiString(DataInputStream din) throws IOException { - byte[] bytes = new byte[din.readByte() & 0xFF]; - din.readFully(bytes); - return new String(bytes, "US-ASCII"); - } - - private static int readTni(DataInputStream din) throws IOException { - return Integer.reverseBytes(din.readInt()); - } - - private static final int CODEFLAG = Integer.reverseBytes(2); - private static final int NEXTSLICEFLAG = Integer.reverseBytes(6); - - public static QBModel loadQB(InputStream input) throws IOException { - DataInputStream din = new DataInputStream(input); - - QBModel m = new QBModel(); - int version = din.readInt(); - int colorFormat = din.readInt(); - m.rightHanded = din.readInt() != 0; - boolean compressed = din.readInt() != 0; - boolean visEncoded = din.readInt() != 0; - - if (visEncoded) { - throw new IllegalArgumentException("Encoded Visiblity States not supported"); - } - - m.matrices = new QBMatrix[readTni(din)]; - for (int i = 0; i < m.matrices.length; i++) { - QBMatrix mat = new QBMatrix(); - m.matrices[i] = mat; - mat.name = readAsciiString(din); - mat.size = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.pos = new BlockCoord(readTni(din), readTni(din), readTni(din)); - mat.matrix = new int[mat.size.x][mat.size.y][mat.size.z]; - mat.readMatrix(din, compressed); - if (colorFormat == 1) { - mat.convertBGRAtoRGBA(); - } - } - - return m; - } - - public static QBModel loadQB(ResourceLocation res) { - try { - return loadQB(Minecraft.getMinecraft().getResourceManager().getResource(res).getInputStream()); - } catch (Exception e) { - throw new RuntimeException("failed to load model: " + res, e); - } - } - - public static QBModel loadQB(File file) { - try { - FileInputStream fin = new FileInputStream(file); - try { - return loadQB(fin); - } finally { - fin.close(); - } - } catch (Exception e) { - throw new RuntimeException("failed to load model: " + file.getPath(), e); - } - } -} diff --git a/archive/codechicken/lib/tool/LibDownloader.java b/archive/codechicken/lib/tool/LibDownloader.java deleted file mode 100644 index 7840cfb3..00000000 --- a/archive/codechicken/lib/tool/LibDownloader.java +++ /dev/null @@ -1,111 +0,0 @@ -package codechicken.lib.tool; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.nio.ByteBuffer; -import java.util.LinkedList; -import java.util.List; - -public class LibDownloader { - - private static String[] libs = new String[] { "org/ow2/asm/asm-debug-all/5.0.3/asm-debug-all-5.0.3.jar", "com/google/guava/guava/14.0/guava-14.0.jar", "net/sf/jopt-simple/jopt-simple/4.5/jopt-simple-4.5.jar", "org/apache/logging/log4j/log4j-core/2.0-beta9/log4j-core-2.0-beta9.jar", "org/apache/logging/log4j/log4j-api/2.0-beta9/log4j-api-2.0-beta9.jar" }; - private static File libDir = new File("lib"); - - private static ByteBuffer downloadBuffer = ByteBuffer.allocateDirect(1 << 23); - - public static void load() { - if (!libDir.exists()) { - libDir.mkdir(); - } - if (!libDir.isDirectory()) { - throw new RuntimeException("/lib is not a directory"); - } - - List missing = checkExists(); - for (String lib : missing) { - download(lib); - } - addPaths(libs); - } - - private static void addPaths(String[] libs) { - try { - URLClassLoader cl = (URLClassLoader) ClassLoader.getSystemClassLoader(); - Method m_addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); - m_addURL.setAccessible(true); - for (String lib : libs) { - m_addURL.invoke(cl, new File(libDir, fileName(lib)).toURI().toURL()); - } - } catch (Exception e) { - throw new RuntimeException("Failed to add libraries to classpath", e); - } - } - - private static void download(String lib) { - File libFile = new File(libDir, fileName(lib)); - try { - URL libDownload = new URL("http://repo1.maven.org/maven2/" + lib); - URLConnection connection = libDownload.openConnection(); - connection.setConnectTimeout(5000); - connection.setReadTimeout(5000); - connection.setRequestProperty("User-Agent", "CodeChickenLib Downloader"); - int sizeGuess = connection.getContentLength(); - download(connection.getInputStream(), sizeGuess, libFile); - } catch (Exception e) { - libFile.delete(); - throw new RuntimeException("A download error occured", e); - } - } - - private static void download(InputStream is, int sizeGuess, File target) throws Exception { - String name = target.getName(); - if (sizeGuess > downloadBuffer.capacity()) { - throw new Exception(String.format("The file %s is too large to be downloaded", name)); - } - - downloadBuffer.clear(); - - int bytesRead, fullLength = 0; - - System.out.format("Downloading lib %s", name); - byte[] smallBuffer = new byte[1024]; - while ((bytesRead = is.read(smallBuffer)) >= 0) { - downloadBuffer.put(smallBuffer, 0, bytesRead); - fullLength += bytesRead; - System.out.format("\rDownloading lib %s %d%%", name, fullLength * 100 / sizeGuess); - } - System.out.format("\rDownloaded lib %s \n", name); - is.close(); - downloadBuffer.limit(fullLength); - - if (!target.exists()) { - target.createNewFile(); - } - - downloadBuffer.position(0); - FileOutputStream fos = new FileOutputStream(target); - fos.getChannel().write(downloadBuffer); - fos.close(); - } - - private static String fileName(String lib) { - return lib.replaceAll(".+/", ""); - } - - private static List checkExists() { - LinkedList list = new LinkedList<>(); - for (String lib : libs) { - File file = new File(libDir, fileName(lib)); - if (!file.exists()) { - list.add(lib); - } - } - return list; - } - -} diff --git a/archive/codechicken/lib/tool/MCStripTransformer.java b/archive/codechicken/lib/tool/MCStripTransformer.java deleted file mode 100644 index d9ad82df..00000000 --- a/archive/codechicken/lib/tool/MCStripTransformer.java +++ /dev/null @@ -1,49 +0,0 @@ -package codechicken.lib.tool; - -import codechicken.lib.asm.ASMHelper; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.commons.Remapper; -import org.objectweb.asm.commons.RemappingMethodAdapter; -import org.objectweb.asm.tree.ClassNode; -import org.objectweb.asm.tree.MethodNode; - -import java.util.Iterator; - -public class MCStripTransformer { - - public static class ReferenceDetector extends Remapper { - - boolean found = false; - - @Override - public String map(String typeName) { - if (typeName.startsWith("net/minecraft") || !typeName.contains("/")) { - found = true; - } - return typeName; - } - } - - public static byte[] transform(byte[] bytes) { - ClassNode cnode = ASMHelper.createClassNode(bytes, ClassReader.EXPAND_FRAMES); - - boolean changed = false; - Iterator it = cnode.methods.iterator(); - while (it.hasNext()) { - MethodNode mnode = it.next(); - ReferenceDetector r = new ReferenceDetector(); - mnode.accept(new RemappingMethodAdapter(mnode.access, mnode.desc, new MethodVisitor(Opcodes.ASM4) { - }, r)); - if (r.found) { - it.remove(); - changed = true; - } - } - if (changed) { - bytes = ASMHelper.createBytes(cnode, 0); - } - return bytes; - } -} diff --git a/archive/codechicken/lib/tool/Main.java b/archive/codechicken/lib/tool/Main.java deleted file mode 100644 index 039121ca..00000000 --- a/archive/codechicken/lib/tool/Main.java +++ /dev/null @@ -1,14 +0,0 @@ -package codechicken.lib.tool; - -public class Main { - - public static void main(String[] args) { - LibDownloader.load(); - try { - Class c_toolMain = new StripClassLoader().loadClass("codechicken.lib.tool.ToolMain"); - c_toolMain.getDeclaredMethod("main", String[].class).invoke(null, new Object[] { args }); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} diff --git a/archive/codechicken/lib/tool/StripClassLoader.java b/archive/codechicken/lib/tool/StripClassLoader.java deleted file mode 100644 index 1a2f86db..00000000 --- a/archive/codechicken/lib/tool/StripClassLoader.java +++ /dev/null @@ -1,53 +0,0 @@ -package codechicken.lib.tool; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; - -public class StripClassLoader extends URLClassLoader { - - public StripClassLoader() { - super(new URL[0], StripClassLoader.class.getClassLoader()); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (!name.startsWith("codechicken.lib")) { - return super.loadClass(name); - } - - try { - String resName = name.replace('.', '/') + ".class"; - InputStream res = getResourceAsStream(resName); - if (res == null) { - throw new ClassNotFoundException("Could not find resource: " + resName); - } - byte[] bytes = readFully(res); - bytes = transform(bytes); - return defineClass(name, bytes, 0, bytes.length); - - } catch (IOException e) { - throw new ClassNotFoundException(name, e); - } - } - - public static byte[] readFully(InputStream is) throws IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - - int read; - byte[] data = new byte[16384]; - while ((read = is.read(data, 0, data.length)) > 0) { - buffer.write(data, 0, read); - } - - return buffer.toByteArray(); - } - - private byte[] transform(byte[] bytes) { - - bytes = MCStripTransformer.transform(bytes); - return bytes; - } -} diff --git a/archive/codechicken/lib/tool/ToolMain.java b/archive/codechicken/lib/tool/ToolMain.java deleted file mode 100644 index 46dd0353..00000000 --- a/archive/codechicken/lib/tool/ToolMain.java +++ /dev/null @@ -1,48 +0,0 @@ -package codechicken.lib.tool; - -import codechicken.lib.tool.module.ModuleQBConverter; - -public class ToolMain { - - public interface Module { - - void main(String[] args); - - String name(); - - void printHelp(); - } - - public static Module[] modules = new Module[] { new ModuleQBConverter() }; - - private static void printHelp() { - System.out.println("Usage: [module] [args]"); - System.out.println(" Modules: "); - for (Module m : modules) { - System.out.println(" - " + m.name()); - } - System.out.println("-h [module] for module help"); - } - - public static void main(String[] args) { - if (args.length > 0) { - for (Module m : modules) { - if (args[0].equals(m.name())) { - String[] args2 = new String[args.length - 1]; - System.arraycopy(args, 1, args2, 0, args2.length); - m.main(args2); - return; - } - } - if (args[0].equals("-h") && args.length >= 2) { - for (Module m : modules) { - if (args[1].equals(m.name())) { - m.printHelp(); - return; - } - } - } - } - printHelp(); - } -} diff --git a/archive/codechicken/lib/tool/module/JOptModule.java b/archive/codechicken/lib/tool/module/JOptModule.java deleted file mode 100644 index 54933995..00000000 --- a/archive/codechicken/lib/tool/module/JOptModule.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.tool.module; - -import codechicken.lib.tool.ToolMain; -import joptsimple.OptionException; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import java.io.IOException; - -public abstract class JOptModule implements ToolMain.Module { - - OptionParser parser = new OptionParser(); - - @Override - public void main(String[] args) { - OptionSet options; - try { - options = parser.parse(args); - } catch (OptionException ex) { - System.err.println(ex.getLocalizedMessage()); - System.exit(-1); - return; - } - - try { - main(parser, options); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - protected abstract void main(OptionParser parser, OptionSet options); - - @Override - public void printHelp() { - try { - parser.printHelpOn(System.out); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/archive/codechicken/lib/tool/module/ModuleQBConverter.java b/archive/codechicken/lib/tool/module/ModuleQBConverter.java deleted file mode 100644 index 1110edce..00000000 --- a/archive/codechicken/lib/tool/module/ModuleQBConverter.java +++ /dev/null @@ -1,82 +0,0 @@ -package codechicken.lib.tool.module; - -import codechicken.lib.render.QBImporter; -import joptsimple.OptionParser; -import joptsimple.OptionSet; - -import java.io.File; - -import static java.util.Arrays.asList; - -public class ModuleQBConverter extends JOptModule { - - public ModuleQBConverter() { - parser.acceptsAll(asList("?", "h", "help"), "Show the help"); - parser.acceptsAll(asList("i", "input"), "comma separated list of paths to models (.qb or directories)").withRequiredArg().ofType(File.class).withValuesSeparatedBy(',').required(); - parser.acceptsAll(asList("o", "out"), "Output Directory").withRequiredArg().ofType(File.class); - parser.acceptsAll(asList("o2", "textureplanes"), "2nd level optimisation. Merges coplanar polygons. Increases texture size"); - parser.acceptsAll(asList("s", "squaretextures"), "Produce square textures"); - parser.acceptsAll(asList("t", "mergetextures"), "Use the same texture for all models"); - parser.acceptsAll(asList("r", "scalemc"), "Resize model to mc standard (shrink by factor of 16)"); - } - - protected void main(OptionParser parser, OptionSet options) { - int flags = 0; - if (options.has("o2")) { - flags |= QBImporter.TEXTUREPLANES; - } - if (options.has("s")) { - flags |= QBImporter.SQUARETEXTURE; - } - if (options.has("t")) { - flags |= QBImporter.MERGETEXTURES; - } - if (options.has("r")) { - flags |= QBImporter.SCALEMC; - } - - File[] input = options.valuesOf("input").toArray(new File[0]); - File[] outDir = new File[input.length]; - if (options.has("out")) { - File output = (File) options.valueOf("out"); - if (output.isFile()) { - throw new RuntimeException("Output Path is not a directory"); - } - if (!output.exists()) { - output.mkdirs(); - } - - for (int i = 0; i < input.length; i++) { - outDir[i] = output; - } - } else { - for (int i = 0; i < input.length; i++) { - outDir[i] = input[i].isDirectory() ? input[i] : input[i].getParentFile(); - } - } - - for (int i = 0; i < input.length; i++) { - File file = input[i]; - if (file.isDirectory()) { - for (File file2 : file.listFiles()) { - if (file2.getName().endsWith(".qb")) { - convert(file2, outDir[i], flags); - } - } - } else { - convert(file, outDir[i], flags); - } - } - } - - private void convert(File in, File outDir, int flags) { - System.out.println("Converting: " + in.getName()); - QBImporter.RasterisedModel m = QBImporter.loadQB(in).toRasterisedModel(flags); - m.export(new File(outDir, in.getName().replace(".qb", ".obj")), outDir); - } - - @Override - public String name() { - return "QBConverter"; - } -} diff --git a/build.gradle b/build.gradle index 9eb6ecd7..f01f6ca5 100644 --- a/build.gradle +++ b/build.gradle @@ -1,168 +1,172 @@ -buildscript { - repositories { - mavenLocal() - jcenter() - maven { url = "https://maven.minecraftforge.net/" } - maven { url = "https://repo.spongepowered.org/maven" } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:5.1.+' - classpath 'org.spongepowered:mixingradle:0.7-SNAPSHOT' - } -} +import groovy.json.JsonOutput plugins { - id 'java' + id 'java-library' id 'maven-publish' - id 'com.github.johnrengelman.shadow' version '7.1.2' - id "net.covers1624.signing" version '1.1.4' + id 'signing' + id 'net.neoforged.moddev' version '2.0.141' } -apply plugin: 'net.minecraftforge.gradle' -apply plugin: "org.spongepowered.mixin" - -java.toolchain.languageVersion = JavaLanguageVersion.of(17) +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } + withSourcesJar() + withJavadocJar() +} -group = 'codechicken' -archivesBaseName = 'CodeChickenLib' +group = 'io.codechicken' +base { + archivesName = 'CodeChickenLib' +} sourceSets.main.resources.srcDirs += "src/main/generated" -file('build.properties').withReader { - def prop = new Properties() - prop.load(it) - project.ext.config = new ConfigSlurper().parse prop -} +mod_version = "${mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") +version = "${mc_version}-${mod_version}" +println "Starting build of ${base.archivesName.get()}, Version: ${mod_version}" +println "Using Forge: ${forge_version}, for Minecraft: ${mc_version}" -def signProps = [:] -if (System.getenv("KEY_STORE")) { - println "Using Env variables for jar signing." - signProps['keyStore'] = System.getenv("KEY_STORE") - file(System.getenv("KEY_STORE_PROPS")).withReader { - def props = new Properties() - props.load(it) - signProps.putAll(props) +neoForge { + enable { + version = forge_version + enabledSourceSets += sourceSets.test } -} else if (project.hasProperty('keyStore')) { - println "Using Project properties for jar signing." - signProps['keyStore'] = project.getProperty('keyStore') - signProps['storePass'] = project.getProperty('keyStorePass') - signProps['alias'] = project.getProperty('keyStoreAlias') - signProps['keyPass'] = project.getProperty('keyStoreKeyPass') -} else { - println 'No signing secrets found, build will not be signed.' -} -config.mod_version = "${config.mod_version}." + (System.getenv("BUILD_NUMBER") ?: "1") -version = "${config.mc_version}-${config.mod_version}" -println "Starting build of ${archivesBaseName}, Version: ${config.mod_version}" -println "Using Forge: ${config.forge_version}, for Minecraft: ${config.mc_version}" + accessTransformers { + publish file("src/main/resources/META-INF/accesstransformer.cfg") + } + + interfaceInjectionData { + from file('src/main/resources/META-INF/interfaces.json') + publish file('src/main/resources/META-INF/interfaces.json') + } -minecraft { - mappings channel: 'official', version: config.mc_version - accessTransformer = file("src/main/resources/META-INF/accesstransformer.cfg") runs { client { - workingDirectory file('run') - mods { codechickenlib { source sourceSets.main } } + client() } server { - workingDirectory file('run') - mods { codechickenlib { source sourceSets.main } } + server() } data { - workingDirectory file('run') - args '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated"), '--existing', file("src/main/resources") - mods { codechickenlib { source sourceSets.main } } + data() + programArguments.addAll '--mod', 'codechickenlib', '--all', '--output', file("src/main/generated").absolutePath, '--existing', file("src/main/resources").absolutePath } } -} -mixin { - add(sourceSets.main, "mixins.codechickenlib.refmap.json") + mods { + codechickenlib { + sourceSet sourceSets.main + } + } } processResources { - inputs.property 'mod_version', config.mod_version - inputs.property 'mc_version', config.mc_version - - filesMatching('META-INF/mods.toml') { - expand 'file': ['jarVersion': config.mod_version], - 'mc_version': config.mc_version, - 'forge_version': config.forge_version, - 'lang_version': config.forge_version.split('\\.')[0] + inputs.property 'mod_version', mod_version + inputs.property 'mc_version', mc_version + + filesMatching('META-INF/neoforge.mods.toml') { + expand 'file': ['jarVersion': mod_version], + 'mc_version': mc_version, + 'forge_version': forge_version, + 'lang_version': forge_version.split('\\.')[0] } } -configurations { - shadow - implementation.extendsFrom shadow - annotationProcessor.extendsFrom minecraft -} - repositories { mavenLocal() maven { url "https://maven.covers1624.net/" } + maven { url "https://maven.blamejared.com/" } } dependencies { - minecraft "net.minecraftforge:forge:${config.mc_version}-${config.forge_version}" + jarJar(api('net.covers1624:Quack')) { + version { + strictly '[0.4.10,0.5)' + prefer '0.4.10.128' + } + } - shadow 'net.covers1624:Quack:0.4.7.72' + compileOnly("mezz.jei:jei-${mc_version}-neoforge:${jei_version}") { + transitive false + } - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2' + testImplementation platform('org.junit:junit-bom:6.0.0') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } test { useJUnitPlatform() } -reobf { - shadowJar {} - jar { enabled = false } // Disable jar. -} - -signing { - if (!signProps.isEmpty()) { - jars { - sign shadowJar - after 'reobfShadowJar' - - keyStore = signProps.keyStore - alias = signProps.alias - storePass = signProps.storePass - keyPass = signProps.keyPass - } - } -} - def commonManifest = { - attributes 'Specification-Title': archivesBaseName + attributes 'Specification-Title': base.archivesName.get() attributes 'Specification-Vendor': 'covers1624' attributes 'Specification-Version': "1" - attributes 'Implementation-Title': archivesBaseName + attributes 'Implementation-Title': base.archivesName.get() attributes 'Implementation-Vendor': 'covers1624' - attributes 'Implementation-Version': config.mod_version + attributes 'Implementation-Version': mod_version attributes 'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") attributes 'MixinConfigs': 'mixins.codechickenlib.json' } -jar.enabled = false -shadowJar { - finalizedBy 'reobfShadowJar' - classifier = 'universal' +def publishingMetadata = project.layout.buildDirectory.file("libs/${base.archivesName.get()}-$version-publishing.json") +def publishingMetadataTask = tasks.register("publishingMetadata") { + outputs.file(publishingMetadata) + doFirst { + publishingMetadata.get().asFile.text = JsonOutput.prettyPrint(JsonOutput.toJson([ + [ + 'displayName' : "CodeChicken Lib ${version}", + 'mcVersion' : "${mc_version}", + 'version' : "${mod_version}", + 'classifier' : null, + 'modLoader' : ['neoforge'], + 'curseforgeId': '242818', + 'modrinthId' : '2gq0ALnz' + ] + ])) + } +} + +jar { + finalizedBy 'signJar' manifest commonManifest - configurations = [project.configurations.shadow] from file("LICENSE") } -task srcJar(type: Jar) { - build.dependsOn it - from sourceSets.main.allSource - classifier = 'sources' - from file("LICENSE") +tasks.register("signJar") { + dependsOn("jar") + + doFirst { + def args = [:] + args['jar'] = jar.archiveFile.get().asFile + if (System.getenv("KEY_STORE")) { + args['keyStore'] = System.getenv("KEY_STORE") + file(System.getenv("KEY_STORE_PROPS")).withReader { + def props = new Properties() + props.load(it) + args.putAll(props) + } + } else if (project.hasProperty('keyStore')) { + args['keyStore'] = project.getProperty('keyStore') + args['alias'] = project.getProperty('keyStoreAlias') + args['storePass'] = project.getProperty('keyStorePass') + args['keyPass'] = project.getProperty('keyStoreKeyPass') + } else { + println "No signing properties." + state.setOutcome(org.gradle.api.internal.tasks.TaskExecutionOutcome.UP_TO_DATE) + didWork = false + return + } + project.ant.invokeMethod('signjar', args) + } +} + +javadoc { + options.addBooleanOption("Xdoclint:none", true) } publishing { @@ -177,26 +181,32 @@ publishing { } } } + publications { CodeChickenLib(MavenPublication) { groupId project.group - artifactId project.archivesBaseName + artifactId project.base.archivesName.get() version project.version - artifact shadowJar - artifact srcJar + + from components['java'] + + artifact(publishingMetadata) { + builtBy publishingMetadataTask + classifier 'publishing' + } pom { - name = archivesBaseName - description = archivesBaseName - url = "https://github.com/TheCBProject/${archivesBaseName}" + name = base.archivesName.get() + description = base.archivesName.get() + url = "https://github.com/TheCBProject/${base.archivesName.get()}" scm { - url = "https://github.com/TheCBProject/${archivesBaseName}" - connection = "scm:git:git@github.com:TheCBProject/${archivesBaseName}.git" + url = "https://github.com/TheCBProject/${base.archivesName.get()}" + connection = "scm:git:git@github.com:TheCBProject/${base.archivesName.get()}.git" } issueManagement { system = 'github' - url = "https://github.com/TheCBProject/${archivesBaseName}/issues" + url = "https://github.com/TheCBProject/${base.archivesName.get()}/issues" } licenses { license { @@ -222,33 +232,19 @@ publishing { } } -/** - * Polls the 'compile' configuration for a dependency with the given module name - * and resolves, and returns its version. E.g: '1.2.+' will resolve to '1.2.3.4' - * - * @param module The module to search for. - * @param chop If the string should be chopped on the last '-' in its string. - * @param configuration The name of the configuration to search. - * @param errorMissing If an error should be thrown if it can't be found. - * @return The version string, '0' if 'errorMissing' is false and nothing was found. - */ -def resolve(module, chop = true, configuration = 'compile', errorMissing = true) { - //Copy and lenient resolve the configuration, Forge cant be resolved at this time so lenient is required. - def filtered = configurations.getByName(configuration).copy().incoming.artifactView({ it.lenient = true }).artifacts - .findAll { it.id.componentIdentifier.module == module } - .collect { it.id.componentIdentifier.version } - if (filtered.size() > 1) { - println "WARNING: Found ${filtered.size()} Dependencies with ModuleName '${module}' in configuration '${configuration.name}'" - } - if (errorMissing && filtered.isEmpty()) { - throw new RuntimeException("Failed resolve dependency version for '${module}'") - } - if (filtered.isEmpty()) return "0" - def version = filtered.first() as String - if (chop) { - def idx = version.lastIndexOf('-') - return version.substring(idx + 1) +signing { + if (System.getenv('GPG_PRIVATE_KEY')) { + useInMemoryPgpKeys( + new File(System.getenv('GPG_PRIVATE_KEY')).text, + System.getenv('GPG_PRIVATE_KEY_PASS') + ) + } else if (project.hasProperty('gpgPrivateKey')) { + useInMemoryPgpKeys( + new File(project.getProperty('gpgPrivateKey')).text, + project.getProperty('gpgPrivateKeyPass') + ) + } else { + return } - return version + sign publishing.publications.CodeChickenLib } - diff --git a/build.properties b/build.properties deleted file mode 100644 index e1e50f68..00000000 --- a/build.properties +++ /dev/null @@ -1,3 +0,0 @@ -mc_version=1.19.2 -forge_version=43.2.0 -mod_version=4.3.2 diff --git a/gradle.properties b/gradle.properties index 6b1823d8..628fea70 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,6 @@ org.gradle.daemon=false + +mc_version=1.21.11 +forge_version=21.11.42 +mod_version=4.7.0 +jei_version=27.9.0.38 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 41d9927a..b1b8ef56 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 00e33ede..a9db1155 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,9 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c7873..249efbb0 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,10 +15,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -27,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -133,22 +132,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -165,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32..a51ec4f5 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,22 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +43,15 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +59,24 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle index 398e21f6..d6eca52a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,19 +1,13 @@ -/* - * This settings file was auto generated by the Gradle buildInit task - * by 'sunstrike' at '21/11/13 14:14' with Gradle 1.9 - * - * The settings file is used to specify which projects to include in your build. - * In a single project build this file can be empty or even removed. - * - * Detailed information about configuring a multi-project build in Gradle can be found - * in the user guide at http://gradle.org/docs/1.9/userguide/multi_project_builds.html - */ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + maven { url 'https://maven.neoforged.net/releases' } + } +} -/* -// To declare projects as part of a multi-project build use the 'include' method -include 'shared' -include 'api' -include 'services:webservice' -*/ +plugins { + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0' +} rootProject.name = 'CodeChickenLib' diff --git a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 index 01575e6a..eb39e337 100644 --- a/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 +++ b/src/main/generated/.cache/15d5dd4ace2ad25407a17728f6fbc07b246efd63 @@ -1,3 +1,3 @@ -// 1.19 2022-06-22T22:36:02.635898629 codechickenlib Languages: en_us -ce1ce42a962941336b9de69689e94a97219ad7d9 assets/codechickenlib/lang/en_us.json -ce1ce42a962941336b9de69689e94a97219ad7d9 data/codechickenlib/lang/en_us.json +// 1.21.10 2025-11-01T00:02:49.273916263 codechickenlib Languages: en_us +d535acbe9649e564744ed63aef209ce1508ec451 assets/codechickenlib/lang/en_us.json +d535acbe9649e564744ed63aef209ce1508ec451 data/codechickenlib/lang/en_us.json diff --git a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 index 38272923..299ba6c3 100644 --- a/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 +++ b/src/main/generated/.cache/95d738e2c774c5a4b0452cf55df2775d732b2634 @@ -1,18 +1,18 @@ -// 1.19 2022-06-22T22:36:02.63605193 CodeChickenLib Block tags. -48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/blocks/wool.json -dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/blocks/wool/black.json -4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/blocks/wool/blue.json -9f867580ce1e743583fab6a17e3d03248865eafc data/forge/tags/blocks/wool/brown.json -b4b458788e919f93343c36ef996f828bcf610abc data/forge/tags/blocks/wool/cyan.json -62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/forge/tags/blocks/wool/gray.json -1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/forge/tags/blocks/wool/green.json -e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/forge/tags/blocks/wool/light_blue.json -bf7627f1264b6899bedb6f55e19898dad5d03d8c data/forge/tags/blocks/wool/light_gray.json -aceb5be462f62f63438e67877d38c89951e8919e data/forge/tags/blocks/wool/lime.json -cfd0d2c16adae65fbf8640439a1814ab244082cb data/forge/tags/blocks/wool/magenta.json -842c228466435a5cc9221a17f70a778db8617590 data/forge/tags/blocks/wool/orange.json -3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/forge/tags/blocks/wool/pink.json -fec60767247bdbebf6cd451bb3692c9a8ffef908 data/forge/tags/blocks/wool/purple.json -85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/forge/tags/blocks/wool/red.json -8e71446b54f055edb3ba7a025d4335cb78da1b45 data/forge/tags/blocks/wool/white.json -0de700cdfc12e281290ea7bc709d3241620ec9fb data/forge/tags/blocks/wool/yellow.json +// 1.21.10 2025-11-01T00:02:49.272952237 CodeChickenLib Block tags. +9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/block/wools.json +dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/block/wools/black.json +4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/block/wools/blue.json +9f867580ce1e743583fab6a17e3d03248865eafc data/c/tags/block/wools/brown.json +b4b458788e919f93343c36ef996f828bcf610abc data/c/tags/block/wools/cyan.json +62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/c/tags/block/wools/gray.json +1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/c/tags/block/wools/green.json +e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/c/tags/block/wools/light_blue.json +bf7627f1264b6899bedb6f55e19898dad5d03d8c data/c/tags/block/wools/light_gray.json +aceb5be462f62f63438e67877d38c89951e8919e data/c/tags/block/wools/lime.json +cfd0d2c16adae65fbf8640439a1814ab244082cb data/c/tags/block/wools/magenta.json +842c228466435a5cc9221a17f70a778db8617590 data/c/tags/block/wools/orange.json +3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/c/tags/block/wools/pink.json +fec60767247bdbebf6cd451bb3692c9a8ffef908 data/c/tags/block/wools/purple.json +85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/c/tags/block/wools/red.json +8e71446b54f055edb3ba7a025d4335cb78da1b45 data/c/tags/block/wools/white.json +0de700cdfc12e281290ea7bc709d3241620ec9fb data/c/tags/block/wools/yellow.json diff --git a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 index 3940ce49..7d45eab0 100644 --- a/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 +++ b/src/main/generated/.cache/f0722e2ccb61f3087e21fc378db7b4f9b32dbea1 @@ -1,18 +1,18 @@ -// 1.19 2022-06-22T22:36:02.634627369 CodeChickenLib Item tags. -48ffc90719924738f43a8ea0c526941cbbb83318 data/forge/tags/items/wool.json -dc26d59698d238e0c60c400dbffea2ba82af4365 data/forge/tags/items/wool/black.json -4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/forge/tags/items/wool/blue.json -9f867580ce1e743583fab6a17e3d03248865eafc data/forge/tags/items/wool/brown.json -b4b458788e919f93343c36ef996f828bcf610abc data/forge/tags/items/wool/cyan.json -62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/forge/tags/items/wool/gray.json -1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/forge/tags/items/wool/green.json -e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/forge/tags/items/wool/light_blue.json -bf7627f1264b6899bedb6f55e19898dad5d03d8c data/forge/tags/items/wool/light_gray.json -aceb5be462f62f63438e67877d38c89951e8919e data/forge/tags/items/wool/lime.json -cfd0d2c16adae65fbf8640439a1814ab244082cb data/forge/tags/items/wool/magenta.json -842c228466435a5cc9221a17f70a778db8617590 data/forge/tags/items/wool/orange.json -3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/forge/tags/items/wool/pink.json -fec60767247bdbebf6cd451bb3692c9a8ffef908 data/forge/tags/items/wool/purple.json -85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/forge/tags/items/wool/red.json -8e71446b54f055edb3ba7a025d4335cb78da1b45 data/forge/tags/items/wool/white.json -0de700cdfc12e281290ea7bc709d3241620ec9fb data/forge/tags/items/wool/yellow.json +// 1.21.10 2025-11-01T00:02:49.274097985 CodeChickenLib Item tags. +9b9a1318b746e42366ee1747896a1c61d71bc0ae data/c/tags/item/wools.json +dc26d59698d238e0c60c400dbffea2ba82af4365 data/c/tags/item/wools/black.json +4b007eca91284e115e6a0c208c8dddbbf0aed7bc data/c/tags/item/wools/blue.json +9f867580ce1e743583fab6a17e3d03248865eafc data/c/tags/item/wools/brown.json +b4b458788e919f93343c36ef996f828bcf610abc data/c/tags/item/wools/cyan.json +62e9def05a24ce6a0f8b7fdb1490d7e856991d47 data/c/tags/item/wools/gray.json +1bdd1be741fcfa89c90c2bf0af6706b6c63139ca data/c/tags/item/wools/green.json +e054a5fe2248aa8c0a7f66d210cb54a639c661f6 data/c/tags/item/wools/light_blue.json +bf7627f1264b6899bedb6f55e19898dad5d03d8c data/c/tags/item/wools/light_gray.json +aceb5be462f62f63438e67877d38c89951e8919e data/c/tags/item/wools/lime.json +cfd0d2c16adae65fbf8640439a1814ab244082cb data/c/tags/item/wools/magenta.json +842c228466435a5cc9221a17f70a778db8617590 data/c/tags/item/wools/orange.json +3ff0870e67b5b9c122d8e59400180e4bd93780a3 data/c/tags/item/wools/pink.json +fec60767247bdbebf6cd451bb3692c9a8ffef908 data/c/tags/item/wools/purple.json +85f94b89b0d20e38f4e9f464fb443064c29f2bf1 data/c/tags/item/wools/red.json +8e71446b54f055edb3ba7a025d4335cb78da1b45 data/c/tags/item/wools/white.json +0de700cdfc12e281290ea7bc709d3241620ec9fb data/c/tags/item/wools/yellow.json diff --git a/src/main/generated/assets/codechickenlib/lang/en_us.json b/src/main/generated/assets/codechickenlib/lang/en_us.json index ccfb00ae..b647596b 100644 --- a/src/main/generated/assets/codechickenlib/lang/en_us.json +++ b/src/main/generated/assets/codechickenlib/lang/en_us.json @@ -7,5 +7,14 @@ "ccl.commands.killall.fail": "Found no entities.", "ccl.commands.killall.fail.player": "You cannot kill players with this command.", "ccl.commands.killall.success": "Killed %s entities.", - "ccl.commands.killall.success.line": "Killed %s" + "ccl.commands.killall.success.line": "Killed %s", + "ccl.energy_bar.capacity": "Capacity:", + "ccl.energy_bar.energy_storage": "Energy Storage", + "ccl.energy_bar.rf": "RF", + "ccl.energy_bar.stored": "Stored:", + "ccl.fluid_tank.capacity": "Capacity:", + "ccl.fluid_tank.contains": "Contains:", + "ccl.fluid_tank.fluid_storage": "Fluid Storage", + "ccl.fluid_tank.mb": "mB", + "ccl.fluid_tank.stored": "Stored:" } \ No newline at end of file diff --git a/src/main/generated/data/c/tags/block/wools.json b/src/main/generated/data/c/tags/block/wools.json new file mode 100644 index 00000000..10f4aa19 --- /dev/null +++ b/src/main/generated/data/c/tags/block/wools.json @@ -0,0 +1,20 @@ +{ + "values": [ + "#c:wools/white", + "#c:wools/orange", + "#c:wools/magenta", + "#c:wools/light_blue", + "#c:wools/yellow", + "#c:wools/lime", + "#c:wools/pink", + "#c:wools/gray", + "#c:wools/light_gray", + "#c:wools/cyan", + "#c:wools/purple", + "#c:wools/blue", + "#c:wools/brown", + "#c:wools/green", + "#c:wools/red", + "#c:wools/black" + ] +} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/blocks/wool/black.json b/src/main/generated/data/c/tags/block/wools/black.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/black.json rename to src/main/generated/data/c/tags/block/wools/black.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/blue.json b/src/main/generated/data/c/tags/block/wools/blue.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/blue.json rename to src/main/generated/data/c/tags/block/wools/blue.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/brown.json b/src/main/generated/data/c/tags/block/wools/brown.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/brown.json rename to src/main/generated/data/c/tags/block/wools/brown.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/cyan.json b/src/main/generated/data/c/tags/block/wools/cyan.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/cyan.json rename to src/main/generated/data/c/tags/block/wools/cyan.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/gray.json b/src/main/generated/data/c/tags/block/wools/gray.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/gray.json rename to src/main/generated/data/c/tags/block/wools/gray.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/green.json b/src/main/generated/data/c/tags/block/wools/green.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/green.json rename to src/main/generated/data/c/tags/block/wools/green.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/light_blue.json b/src/main/generated/data/c/tags/block/wools/light_blue.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/light_blue.json rename to src/main/generated/data/c/tags/block/wools/light_blue.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/light_gray.json b/src/main/generated/data/c/tags/block/wools/light_gray.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/light_gray.json rename to src/main/generated/data/c/tags/block/wools/light_gray.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/lime.json b/src/main/generated/data/c/tags/block/wools/lime.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/lime.json rename to src/main/generated/data/c/tags/block/wools/lime.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/magenta.json b/src/main/generated/data/c/tags/block/wools/magenta.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/magenta.json rename to src/main/generated/data/c/tags/block/wools/magenta.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/orange.json b/src/main/generated/data/c/tags/block/wools/orange.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/orange.json rename to src/main/generated/data/c/tags/block/wools/orange.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/pink.json b/src/main/generated/data/c/tags/block/wools/pink.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/pink.json rename to src/main/generated/data/c/tags/block/wools/pink.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/purple.json b/src/main/generated/data/c/tags/block/wools/purple.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/purple.json rename to src/main/generated/data/c/tags/block/wools/purple.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/red.json b/src/main/generated/data/c/tags/block/wools/red.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/red.json rename to src/main/generated/data/c/tags/block/wools/red.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/white.json b/src/main/generated/data/c/tags/block/wools/white.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/white.json rename to src/main/generated/data/c/tags/block/wools/white.json diff --git a/src/main/generated/data/forge/tags/blocks/wool/yellow.json b/src/main/generated/data/c/tags/block/wools/yellow.json similarity index 100% rename from src/main/generated/data/forge/tags/blocks/wool/yellow.json rename to src/main/generated/data/c/tags/block/wools/yellow.json diff --git a/src/main/generated/data/c/tags/item/wools.json b/src/main/generated/data/c/tags/item/wools.json new file mode 100644 index 00000000..10f4aa19 --- /dev/null +++ b/src/main/generated/data/c/tags/item/wools.json @@ -0,0 +1,20 @@ +{ + "values": [ + "#c:wools/white", + "#c:wools/orange", + "#c:wools/magenta", + "#c:wools/light_blue", + "#c:wools/yellow", + "#c:wools/lime", + "#c:wools/pink", + "#c:wools/gray", + "#c:wools/light_gray", + "#c:wools/cyan", + "#c:wools/purple", + "#c:wools/blue", + "#c:wools/brown", + "#c:wools/green", + "#c:wools/red", + "#c:wools/black" + ] +} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/items/wool/black.json b/src/main/generated/data/c/tags/item/wools/black.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/black.json rename to src/main/generated/data/c/tags/item/wools/black.json diff --git a/src/main/generated/data/forge/tags/items/wool/blue.json b/src/main/generated/data/c/tags/item/wools/blue.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/blue.json rename to src/main/generated/data/c/tags/item/wools/blue.json diff --git a/src/main/generated/data/forge/tags/items/wool/brown.json b/src/main/generated/data/c/tags/item/wools/brown.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/brown.json rename to src/main/generated/data/c/tags/item/wools/brown.json diff --git a/src/main/generated/data/forge/tags/items/wool/cyan.json b/src/main/generated/data/c/tags/item/wools/cyan.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/cyan.json rename to src/main/generated/data/c/tags/item/wools/cyan.json diff --git a/src/main/generated/data/forge/tags/items/wool/gray.json b/src/main/generated/data/c/tags/item/wools/gray.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/gray.json rename to src/main/generated/data/c/tags/item/wools/gray.json diff --git a/src/main/generated/data/forge/tags/items/wool/green.json b/src/main/generated/data/c/tags/item/wools/green.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/green.json rename to src/main/generated/data/c/tags/item/wools/green.json diff --git a/src/main/generated/data/forge/tags/items/wool/light_blue.json b/src/main/generated/data/c/tags/item/wools/light_blue.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/light_blue.json rename to src/main/generated/data/c/tags/item/wools/light_blue.json diff --git a/src/main/generated/data/forge/tags/items/wool/light_gray.json b/src/main/generated/data/c/tags/item/wools/light_gray.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/light_gray.json rename to src/main/generated/data/c/tags/item/wools/light_gray.json diff --git a/src/main/generated/data/forge/tags/items/wool/lime.json b/src/main/generated/data/c/tags/item/wools/lime.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/lime.json rename to src/main/generated/data/c/tags/item/wools/lime.json diff --git a/src/main/generated/data/forge/tags/items/wool/magenta.json b/src/main/generated/data/c/tags/item/wools/magenta.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/magenta.json rename to src/main/generated/data/c/tags/item/wools/magenta.json diff --git a/src/main/generated/data/forge/tags/items/wool/orange.json b/src/main/generated/data/c/tags/item/wools/orange.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/orange.json rename to src/main/generated/data/c/tags/item/wools/orange.json diff --git a/src/main/generated/data/forge/tags/items/wool/pink.json b/src/main/generated/data/c/tags/item/wools/pink.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/pink.json rename to src/main/generated/data/c/tags/item/wools/pink.json diff --git a/src/main/generated/data/forge/tags/items/wool/purple.json b/src/main/generated/data/c/tags/item/wools/purple.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/purple.json rename to src/main/generated/data/c/tags/item/wools/purple.json diff --git a/src/main/generated/data/forge/tags/items/wool/red.json b/src/main/generated/data/c/tags/item/wools/red.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/red.json rename to src/main/generated/data/c/tags/item/wools/red.json diff --git a/src/main/generated/data/forge/tags/items/wool/white.json b/src/main/generated/data/c/tags/item/wools/white.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/white.json rename to src/main/generated/data/c/tags/item/wools/white.json diff --git a/src/main/generated/data/forge/tags/items/wool/yellow.json b/src/main/generated/data/c/tags/item/wools/yellow.json similarity index 100% rename from src/main/generated/data/forge/tags/items/wool/yellow.json rename to src/main/generated/data/c/tags/item/wools/yellow.json diff --git a/src/main/generated/data/codechickenlib/lang/en_us.json b/src/main/generated/data/codechickenlib/lang/en_us.json index ccfb00ae..b647596b 100644 --- a/src/main/generated/data/codechickenlib/lang/en_us.json +++ b/src/main/generated/data/codechickenlib/lang/en_us.json @@ -7,5 +7,14 @@ "ccl.commands.killall.fail": "Found no entities.", "ccl.commands.killall.fail.player": "You cannot kill players with this command.", "ccl.commands.killall.success": "Killed %s entities.", - "ccl.commands.killall.success.line": "Killed %s" + "ccl.commands.killall.success.line": "Killed %s", + "ccl.energy_bar.capacity": "Capacity:", + "ccl.energy_bar.energy_storage": "Energy Storage", + "ccl.energy_bar.rf": "RF", + "ccl.energy_bar.stored": "Stored:", + "ccl.fluid_tank.capacity": "Capacity:", + "ccl.fluid_tank.contains": "Contains:", + "ccl.fluid_tank.fluid_storage": "Fluid Storage", + "ccl.fluid_tank.mb": "mB", + "ccl.fluid_tank.stored": "Stored:" } \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/blocks/wool.json b/src/main/generated/data/forge/tags/blocks/wool.json deleted file mode 100644 index 3754cb21..00000000 --- a/src/main/generated/data/forge/tags/blocks/wool.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "values": [ - "#forge:wool/white", - "#forge:wool/orange", - "#forge:wool/magenta", - "#forge:wool/light_blue", - "#forge:wool/yellow", - "#forge:wool/lime", - "#forge:wool/pink", - "#forge:wool/gray", - "#forge:wool/light_gray", - "#forge:wool/cyan", - "#forge:wool/purple", - "#forge:wool/blue", - "#forge:wool/brown", - "#forge:wool/green", - "#forge:wool/red", - "#forge:wool/black" - ] -} \ No newline at end of file diff --git a/src/main/generated/data/forge/tags/items/wool.json b/src/main/generated/data/forge/tags/items/wool.json deleted file mode 100644 index 3754cb21..00000000 --- a/src/main/generated/data/forge/tags/items/wool.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "values": [ - "#forge:wool/white", - "#forge:wool/orange", - "#forge:wool/magenta", - "#forge:wool/light_blue", - "#forge:wool/yellow", - "#forge:wool/lime", - "#forge:wool/pink", - "#forge:wool/gray", - "#forge:wool/light_gray", - "#forge:wool/cyan", - "#forge:wool/purple", - "#forge:wool/blue", - "#forge:wool/brown", - "#forge:wool/green", - "#forge:wool/red", - "#forge:wool/black" - ] -} \ No newline at end of file diff --git a/src/main/java/codechicken/lib/CodeChickenLib.java b/src/main/java/codechicken/lib/CodeChickenLib.java index 84797e52..10a8ea3e 100644 --- a/src/main/java/codechicken/lib/CodeChickenLib.java +++ b/src/main/java/codechicken/lib/CodeChickenLib.java @@ -2,19 +2,17 @@ import codechicken.lib.config.ConfigCategory; import codechicken.lib.config.ConfigFile; +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.internal.CCLNetwork; +import codechicken.lib.internal.ClientInit; +import codechicken.lib.internal.DataGenerators; +import codechicken.lib.internal.TileChunkLoadHook; import codechicken.lib.internal.command.CCLCommands; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.internal.proxy.Proxy; -import codechicken.lib.internal.proxy.ProxyClient; -import codechicken.lib.datagen.ConditionalIngredient; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.DistExecutor; -import net.minecraftforge.fml.common.Mod; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLConfig; +import net.neoforged.fml.loading.FMLEnvironment; import java.nio.file.Paths; @@ -24,35 +22,32 @@ @Mod (CodeChickenLib.MOD_ID) public class CodeChickenLib { + static { + if (Boolean.getBoolean("ccl.noModUpdateChecking")) { + FMLConfig.updateConfig(FMLConfig.ConfigValue.VERSION_CHECK, false); + } + } + public static final String MOD_ID = "codechickenlib"; public static ConfigCategory config; - public static Proxy proxy; - - public CodeChickenLib() { + public CodeChickenLib(ModContainer container, IEventBus modBus) { config = new ConfigFile(MOD_ID) .path(Paths.get("config/ccl.cfg")) .load(); - proxy = DistExecutor.safeRunForDist(() -> ProxyClient::new, () -> Proxy::new); - FMLJavaModLoadingContext.get().getModEventBus().register(this); - CCLCommands.init(); - ConditionalIngredient.Serializer.init(); - } - @SubscribeEvent - public void onCommonSetup(FMLCommonSetupEvent event) { - proxy.commonSetup(event); - CCLNetwork.init(); - } - @SubscribeEvent - public void onClientSetup(FMLClientSetupEvent event) { - proxy.clientSetup(event); - } + ConfigSyncManager.init(modBus); - @SubscribeEvent - public void onServerSetup(FMLDedicatedServerSetupEvent event) { - proxy.serverSetup(event); + CCLCommands.init(); + CCLNetwork.init(modBus, container); + TileChunkLoadHook.init(); +// ConditionalIngredient.Serializer.init(); + DataGenerators.init(modBus); + + if (FMLEnvironment.getDist().isClient()) { + ClientInit.init(modBus); + } } } diff --git a/src/main/java/codechicken/lib/block/LazyStateBlock.java b/src/main/java/codechicken/lib/block/LazyStateBlock.java index ab7a0264..38223730 100644 --- a/src/main/java/codechicken/lib/block/LazyStateBlock.java +++ b/src/main/java/codechicken/lib/block/LazyStateBlock.java @@ -4,10 +4,12 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.Property; +import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.ApiStatus; import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Function; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -18,6 +20,7 @@ *

* Created by covers1624 on 18/7/22. */ +// TODO On Java25 this may not be required anymore as we can do stuff before a super ctor call. @ApiStatus.Experimental public abstract class LazyStateBlock extends Block { @@ -95,4 +98,16 @@ private void computeState() { protected final void createBlockStateDefinition(StateDefinition.Builder builder) { // Explicitly disallowed. } + + @Override + protected Function getShapeForEachState(Function shapeGetter) { + computeState(); + return super.getShapeForEachState(shapeGetter); + } + + @Override + protected Function getShapeForEachState(Function shapeGetter, Property... properties) { + computeState(); + return super.getShapeForEachState(shapeGetter, properties); + } } diff --git a/src/main/java/codechicken/lib/block/ModularBlock.java b/src/main/java/codechicken/lib/block/ModularBlock.java index 5a43f801..26e7fe99 100644 --- a/src/main/java/codechicken/lib/block/ModularBlock.java +++ b/src/main/java/codechicken/lib/block/ModularBlock.java @@ -8,7 +8,7 @@ import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.data.loading.DatagenModLoader; +import net.neoforged.neoforge.data.loading.DatagenModLoader; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/codechicken/lib/block/ModularBlockEntity.java b/src/main/java/codechicken/lib/block/ModularBlockEntity.java index 093192cd..0a67f4c2 100644 --- a/src/main/java/codechicken/lib/block/ModularBlockEntity.java +++ b/src/main/java/codechicken/lib/block/ModularBlockEntity.java @@ -1,14 +1,22 @@ package codechicken.lib.block; import codechicken.lib.block.ModularTileBlock.TileComponent; +import codechicken.lib.internal.CCLNetwork; import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import net.neoforged.neoforge.network.handling.IPayloadContext; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.MustBeInvokedByOverriders; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -18,6 +26,8 @@ @ApiStatus.Experimental public abstract class ModularBlockEntity extends BlockEntity { + private static final byte COMPONENT_MESSAGE = 1; + private final ModularTileBlock block; private final DataComponent[] components; @@ -43,25 +53,52 @@ public final T getData(TileComponent component) { @Override @MustBeInvokedByOverriders - protected void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); + protected void saveAdditional(ValueOutput output) { + super.saveAdditional(output); for (DataComponent component : components) { - CompoundTag componentTag = new CompoundTag(); - component.save(componentTag); - tag.put(component.tileComponent.name, componentTag); + component.save(output.child(component.tileComponent.name)); } } @Override @MustBeInvokedByOverriders - public void load(CompoundTag tag) { - super.load(tag); + protected void loadAdditional(ValueInput input) { + super.loadAdditional(input); for (DataComponent component : components) { - if (tag.contains(component.tileComponent.name)) { - component.load(tag.getCompound(component.tileComponent.name)); - } + var childIn = input.child(component.tileComponent.name); + childIn.ifPresent(component::load); + } + } + + private void sendServerPacket(Consumer cons) { + var packet = CCLNetwork.TILE_MESSAGE.toServer(); + packet.writeBlockPos(getBlockPos()); + cons.accept(packet); + packet.sendToServer(); + } + + public final void onInternalServerPacket(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + switch (packet.readUnsignedByte()) { + case COMPONENT_MESSAGE -> components[packet.readVarInt()].onServerPacket(packet, ctx); + } + } + + private void sendClientPacket(@Nullable ServerPlayer to, Consumer cons) { + var packet = CCLNetwork.TILE_MESSAGE.toClient(this); + packet.writeBlockPos(getBlockPos()); + cons.accept(packet); + if (to == null) { + packet.sendToChunk(this); + } else { + packet.sendToPlayer(to); + } + } + + public final void onInternalClientPacket(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + switch (packet.readUnsignedByte()) { + case COMPONENT_MESSAGE -> components[packet.readVarInt()].onClientPacket(packet, ctx); } } @@ -75,10 +112,32 @@ protected DataComponent(ModularBlockEntity tile, TileComponent tileComponent) this.tileComponent = tileComponent; } - protected void save(CompoundTag tag) { + protected final void sendToServer(Consumer cons) { + tile.sendServerPacket(p -> { + p.writeByte(COMPONENT_MESSAGE); + p.writeVarInt(tileComponent.id); + cons.accept(p); + }); + } + + protected void onServerPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + } + + protected final void sendToClient(@Nullable ServerPlayer to, Consumer cons) { + tile.sendClientPacket(to, p -> { + p.writeByte(COMPONENT_MESSAGE); + p.writeVarInt(tileComponent.id); + cons.accept(p); + }); + } + + protected void onClientPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + } + + protected void save(ValueOutput output) { } - protected void load(CompoundTag tag) { + protected void load(ValueInput input) { } } } diff --git a/src/main/java/codechicken/lib/block/ModularTileBlock.java b/src/main/java/codechicken/lib/block/ModularTileBlock.java index 111fd5fa..352ea958 100644 --- a/src/main/java/codechicken/lib/block/ModularTileBlock.java +++ b/src/main/java/codechicken/lib/block/ModularTileBlock.java @@ -24,12 +24,12 @@ public abstract class ModularTileBlock extends ModularBlock implements EntityBlock { final Map> namedComponents = new HashMap<>(); - private final LazyValue> type; + private final Supplier> type; - private final TickList clientTicks = new TickList(); - private final TickList serverTicks = new TickList(); + protected final TickList clientTicks = new TickList<>(); + protected final TickList serverTicks = new TickList<>(); - public ModularTileBlock(Properties props, Supplier> typeSupplier) { + public ModularTileBlock(Properties props, Supplier> typeSupplier) { super(props); type = new LazyValue<>(typeSupplier); } @@ -52,14 +52,21 @@ public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { @Nullable @Override @SuppressWarnings ("unchecked") - public final BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { + public final BlockEntityTicker getTicker(Level level, BlockState state, BlockEntityType type) { if (type != this.type.get()) return null; - if (level.isClientSide) { - return (BlockEntityTicker) clientTicks.compileTicker(); + if (level.isClientSide()) { + return (BlockEntityTicker) clientTicks.compileTicker(); } - return (BlockEntityTicker)serverTicks.compileTicker(); + return (BlockEntityTicker) serverTicks.compileTicker(); + } + + @Override + protected boolean triggerEvent(BlockState state, Level level, BlockPos pos, int id, int param) { + super.triggerEvent(state, level, pos, id, param); + BlockEntity be = level.getBlockEntity(pos); + return be != null && be.triggerEvent(id, param); } public static abstract class TileComponent extends Component { @@ -70,26 +77,26 @@ public static abstract class TileComponent extends Comp protected abstract D createData(ModularBlockEntity ent); } - private static class TickList { + public static class TickList { - private final LinkedList> tickers = new LinkedList<>(); + private final LinkedList> tickers = new LinkedList<>(); @Nullable - private BlockEntityTicker compiled; + private BlockEntityTicker compiled; - private void addTickerFirst(BlockEntityTicker pre) { + public void addTickerFirst(BlockEntityTicker pre) { assert compiled == null : "Unable to hot-add new tickers."; tickers.addFirst(pre); } - private void addTicker(BlockEntityTicker ticker) { + public void addTicker(BlockEntityTicker ticker) { assert compiled == null : "Unable to hot-add new tickers."; tickers.add(ticker); } @Nullable - private BlockEntityTicker compileTicker() { + private BlockEntityTicker compileTicker() { if (compiled != null) return compiled; if (tickers.isEmpty()) return null; @@ -98,10 +105,10 @@ private BlockEntityTicker compileTicker() { tickers.clear(); } else { @SuppressWarnings ("unchecked") - BlockEntityTicker[] tickers = this.tickers.toArray(new BlockEntityTicker[0]); + BlockEntityTicker[] tickers = this.tickers.toArray(BlockEntityTicker[]::new); this.tickers.clear(); compiled = (level, pos, state, tile) -> { - for (BlockEntityTicker ticker : tickers) { + for (var ticker : tickers) { ticker.tick(level, pos, state, tile); } }; diff --git a/src/main/java/codechicken/lib/block/component/DirectionComponent.java b/src/main/java/codechicken/lib/block/component/DirectionComponent.java index d145d80b..e5d58c80 100644 --- a/src/main/java/codechicken/lib/block/component/DirectionComponent.java +++ b/src/main/java/codechicken/lib/block/component/DirectionComponent.java @@ -20,6 +20,7 @@ public class DirectionComponent extends PropertyComponent { public static PlacementFunc NONE = (state, ctx) -> null; public static PlacementFunc PLAYER_HORIZONTAL = (state, ctx) -> ctx.getHorizontalDirection(); + public static PlacementFunc PLAYER_HORIZONTAL_OPPOSITE = (state, ctx) -> ctx.getHorizontalDirection().getOpposite(); public static PlacementFunc PLAYER_LOOKING_NEAREST = (state, ctx) -> ctx.getNearestLookingDirection().getOpposite(); public static PlacementFunc FACE_NORMAL = (state, ctx) -> ctx.getClickedFace(); diff --git a/src/main/java/codechicken/lib/block/component/PropertyComponent.java b/src/main/java/codechicken/lib/block/component/PropertyComponent.java index 7f6cf5d3..3d83924f 100644 --- a/src/main/java/codechicken/lib/block/component/PropertyComponent.java +++ b/src/main/java/codechicken/lib/block/component/PropertyComponent.java @@ -1,5 +1,6 @@ package codechicken.lib.block.component; +import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.Property; import org.jetbrains.annotations.ApiStatus; @@ -16,4 +17,8 @@ protected PropertyComponent(Property property, V defaultValue) { this.property = property; this.defaultValue = defaultValue; } + + public final V get(BlockState state) { + return state.getValue(property); + } } diff --git a/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java b/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java index 7928d732..6bf82a8b 100644 --- a/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/DataGenComponent.java @@ -3,8 +3,8 @@ import codechicken.lib.block.ModularBlock; import net.minecraft.data.DataProvider; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.DeferredRegister; -import net.minecraftforge.registries.RegistryObject; +import net.neoforged.neoforge.registries.DeferredHolder; +import net.neoforged.neoforge.registries.DeferredRegister; import org.jetbrains.annotations.ApiStatus; /** @@ -14,7 +14,7 @@ * to each {@link DataProvider} *

* You can either add each block manually via {@link #addToProvider(ModularBlock, DataProvider)}. Or you - * can register your entire {@link DeferredRegister} via {@link #addAllToProvider(DeferredRegister, DataProvider)} + * can register your entire {@link DeferredRegister } via {@link #addAllToProvider(DeferredRegister, DataProvider)} *

* Created by covers1624 on 22/7/22. */ @@ -51,7 +51,7 @@ public static void addToProvider(ModularBlock block, DataProvider provider) { * @param provider The {@link DataProvider} to add things to. */ public static void addAllToProvider(DeferredRegister blocks, DataProvider provider) { - for (RegistryObject entry : blocks.getEntries()) { + for (DeferredHolder entry : blocks.getEntries()) { if (entry.get() instanceof ModularBlock block) { addToProvider(block, provider); } diff --git a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java index 3cee2f73..98c141a4 100644 --- a/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/LootTableComponent.java @@ -1,16 +1,19 @@ package codechicken.lib.block.component.data; import codechicken.lib.block.ModularBlock; -import codechicken.lib.datagen.LootTableProvider; +import codechicken.lib.datagen.NoValidationBLockLootSubProvider; +import net.minecraft.core.HolderLookup; import net.minecraft.data.DataProvider; +import net.minecraft.data.loot.LootTableProvider; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.storage.loot.LootPool; import net.minecraft.world.level.storage.loot.LootTable; import net.minecraft.world.level.storage.loot.entries.LootItem; +import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; import java.util.function.Consumer; /** @@ -29,10 +32,24 @@ public LootTableComponent(Consumer configure) { } @Override - protected void addToProvider(DataProvider provider) { - if (provider instanceof LootTableProvider.BlockLootProvider loot) { + protected void addToProvider(DataProvider p) { + if (p instanceof LootTableProvider provider) { + if (!(provider.subProviders instanceof ArrayList)) { + provider.subProviders = new ArrayList<>(provider.subProviders); + } + provider.subProviders.add( + new LootTableProvider.SubProviderEntry( + registries -> new NoValidationBLockLootSubProvider(registries) { + @Override + protected void generate() { + add(getBlock(), table); + } + }, + LootContextParamSets.BLOCK + ) + ); + configure.accept(this); - loot.register(getBlock(), table); } } diff --git a/src/main/java/codechicken/lib/block/component/data/TagComponent.java b/src/main/java/codechicken/lib/block/component/data/TagComponent.java index 53509d3d..ad4caca7 100644 --- a/src/main/java/codechicken/lib/block/component/data/TagComponent.java +++ b/src/main/java/codechicken/lib/block/component/data/TagComponent.java @@ -1,9 +1,9 @@ package codechicken.lib.block.component.data; import net.minecraft.data.DataProvider; -import net.minecraft.data.tags.BlockTagsProvider; import net.minecraft.tags.TagKey; import net.minecraft.world.level.block.Block; +import net.neoforged.neoforge.common.data.BlockTagsProvider; import org.jetbrains.annotations.ApiStatus; /** diff --git a/src/main/java/codechicken/lib/block/component/data/package-info.java b/src/main/java/codechicken/lib/block/component/data/package-info.java index 03be7414..d64bcf22 100644 --- a/src/main/java/codechicken/lib/block/component/data/package-info.java +++ b/src/main/java/codechicken/lib/block/component/data/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component.data; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/component/package-info.java b/src/main/java/codechicken/lib/block/component/package-info.java index 6efe124d..8e81d8a4 100644 --- a/src/main/java/codechicken/lib/block/component/package-info.java +++ b/src/main/java/codechicken/lib/block/component/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java index 4784432b..b55d6b8e 100644 --- a/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java +++ b/src/main/java/codechicken/lib/block/component/tile/InventoryComponent.java @@ -4,11 +4,11 @@ import codechicken.lib.block.ModularTileBlock; import codechicken.lib.inventory.InventoryUtils; import codechicken.lib.util.ArrayUtils; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.Tag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; import org.jetbrains.annotations.ApiStatus; import java.util.LinkedList; @@ -121,13 +121,13 @@ public int getMaxStackSize() { } @Override - protected void save(CompoundTag tag) { - tag.put("Items", InventoryUtils.writeItemStacksToTag(items)); + protected void save(ValueOutput output) { + InventoryUtils.writeItemStacksToOutput(output, items); } @Override - protected void load(CompoundTag tag) { - InventoryUtils.readItemStacksFromTag(items, tag.getList("Items", Tag.TAG_COMPOUND)); + protected void load(ValueInput input) { + InventoryUtils.readItemStacksFromInput(input, items); } } } diff --git a/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java b/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java new file mode 100644 index 00000000..61820a66 --- /dev/null +++ b/src/main/java/codechicken/lib/block/component/tile/ValueComponent.java @@ -0,0 +1,109 @@ +package codechicken.lib.block.component.tile; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.block.ModularTileBlock; +import com.mojang.serialization.Codec; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +/** + * Created by covers1624 on 3/29/26. + */ +@ApiStatus.Experimental +public class ValueComponent extends ModularTileBlock.TileComponent.Data> { + + private final Codec codec; + private final V defaultValue; + + private @Nullable StreamCodec streamCodec; + + public ValueComponent(Codec codec, V defaultValue) { + this.codec = codec; + this.defaultValue = defaultValue; + } + + public ValueComponent syncToClient(StreamCodec codec) { + streamCodec = codec; + return this; + } + + @Override + protected Data createData(ModularBlockEntity ent) { + return new Data(ent, this); + } + + public class Data extends ModularBlockEntity.DataComponent { + + private final List> onChanged = new ArrayList<>(0); + + private V value = defaultValue; + + protected Data(ModularBlockEntity tile, ModularTileBlock.TileComponent tileComponent) { + super(tile, tileComponent); + } + + public Data onChanged(Consumer cons) { + onChanged.add(cons); + return this; + } + + public V get() { + return value; + } + + public void set(V value) { + if (!this.value.equals(value)) { + forceSet(value); + onChanged(); + } + } + + public void forceSet(V value) { + this.value = value; + } + + public void onChanged() { + onChanged.forEach(e -> e.accept(value)); + + syncToClient(); + } + + public void syncToClient() { + if (tile.getLevel().isClientSide()) return; + if (streamCodec == null) throw new UnsupportedOperationException("No stream codec supplied."); + + sendToClient(null, p -> { + p.cc$writeWithRegistryCodec(streamCodec, value); + }); + } + + @Override + protected void onClientPacket(RegistryFriendlyByteBuf buf, IPayloadContext ctx) { + if (streamCodec == null) throw new IllegalStateException("Somehow received packet for component which does not have a codec.."); + + forceSet(buf.cc$readWithRegistryCodec(streamCodec)); + onChanged(); + } + + @Override + protected void save(ValueOutput output) { + super.save(output); + output.store("value", codec, value); + } + + @Override + protected void load(ValueInput input) { + super.load(input); + value = input.read("value", codec).orElse(defaultValue); + } + } +} diff --git a/src/main/java/codechicken/lib/block/component/tile/package-info.java b/src/main/java/codechicken/lib/block/component/tile/package-info.java index 41dcaf33..6f27633e 100644 --- a/src/main/java/codechicken/lib/block/component/tile/package-info.java +++ b/src/main/java/codechicken/lib/block/component/tile/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block.component.tile; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/block/package-info.java b/src/main/java/codechicken/lib/block/package-info.java index 74498270..0c8f7368 100644 --- a/src/main/java/codechicken/lib/block/package-info.java +++ b/src/main/java/codechicken/lib/block/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.block; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/capability/CapabilityCache.java b/src/main/java/codechicken/lib/capability/CapabilityCache.java index 401c0044..2de066b5 100644 --- a/src/main/java/codechicken/lib/capability/CapabilityCache.java +++ b/src/main/java/codechicken/lib/capability/CapabilityCache.java @@ -1,29 +1,26 @@ package codechicken.lib.capability; -import codechicken.lib.math.MathHelper; -import com.google.common.collect.Iterables; -import net.covers1624.quack.collection.Object2IntPair; +import net.covers1624.quack.util.SneakyUtils; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.common.util.NonNullSupplier; +import net.minecraft.server.level.ServerLevel; +import net.neoforged.neoforge.capabilities.BlockCapability; +import net.neoforged.neoforge.capabilities.BlockCapabilityCache; +import net.neoforged.neoforge.capabilities.ICapabilityInvalidationListener; +import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; /** * A simple cache for capabilities as viewed from a specific world position. *

- * Several things need to be implemented depending on your usage, if you wish to have a time-out - * based cache, meaning if a capability for a block is 'empty', it will wait {@link #setWaitTicks} - * number of ticks to check again, if you are using this class in that mode, you must call - * {@link #tick()} each game tick otherwise nothing will ever re-cache.
- * You can also call {@link #onNeighborChanged}, doing so will force a re-cache of all empty capabilities - * from the block that notified us of a change, on the next query.
- * For Support of API's that notify you when your host was moved, you should probably call {@link #setWorldPos} - * to clear the entire cache and notify of world and/or position change. + * Provides a cleaner api to the Neo provided {@link BlockCapabilityCache}. The Neo cache requires you know, up-front, + * what capabilities you wish to receive, this is not always the case and not always easily computable. + *

+ * For Support of API's that notify you when your host was moved, you should call {@link #setLevelPos} + * to ensure the capability cache *

* It is also possible to create {@link CapabilityCache} without a world and position. Doing so, will * cause all getters to return 'empty' until one is assigned. @@ -32,181 +29,136 @@ */ public class CapabilityCache { - private final Map, Object2IntPair>> selfCache = new HashMap<>(); - private final EnumMap, Object2IntPair>>> sideCache = new EnumMap<>(Direction.class); - - private Level world; - private BlockPos pos; + private final SideCache[] cache; - private int ticks; - private int waitTicks = 5 * 20; + private @Nullable ServerLevel level; + private @Nullable BlockPos pos; + private int moveCookie; public CapabilityCache() { + cache = new SideCache[7]; + for (int i = 0; i < cache.length; i++) { + cache[i] = new SideCache(); + } } - public CapabilityCache(Level world, BlockPos pos) { - this.world = world; - this.pos = pos; - } - - /** - * Sets the number of ticks to wait between re-caching an 'empty' capability.
- * The default is to wait 5 seconds. - * - * @param ticks The number of game ticks to wait. - */ - public void setWaitTicks(int ticks) { - this.waitTicks = ticks; - } - - /** - * Call this to notify of a new game tick. - */ - public void tick() { - ticks++; + public CapabilityCache(ServerLevel level, BlockPos pos) { + this(); + setLevelPos(level, pos); } /** * Call this when {@link CapabilityCache}'s host has been moved.
* Clears all internal state and sets a new world / pos. * - * @param world The new world. + * @param level The new world. * @param pos The new pos. */ - public void setWorldPos(Level world, BlockPos pos) { + public void setLevelPos(ServerLevel level, BlockPos pos) { clear(); - this.world = world; + this.level = level; this.pos = pos; + this.moveCookie++; } /** * Clears all internal state. Everything will be re-cached. */ public void clear() { - selfCache.clear(); - Arrays.stream(Direction.BY_3D_DATA).map(this::getCacheForSide).forEach(Map::clear); - } - - /** - * Notifies {@link CapabilityCache} of a {@link Block#onNeighborChange} event.
- * Marks all empty capabilities provided by from block, to be re-cached - * next query. - * - * @param from The from position. - */ - public void onNeighborChanged(BlockPos from) { - if (world == null || pos == null) { - return; - } - BlockPos offset = from.subtract(pos); - int diff = MathHelper.absSum(offset); - int side = MathHelper.toSide(offset); - if (side < 0 || diff != 1) { - return; + for (SideCache sideCache : cache) { + sideCache.cache.clear(); + sideCache.listener = null; } - Direction sideChanged = Direction.BY_3D_DATA[side]; - - Iterables.concat(selfCache.entrySet(), getCacheForSide(sideChanged).entrySet()).forEach(entry -> { - Object2IntPair> pair = entry.getValue(); - if (pair.getKey() != null && !pair.getKey().isPresent()) { - pair.setKey(null); - pair.setValue(ticks); - } - }); } /** - * Overload of {@link #getCapability} with support for evaluating a {@link NonNullSupplier} - * when empty. + * Overload of {@link #getCapability} with support for returning another object when empty. * * @param capability The capability to get. * @param to The direction to ask. - * @param default_ The supplier to evaluate when empty. - * @return The instance, either the capability at to or what default_ supplies. + * @param default_ The object to return when empty. + * @return The instance, either the capability at to or default_ */ - public T getCapabilityOr(Capability capability, Direction to, NonNullSupplier default_) { - return getCapability(capability, to).orElseGet(default_); + public T getCapabilityOr(BlockCapability capability, Direction to, T default_) { + T ret = getCapability(capability, to); + if (ret == null) return default_; + + return ret; } /** - * Overload of {@link #getCapability} with support for returning another object when empty. + * Gets a capability from the block in to direction from {@link CapabilityCache}'s + * position. For example, calling this with NORTH, will get a capability from the block + * IN NORTH direction on ITS SOUTH face. * * @param capability The capability to get. * @param to The direction to ask. - * @param default_ The object to return when empty. - * @return The instance, either the capability at to or default_ + * @return The capability instance or {@code null}. */ - public T getCapabilityOr(Capability capability, Direction to, T default_) { - return getCapability(capability, to).orElse(default_); + public @Nullable T getCapability(BlockCapability capability, Direction to) { + return getCapability(capability, to, to.getOpposite()); } /** * Gets a capability from the block in to direction from {@link CapabilityCache}'s - * position. For example, calling this with NORTH, will get a capability from the block - * IN NORTH direction on ITS SOUTH face. + * position. * * @param capability The capability to get. * @param to The direction to ask. - * @return A {@link LazyOptional} of the capability, may be empty. + * @param ctx The context, usually the face. + * @return The capability instance or {@code null}. */ - public LazyOptional getCapability(Capability capability, Direction to) { + public @Nullable T getCapability(BlockCapability capability, Direction to, C ctx) { Objects.requireNonNull(capability, "Null capability."); - if (world == null || pos == null) { - return LazyOptional.empty().cast(); - } - Map, Object2IntPair>> sideCache = getCacheForSide(to); - Object2IntPair> cache = sideCache.get(capability); - if (cache == null) { - cache = new Object2IntPair<>(null, ticks); - sideCache.put(capability, cache); - return tryReCache(capability, to, cache).cast(); - } - LazyOptional lookup = cache.getKey(); - if (lookup == null || !lookup.isPresent()) { - return tryReCache(capability, to, cache).cast(); + if (level == null || pos == null) return null; + + SideCache sideCache = cache[idxForDir(to)]; + CacheKey key = new CacheKey(capability, ctx); + CacheValue val = SneakyUtils.unsafeCast(sideCache.cache.get(key)); + if (val != null) return val.obj; + + BlockPos there = pos.relative(to); + T obj; + if (level.isLoaded(there)) { + obj = level.getCapability(capability, there, ctx); + sideCache.addListener(there); + } else { + obj = null; } - return lookup.cast(); + sideCache.cache.put(key, new CacheValue<>(obj)); + return obj; } - //TODO this logic should be unified and merged with above, There is a potential case where we could leak the Object2IntPair - //TODO instance if a mod does weird things with their invalidations of LazyOptionals - private LazyOptional tryReCache(Capability capability, Direction to, Object2IntPair> cache) { - boolean isFirst = cache.getKey() == null; - if (isFirst || !cache.getKey().isPresent()) { - if (isFirst || cache.getValue() + waitTicks <= ticks) { - LazyOptional lookup = requestCapability(capability, to); - if (lookup.isPresent()) { - cache.setKey(lookup); - cache.setValue(ticks); - lookup.addListener(l -> {//TODO, probably not needed? we check every lookup anyway.. - //When the LazyOptional notifies us that its gone, - //set the cache to empty, and mark ticks. - cache.setKey(LazyOptional.empty()); - cache.setValue(ticks); - }); - } else { - cache.setKey(LazyOptional.empty()); - cache.setValue(ticks); - } - } - } - return cache.getKey(); + private static int idxForDir(@Nullable Direction dir) { + return dir == null ? 6 : dir.ordinal(); } - private LazyOptional requestCapability(Capability capability, Direction to) { - BlockEntity tile = world.getBlockEntity(pos.relative(to)); - Direction inverse = to == null ? null : to.getOpposite(); - if (tile != null) { - return tile.getCapability(capability, inverse); - } - return LazyOptional.empty(); - } + private final class SideCache { + + private final Map> cache = new HashMap<>(); + private @Nullable ICapabilityInvalidationListener listener; + + public void addListener(BlockPos pos) { + if (listener != null) return; + if (level == null) throw new RuntimeException("Level is null?? What?"); - private Map, Object2IntPair>> getCacheForSide(Direction side) { - if (side == null) { - return selfCache; + listener = new ICapabilityInvalidationListener() { + private final int cookie = moveCookie; + + @Override + public boolean onInvalidate() { + if (cookie != moveCookie) return false; + + cache.clear(); + return true; + } + }; + level.registerCapabilityListener(pos, listener); } - return sideCache.computeIfAbsent(side, s -> new HashMap<>()); } + private record CacheKey(BlockCapability capability, @Nullable Object context) { } + + private record CacheValue(@Nullable T obj) { } + } diff --git a/src/main/java/codechicken/lib/capability/SimpleCapProvider.java b/src/main/java/codechicken/lib/capability/SimpleCapProvider.java deleted file mode 100644 index 6272878c..00000000 --- a/src/main/java/codechicken/lib/capability/SimpleCapProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.capability; - -import net.minecraft.core.Direction; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Created by covers1624 on 17/5/20. - */ -public class SimpleCapProvider implements ICapabilityProvider { - - protected final Capability capability; - protected final T instance; - protected final LazyOptional instanceOpt; - - public SimpleCapProvider(Capability capability, T instance) { - this.capability = capability; - this.instance = instance; - instanceOpt = LazyOptional.of(() -> this.instance); - } - - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull Capability cap, @Nullable Direction side) { - if (capability == cap) { - return instanceOpt.cast(); - } - return LazyOptional.empty(); - } -} diff --git a/src/main/java/codechicken/lib/capability/package-info.java b/src/main/java/codechicken/lib/capability/package-info.java new file mode 100644 index 00000000..926eb037 --- /dev/null +++ b/src/main/java/codechicken/lib/capability/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.capability; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/colour/Colour.java b/src/main/java/codechicken/lib/colour/Colour.java index 00edece3..9a8165e7 100644 --- a/src/main/java/codechicken/lib/colour/Colour.java +++ b/src/main/java/codechicken/lib/colour/Colour.java @@ -2,6 +2,7 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; +import org.jetbrains.annotations.Nullable; import static java.lang.Math.max; @@ -134,6 +135,78 @@ public Colour set(float[] floats) { return set(floats[0], floats[1], floats[2], floats[3]); } + public Colour rF(float r) { + this.r = (byte) (255F * r); + return this; + } + + public Colour gF(float g) { + this.g = (byte) (255F * g); + return this; + } + + public Colour bF(float b) { + this.b = (byte) (255F * b); + return this; + } + + public Colour aF(float a) { + this.a = (byte) (255F * a); + return this; + } + + public Colour rF(int r) { + this.r = (byte) r; + return this; + } + + public Colour gF(int g) { + this.g = (byte) g; + return this; + } + + public Colour bF(int b) { + this.b = (byte) b; + return this; + } + + public Colour aF(int a) { + this.a = (byte) a; + return this; + } + + public float rF() { + return r() / 255F; + } + + public float gF() { + return g() / 255F; + } + + public float bF() { + return b() / 255F; + } + + public float aF() { + return a() / 255F; + } + + public int r() { + return r & 0xFF; + } + + public int g() { + return g & 0xFF; + } + + public int b() { + return b & 0xFF; + } + + public int a() { + return a & 0xFF; + } + /** * Flips a color between ABGR and RGBA. * @@ -196,8 +269,84 @@ public static int packARGB(float[] data) { return packARGB(data[0], data[1], data[2], data[3]); } - public boolean equals(Colour colour) { - return colour != null && rgba() == colour.rgba(); + public static int replace(int c, int i, float v) { + return replace(c, i, (int) (v * 255F)); + } + + /** + * Replace the packed 8-bit color component at the specified index. + * + * @param c The packed color. + * @param i The index to replace. + * @param v The value to replace with. + * @return The new packed color. + */ + public static int replace(int c, int i, int v) { + int mask = ~(0xFF << i * 8); + return c & mask | (v & 0xFF) << i * 8; + } + + public static int unpack(int c, int i) { + return (c >> (8 * i)) & 0xFF; + } + + public static int pack(int c, int i) { + return (c & 0xFF) << 8 * i; + } + + /** + * For each color component in c1 and c2, adds them together + * clamping to 0 - 255. + *

+ * Agnostic of color packing order. + */ + public static int add(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(Math.min(a + b, 255), i); + } + return r; + } + + /** + * For each color component in c1 and c2, subtracts them + * clamping to 0 - 255. + *

+ * Agnostic of color packing order. + */ + public static int sub(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(Math.max(a - b, 0), i); + } + return r; + } + + /** + * For each color component in c1 and c2, calculates the midpoint. + *

+ * Agnostic of color packing order. + */ + public static int mid(int c1, int c2) { + int r = 0; + for (int i = 0; i < 4; i++) { + int a = unpack(c1, i); + int b = unpack(c2, i); + r |= pack(b + (a - b) / 2, i); + } + return r; + } + + public boolean equals(@Nullable Colour other) { + if (other == null) return false; + if (r != other.r) return false; + if (g != other.g) return false; + if (b != other.b) return false; + return a == other.a; } @Override @@ -205,10 +354,7 @@ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Colour colour)) return false; - if (r != colour.r) return false; - if (g != colour.g) return false; - if (b != colour.b) return false; - return a == colour.a; + return equals(colour); } @Override diff --git a/src/main/java/codechicken/lib/colour/CustomGradient.java b/src/main/java/codechicken/lib/colour/CustomGradient.java index 222b1e33..432db882 100644 --- a/src/main/java/codechicken/lib/colour/CustomGradient.java +++ b/src/main/java/codechicken/lib/colour/CustomGradient.java @@ -2,7 +2,7 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.texture.TextureUtils; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import java.awt.image.BufferedImage; @@ -10,10 +10,10 @@ public class CustomGradient { public int[] gradient; - public CustomGradient(ResourceLocation textureFile) { + public CustomGradient(Identifier textureFile) { BufferedImage img = TextureUtils.loadBufferedImage(textureFile); if (img == null) { - throw new RuntimeException("File not found: " + textureFile.toString()); + throw new RuntimeException("File not found: " + textureFile); } int[] data = new int[img.getWidth()]; diff --git a/src/main/java/codechicken/lib/colour/EnumColour.java b/src/main/java/codechicken/lib/colour/EnumColour.java index c653d2d1..bcec7d79 100644 --- a/src/main/java/codechicken/lib/colour/EnumColour.java +++ b/src/main/java/codechicken/lib/colour/EnumColour.java @@ -3,18 +3,22 @@ import com.google.common.collect.HashBasedTable; import com.google.common.collect.ImmutableTable; import com.google.common.collect.Table; +import io.netty.buffer.ByteBuf; +import net.covers1624.quack.collection.FastStream; import net.minecraft.client.resources.language.I18n; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; +import net.minecraft.util.ByIdMap; import net.minecraft.util.StringRepresentable; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.ForgeRegistries; +import org.jetbrains.annotations.Nullable; -import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.function.Function; -import java.util.stream.Collectors; +import java.util.function.IntFunction; /** * Created by covers1624 on 16/09/2016. @@ -22,40 +26,44 @@ public enum EnumColour implements StringRepresentable { //@formatter:off - WHITE ("white", "forge:dyes/white", "forge:wool/white", "item.minecraft.firework_star.white", 0xFFFFFF), - ORANGE ("orange", "forge:dyes/orange", "forge:wool/orange", "item.minecraft.firework_star.orange", 0xC06300), - MAGENTA ("magenta", "forge:dyes/magenta", "forge:wool/magenta", "item.minecraft.firework_star.magenta", 0xB51AB5), - LIGHT_BLUE("light_blue", "forge:dyes/light_blue", "forge:wool/light_blue", "item.minecraft.firework_star.light_blue", 0x6F84F1), - YELLOW ("yellow", "forge:dyes/yellow", "forge:wool/yellow", "item.minecraft.firework_star.yellow", 0xBFBF00), - LIME ("lime", "forge:dyes/lime", "forge:wool/lime", "item.minecraft.firework_star.lime", 0x6BF100), - PINK ("pink", "forge:dyes/pink", "forge:wool/pink", "item.minecraft.firework_star.pink", 0xF14675), - GRAY ("gray", "forge:dyes/gray", "forge:wool/gray", "item.minecraft.firework_star.gray", 0x535353), - LIGHT_GRAY("light_gray", "forge:dyes/light_gray", "forge:wool/light_gray", "item.minecraft.firework_star.light_gray", 0x939393), - CYAN ("cyan", "forge:dyes/cyan", "forge:wool/cyan", "item.minecraft.firework_star.cyan", 0x008787), - PURPLE ("purple", "forge:dyes/purple", "forge:wool/purple", "item.minecraft.firework_star.purple", 0x5E00C0), - BLUE ("blue", "forge:dyes/blue", "forge:wool/blue", "item.minecraft.firework_star.blue", 0x1313C0), - BROWN ("brown", "forge:dyes/brown", "forge:wool/brown", "item.minecraft.firework_star.brown", 0x4F2700), - GREEN ("green", "forge:dyes/green", "forge:wool/green", "item.minecraft.firework_star.green", 0x088700), - RED ("red", "forge:dyes/red", "forge:wool/red", "item.minecraft.firework_star.red", 0xA20F06), - BLACK ("black", "forge:dyes/black", "forge:wool/black", "item.minecraft.firework_star.black", 0x1F1F1F); + WHITE ("white", "c:dyes/white", "c:wools/white", "item.minecraft.firework_star.white", 0xFFFFFF), + ORANGE ("orange", "c:dyes/orange", "c:wools/orange", "item.minecraft.firework_star.orange", 0xC06300), + MAGENTA ("magenta", "c:dyes/magenta", "c:wools/magenta", "item.minecraft.firework_star.magenta", 0xB51AB5), + LIGHT_BLUE("light_blue", "c:dyes/light_blue", "c:wools/light_blue", "item.minecraft.firework_star.light_blue", 0x6F84F1), + YELLOW ("yellow", "c:dyes/yellow", "c:wools/yellow", "item.minecraft.firework_star.yellow", 0xBFBF00), + LIME ("lime", "c:dyes/lime", "c:wools/lime", "item.minecraft.firework_star.lime", 0x6BF100), + PINK ("pink", "c:dyes/pink", "c:wools/pink", "item.minecraft.firework_star.pink", 0xF14675), + GRAY ("gray", "c:dyes/gray", "c:wools/gray", "item.minecraft.firework_star.gray", 0x535353), + LIGHT_GRAY("light_gray", "c:dyes/light_gray", "c:wools/light_gray", "item.minecraft.firework_star.light_gray", 0x939393), + CYAN ("cyan", "c:dyes/cyan", "c:wools/cyan", "item.minecraft.firework_star.cyan", 0x008787), + PURPLE ("purple", "c:dyes/purple", "c:wools/purple", "item.minecraft.firework_star.purple", 0x5E00C0), + BLUE ("blue", "c:dyes/blue", "c:wools/blue", "item.minecraft.firework_star.blue", 0x1313C0), + BROWN ("brown", "c:dyes/brown", "c:wools/brown", "item.minecraft.firework_star.brown", 0x4F2700), + GREEN ("green", "c:dyes/green", "c:wools/green", "item.minecraft.firework_star.green", 0x088700), + RED ("red", "c:dyes/red", "c:wools/red", "item.minecraft.firework_star.red", 0xA20F06), + BLACK ("black", "c:dyes/black", "c:wools/black", "item.minecraft.firework_star.black", 0x1F1F1F); //@formatter:on + public static final StringRepresentable.EnumCodec CODEC = StringRepresentable.fromEnum(EnumColour::values); + public static final IntFunction BY_ID = ByIdMap.continuous(EnumColour::ordinal, values(), ByIdMap.OutOfBoundsStrategy.WRAP); + public static final StreamCodec STREAM_CODEC = ByteBufCodecs.idMapper(BY_ID, EnumColour::ordinal); + private final String name; - private final ResourceLocation dyeTagName; - private final ResourceLocation woolTagName; + private final Identifier dyeTagName; + private final Identifier woolTagName; private final String unlocalizedName; private final int rgb; private static final ImmutableTable mixMap; - private static final Map nameLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.name, Function.identity())); + private static final Map nameLookup = FastStream.of(values()) + .toMap(e -> e.name, Function.identity()); - private static final Map dyeTagLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.dyeTagName, Function.identity())); + private static final Map dyeTagLookup = FastStream.of(values()) + .toMap(e -> e.dyeTagName, Function.identity()); - private static final Map woolTagLookup = Arrays.stream(values())// - .collect(Collectors.toMap(e -> e.woolTagName, Function.identity())); + private static final Map woolTagLookup = FastStream.of(values()) + .toMap(e -> e.woolTagName, Function.identity()); static { Table tmp = HashBasedTable.create(); @@ -88,8 +96,8 @@ public enum EnumColour implements StringRepresentable { EnumColour(String name, String dyeTagName, String woolTagName, String unlocalizedName, int rgb) { this.name = name; - this.dyeTagName = new ResourceLocation(dyeTagName); - this.woolTagName = new ResourceLocation(woolTagName); + this.dyeTagName = Identifier.parse(dyeTagName); + this.woolTagName = Identifier.parse(woolTagName); this.unlocalizedName = unlocalizedName; this.rgb = rgb; } @@ -99,11 +107,11 @@ public String getSerializedName() { return name; } - public ResourceLocation getDyeTagName() { + public Identifier getDyeTagName() { return dyeTagName; } - public ResourceLocation getWoolTagName() { + public Identifier getWoolTagName() { return woolTagName; } @@ -163,11 +171,11 @@ public ColourRGBA getColour(int alpha) { return new ColourRGBA(rgba(alpha)); } - public EnumColour mix(EnumColour b) { + public @Nullable EnumColour mix(EnumColour b) { return mix(this, b); } - public static EnumColour mix(EnumColour a, EnumColour b) { + public static @Nullable EnumColour mix(EnumColour a, EnumColour b) { if (a == b) { return a; } @@ -182,37 +190,31 @@ public static EnumColour fromDyeMeta(int id) { return values()[15 - id]; } - public static EnumColour fromDyeTag(ResourceLocation tag) { + public static @Nullable EnumColour fromDyeTag(Identifier tag) { return dyeTagLookup.get(tag); } - public static EnumColour fromWoolTag(ResourceLocation tag) { + public static @Nullable EnumColour fromWoolTag(Identifier tag) { return woolTagLookup.get(tag); } - public static EnumColour fromDyeStack(ItemStack stack) { - return ForgeRegistries.ITEMS.getHolder(stack.getItem()) - .flatMap(e -> e.getTagKeys() - .map(TagKey::location) - .map(dyeTagLookup::get) - .filter(Objects::nonNull) - .findFirst() - ) - .orElse(null); + public static @Nullable EnumColour fromDyeStack(ItemStack stack) { + return FastStream.of(stack.getTags()) + .map(TagKey::location) + .map(dyeTagLookup::get) + .filter(Objects::nonNull) + .firstOrDefault(); } - public static EnumColour fromWoolStack(ItemStack stack) { - return ForgeRegistries.ITEMS.getHolder(stack.getItem()) - .flatMap(e -> e.getTagKeys() - .map(TagKey::location) - .map(woolTagLookup::get) - .filter(Objects::nonNull) - .findFirst() - ) - .orElse(null); + public static @Nullable EnumColour fromWoolStack(ItemStack stack) { + return FastStream.of(stack.getTags()) + .map(TagKey::location) + .map(woolTagLookup::get) + .filter(Objects::nonNull) + .firstOrDefault(); } - public static EnumColour fromName(String name) { + public static @Nullable EnumColour fromName(String name) { return nameLookup.get(name); } } diff --git a/src/main/java/codechicken/lib/colour/package-info.java b/src/main/java/codechicken/lib/colour/package-info.java new file mode 100644 index 00000000..e2b8353a --- /dev/null +++ b/src/main/java/codechicken/lib/colour/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.colour; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java index 6185c64a..92f3657a 100644 --- a/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigCategoryImpl.java @@ -1,8 +1,7 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.ColUtils; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Nullable; import java.util.*; @@ -157,7 +156,7 @@ public void runSync(ConfigCallback.Reason reason) { @Override public boolean isDirty() { - return super.isDirty() || StreamableIterable.of(getChildren()).anyMatch(ConfigTag::isDirty); + return super.isDirty() || ColUtils.anyMatch(getChildren(), ConfigTag::isDirty); } @Override @@ -182,39 +181,35 @@ public ConfigCategoryImpl copy(@Nullable ConfigCategoryImpl parent) { } @Override - public void write(MCDataOutput out) { - out.writeVarInt(tagMap.size()); + public void write(FriendlyByteBuf packet) { + packet.writeVarInt(tagMap.size()); for (AbstractConfigTag child : tagMap.values()) { if (!child.requiresClientSync()) { - out.writeByte(NET_NO_TAG); + packet.writeByte(NET_NO_TAG); continue; } - if (child instanceof ConfigCategory) { - out.writeByte(NET_CAT_TAG); - } else if (child instanceof ConfigValue) { - out.writeByte(NET_VAL_TAG); - } else if (child instanceof ConfigValueList) { - out.writeByte(NET_VAL_LST); - } else { - throw new IllegalStateException("Unknown tag class. " + child.getClass()); + switch (child) { + case ConfigCategory cat -> packet.writeByte(NET_CAT_TAG); + case ConfigValue val -> packet.writeByte(NET_VAL_TAG); + case ConfigValueList list -> packet.writeByte(NET_VAL_LST); + default -> throw new IllegalStateException("Unknown tag class. " + child.getClass()); } - out.writeString(child.getName()); - child.write(out); + packet.writeUtf(child.getName()); + child.write(packet); } } @Override - public void read(MCDataInput in) { + public void read(FriendlyByteBuf in) { int numTags = in.readVarInt(); for (int i = 0; i < numTags; i++) { byte t = in.readByte(); if (t == NET_NO_TAG) continue; - String name = in.readString(); + String name = in.readUtf(); ConfigTag tag = findTag(name); switch (t) { - default -> throw new IllegalStateException("Unknown tag network type: " + t); case NET_CAT_TAG -> { if (tag != null && !(tag instanceof ConfigCategoryImpl)) throw new IllegalStateException("Tried to read category into " + tag.getClass().getSimpleName()); if (tag == null) { @@ -239,6 +234,7 @@ public void read(MCDataInput in) { tag = cat; } } + default -> throw new IllegalStateException("Unknown tag network type: " + t); } tag.read(in); } diff --git a/src/main/java/codechicken/lib/config/ConfigFile.java b/src/main/java/codechicken/lib/config/ConfigFile.java index ef1e9766..1d4cca1b 100644 --- a/src/main/java/codechicken/lib/config/ConfigFile.java +++ b/src/main/java/codechicken/lib/config/ConfigFile.java @@ -1,9 +1,8 @@ package codechicken.lib.config; import codechicken.lib.config.parser.ConfigSerializer; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.NotImplementedException; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -38,7 +37,7 @@ public final class ConfigFile { *

* The {@code rootName} is used when creating translation keys for * a given tag. It is recommended that you use your ModID for this, or - * a {@link ResourceLocation} like string. + * a {@link Identifier} like string. * * @param rootName The root name for the returned config. Usually * your ModID. diff --git a/src/main/java/codechicken/lib/config/ConfigSyncManager.java b/src/main/java/codechicken/lib/config/ConfigSyncManager.java index b9cc961c..b45ecfd5 100644 --- a/src/main/java/codechicken/lib/config/ConfigSyncManager.java +++ b/src/main/java/codechicken/lib/config/ConfigSyncManager.java @@ -1,18 +1,26 @@ package codechicken.lib.config; -import codechicken.lib.packet.PacketCustom; +import codechicken.lib.packet.ConfigurationStreamPacket; +import codechicken.lib.packet.StreamNetworkChannel; import com.google.common.base.Joiner; -import net.minecraft.resources.ResourceLocation; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; +import net.minecraft.server.network.ConfigurationTask; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; +import net.neoforged.neoforge.network.handling.IPayloadContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.ApiStatus; import java.util.HashMap; import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; -import static codechicken.lib.internal.network.CCLNetwork.NET_CHANNEL; +import java.util.function.Consumer; /** * Created by covers1624 on 19/5/22. @@ -20,8 +28,9 @@ public class ConfigSyncManager { private static final Logger LOGGER = LogManager.getLogger(); + private static final CrashLock LOCK = new CrashLock("Already Initialized."); - private static final Map SYNC_MAP = new HashMap<>(); + private static final Map SYNC_MAP = new HashMap<>(); /** * Registers the specified {@link ConfigTag} for syncing. @@ -31,34 +40,27 @@ public class ConfigSyncManager { * @param key The unique id to associate this tag. * @param tag The Tag to sync. */ - public static void registerSync(ResourceLocation key, ConfigTag tag) { + public static void registerSync(Identifier key, ConfigTag tag) { ConfigTag prev = SYNC_MAP.put(key, tag); if (prev != null) { throw new IllegalArgumentException("Key '" + key + "' already registered."); } } - public static void handleLogin(BiConsumer> consumer) { - if (SYNC_MAP.isEmpty()) return; - - consumer.accept("config_sync", () -> { - PacketCustom packet = new PacketCustom(NET_CHANNEL, L_CONFIG_SYNC); - packet.writeVarInt(SYNC_MAP.size()); - for (Map.Entry entry : SYNC_MAP.entrySet()) { - packet.writeResourceLocation(entry.getKey()); - entry.getValue().write(packet); - } + @ApiStatus.Internal + public static void init(IEventBus modBus) { + LOCK.lock(); - String mods = Joiner.on(", ").join(SYNC_MAP.keySet()); - LOGGER.info("Sending config sync packet for {} to connecting player.", mods); - return packet; - }); + if (FMLEnvironment.getDist().isClient()) { + NeoForge.EVENT_BUS.addListener(ConfigSyncManager::onClientDisconnected); + } } - public static void readSyncPacket(PacketCustom packet) { + @ApiStatus.Internal + public static void readSyncPacket(FriendlyByteBuf packet, IPayloadContext ctx) { int numPackets = packet.readVarInt(); for (int i = 0; i < numPackets; i++) { - ResourceLocation ident = packet.readResourceLocation(); + Identifier ident = packet.readIdentifier(); LOGGER.info("Applying config sync for {}.", ident); ConfigTag config = SYNC_MAP.get(ident); if (config == null) { @@ -70,12 +72,33 @@ public static void readSyncPacket(PacketCustom packet) { } } - public static void onClientDisconnected() { - for (Map.Entry entry : SYNC_MAP.entrySet()) { + private static void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { + for (Map.Entry entry : SYNC_MAP.entrySet()) { LOGGER.info("Client disconnected, rolling back config for {}.", entry.getKey()); ConfigTag config = entry.getValue(); config.resetFromNetwork(); config.runSync(ConfigCallback.Reason.ROLLBACK); } } + + @ApiStatus.Internal + public record ConfigSyncConfigurationTask(ConfigurationTask.Type type, StreamNetworkChannel.ConfigurationContext ctx) implements ICustomConfigurationTask { + + @Override + public void run(Consumer sender) { + if (!SYNC_MAP.isEmpty()) { + ConfigurationStreamPacket packet = ctx.newPacket(); + packet.writeVarInt(SYNC_MAP.size()); + for (Map.Entry entry : SYNC_MAP.entrySet()) { + packet.writeIdentifier(entry.getKey()); + entry.getValue().write(packet); + } + + String mods = Joiner.on(", ").join(SYNC_MAP.keySet()); + LOGGER.info("Sending config sync packet for {} to connecting player.", mods); + sender.accept(packet); + } + ctx.packetListener().finishCurrentTask(type); + } + } } diff --git a/src/main/java/codechicken/lib/config/ConfigTag.java b/src/main/java/codechicken/lib/config/ConfigTag.java index c23da9bd..19da0e64 100644 --- a/src/main/java/codechicken/lib/config/ConfigTag.java +++ b/src/main/java/codechicken/lib/config/ConfigTag.java @@ -1,8 +1,7 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.Identifier; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -74,7 +73,7 @@ default String getDesc() { /** * Sets this tag as requiring syncing to the client. *

- * Register your root tag via {@link ConfigSyncManager#registerSync(ResourceLocation, ConfigTag)}. + * Register your root tag via {@link ConfigSyncManager#registerSync(Identifier, ConfigTag)}. */ ConfigTag syncTagToClient(); @@ -168,16 +167,16 @@ default void delete() { ConfigTag copy(); /** - * Write this tag to a {@link MCDataOutput}. + * Write this tag to a {@link FriendlyByteBuf} packet. * Only categories and/or tags which have {@link #syncTagToClient()} set * will be written. * - * @param out The output stream. + * @param packet The packet to write to. */ - void write(MCDataOutput out); + void write(FriendlyByteBuf packet); /** - * Read this tag from a {@link MCDataInput}. + * Read this tag from a {@link FriendlyByteBuf} packet. * All tags and values will be read and inserted into the tree. *

* If a tag does not already exist in the tree, one will be added and marked @@ -186,9 +185,9 @@ default void delete() { * All tags with a network value will be reset to default when {@link #resetFromNetwork()} * is called, whilst any 'network only' tags will be deleted. * - * @param in The input stream. + * @param packet The packet to read from. */ - void read(MCDataInput in); + void read(FriendlyByteBuf packet); /** * Resets all network tags back to their original value. diff --git a/src/main/java/codechicken/lib/config/ConfigValueImpl.java b/src/main/java/codechicken/lib/config/ConfigValueImpl.java index 206302b8..4cb07610 100644 --- a/src/main/java/codechicken/lib/config/ConfigValueImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigValueImpl.java @@ -1,7 +1,6 @@ package codechicken.lib.config; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; +import net.minecraft.network.FriendlyByteBuf; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -438,22 +437,22 @@ public AbstractConfigTag copy(@Nullable ConfigCategoryImpl parent) } @Override - public void write(MCDataOutput out) { + public void write(FriendlyByteBuf packet) { if (type == ValueType.UNKNOWN) throw new IllegalStateException("Tried to write UNKNOWN tag to network"); - out.writeEnum(type); + packet.writeEnum(type); switch (type) { - case BOOLEAN -> out.writeBoolean(getBoolean()); - case STRING -> out.writeString(getString()); - case INT -> out.writeInt(getInt()); // TODO varint? signedVarint? - case LONG -> out.writeLong(getLong()); // TODO varlong? signedVarlong? - case HEX -> out.writeInt(getHex()); // TODO varint? signedVarint? - case DOUBLE -> out.writeDouble(getDouble()); + case BOOLEAN -> packet.writeBoolean(getBoolean()); + case STRING -> packet.writeUtf(getString()); + case INT -> packet.writeInt(getInt()); // TODO varint? signedVarint? + case LONG -> packet.writeLong(getLong()); // TODO varlong? signedVarlong? + case HEX -> packet.writeInt(getHex()); // TODO varint? signedVarint? + case DOUBLE -> packet.writeDouble(getDouble()); } } @Override - public void read(MCDataInput in) { - ValueType netType = in.readEnum(ValueType.class); + public void read(FriendlyByteBuf packet) { + ValueType netType = packet.readEnum(ValueType.class); if (networkSynthetic) { type = netType; } @@ -461,11 +460,11 @@ public void read(MCDataInput in) { if (netType != type) throw new IllegalStateException("Tried to read a " + netType + " tag from the network into a " + type + " tag"); switch (type) { - case BOOLEAN -> networkValue = in.readBoolean(); - case STRING -> networkValue = in.readString(); - case INT, HEX -> networkValue = in.readInt(); - case LONG -> networkValue = in.readLong(); - case DOUBLE -> networkValue = in.readDouble(); + case BOOLEAN -> networkValue = packet.readBoolean(); + case STRING -> networkValue = packet.readUtf(); + case INT, HEX -> networkValue = packet.readInt(); + case LONG -> networkValue = packet.readLong(); + case DOUBLE -> networkValue = packet.readDouble(); } } diff --git a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java index e2505ed1..a1804100 100644 --- a/src/main/java/codechicken/lib/config/ConfigValueListImpl.java +++ b/src/main/java/codechicken/lib/config/ConfigValueListImpl.java @@ -1,8 +1,7 @@ package codechicken.lib.config; import codechicken.lib.config.ListRestriction.Failure; -import codechicken.lib.data.MCDataInput; -import codechicken.lib.data.MCDataOutput; +import codechicken.lib.packet.CCStreamCodecs; import it.unimi.dsi.fastutil.booleans.BooleanArrayList; import it.unimi.dsi.fastutil.booleans.BooleanList; import it.unimi.dsi.fastutil.booleans.BooleanLists; @@ -15,7 +14,9 @@ import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; import it.unimi.dsi.fastutil.longs.LongLists; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.VisibleForTesting; import org.slf4j.Logger; @@ -350,28 +351,22 @@ public AbstractConfigTag copy(@Nullable ConfigCategoryImpl pare } @Override - public void write(MCDataOutput out) { + public void write(FriendlyByteBuf packet) { if (type == ValueType.UNKNOWN) throw new IllegalStateException("Tried to write UNKNOWN tag to network"); - out.writeEnum(type); + packet.writeEnum(type); switch (type) { - case STRING -> { - List values = getStrings(); - out.writeVarInt(values.size()); - for (String s : values) { - out.writeString(s); - } - } - case BOOLEAN -> out.writeBooleans(getBooleans().toBooleanArray()); - case INT -> out.writeInts(getInts().toIntArray()); - case LONG -> out.writeLongs(getLongs().toLongArray()); - case HEX -> out.writeInts(getHexs().toIntArray()); - case DOUBLE -> out.writeDoubles(getDoubles().toDoubleArray()); + case STRING -> packet.writeCollection(getStrings(), ByteBufCodecs.STRING_UTF8); + case BOOLEAN -> packet.cc$writeWithCodec(CCStreamCodecs.BOOLEAN_ARRAY, getBooleans().toBooleanArray()); + case INT -> packet.cc$writeWithCodec(CCStreamCodecs.INT_ARRAY, getInts().toIntArray()); + case LONG -> packet.cc$writeWithCodec(CCStreamCodecs.LONG_ARRAY, getLongs().toLongArray()); + case HEX -> packet.cc$writeWithCodec(CCStreamCodecs.INT_ARRAY, getHexs().toIntArray()); + case DOUBLE -> packet.cc$writeWithCodec(CCStreamCodecs.DOUBLE_ARRAY, getDoubles().toDoubleArray()); } } @Override - public void read(MCDataInput in) { - ValueType netType = in.readEnum(ValueType.class); + public void read(FriendlyByteBuf packet) { + ValueType netType = packet.readEnum(ValueType.class); if (networkSynthetic) { type = netType; } @@ -379,11 +374,11 @@ public void read(MCDataInput in) { if (netType != type) throw new IllegalStateException("Tried to read a " + netType + " tag from the network into a " + type + " tag"); switch (type) { - case STRING -> networkValue = readStringList(in); - case BOOLEAN -> networkValue = new BooleanArrayList(in.readBooleans()); - case INT, HEX -> networkValue = new IntArrayList(in.readInts()); - case LONG -> networkValue = new LongArrayList(in.readLongs()); - case DOUBLE -> networkValue = new DoubleArrayList(in.readDoubles()); + case STRING -> networkValue = packet.readList(ByteBufCodecs.STRING_UTF8); + case BOOLEAN -> networkValue = new BooleanArrayList(packet.cc$readWithCodec(CCStreamCodecs.BOOLEAN_ARRAY)); + case INT, HEX -> networkValue = new IntArrayList(packet.cc$readWithCodec(CCStreamCodecs.INT_ARRAY)); + case LONG -> networkValue = new LongArrayList(packet.cc$readWithCodec(CCStreamCodecs.LONG_ARRAY)); + case DOUBLE -> networkValue = new DoubleArrayList(packet.cc$readWithCodec(CCStreamCodecs.DOUBLE_ARRAY)); } } @@ -392,15 +387,6 @@ public void resetFromNetwork() { networkValue = null; } - private List readStringList(MCDataInput in) { - int len = in.readVarInt(); - List values = new ArrayList<>(len); - for (int i = 0; i < len; i++) { - values.add(in.readString()); - } - return values; - } - public ConfigValueList setValue(List value) { this.value = value; if (type != ValueType.UNKNOWN) { @@ -503,7 +489,7 @@ private static BooleanList convertToBooleans(List list) { private static List convertToStrings(List list) { if (list instanceof StringList sList) return sList; - return new StringList(StreamableIterable.of(list).map(Object::toString).toList()); + return new StringList(FastStream.of(list).map(Object::toString).toList()); } private static IntList convertToInts(List list) { diff --git a/src/main/java/codechicken/lib/config/package-info.java b/src/main/java/codechicken/lib/config/package-info.java index 3defeddf..32627ba9 100644 --- a/src/main/java/codechicken/lib/config/package-info.java +++ b/src/main/java/codechicken/lib/config/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.config; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java b/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java index b588df8f..41f13848 100644 --- a/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java +++ b/src/main/java/codechicken/lib/config/parser/LegacyConfigSerializer.java @@ -6,7 +6,7 @@ import it.unimi.dsi.fastutil.objects.Object2CharArrayMap; import it.unimi.dsi.fastutil.objects.Object2CharMap; import net.covers1624.quack.io.IOUtils; -import net.minecraft.Util; +import net.minecraft.util.Util; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java b/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java index 0b2fb196..714e9421 100644 --- a/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java +++ b/src/main/java/codechicken/lib/config/parser/TomlConfigSerializer.java @@ -18,7 +18,7 @@ public class TomlConfigSerializer implements ConfigSerializer { @Override public void parse(Path file, ConfigCategoryImpl rootTag) throws IOException { - try (CommentedFileConfig tomlConfig = CommentedFileConfig.builder(file).preserveInsertionOrder().build()) { + try (CommentedFileConfig tomlConfig = CommentedFileConfig.builder(file).sync().preserveInsertionOrder().build()) { tomlConfig.load(); load("", rootTag, tomlConfig); } diff --git a/src/main/java/codechicken/lib/config/parser/package-info.java b/src/main/java/codechicken/lib/config/parser/package-info.java index ddb4e618..8ecda292 100644 --- a/src/main/java/codechicken/lib/config/parser/package-info.java +++ b/src/main/java/codechicken/lib/config/parser/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.config.parser; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/data/DataUtils.java b/src/main/java/codechicken/lib/data/DataUtils.java index c29909bf..6436f7f4 100644 --- a/src/main/java/codechicken/lib/data/DataUtils.java +++ b/src/main/java/codechicken/lib/data/DataUtils.java @@ -5,6 +5,7 @@ /** * Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) class DataUtils { /** diff --git a/src/main/java/codechicken/lib/data/MCByteStream.java b/src/main/java/codechicken/lib/data/MCByteStream.java index e7938c7b..988c1a94 100644 --- a/src/main/java/codechicken/lib/data/MCByteStream.java +++ b/src/main/java/codechicken/lib/data/MCByteStream.java @@ -8,6 +8,7 @@ *

* Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCByteStream extends MCDataOutputStream { private final ByteArrayOutputStream bos; diff --git a/src/main/java/codechicken/lib/data/MCDataByteBuf.java b/src/main/java/codechicken/lib/data/MCDataByteBuf.java index eb8169ae..2b835aca 100644 --- a/src/main/java/codechicken/lib/data/MCDataByteBuf.java +++ b/src/main/java/codechicken/lib/data/MCDataByteBuf.java @@ -2,10 +2,16 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; import net.minecraft.nbt.ByteArrayTag; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.Tag; import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; +import net.neoforged.neoforge.network.connection.ConnectionType; +import org.jetbrains.annotations.Nullable; /** * An {@link MCDataInput} and {@link MCDataOutput} implementation, @@ -13,16 +19,30 @@ *

* Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCDataByteBuf implements MCDataInput, MCDataOutput { protected final ByteBuf buf; + protected final @Nullable RegistryAccess registryAccess; public MCDataByteBuf() { - this(Unpooled.buffer()); + this(Unpooled.buffer(), null); + } + + public MCDataByteBuf(@Nullable RegistryAccess registryAccess) { + this(Unpooled.buffer(), registryAccess); } public MCDataByteBuf(ByteBuf buf) { + this(buf, null); + } + + public MCDataByteBuf(ByteBuf buf, @Nullable RegistryAccess registryAccess) { this.buf = buf; + if (registryAccess == null && buf instanceof RegistryFriendlyByteBuf rBuf) { + registryAccess = rBuf.registryAccess(); + } + this.registryAccess = registryAccess; } /** @@ -30,19 +50,27 @@ public MCDataByteBuf(ByteBuf buf) { * * @return The {@link FriendlyByteBuf}. */ - public FriendlyByteBuf toPacketBuffer() { + public FriendlyByteBuf toFriendlyByteBuf() { return buf instanceof FriendlyByteBuf ? (FriendlyByteBuf) buf : new FriendlyByteBuf(buf); } + public RegistryFriendlyByteBuf toRegistryFriendlyByteBuf() { + if (buf instanceof RegistryFriendlyByteBuf rBuf) return rBuf; + if (registryAccess == null) { + throw new RuntimeException("RegistryAccess required for this operation."); + } + return new RegistryFriendlyByteBuf(buf, registryAccess, ConnectionType.NEOFORGE); + } + public Tag toTag() { return new ByteArrayTag(buf.array()); } - public static MCDataByteBuf fromTag(Tag tag) { + public static MCDataByteBuf fromTag(Tag tag, RegistryAccess registries) { if (!(tag instanceof ByteArrayTag)) { throw new IllegalArgumentException("Expected ByteArrayNBT, got: " + tag.getClass().getSimpleName()); } - return new MCDataByteBuf(Unpooled.copiedBuffer(((ByteArrayTag) tag).getAsByteArray())); + return new MCDataByteBuf(Unpooled.copiedBuffer(((ByteArrayTag) tag).getAsByteArray()), registries); } public CompoundTag writeToNBT(CompoundTag tag, String key) { @@ -50,8 +78,30 @@ public CompoundTag writeToNBT(CompoundTag tag, String key) { return tag; } - public static MCDataByteBuf readFromNBT(CompoundTag tag, String key) { - return fromTag(tag.get(key)); + public static MCDataByteBuf readFromNBT(CompoundTag tag, String key, RegistryAccess registries) { + return fromTag(tag.get(key), registries); + } + + @Override + public MCDataOutput writeWithCodec(StreamEncoder codec, T thing) { + codec.encode(toFriendlyByteBuf(), thing); + return this; + } + + @Override + public MCDataOutput writeWithRegistryCodec(StreamEncoder codec, T thing) { + codec.encode(toRegistryFriendlyByteBuf(), thing); + return this; + } + + @Override + public T readWithCodec(StreamDecoder codec) { + return codec.decode(toFriendlyByteBuf()); + } + + @Override + public T readWithRegistryCodec(StreamDecoder codec) { + return codec.decode(toRegistryFriendlyByteBuf()); } //@formatter:off diff --git a/src/main/java/codechicken/lib/data/MCDataInput.java b/src/main/java/codechicken/lib/data/MCDataInput.java index 35352c64..498ce3bf 100644 --- a/src/main/java/codechicken/lib/data/MCDataInput.java +++ b/src/main/java/codechicken/lib/data/MCDataInput.java @@ -2,31 +2,30 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.math.Vector3f; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.EncoderException; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; +import net.minecraft.core.*; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtAccounter; import net.minecraft.nbt.NbtIo; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.ComponentSerialization; import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.resources.Identifier; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.IForgeRegistry; -import net.minecraftforge.registries.RegistryManager; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; -import javax.annotation.Nullable; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; @@ -35,6 +34,7 @@ import java.nio.charset.StandardCharsets; import java.util.UUID; +import static java.util.Objects.requireNonNull; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; /** @@ -44,6 +44,7 @@ *

* Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public interface MCDataInput { //region Primitives @@ -528,12 +529,12 @@ default Cuboid6 readCuboid() { //region MinecraftObjects /** - * Reads a {@link ResourceLocation} from the stream. + * Reads a {@link Identifier} from the stream. * - * @return The {@link ResourceLocation}. + * @return The {@link Identifier}. */ - default ResourceLocation readResourceLocation() { - return new ResourceLocation(readString()); + default Identifier readResourceLocation() { + return Identifier.parse(readString()); } /** @@ -586,19 +587,25 @@ default Vector3f readVec3f() { * * @return The {@link CompoundTag}. */ - @Nullable default CompoundTag readCompoundNBT() { - if (!readBoolean()) { - return null; - } else { - try { - return NbtIo.read(toDataInput(), new NbtAccounter(2097152L)); - } catch (IOException e) { - throw new EncoderException("Failed to read CompoundNBT from stream.", e); - } + try { + return NbtIo.read(toDataInput(), NbtAccounter.create(2097152L)); + } catch (IOException e) { + throw new EncoderException("Failed to read CompoundNBT from stream.", e); } } + /** + * Reads a {@link CompoundTag} from the stream. + * + * @return The {@link CompoundTag} or {@code null}. + */ + default @Nullable CompoundTag readNullableCompoundNBT() { + if (!readBoolean()) return null; + + return readCompoundNBT(); + } + /** * Reads an {@link ItemStack} from the stream. * It should also be noted that this implementation reads the {@link ItemStack#getCount()} @@ -607,15 +614,7 @@ default CompoundTag readCompoundNBT() { * @return The {@link ItemStack}. */ default ItemStack readItemStack() { - if (!readBoolean()) { - return ItemStack.EMPTY; - } else { - Item item = readRegistryIdDirect(ForgeRegistries.ITEMS); - int count = readVarInt(); - ItemStack stack = new ItemStack(item, count); - stack.readShareTag(readCompoundNBT()); - return stack; - } + return readWithRegistryCodec(ItemStack.OPTIONAL_STREAM_CODEC); } /** @@ -624,17 +623,7 @@ default ItemStack readItemStack() { * @return The {@link FluidStack}. */ default FluidStack readFluidStack() { - if (!readBoolean()) { - return FluidStack.EMPTY; - } else { - Fluid fluid = readRegistryIdDirect(ForgeRegistries.FLUIDS); - int amount = readVarInt(); - CompoundTag tag = readCompoundNBT(); - if (fluid == Fluids.EMPTY) { - return FluidStack.EMPTY; - } - return new FluidStack(fluid, amount, tag); - } + return readWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC); } /** @@ -642,34 +631,40 @@ default FluidStack readFluidStack() { * * @return The {@link Component}. */ - default MutableComponent readTextComponent() { - return Component.Serializer.fromJson(readString()); + default Component readTextComponent() { + return readWithRegistryCodec(ComponentSerialization.STREAM_CODEC); } /** * Reads a registry object from the stream. * - * @param registry The {@link IForgeRegistry} to load the entry from. + * @param registry The {@link Registry} to load the entry from. * @return The registry object.. - * @see MCDataOutput#writeRegistryIdDirect(IForgeRegistry, Object) - * @see MCDataOutput#writeRegistryIdDirect(IForgeRegistry, ResourceLocation) + * @see MCDataOutput#writeRegistryIdDirect(Registry, Object) + * @see MCDataOutput#writeRegistryIdDirect(Registry, ResourceLocation) */ - default T readRegistryIdDirect(IForgeRegistry registry) { - ForgeRegistry _registry = unsafeCast(registry); - return _registry.getValue(readVarInt()); + default T readRegistryIdDirect(Registry registry) { + return requireNonNull(registry.byId(readVarInt()), "Registry entry did not exist."); } /** * Reads a registry object from the stream. * * @return The registry object. - * @see MCDataOutput#writeRegistryId(IForgeRegistry, Object) - * @see MCDataOutput#writeRegistryId(IForgeRegistry, ResourceLocation) + * @see MCDataOutput#writeRegistryId(Registry, Object) + * @see MCDataOutput#writeRegistryId(Registry, ResourceLocation) */ default T readRegistryId() { - ResourceLocation rName = readResourceLocation(); - ForgeRegistry registry = RegistryManager.ACTIVE.getRegistry(rName); - return readRegistryIdDirect(registry); + Identifier rName = readResourceLocation(); + return readRegistryIdDirect(unsafeCast(requireNonNull(BuiltInRegistries.REGISTRY.get(rName), "Registry " + rName + " not found."))); + } + + default T readWithCodec(StreamDecoder codec) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } + + default T readWithRegistryCodec(StreamDecoder codec) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); } //endregion diff --git a/src/main/java/codechicken/lib/data/MCDataInputStream.java b/src/main/java/codechicken/lib/data/MCDataInputStream.java index 0b6e5b86..35a6fa1e 100644 --- a/src/main/java/codechicken/lib/data/MCDataInputStream.java +++ b/src/main/java/codechicken/lib/data/MCDataInputStream.java @@ -14,6 +14,7 @@ *

* Created by covers1624 on 4/16/20. */ +@Deprecated (forRemoval = true) public class MCDataInputStream implements MCDataInput { private final DataInput in; diff --git a/src/main/java/codechicken/lib/data/MCDataOutput.java b/src/main/java/codechicken/lib/data/MCDataOutput.java index d9f14cc7..9a11a695 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutput.java +++ b/src/main/java/codechicken/lib/data/MCDataOutput.java @@ -2,23 +2,22 @@ import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.math.Vector3f; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.EncoderException; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; +import net.minecraft.core.*; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; +import net.minecraft.network.chat.ComponentSerialization; +import net.minecraft.network.codec.StreamEncoder; +import net.minecraft.resources.Identifier; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.registries.ForgeRegistries; -import net.minecraftforge.registries.ForgeRegistry; -import net.minecraftforge.registries.IForgeRegistry; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; import java.io.DataOutput; import java.io.DataOutputStream; @@ -30,8 +29,6 @@ import java.util.UUID; import static codechicken.lib.data.DataUtils.checkLen; -import static java.text.MessageFormat.format; -import static net.covers1624.quack.util.SneakyUtils.unsafeCast; /** * Provides the ability to write various datas to some sort of data stream. @@ -40,6 +37,7 @@ *

* Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public interface MCDataOutput { //region Primitives. @@ -386,7 +384,7 @@ default MCDataOutput append(byte[] bytes) { /** * Writes a Variable length int. * Doesn't handle Signed ints well, they end up as 5 bytes, - * instead of 4, Use {@link #writeSignedVarInt} if you requires numbers <= -1 + * instead of 4, Use {@link #writeSignedVarInt} if you require numbers {@code <= -1} * * @param i The int. * @return The same stream. @@ -404,7 +402,7 @@ default MCDataOutput writeVarInt(int i) { /** * Writes a Variable length long. * Doesn't handle Signed longs well, they end up as 10 bytes, - * instead of 8, Use {@link #writeSignedVarLong} if you requires numbers <= -1 + * instead of 8, Use {@link #writeSignedVarLong} if you require numbers {@code <= -1} * * @param l The long. * @return The same stream. @@ -420,7 +418,7 @@ default MCDataOutput writeVarLong(long l) { /** * Writes a Signed Variable length int. - * Favourable for numbers <= -1 + * Favourable for numbers {@code <= -1} * * @param i The int. * @return The same stream. @@ -431,7 +429,7 @@ default MCDataOutput writeSignedVarInt(int i) { /** * Writes a Signed Variable length long. - * Favourable for numbers <= -1 + * Favourable for numbers {@code <= -1} * * @param i The long. * @return The same stream. @@ -762,12 +760,12 @@ default MCDataOutput writeCuboid(Cuboid6 cuboid) { //region Minecraft Objects. /** - * Writes a {@link ResourceLocation} to the stream. + * Writes a {@link Identifier} to the stream. * - * @param loc The {@link ResourceLocation}. + * @param loc The {@link Identifier}. * @return The same stream. */ - default MCDataOutput writeResourceLocation(ResourceLocation loc) { + default MCDataOutput writeResourceLocation(Identifier loc) { return writeString(loc.toString()); } @@ -837,61 +835,41 @@ default MCDataOutput writeVec3d(Vec3 vec) { * @return The same stream. */ default MCDataOutput writeCompoundNBT(CompoundTag tag) { - if (tag == null) { - writeBoolean(false); - } else { - try { - writeBoolean(true); - NbtIo.write(tag, toDataOutput()); - } catch (IOException e) { - throw new EncoderException("Failed to write CompoundNBT to stream.", e); - } + try { + NbtIo.write(tag, toDataOutput()); + } catch (IOException e) { + throw new EncoderException("Failed to write CompoundNBT to stream.", e); } return this; } /** - * Writes an {@link ItemStack} to the stream. - * Overload for {@link #writeItemStack(ItemStack, boolean)} passing true. + * Writes a Nullable {@link CompoundTag} to the stream. * - * @param stack The {@link ItemStack}. + * @param tag The {@link CompoundTag} or {@code null}. * @return The same stream. */ - default MCDataOutput writeItemStack(ItemStack stack) { - return writeItemStack(stack, true); + default MCDataOutput writeNullableCompoundNBT(@Nullable CompoundTag tag) { + if (tag == null) { + writeBoolean(false); + } else { + writeBoolean(true); + writeCompoundNBT(tag); + } + return this; } /** * Writes an {@link ItemStack} to the stream. - * The limitedTag parameter, can be used to force the use of - * the stack {@link ItemStack#getShareTag()} instead of its {@link ItemStack#getTag()}. - * Under normal circumstances in Server -> Client sync, not all NBT tags are required, - * to be sent to the client. For Example, the inventory of a pouch / bag(Containers sync it). - * However, in Client -> Server sync, the entire tag may be required, modders can choose, - * if they want a stacks full tag or not. The default is to use {@link ItemStack#getShareTag()}. *

* It should also be noted that this implementation writes the {@link ItemStack#getCount()} * as a varInt opposed to a byte, as that is favourable in some cases. * - * @param stack The {@link ItemStack}. - * @param limitedTag Weather to use the stacks {@link ItemStack#getShareTag()} instead. + * @param stack The {@link ItemStack}. * @return The same stream. */ - default MCDataOutput writeItemStack(ItemStack stack, boolean limitedTag) { - if (stack.isEmpty()) { - writeBoolean(false); - } else { - writeBoolean(true); - Item item = stack.getItem(); - writeRegistryIdDirect(ForgeRegistries.ITEMS, item); - writeVarInt(stack.getCount()); - CompoundTag nbt = null; - if (item.canBeDepleted() || item.shouldOverrideMultiplayerNbt()) { - nbt = limitedTag ? stack.getShareTag() : stack.getTag(); - } - writeCompoundNBT(nbt); - } - return this; + default MCDataOutput writeItemStack(ItemStack stack) { + return writeWithRegistryCodec(ItemStack.OPTIONAL_STREAM_CODEC, stack); } /** @@ -901,15 +879,7 @@ default MCDataOutput writeItemStack(ItemStack stack, boolean limitedTag) { * @return The same stream. */ default MCDataOutput writeFluidStack(FluidStack stack) { - if (stack.isEmpty()) { - writeBoolean(false); - } else { - writeBoolean(true); - writeRegistryIdDirect(ForgeRegistries.FLUIDS, stack.getFluid()); - writeVarInt(stack.getAmount()); - writeCompoundNBT(stack.getTag()); - } - return this; + return writeWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC, stack); } /** @@ -919,7 +889,7 @@ default MCDataOutput writeFluidStack(FluidStack stack) { * @return The same stream. */ default MCDataOutput writeTextComponent(Component component) { - return writeString(Component.Serializer.toJson(component), 262144);//32kb + return writeWithRegistryCodec(ComponentSerialization.STREAM_CODEC, component); } /** @@ -931,9 +901,8 @@ default MCDataOutput writeTextComponent(Component component) { * @param entry The object to write to the stream. * @return The same stream. */ - default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, T entry) { - ForgeRegistry r = unsafeCast(Objects.requireNonNull(registry)); - writeVarInt(r.getID(entry)); + default MCDataOutput writeRegistryIdDirect(Registry registry, T entry) { + writeVarInt(registry.getId(entry)); return this; } @@ -946,9 +915,8 @@ default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, T ent * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, ResourceLocation entry) { - ForgeRegistry r = unsafeCast(Objects.requireNonNull(registry)); - writeVarInt(r.getID(entry)); + default MCDataOutput writeRegistryIdDirect(Registry registry, Identifier entry) { + writeVarInt(registry.getId(entry)); return this; } @@ -960,14 +928,14 @@ default MCDataOutput writeRegistryIdDirect(IForgeRegistry registry, Resou * @param entry The object to write to the stream. * @return The same stream. */ - default MCDataOutput writeRegistryId(IForgeRegistry registry, T entry) { - ResourceLocation rName = registry.getRegistryName(); + default MCDataOutput writeRegistryId(Registry registry, T entry) { + Identifier rName = registry.key().identifier(); if (!registry.containsValue(entry)) { - throw new IllegalArgumentException(format("Registry '{0}' does not contain entry '{1}'", rName, entry)); + throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } writeResourceLocation(rName); writeRegistryIdDirect(registry, entry); - return null; + return this; } /** @@ -978,14 +946,22 @@ default MCDataOutput writeRegistryId(IForgeRegistry registry, T entry) { * @param entry The name of the registry object to write. * @return The same stream. */ - default MCDataOutput writeRegistryId(IForgeRegistry registry, ResourceLocation entry) { - ResourceLocation rName = registry.getRegistryName(); + default MCDataOutput writeRegistryId(Registry registry, Identifier entry) { + Identifier rName = registry.key().identifier(); if (!registry.containsKey(entry)) { - throw new IllegalArgumentException(format("Registry '{0}' does not contain entry '{1}'", rName, entry)); + throw new IllegalArgumentException(String.format("Registry '%s' does not contain entry '%s'", rName, entry)); } writeResourceLocation(rName); writeRegistryIdDirect(registry, entry); - return null; + return this; + } + + default MCDataOutput writeWithCodec(StreamEncoder codec, T thing) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); + } + + default MCDataOutput writeWithRegistryCodec(StreamEncoder codec, T thing) { + throw new RuntimeException("Only able to use StreamCodec's with PacketCustom instances."); } //endregion diff --git a/src/main/java/codechicken/lib/data/MCDataOutputStream.java b/src/main/java/codechicken/lib/data/MCDataOutputStream.java index 92a65f98..589d4b72 100644 --- a/src/main/java/codechicken/lib/data/MCDataOutputStream.java +++ b/src/main/java/codechicken/lib/data/MCDataOutputStream.java @@ -14,6 +14,7 @@ *

* Created by covers1624 on 4/15/20. */ +@Deprecated (forRemoval = true) public class MCDataOutputStream implements MCDataOutput { private final DataOutput out; diff --git a/src/main/java/codechicken/lib/data/package-info.java b/src/main/java/codechicken/lib/data/package-info.java new file mode 100644 index 00000000..107cbc61 --- /dev/null +++ b/src/main/java/codechicken/lib/data/package-info.java @@ -0,0 +1,5 @@ +@NonNullApi +@Deprecated (forRemoval = true) +package codechicken.lib.data; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java b/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java deleted file mode 100644 index bc39fc94..00000000 --- a/src/main/java/codechicken/lib/datagen/ConditionalIngredient.java +++ /dev/null @@ -1,137 +0,0 @@ -package codechicken.lib.datagen; - -import codechicken.lib.datagen.recipe.ConditionBuilder; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.covers1624.quack.util.CrashLock; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.crafting.AbstractIngredient; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.IIngredientSerializer; -import net.minecraftforge.common.crafting.conditions.ICondition; -import net.minecraftforge.event.AddReloadListenerEvent; -import org.jetbrains.annotations.Nullable; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.Function; - -import static codechicken.lib.CodeChickenLib.MOD_ID; - -/** - * Created by covers1624 on 24/9/22. - */ -public class ConditionalIngredient extends AbstractIngredient { - - private static final ResourceLocation TYPE = new ResourceLocation(MOD_ID, "conditional"); - - private final List conditions; - private final Ingredient pass; - @Nullable - private final Ingredient fail; - - private ConditionalIngredient(List conditions, Ingredient pass, @Nullable Ingredient fail) { - this.conditions = conditions; - this.pass = pass; - this.fail = fail; - } - - public static ConditionalIngredient.Builder builder() { - return new ConditionalIngredient.Builder(); - } - - @Override - public JsonElement toJson() { - JsonObject obj = new JsonObject(); - obj.addProperty("type", TYPE.toString()); - JsonArray conditions = new JsonArray(); - for (ICondition condition : this.conditions) { - conditions.add(CraftingHelper.serialize(condition)); - } - obj.add("conditions", conditions); - obj.add("pass", pass.toJson()); - if (fail != null) { - obj.add("fail", fail.toJson()); - } - return obj; - } - - // @formatter:off - @Override public ItemStack[] getItems() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - @Override public boolean isSimple() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - @Override public IIngredientSerializer getSerializer() { throw new UnsupportedOperationException("Exists for DataGeneration only."); } - // @formatter:on - - public static class Builder { - - private List conditions = new LinkedList<>(); - private Ingredient pass = null; - private Ingredient fail = null; - - private Builder() { - } - - public Builder withCondition(Function func) { - conditions.add(func.apply(ConditionBuilder.INSTANCE)); - return this; - } - - public Builder withPass(Ingredient ing) { - if (pass != null) throw new IllegalStateException("Pass Ingredient already specified."); - this.pass = ing; - return this; - } - - public Builder withFail(Ingredient ing) { - if (fail != null) throw new IllegalStateException("Pass Ingredient already specified."); - this.fail = ing; - return this; - } - - public ConditionalIngredient build() { - if (conditions.isEmpty()) throw new IllegalStateException("No conditions specified."); - if (pass == null) throw new IllegalStateException("Pass Ingredient is required."); - - return new ConditionalIngredient(conditions, pass, fail); - } - } - - public static class Serializer implements IIngredientSerializer { - - private static final CrashLock LOCK = new CrashLock("Already Initialized"); - private static ICondition.IContext conditionContext = ICondition.IContext.EMPTY; - - public static void init() { - LOCK.lock(); - MinecraftForge.EVENT_BUS.addListener(Serializer::onAddReloadListenerEvent); - CraftingHelper.register(TYPE, new Serializer()); - } - - private static void onAddReloadListenerEvent(AddReloadListenerEvent event) { - conditionContext = event.getConditionContext(); - } - - @Override - public Ingredient parse(JsonObject json) { - if (!CraftingHelper.processConditions(json, "conditions", conditionContext)) { - if (json.has("fail")) { - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "fail")); - } - return Ingredient.EMPTY; - } - return CraftingHelper.getIngredient(GsonHelper.getAsJsonObject(json, "pass")); - } - - // We don't operate like this, we always return a different ingredient. - // @formatter:off - @Override public Ingredient parse(FriendlyByteBuf buffer) { throw new UnsupportedOperationException(); } - @Override public void write(FriendlyByteBuf buffer, Ingredient ingredient) { throw new UnsupportedOperationException(); } - // @formatter:on - } -} diff --git a/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java new file mode 100644 index 00000000..fba42eb1 --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/DynamicTextureProvider.java @@ -0,0 +1,188 @@ +package codechicken.lib.datagen; + +import codechicken.lib.gui.modular.lib.DynamicTextures; +import com.google.common.hash.Hashing; +import com.google.common.hash.HashingOutputStream; +import net.minecraft.util.Util; +import net.minecraft.data.CachedOutput; +import net.minecraft.data.DataGenerator; +import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.Resource; +import net.minecraft.server.packs.resources.ResourceManager; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** + * This provider can be used to create a data generator that can generate various textures programmatically. + * The primary function is to convert dynamically resized textures into new fixed size textures. + *

+ * Created by brandon3055 on 07/09/2023 + */ +public class DynamicTextureProvider implements DataProvider { + + private final DataGenerator gen; + private final ResourceManager resourceManager; + private final String modid; + private final List results = new ArrayList<>(); + + public DynamicTextureProvider(DataGenerator gen, ResourceManager resourceManager, String modid) { + this.gen = gen; + this.resourceManager = resourceManager; + this.modid = modid; + } + + /** + * If you are extending this provider, then override this method to add your textures. + */ + public void addTextures() { + } + + public void addDynamicTextures(DynamicTextures dynamicTextures) { + dynamicTextures.makeTextures(t -> { + addDynamicTexture(t.dynamicInput(), t.outputLocation(), t.width(), t.height(), t.topBorder(), t.leftBorder(), t.bottomBorder(), t.rightBorder()); + return t.guiTexturePath(); + }); + } + + public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int border) { + addDynamicTexture(dynamicInput, outputTexture, width, height, border, border, border, border); + } + + public void addDynamicTexture(String dynamicInput, String outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + addDynamicTexture(Identifier.fromNamespaceAndPath(modid, dynamicInput), Identifier.fromNamespaceAndPath(modid, outputTexture), width, height, topBorder, leftBorder, bottomBorder, rightBorder); + } + + public void addDynamicTexture(Identifier dynamicInput, Identifier outputTexture, int width, int height, int border) { + addDynamicTexture(dynamicInput, outputTexture, width, height, border, border, border, border); + } + + public void addDynamicTexture(Identifier dynamicInput, Identifier outputTexture, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + try { + if (!dynamicInput.getPath().endsWith(".png")) { + dynamicInput = Identifier.fromNamespaceAndPath(dynamicInput.getNamespace(), dynamicInput.getPath() + ".png"); + } + if (!outputTexture.getPath().endsWith(".png")) { + outputTexture = Identifier.fromNamespaceAndPath(outputTexture.getNamespace(), outputTexture.getPath() + ".png"); + } + + Resource inputResource = resourceManager.getResource(dynamicInput).orElse(null); + if (inputResource == null) throw new RuntimeException("Dynamic input " + dynamicInput + " does not exist."); + + PackOutput packOutput = gen.getPackOutput("assets/" + outputTexture.getNamespace()); + Path outputFile = packOutput.getOutputFolder().resolve(outputTexture.getPath()); + + BufferedImage input = ImageIO.read(inputResource.open()); + BufferedImage output = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); + Graphics2D graphics = output.createGraphics(); + + int texWidth = input.getWidth(); + int texHeight = input.getHeight(); + int trimWidth = texWidth - leftBorder - rightBorder; + int trimHeight = texHeight - topBorder - bottomBorder; + if (width <= texWidth) trimWidth = Math.min(trimWidth, width - rightBorder); + if (width <= 0 || height <= 0 || trimWidth <= 0 || trimHeight <= 0) throw new IllegalArgumentException("Invalid size parameters"); + + for (int x = 0; x < width; ) { + int rWidth = Math.min(width - x, trimWidth); + int trimU = 0; + if (x != 0) { + if (x + leftBorder + trimWidth <= width) { + trimU = leftBorder; + } else { + trimU = (texWidth - (width - x)); + } + } + + //Top & Bottom trim + bufferDynamic(graphics, input, x, 0, trimU, 0, rWidth, topBorder); + bufferDynamic(graphics, input, x, height - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder); + + rWidth = Math.min(width - x - leftBorder - rightBorder, trimWidth); + for (int y = 0; y < height; ) { + int rHeight = Math.min(height - y - topBorder - bottomBorder, trimHeight); + int trimV; + if (y + (texHeight - topBorder - bottomBorder) <= height) { + trimV = topBorder; + } else { + trimV = texHeight - (height - y); + } + + //Left & Right trim + if (x == 0 && y + topBorder < height - bottomBorder) { + bufferDynamic(graphics, input, 0, y + topBorder, 0, trimV, leftBorder, rHeight); + bufferDynamic(graphics, input, width - rightBorder, y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight); + } + + //Core + if (y + topBorder < height - bottomBorder && x + leftBorder < width - rightBorder) { + bufferDynamic(graphics, input, x + leftBorder, y + topBorder, leftBorder, topBorder, rWidth, rHeight); + } + y += trimHeight; + } + x += trimWidth; + } + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ImageIO.write(output, "png", bos); + results.add(new GeneratorResult(bos.toByteArray(), outputFile)); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private void bufferDynamic(Graphics2D graphics, BufferedImage image, int x, int y, int textureX, int textureY, int width, int height) { + graphics.drawImage(image, x, y, x + width, y + height, textureX, textureY, textureX + width, textureY + height, null); + } + + @Override + public CompletableFuture run(CachedOutput writer) { + addTextures(); + CompletableFuture[] futures = new CompletableFuture[results.size()]; + for (int i = 0; i < results.size(); i++) { + futures[i] = saveResult(writer, results.get(i)); + } + return CompletableFuture.allOf(futures); + } + + @SuppressWarnings ("UnstableApiUsage") + static CompletableFuture saveResult(CachedOutput arg, GeneratorResult result) { + return CompletableFuture.runAsync(() -> { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + HashingOutputStream hos = new HashingOutputStream(Hashing.sha1(), bos); + hos.write(result.fileBytes); + arg.writeIfNeeded(result.path, bos.toByteArray(), hos.hash()); + LOGGER.info("Saved file to {}", result.path); + } catch (IOException ex) { + LOGGER.error("Failed to save file to {}", result.path, ex); + } + + }, Util.backgroundExecutor()); + } + + @Override + public String getName() { + return "dynamic-textures:" + modid; + } + + private static class GeneratorResult { + + private final byte[] fileBytes; + private final Path path; + + private GeneratorResult(byte[] fileBytes, Path filePath) { + this.fileBytes = fileBytes; + this.path = filePath; + } + } +} diff --git a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java b/src/main/java/codechicken/lib/datagen/ItemModelProvider.java deleted file mode 100644 index 60355fa9..00000000 --- a/src/main/java/codechicken/lib/datagen/ItemModelProvider.java +++ /dev/null @@ -1,324 +0,0 @@ -package codechicken.lib.datagen; - -import com.google.gson.JsonObject; -import net.minecraft.data.DataGenerator; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraftforge.client.model.generators.ItemModelBuilder; -import net.minecraftforge.client.model.generators.ModelFile; -import net.minecraftforge.client.model.generators.ModelProvider; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Created by covers1624 on 15/10/20. - */ -public abstract class ItemModelProvider extends ModelProvider { - - private static final Logger LOGGER = LogManager.getLogger(); - - protected static final ModelFile.UncheckedModelFile GENERATED = new ModelFile.UncheckedModelFile("item/generated"); - protected static final ModelFile.UncheckedModelFile HANDHELD = new ModelFile.UncheckedModelFile("item/handheld"); - - public ItemModelProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) { - super(generator, modid, ITEM_FOLDER, WrappedItemModelBuilder::new, existingFileHelper); - } - - //region Location helpers - protected String name(ItemLike item) { - return ForgeRegistries.ITEMS.getKey(item.asItem()).getPath(); - } - - protected ResourceLocation itemTexture(ItemLike item) { - return itemTexture(item, ""); - } - - protected ResourceLocation itemTexture(Supplier item) { - return itemTexture(item, ""); - } - - protected ResourceLocation itemTexture(ItemLike item, String folder) { - String f = ""; - if (!StringUtils.isEmpty(folder)) { - f = StringUtils.appendIfMissing(folder, "/"); - } - return modLoc("item/" + f + name(item)); - } - - protected ResourceLocation itemTexture(Supplier item, String folder) { - return itemTexture(item.get(), folder); - } - - protected ResourceLocation blockTexture(Block block) { - return blockTexture(block, ""); - } - - protected ResourceLocation blockTexture(Supplier block) { - return blockTexture(block, ""); - } - - protected ResourceLocation blockTexture(Block block, String folder) { - String f = ""; - if (!StringUtils.isEmpty(folder)) { - f = StringUtils.appendIfMissing(folder, "/"); - } - return modLoc("block/" + f + name(block)); - } - - protected ResourceLocation blockTexture(Supplier block, String folder) { - return blockTexture(block.get(), folder); - } - //endregion - - //region Builder helpers. - protected ItemModelBuilder getBuilder(ItemLike item) { - return getBuilder(name(item)); - } - - protected ItemModelBuilder getBuilder(Supplier item) { - return getBuilder(name(item.get())); - } - //endregion - - //region Simple builder - protected SimpleItemModelBuilder getSimple(ItemLike item) { - WrappedItemModelBuilder builder = (WrappedItemModelBuilder) getBuilder(item); - if (builder.simpleBuilder == null) { - builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); - } - return builder.simpleBuilder; - } - - protected SimpleItemModelBuilder getSimple(ItemLike item, String name) { - WrappedItemModelBuilder builder = (WrappedItemModelBuilder) getBuilder(name); - if (builder.simpleBuilder == null) { - builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem()); - } - return builder.simpleBuilder; - } - - protected SimpleItemModelBuilder getSimple(Supplier item) { - return getSimple(item.get()); - } - - protected SimpleItemModelBuilder generated(ItemLike item) { - return getSimple(item) - .parent(GENERATED); - } - - protected SimpleItemModelBuilder generated(Supplier item) { - return generated(item.get()); - } - - protected SimpleItemModelBuilder handheld(ItemLike item) { - return getSimple(item) - .parent(HANDHELD); - } - - protected SimpleItemModelBuilder handheld(Supplier item) { - return handheld(item.get()); - } - - protected void simpleItemBlock(Block block) { - getSimple(block) - .parent(new ModelFile.UncheckedModelFile(modLoc("block/" + name(block)))) - .noTexture(); - } - //endregion - - private ExistingFileHelper getExistingFileHelper() { - return existingFileHelper; - } - - public static class SimpleItemModelBuilder { - - private final ItemModelProvider provider; - private final ItemModelBuilder builder; - private final Item item; - private final Map layers = new HashMap<>(); - private ModelFile parent; - private boolean noTexture = false; - private String folder = ""; - - @Nullable - private CustomLoaderBuilder loader; - - private boolean built = false; - - private SimpleItemModelBuilder(ItemModelProvider provider, ItemModelBuilder builder, Item item) { - this.provider = provider; - this.builder = builder; - this.item = item; - } - - public SimpleItemModelBuilder parent(ModelFile parent) { - this.parent = Objects.requireNonNull(parent); - return this; - } - - public SimpleItemModelBuilder texture(ResourceLocation texture) { - if (texture == null) throw new IllegalStateException("Use '.noTexture()' instead of '.texture(null)'"); - return texture("layer0", texture); - } - - public SimpleItemModelBuilder texture(String layer, ResourceLocation texture) { - if (noTexture) throw new IllegalStateException("Unable to set texture. NoTexture set."); - if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Adding texture would ignore existing folder."); - - ResourceLocation existing = layers.put(layer, Objects.requireNonNull(texture)); - if (existing != null) { - LOGGER.warn("Overwriting layer '{}' texture '{}' with '{}'", layer, existing, texture); - } - return this; - } - - public SimpleItemModelBuilder folder(String folder) { - if (!layers.isEmpty()) throw new IllegalStateException("Textures set, folder would be ignored."); - if (noTexture) throw new IllegalStateException("No Texture set, folder would be ignored."); - - this.folder = Objects.requireNonNull(folder); - return this; - } - - public SimpleItemModelBuilder noTexture() { - if (!layers.isEmpty()) throw new IllegalStateException("Setting No Texture would ignore textures."); - if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Setting No Texture would ignore existing folder."); - this.noTexture = true; - return this; - } - - public SimpleItemModelBuilder override(Consumer cons) { - ItemModelBuilder.OverrideBuilder forgeBuilder = builder.override(); - OverrideBuilder builder = new OverrideBuilder(this, forgeBuilder); - cons.accept(builder); - return this; - } - - public L customLoader(Function factory) { - if (loader != null) throw new IllegalStateException("Loader already set!"); - - L loader = factory.apply(this); - this.loader = loader; - return loader; - } - - public ModelFile getModel() { - return builder; - } - - private void build() { - if (!built) { - builder.parent(parent); - if (!noTexture) { - if (layers.isEmpty()) { - builder.texture("layer0", provider.itemTexture(item, folder)); - } else { - layers.forEach(builder::texture); - } - } - if (loader != null) { - loader.build(builder); - } - built = true; - } - } - } - - private static class WrappedItemModelBuilder extends ItemModelBuilder { - - private SimpleItemModelBuilder simpleBuilder; - - public WrappedItemModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper) { - super(outputLocation, existingFileHelper); - } - - @Override - public JsonObject toJson() { - if (simpleBuilder != null) { - simpleBuilder.build(); - if (simpleBuilder.loader != null) { - return simpleBuilder.loader.toJson(super.toJson()); - } - } - return super.toJson(); - } - } - - public static class OverrideBuilder { - - private final SimpleItemModelBuilder parent; - private final ItemModelBuilder.OverrideBuilder forgeBuilder; - - public OverrideBuilder(SimpleItemModelBuilder parent, ItemModelBuilder.OverrideBuilder forgeBuilder) { - this.parent = parent; - this.forgeBuilder = forgeBuilder; - } - - public OverrideBuilder model(String name, Consumer cons) { - SimpleItemModelBuilder model = parent.provider.getSimple(parent.item, name); - forgeBuilder.model(model.getModel()); - cons.accept(model); - return this; - } - - public OverrideBuilder predicate(ResourceLocation key, float value) { - forgeBuilder.predicate(key, value); - return this; - } - } - - public static class CustomLoaderBuilder { - - protected final ResourceLocation loaderId; - protected final SimpleItemModelBuilder parent; - protected final ExistingFileHelper existingFileHelper; - protected final Map visibility = new LinkedHashMap<>(); - - protected CustomLoaderBuilder(ResourceLocation loaderId, SimpleItemModelBuilder parent) { - this.loaderId = loaderId; - this.parent = parent; - existingFileHelper = parent.provider.getExistingFileHelper(); - } - - public CustomLoaderBuilder visibility(String partName, boolean show) { - this.visibility.put(partName, show); - return this; - } - - public SimpleItemModelBuilder end() { - return parent; - } - - protected void build(ItemModelBuilder builder) { - } - - protected JsonObject toJson(JsonObject json) { - json.addProperty("loader", loaderId.toString()); - - if (!visibility.isEmpty()) { - JsonObject visibilityObj = new JsonObject(); - - for (Map.Entry entry : visibility.entrySet()) { - visibilityObj.addProperty(entry.getKey(), entry.getValue()); - } - json.add("visibility", visibilityObj); - } - - return json; - } - } -} diff --git a/src/main/java/codechicken/lib/datagen/LanguageProvider.java b/src/main/java/codechicken/lib/datagen/LanguageProvider.java index 82663f96..7cb2855a 100644 --- a/src/main/java/codechicken/lib/datagen/LanguageProvider.java +++ b/src/main/java/codechicken/lib/datagen/LanguageProvider.java @@ -3,20 +3,21 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; +import net.minecraft.data.PackOutput; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.Enchantment; +import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.data.event.GatherDataEvent; -import java.io.IOException; import java.nio.file.Path; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; /** @@ -27,29 +28,29 @@ public abstract class LanguageProvider implements DataProvider { private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().disableHtmlEscaping().create(); private final Map client = new TreeMap<>(); private final Map server = new TreeMap<>(); - private final DataGenerator gen; + private final PackOutput output; private final String modid; private final String locale; - private final Side distFilter; - protected LanguageProvider(DataGenerator gen, String modid, String locale, Side distFilter) { - this.gen = gen; + protected LanguageProvider(PackOutput output, String modid, String locale) { + this.output = output; this.modid = modid; this.locale = locale; - this.distFilter = distFilter; } protected abstract void addTranslations(); @Override - public void run(CachedOutput p_200398_1_) throws IOException { + public CompletableFuture run(CachedOutput output) { addTranslations(); - if (distFilter.includeClient() && !client.isEmpty()) { - save(p_200398_1_, client, gen.getOutputFolder().resolve("assets/" + modid + "/lang/" + locale + ".json")); + List> futures = new LinkedList<>(); + if (!client.isEmpty()) { + futures.add(DataProvider.saveStable(output, GSON.toJsonTree(client), this.output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(modid + "/lang/" + locale + ".json"))); } - if (distFilter.includeServer() && !server.isEmpty()) { - save(p_200398_1_, server, gen.getOutputFolder().resolve("data/" + modid + "/lang/" + locale + ".json")); + if (!server.isEmpty()) { + futures.add(DataProvider.saveStable(output, GSON.toJsonTree(server), this.output.getOutputFolder(PackOutput.Target.DATA_PACK).resolve(modid + "/lang/" + locale + ".json"))); } + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } @Override @@ -61,21 +62,20 @@ public String getLocale() { return locale; } - private void save(CachedOutput cache, Object object, Path target) throws IOException { + private void save(CachedOutput cache, Object object, Path target) { DataProvider.saveStable(cache, GSON.toJsonTree(object), target); } //@formatter:off public void add(Block key, String name) { add(key.getDescriptionId(), name); } public void add(Item key, String name) { add(key.getDescriptionId(), name); } - public void add(ItemStack key, String name) { add(key.getDescriptionId(), name); } - public void add(Enchantment key, String name) { add(key.getDescriptionId(), name); } + public void add(Supplier key, String name) { add(key.get().asItem(), name); } + public void add(ItemStack key, String name) { add(key.getItem(), name); } public void add(MobEffect key, String name) { add(key.getDescriptionId(), name); } public void add(EntityType key, String name) { add(key.getDescriptionId(), name); } public void addBlock(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addItem(Supplier key, String name) { add(key.get().getDescriptionId(), name); } - public void addItemStack(Supplier key, String name) { add(key.get().getDescriptionId(), name); } - public void addEnchantment(Supplier key, String name) { add(key.get().getDescriptionId(), name); } + public void addItemStack(Supplier key, String name) { add(key.get(), name); } public void addEffect(Supplier key, String name) { add(key.get().getDescriptionId(), name); } public void addEntityType(Supplier> key, String name) { add(key.get().getDescriptionId(), name); } //@formatter:on @@ -92,26 +92,4 @@ public void addServer(String key, String name) { throw new IllegalArgumentException("Duplicate translation key :" + key); } } - - public static Side getDist(GatherDataEvent event) { - if (event.includeServer() && event.includeClient()) return Side.BOTH; - if (event.includeServer()) return Side.SERVER; - if (event.includeClient()) return Side.CLIENT; - return Side.NONE; - } - - public enum Side { - CLIENT, - SERVER, - BOTH, - NONE; - - public boolean includeClient() { - return this == CLIENT || this == BOTH; - } - - public boolean includeServer() { - return this == SERVER || this == BOTH; - } - } } diff --git a/src/main/java/codechicken/lib/datagen/LootTableProvider.java b/src/main/java/codechicken/lib/datagen/LootTableProvider.java deleted file mode 100644 index 7f58840c..00000000 --- a/src/main/java/codechicken/lib/datagen/LootTableProvider.java +++ /dev/null @@ -1,167 +0,0 @@ -package codechicken.lib.datagen; - -import com.google.common.collect.Multimap; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import net.minecraft.advancements.critereon.EnchantmentPredicate; -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.advancements.critereon.MinMaxBounds; -import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; -import net.minecraft.data.DataProvider; -import net.minecraft.data.HashCache; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.storage.loot.LootPool; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.LootTables; -import net.minecraft.world.level.storage.loot.ValidationContext; -import net.minecraft.world.level.storage.loot.entries.LootItem; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraft.world.level.storage.loot.functions.ApplyBonusCount; -import net.minecraft.world.level.storage.loot.functions.SetItemCountFunction; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; -import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.predicates.MatchTool; -import net.minecraft.world.level.storage.loot.providers.number.ConstantValue; -import net.minecraft.world.level.storage.loot.providers.number.UniformGenerator; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; - -/** - * Created by covers1624 on 7/10/20. - */ -public abstract class LootTableProvider implements DataProvider { - - private static final Logger logger = LogManager.getLogger(); - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - - private final DataGenerator dataGenerator; - private final Map tables = new HashMap<>(); - - protected LootTableProvider(DataGenerator dataGenerator) { - this.dataGenerator = dataGenerator; - } - - @Override - public void run(CachedOutput cache) { - tables.clear(); - Path out = dataGenerator.getOutputFolder(); - - registerTables(); - - ValidationContext validator = new ValidationContext(LootContextParamSets.ALL_PARAMS, e -> null, tables::get); - - tables.forEach((name, table) -> { - LootTables.validate(validator, name, table); - }); - - Multimap problems = validator.getProblems(); - if (!problems.isEmpty()) { - logger.warn("Problems detected for LootTableGenerator: " + getName()); - problems.forEach((name, table) -> { - logger.warn("Found validation problem in {}: {}", name, table); - }); - throw new IllegalStateException("Failed to validate loot tables, see logs."); - } - tables.forEach((name, table) -> { - Path output = getPath(out, name); - try { - DataProvider.saveStable(cache, LootTables.serialize(table), output); - } catch (IOException e) { - logger.error("Couldn't save loot table {}", output, e); - } - }); - } - - protected abstract void registerTables(); - - protected void registerTable(ResourceLocation name, LootTable table) { - if (tables.put(name, table) != null) { - throw new IllegalArgumentException("Duplicate loot table registered: " + name); - } - } - - private static Path getPath(Path pathIn, ResourceLocation id) { - return pathIn.resolve("data/" + id.getNamespace() + "/loot_tables/" + id.getPath() + ".json"); - } - - public static abstract class BlockLootProvider extends LootTableProvider { - - protected static final LootItemCondition.Builder SILK_TOUCH = MatchTool.toolMatches(ItemPredicate.Builder.item() - .hasEnchantment(new EnchantmentPredicate(Enchantments.SILK_TOUCH, MinMaxBounds.Ints.atLeast(1))) - ); - protected static final LootItemCondition.Builder NO_SILK_TOUCH = SILK_TOUCH.invert(); - - protected BlockLootProvider(DataGenerator dataGenerator) { - super(dataGenerator); - } - - protected LootPool.Builder singleItem(ItemLike item) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(item)); - } - - protected LootPool.Builder singleItemOr(ItemLike failDrop, LootItemCondition.Builder condition, LootPoolEntryContainer.Builder passDrop) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(failDrop) - .when(condition) - .otherwise(passDrop) - ); - } - - protected LootPool.Builder singleItemOrSilk(ItemLike silk, LootItem.Builder drop) { - return singleItemOr(silk, SILK_TOUCH, drop); - } - - protected LootPool.Builder singleItemOrSilk(ItemLike silk, ItemLike drop) { - return singleItemOrSilk(silk, LootItem.lootTableItem(drop)); - } - - protected LootPool.Builder valueRange(ItemLike item, int min, int max) { - return LootPool.lootPool() - .setRolls(ConstantValue.exactly(1)) - .add(LootItem.lootTableItem(item) - .apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max))) - ); - } - - protected LootPool.Builder valueRangeOrSilk(ItemLike silk, ItemLike drop, int min, int max) { - return singleItemOr(silk, SILK_TOUCH, LootItem.lootTableItem(drop).apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max)))); - } - - protected LootPool.Builder valueRangeOrSilkWithFortune(ItemLike silk, ItemLike drop, int min, int max) { - return singleItemOr(silk, SILK_TOUCH, LootItem.lootTableItem(drop) - .apply(SetItemCountFunction.setCount(UniformGenerator.between(min, max))) - .apply(ApplyBonusCount.addOreBonusCount(Enchantments.BLOCK_FORTUNE)) - ); - } - - protected void register(Block block, LootPool.Builder... pools) { - LootTable.Builder builder = LootTable.lootTable(); - for (LootPool.Builder pool : pools) { - builder.withPool(pool); - } - register(block, builder); - } - - public void register(Block block, LootTable.Builder builder) { - register(ForgeRegistries.BLOCKS.getKey(block), builder); - } - - protected void register(ResourceLocation name, LootTable.Builder builder) { - registerTable(new ResourceLocation(name.getNamespace(), "blocks/" + name.getPath()), builder.setParamSet(LootContextParamSets.BLOCK).build()); - } - } - -} diff --git a/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java new file mode 100644 index 00000000..dc0e7d02 --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/NoValidationBLockLootSubProvider.java @@ -0,0 +1,44 @@ +package codechicken.lib.datagen; + +import net.minecraft.core.HolderLookup; +import net.minecraft.data.loot.BlockLootSubProvider; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.flag.FeatureFlagSet; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.storage.loot.LootTable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.function.BiConsumer; + +/** + * Created by covers1624 on 16/9/24. + */ +public abstract class NoValidationBLockLootSubProvider extends BlockLootSubProvider { + + private final Map, LootTable.Builder> map; + + protected NoValidationBLockLootSubProvider(HolderLookup.Provider registries) { + this(Set.of(), registries); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant, HolderLookup.Provider registries) { + this(explosionResistant, FeatureFlagSet.of(), registries); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, HolderLookup.Provider registries) { + this(explosionResistant, flags, new HashMap<>(), registries); + } + + protected NoValidationBLockLootSubProvider(Set explosionResistant, FeatureFlagSet flags, Map, LootTable.Builder> map, HolderLookup.Provider registries) { + super(explosionResistant, flags, map, registries); + this.map = map; + } + + @Override + public void generate(BiConsumer, LootTable.Builder> cons) { + generate(); + map.forEach(cons); + } +} diff --git a/src/main/java/codechicken/lib/datagen/package-info.java b/src/main/java/codechicken/lib/datagen/package-info.java new file mode 100644 index 00000000..40e9603d --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.datagen; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java index d92c0ecb..fffb276e 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractItemStackRecipeBuilder.java @@ -1,44 +1,20 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderGetter; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraftforge.registries.ForgeRegistries; +import net.minecraft.world.item.crafting.Recipe; /** * Created by covers1624 on 28/12/20. */ public abstract class AbstractItemStackRecipeBuilder> extends AbstractRecipeBuilder { - protected AbstractItemStackRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + protected AbstractItemStackRecipeBuilder(Identifier id, HolderGetter items, ItemStack result) { + super(id, items, result); } @Override - protected ResourceLocation getAdvancementId() { - return new ResourceLocation(id.getNamespace(), "recipes/" + this.result.getItem().getItemCategory().getRecipeFolderName() + "/" + id.getPath()); - } - - @Override - public abstract AbstractItemStackFinishedRecipe _build(); - - public abstract class AbstractItemStackFinishedRecipe extends AbstractFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - JsonObject result = new JsonObject(); - ItemStack resultStack = AbstractItemStackRecipeBuilder.this.result; - result.addProperty("item", ForgeRegistries.ITEMS.getKey(resultStack.getItem()).toString()); - if (resultStack.getCount() > 1) { - result.addProperty("count", resultStack.getCount()); - } - //TODO, caps? - if (resultStack.hasTag()) { - result.addProperty("nbt", resultStack.getTag().toString()); - } - json.add("result", result); - } - } + public abstract Recipe _build(); } diff --git a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java index 27399956..50f9a4b4 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/AbstractRecipeBuilder.java @@ -1,29 +1,22 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import net.minecraft.advancements.Advancement; -import net.minecraft.advancements.AdvancementRewards; -import net.minecraft.advancements.CriterionTriggerInstance; -import net.minecraft.advancements.RequirementsStrategy; -import net.minecraft.advancements.critereon.*; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.advancements.*; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.advancements.criterion.RecipeUnlockedTrigger; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.common.crafting.CraftingHelper; -import net.minecraftforge.common.crafting.conditions.ICondition; -import net.minecraftforge.common.crafting.conditions.IConditionBuilder; -import org.apache.commons.lang3.StringUtils; - -import javax.annotation.Nullable; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.Function; +import net.neoforged.neoforge.common.conditions.ICondition; + +import java.util.*; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; @@ -35,19 +28,21 @@ public abstract class AbstractRecipeBuilder conditions = new LinkedList<>(); - protected final RecipeSerializer serializer; - protected final ResourceLocation id; + protected final Identifier id; + protected final ResourceKey> key; + protected final HolderGetter items; protected final R result; private final Set criteriaItems = new HashSet<>(); private final Set> criteriaTags = new HashSet<>(); private int criteriaCounter = 0; protected boolean generateCriteria = false; protected boolean enableUnlocking = false; - private String group; + protected String group = ""; - protected AbstractRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, R result) { - this.serializer = serializer; + protected AbstractRecipeBuilder(Identifier id, HolderGetter items, R result) { this.id = id; + key = ResourceKey.create(Registries.RECIPE, id); + this.items = items; this.result = result; } @@ -55,10 +50,8 @@ protected T getThis() { return unsafeCast(this); } - protected abstract ResourceLocation getAdvancementId(); - - public T withCondition(Function f) { - conditions.add(f.apply(ConditionBuilder.INSTANCE)); + public T withCondition(ICondition cond) { + conditions.add(cond); return getThis(); } @@ -78,7 +71,7 @@ public T setGroup(String group) { return getThis(); } - public T addCriterion(String name, CriterionTriggerInstance criterion) { + public T addCriterion(String name, Criterion criterion) { if (!enableUnlocking) { throw new IllegalStateException("Recipe unlocking must be enabled with 'enableUnlocking'"); } @@ -87,29 +80,35 @@ public T addCriterion(String name, CriterionTriggerInstance criterion) { } @Override - public final ResourceLocation getId() { + public final Identifier getId() { return id; } @Override - public final FinishedRecipe build() { + public final ResourceKey> getKey() { + return key; + } + + @Override + public final BuiltRecipe build() { validate(); if (enableUnlocking) { - advancementBuilder.parent(new ResourceLocation("recipes/root")) - .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(id)) - .rewards(AdvancementRewards.Builder.recipe(id)) - .requirements(RequirementsStrategy.OR); + advancementBuilder.parent(Identifier.withDefaultNamespace("recipes/root")) + .addCriterion("has_the_recipe", RecipeUnlockedTrigger.unlocked(getKey())) + .rewards(AdvancementRewards.Builder.recipe(getKey())) + .requirements(AdvancementRequirements.Strategy.OR); } - return _build(); + AdvancementHolder advancement = advancementBuilder.build(id.withPrefix("recipes")); + if (advancement.value().criteria().isEmpty()) { + advancement = null; + } + return new BuiltRecipe(_build(), advancement, conditions); } protected void validate() { - if (enableUnlocking && advancementBuilder.getCriteria().isEmpty()) { - throw new IllegalStateException("No way of obtaining recipe " + id, created); - } } - protected abstract AbstractFinishedRecipe _build(); + protected abstract Recipe _build(); protected void addAutoCriteria(ItemLike item) { if (generateCriteria && criteriaItems.add(item)) { @@ -123,54 +122,21 @@ protected void addAutoCriteria(TagKey tag) { } } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { - return this.hasItem(ItemPredicate.Builder.item().of(itemIn).build()); + protected Criterion hasItem(ItemLike itemIn) { + return this.hasItem(ItemPredicate.Builder.item().of(items, itemIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { - return this.hasItem(ItemPredicate.Builder.item().of(tagIn).build()); + protected Criterion hasItem(TagKey tagIn) { + return this.hasItem(ItemPredicate.Builder.item().of(items, tagIn).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(EntityPredicate.Composite.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); - } - - public abstract class AbstractFinishedRecipe implements FinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - if (!conditions.isEmpty()) { - JsonArray conditionArray = new JsonArray(); - for (ICondition condition : conditions) { - conditionArray.add(CraftingHelper.serialize(condition)); - } - json.add("conditions", conditionArray); - } - if (StringUtils.isNotEmpty(group)) { - json.addProperty("group", group); - } - } - - @Override - public RecipeSerializer getType() { - return serializer; - } - - @Override - public ResourceLocation getId() { - return id; - } - - @Nullable - @Override - public JsonObject serializeAdvancement() { - return enableUnlocking ? advancementBuilder.serializeToJson() : null; - } - - @Nullable - @Override - public ResourceLocation getAdvancementId() { - return AbstractRecipeBuilder.this.getAdvancementId(); - } + protected Criterion hasItem(ItemPredicate... predicates) { + return CriteriaTriggers.INVENTORY_CHANGED.createCriterion( + new InventoryChangeTrigger.TriggerInstance( + Optional.empty(), + InventoryChangeTrigger.TriggerInstance.Slots.ANY, + List.of(predicates) + ) + ); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java deleted file mode 100644 index 2566c47e..00000000 --- a/src/main/java/codechicken/lib/datagen/recipe/ConditionBuilder.java +++ /dev/null @@ -1,11 +0,0 @@ -package codechicken.lib.datagen.recipe; - -import net.minecraftforge.common.crafting.conditions.IConditionBuilder; - -/** - * Created by covers1624 on 23/9/22. - */ -public interface ConditionBuilder extends IConditionBuilder { - - ConditionBuilder INSTANCE = new ConditionBuilder() { }; -} diff --git a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java index b55e9d84..9860554a 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/FurnaceRecipeBuilder.java @@ -1,16 +1,20 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonObject; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +import static java.util.Objects.requireNonNull; /** * Created by covers1624 on 28/12/20. @@ -19,131 +23,200 @@ public class FurnaceRecipeBuilder extends AbstractItemStackRecipeBuilder serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + protected FurnaceRecipeBuilder(Identifier id, HolderGetter items, ItemStack result, Factory factory) { + super(id, items, result); + this.factory = factory; } //region Smelting - public static FurnaceRecipeBuilder smelting(ItemLike result) { - return smelting(result, 1); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result) { + return smelting(items, result, 1); } - public static FurnaceRecipeBuilder smelting(ItemLike result, int count) { - return smelting(new ItemStack(result, count)); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result, int count) { + return smelting(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder smelting(ItemLike result, int count, ResourceLocation id) { - return smelting(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemLike result, int count, Identifier id) { + return smelting(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder smelting(ItemStack result) { - return smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result) { + return smelting(items, result.get(), 1); } - public static FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.SMELTING_RECIPE, id, result) + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result, int count) { + return smelting(items, new ItemStack(result.get(), count)); + } + + public static FurnaceRecipeBuilder smelting(HolderGetter items, Supplier result, int count, Identifier id) { + return smelting(items, new ItemStack(result.get(), count), id); + } + + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemStack result) { + return smelting(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static FurnaceRecipeBuilder smelting(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, SmeltingRecipe::new) .cookingTime(200); } //endregion //region Blasting - public static FurnaceRecipeBuilder blasting(ItemLike result) { - return blasting(result, 1); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result) { + return blasting(items, result, 1); + } + + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result, int count) { + return blasting(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder blasting(ItemLike result, int count) { - return blasting(new ItemStack(result, count)); + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemLike result, int count, Identifier id) { + return blasting(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder blasting(ItemLike result, int count, ResourceLocation id) { - return blasting(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result) { + return blasting(items, result.get(), 1); } - public static FurnaceRecipeBuilder blasting(ItemStack result) { - return blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result, int count) { + return blasting(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.BLASTING_RECIPE, id, result) + public static FurnaceRecipeBuilder blasting(HolderGetter items, Supplier result, int count, Identifier id) { + return blasting(items, new ItemStack(result.get(), count), id); + } + + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemStack result) { + return blasting(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static FurnaceRecipeBuilder blasting(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, BlastingRecipe::new) .cookingTime(100); } //endregion //region Smoking - public static FurnaceRecipeBuilder smoking(ItemLike result) { - return smoking(result, 1); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result) { + return smoking(items, result, 1); + } + + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result, int count) { + return smoking(items, new ItemStack(result, count)); } - public static FurnaceRecipeBuilder smoking(ItemLike result, int count) { - return smoking(new ItemStack(result, count)); + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemLike result, int count, Identifier id) { + return smoking(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceLocation id) { - return smoking(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result) { + return smoking(items, result.get(), 1); } - public static FurnaceRecipeBuilder smoking(ItemStack result) { - return smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result, int count) { + return smoking(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.SMOKING_RECIPE, id, result) + public static FurnaceRecipeBuilder smoking(HolderGetter items, Supplier result, int count, Identifier id) { + return smoking(items, new ItemStack(result.get(), count), id); + } + + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemStack result) { + return smoking(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static FurnaceRecipeBuilder smoking(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, SmokingRecipe::new) .cookingTime(100); } //endregion //region Campfire - public static FurnaceRecipeBuilder campfire(ItemLike result) { - return campfire(result, 1); + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result) { + return campfire(items, result, 1); + } + + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result, int count) { + return campfire(items, new ItemStack(result, count)); + } + + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemLike result, int count, Identifier id) { + return campfire(items, new ItemStack(result, count), id); } - public static FurnaceRecipeBuilder campfire(ItemLike result, int count) { - return campfire(new ItemStack(result, count)); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result) { + return campfire(items, result.get(), 1); } - public static FurnaceRecipeBuilder campfire(ItemLike result, int count, ResourceLocation id) { - return campfire(new ItemStack(result, count), id); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result, int count) { + return campfire(items, new ItemStack(result.get(), count)); } - public static FurnaceRecipeBuilder campfire(ItemStack result) { - return campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder campfire(HolderGetter items, Supplier result, int count, Identifier id) { + return campfire(items, new ItemStack(result.get(), count), id); } - public static FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(RecipeSerializer.CAMPFIRE_COOKING_RECIPE, id, result) + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemStack result) { + return campfire(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static FurnaceRecipeBuilder campfire(HolderGetter items, ItemStack result, Identifier id) { + return new FurnaceRecipeBuilder(id, items, result, CampfireCookingRecipe::new) .cookingTime(600); } //endregion //region Custom - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); + } + + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); + } + + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); + } + + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, Factory factory) { + return custom(items, result.get(), 1, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, int count, Factory factory) { + return custom(items, new ItemStack(result.get(), count), factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static FurnaceRecipeBuilder custom(HolderGetter items, Supplier result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result.get(), count), id, factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static FurnaceRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new FurnaceRecipeBuilder(serializer, id, result); + public static FurnaceRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new FurnaceRecipeBuilder(id, items, result, factory); } //endregion + public FurnaceRecipeBuilder category(CookingBookCategory category) { + this.category = category; + return this; + } + public FurnaceRecipeBuilder ingredient(TagKey tag) { addAutoCriteria(tag); - this.ingredient = Ingredient.of(tag); + this.ingredient = Ingredient.of(items.getOrThrow(tag)); return this; } @@ -153,6 +226,12 @@ public FurnaceRecipeBuilder ingredient(ItemLike item) { return this; } + public FurnaceRecipeBuilder ingredient(Supplier item) { + addAutoCriteria(item.get()); + this.ingredient = Ingredient.of(item.get()); + return this; + } + public FurnaceRecipeBuilder ingredient(Ingredient ingredient) { if (generateCriteria) { logger.warn("Criteria not automatically generated for raw ingredient.", new Throwable("Here, have a stack trace")); @@ -172,18 +251,20 @@ public FurnaceRecipeBuilder cookingTime(int cookingTime) { } @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedFurnaceRecipe(); + public Recipe _build() { + return factory.build(group, category, requireNonNull(ingredient), result, experience, cookingTime); } - public class FinishedFurnaceRecipe extends AbstractItemStackFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - json.add("ingredient", ingredient.toJson()); - json.addProperty("experience", experience); - json.addProperty("cookingtime", cookingTime); + @Override + protected void validate() { + super.validate(); + if (ingredient == null) { + throw new IllegalStateException("No ingredient set."); } } + + public interface Factory { + + Recipe build(String group, CookingBookCategory category, Ingredient ingredient, ItemStack result, float experience, int cookingTime); + } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java index 0c94ef1c..d82b5884 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeBuilder.java @@ -1,22 +1,35 @@ package codechicken.lib.datagen.recipe; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.data.recipes.RecipeOutput; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.crafting.Recipe; +import net.neoforged.neoforge.common.conditions.ICondition; +import org.jetbrains.annotations.Nullable; -import java.util.function.Consumer; +import java.util.List; /** * Created by covers1624 on 27/12/20. */ public interface RecipeBuilder { - ResourceLocation getId(); + Identifier getId(); - FinishedRecipe build(); + ResourceKey> getKey(); - //Compat with vanilla's Recipe Provider. - default void build(Consumer consumer) { - consumer.accept(build()); + BuiltRecipe build(); + + // Compat with vanilla's Recipe Provider. + default void build(RecipeOutput output) { + BuiltRecipe built = build(); + output.accept(getKey(), built.recipe, built.advancement, built.conditions.toArray(ICondition[]::new)); } + record BuiltRecipe( + Recipe recipe, + @Nullable AdvancementHolder advancement, + List conditions + ) { } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java index 143f3e19..835177e8 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java +++ b/src/main/java/codechicken/lib/datagen/recipe/RecipeProvider.java @@ -1,59 +1,84 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import net.minecraft.advancements.critereon.*; +import net.minecraft.advancements.Advancement; +import net.minecraft.advancements.AdvancementHolder; +import net.minecraft.advancements.CriteriaTriggers; +import net.minecraft.advancements.Criterion; +import net.minecraft.advancements.criterion.EnterBlockTrigger; +import net.minecraft.advancements.criterion.InventoryChangeTrigger; +import net.minecraft.advancements.criterion.ItemPredicate; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.data.CachedOutput; -import net.minecraft.data.DataGenerator; import net.minecraft.data.DataProvider; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.data.PackOutput; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleRecipeSerializer; +import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import net.neoforged.neoforge.common.conditions.WithConditions; +import org.jetbrains.annotations.Nullable; -import java.io.IOException; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; /** * Created by covers1624 on 27/12/20. */ public abstract class RecipeProvider implements DataProvider { - private static final Logger logger = LogManager.getLogger(); - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private final Map recipes = new HashMap<>(); + private final CompletableFuture registries; + private final PackOutput.PathProvider recipePath; + private final PackOutput.PathProvider advancementPath; + protected final String modId; - private final Map recipes = new HashMap<>(); - private final DataGenerator generator; + private @Nullable HolderGetter items; - public RecipeProvider(DataGenerator generatorIn) { - this.generator = generatorIn; + public RecipeProvider(PackOutput output, CompletableFuture registries, String modId) { + this.registries = registries; + this.modId = modId; + recipePath = output.createRegistryElementsPathProvider(Registries.RECIPE); + advancementPath = output.createRegistryElementsPathProvider(Registries.ADVANCEMENT); } @Override - public final void run(CachedOutput cache) throws IOException { - Path path = generator.getOutputFolder(); - registerRecipes(); - for (Map.Entry entry : recipes.entrySet()) { - ResourceLocation id = entry.getKey(); - FinishedRecipe finishedRecipe = entry.getValue().build(); - saveRecipe(cache, finishedRecipe.serializeRecipe(), path.resolve("data/" + id.getNamespace() + "/recipes/" + id.getPath() + ".json")); + public final CompletableFuture run(CachedOutput cache) { + return registries.thenCompose(registries -> run(cache, registries)); + } - JsonObject advancement = finishedRecipe.serializeAdvancement(); + private CompletableFuture run(CachedOutput cache, HolderLookup.Provider registries) { + registerRecipes(); + List> futures = new LinkedList<>(); + for (Map.Entry entry : recipes.entrySet()) { + Identifier id = entry.getKey(); + RecipeBuilder.BuiltRecipe builtRecipe = entry.getValue().build(); + futures.add(DataProvider.saveStable( + cache, + registries, + Recipe.CONDITIONAL_CODEC, + Optional.of(new WithConditions<>(builtRecipe.conditions(), builtRecipe.recipe())), + recipePath.json(id) + )); + + AdvancementHolder advancement = builtRecipe.advancement(); if (advancement != null) { - saveRecipeAdvancement(cache, advancement, path.resolve("data/" + id.getNamespace() + "/advancements/" + id.getPath() + ".json")); + futures.add(DataProvider.saveStable( + cache, + registries, + Advancement.CONDITIONAL_CODEC, + Optional.of(new WithConditions<>(builtRecipe.conditions(), advancement.value())), + advancementPath.json(id) + )); } } + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } protected abstract void registerRecipes(); @@ -66,86 +91,132 @@ protected T builder(T builder) { return builder; } - //@formatter:off - protected ShapedRecipeBuilder shapedRecipe(ItemLike result) { return builder(ShapedRecipeBuilder.builder(result, 1)); } - protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count))); } - protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(new ItemStack(result, count), id)); } - protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapedRecipeBuilder shapedRecipe(ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.builder(result, id)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(result, 1)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count))); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(new ItemStack(result, count), id)); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.builder(result, id)); } - protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(result, 1)); } - protected FurnaceRecipeBuilder smelting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder smelting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder smelting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smelting(result, id)); } - protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(result, 1)); } - protected FurnaceRecipeBuilder blasting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder blasting(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder blasting(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.blasting(result, id)); } - protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(result, 1)); } - protected FurnaceRecipeBuilder smoking(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder smoking(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder smoking(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.smoking(result, id)); } - protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(result, 1)); } - protected FurnaceRecipeBuilder campfire(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count))); } - protected FurnaceRecipeBuilder campfire(ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder campfire(ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.campfire(result, id)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result) { return builder(ShapedRecipeBuilder.custom(serializer, result, 1)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result) { return builder(ShapedRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapedRecipeBuilder customShaped(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapedRecipeBuilder.custom(serializer, result, id)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, 1)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result) { return builder(ShapelessRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected ShapelessRecipeBuilder customShapeless(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(ShapelessRecipeBuilder.custom(serializer, result, id)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, 1)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count))); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, new ItemStack(result, count), id)); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result) { return builder(FurnaceRecipeBuilder.custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem()))); } - protected FurnaceRecipeBuilder customFurnace(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { return builder(FurnaceRecipeBuilder.custom(serializer, result, id)); } - protected SpecialRecipeBuilder special(SimpleRecipeSerializer serializer, String id) { return builder(SpecialRecipeBuilder.builder(serializer, id)); } - protected SpecialRecipeBuilder special(SimpleRecipeSerializer serializer, ResourceLocation id) { return builder(SpecialRecipeBuilder.builder(serializer, id)); } - //@formatter:on + protected HolderGetter items() { + if (items == null) { + if (!registries.isDone()) throw new RuntimeException("Only available inside registerRecipes() callback."); - private void saveRecipe(CachedOutput cache, JsonObject recipeJson, Path path) { - try { - DataProvider.saveStable(cache, recipeJson, path); - } catch (IOException e) { - logger.error("Couldn't save recipe {}", path, e); + items = registries.join().lookupOrThrow(Registries.ITEM); } + return items; + } + //@formatter:off + protected ShapedRecipeBuilder shapedRecipe(ItemLike result) { return builder(ShapedRecipeBuilder.builder(items(), result, 1)); } + protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result, count))); } + protected ShapedRecipeBuilder shapedRecipe(ItemLike result, int count, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result, count), id)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result) { return builder(ShapedRecipeBuilder.builder(items(), result.get(), 1)); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result.get(), count))); } + protected ShapedRecipeBuilder shapedRecipe(Supplier result, int count, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), new ItemStack(result.get(), count), id)); } + protected ShapedRecipeBuilder shapedRecipe(ItemStack result) { return builder(ShapedRecipeBuilder.builder(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected ShapedRecipeBuilder shapedRecipe(ItemStack result, Identifier id) { return builder(ShapedRecipeBuilder.builder(items(), result, id)); } + + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result) { return builder(ShapelessRecipeBuilder.builder(items(), result, 1)); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result, count))); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemLike result, int count, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result, count), id)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result) { return builder(ShapelessRecipeBuilder.builder(items(), result.get(), 1)); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result.get(), count))); } + protected ShapelessRecipeBuilder shapelessRecipe(Supplier result, int count, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), new ItemStack(result.get(), count), id)); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result) { return builder(ShapelessRecipeBuilder.builder(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected ShapelessRecipeBuilder shapelessRecipe(ItemStack result, Identifier id) { return builder(ShapelessRecipeBuilder.builder(items(), result, id)); } + + protected FurnaceRecipeBuilder smelting(ItemLike result) { return builder(FurnaceRecipeBuilder.smelting(items(), result, 1)); } + protected FurnaceRecipeBuilder smelting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder smelting(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smelting(Supplier result) { return builder(FurnaceRecipeBuilder.smelting(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smelting(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder smelting(ItemStack result) { return builder(FurnaceRecipeBuilder.smelting(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smelting(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.smelting(items(), result, id)); } + + protected FurnaceRecipeBuilder blasting(ItemLike result) { return builder(FurnaceRecipeBuilder.blasting(items(), result, 1)); } + protected FurnaceRecipeBuilder blasting(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder blasting(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder blasting(Supplier result) { return builder(FurnaceRecipeBuilder.blasting(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder blasting(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder blasting(ItemStack result) { return builder(FurnaceRecipeBuilder.blasting(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder blasting(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.blasting(items(), result, id)); } + + protected FurnaceRecipeBuilder smoking(ItemLike result) { return builder(FurnaceRecipeBuilder.smoking(items(), result, 1)); } + protected FurnaceRecipeBuilder smoking(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder smoking(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder smoking(Supplier result) { return builder(FurnaceRecipeBuilder.smoking(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder smoking(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder smoking(ItemStack result) { return builder(FurnaceRecipeBuilder.smoking(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder smoking(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.smoking(items(), result, id)); } + + protected FurnaceRecipeBuilder campfire(ItemLike result) { return builder(FurnaceRecipeBuilder.campfire(items(), result, 1)); } + protected FurnaceRecipeBuilder campfire(ItemLike result, int count) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result, count))); } + protected FurnaceRecipeBuilder campfire(ItemLike result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result, count), id)); } + protected FurnaceRecipeBuilder campfire(Supplier result) { return builder(FurnaceRecipeBuilder.campfire(items(), result.get(), 1)); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result.get(), count))); } + protected FurnaceRecipeBuilder campfire(Supplier result, int count, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), new ItemStack(result.get(), count), id)); } + protected FurnaceRecipeBuilder campfire(ItemStack result) { return builder(FurnaceRecipeBuilder.campfire(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()))); } + protected FurnaceRecipeBuilder campfire(ItemStack result, Identifier id) { return builder(FurnaceRecipeBuilder.campfire(items(), result, id)); } + + protected ShapedRecipeBuilder customShaped(ItemLike result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, 1, factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected ShapedRecipeBuilder customShaped(ItemLike result, int count, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected ShapedRecipeBuilder customShaped(Supplier result, int count, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapedRecipeBuilder customShaped(ItemStack result, Identifier id, ShapedRecipeBuilder.Factory factory) { return builder(ShapedRecipeBuilder.custom(items(), result, id, factory)); } + + protected ShapelessRecipeBuilder customShapeless(ItemLike result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemLike result, int count, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected ShapelessRecipeBuilder customShapeless(Supplier result, int count, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected ShapelessRecipeBuilder customShapeless(ItemStack result, Identifier id, ShapelessRecipeBuilder.Factory factory) { return builder(ShapelessRecipeBuilder.custom(items(), result, id, factory)); } + + protected FurnaceRecipeBuilder customFurnace(ItemLike result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result, count), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemLike result, int count, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result, count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result.get(), 1, factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result.get(), count), factory)); } + protected FurnaceRecipeBuilder customFurnace(Supplier result, int count, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), new ItemStack(result.get(), count), id, factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory)); } + protected FurnaceRecipeBuilder customFurnace(ItemStack result, Identifier id, FurnaceRecipeBuilder.Factory factory) { return builder(FurnaceRecipeBuilder.custom(items(), result, id, factory)); } + + protected SpecialCraftingRecipeBuilder special(ItemLike id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(Supplier id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id.get(), factory)); } + protected SpecialCraftingRecipeBuilder special(ItemStack id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(String id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + protected SpecialCraftingRecipeBuilder special(Identifier id, SpecialCraftingRecipeBuilder.Factory factory) { return builder(SpecialCraftingRecipeBuilder.builder(id, factory)); } + //@formatter:on + + protected Criterion enteredBlock(Block blockIn) { + return CriteriaTriggers.ENTER_BLOCK.createCriterion(new EnterBlockTrigger.TriggerInstance(Optional.empty(), Optional.of(blockIn.builtInRegistryHolder()), Optional.empty())); } - private void saveRecipeAdvancement(CachedOutput cache, JsonObject advancementJson, Path path) { - try { - DataProvider.saveStable(cache, advancementJson, path); - } catch (IOException e) { - logger.error("Couldn't save recipe advancement {}", path, e); - } + protected Criterion hasItem(ItemLike itemIn) { + return hasItem(ItemPredicate.Builder.item().of(items(), itemIn).build()); } - protected EnterBlockTrigger.TriggerInstance enteredBlock(Block blockIn) { - return new EnterBlockTrigger.TriggerInstance(EntityPredicate.Composite.ANY, blockIn, StatePropertiesPredicate.ANY); + protected Criterion hasItem(Supplier itemIn) { + return hasItem(ItemPredicate.Builder.item().of(items(), itemIn.get()).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemLike itemIn) { - return hasItem(ItemPredicate.Builder.item().of(itemIn).build()); + protected Criterion hasItem(TagKey tag) { + return hasItem(ItemPredicate.Builder.item().of(items(), tag).build()); } - protected InventoryChangeTrigger.TriggerInstance hasItem(TagKey tagIn) { - return hasItem(ItemPredicate.Builder.item().of(tagIn).build()); + protected Criterion hasItem(ItemPredicate... predicates) { + return CriteriaTriggers.INVENTORY_CHANGED.createCriterion( + new InventoryChangeTrigger.TriggerInstance( + Optional.empty(), + InventoryChangeTrigger.TriggerInstance.Slots.ANY, + List.of(predicates) + ) + ); } - protected InventoryChangeTrigger.TriggerInstance hasItem(ItemPredicate... predicates) { - return new InventoryChangeTrigger.TriggerInstance(EntityPredicate.Composite.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, MinMaxBounds.Ints.ANY, predicates); + @Override + public String getName() { + return modId + " Recipes."; } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java index fcdbede1..b3b6e8f0 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapedRecipeBuilder.java @@ -1,24 +1,23 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; import it.unimi.dsi.fastutil.chars.Char2ObjectMap; import it.unimi.dsi.fastutil.chars.Char2ObjectOpenHashMap; import it.unimi.dsi.fastutil.chars.CharOpenHashSet; import it.unimi.dsi.fastutil.chars.CharSet; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.*; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.List; +import java.util.function.Supplier; /** * Created by covers1624 on 28/12/20. @@ -27,58 +26,75 @@ public class ShapedRecipeBuilder extends AbstractItemStackRecipeBuilder patternLines = new ArrayList<>(); private final Char2ObjectMap keys = new Char2ObjectOpenHashMap<>(); - protected ShapedRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + private CraftingBookCategory category = CraftingBookCategory.MISC; + private boolean showNotification = true; + + protected ShapedRecipeBuilder(Identifier id, HolderGetter items, ItemStack result, Factory factory) { + super(id, items, result); + this.factory = factory; + } + + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result) { + return builder(items, result, 1); + } + + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result, int count) { + return builder(items, new ItemStack(result, count)); } - public static ShapedRecipeBuilder builder(ItemLike result) { - return builder(result, 1); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemLike result, int count, Identifier id) { + return builder(items, new ItemStack(result, count), id); } - public static ShapedRecipeBuilder builder(ItemLike result, int count) { - return builder(new ItemStack(result, count)); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result) { + return builder(items, result.get(), 1); } - public static ShapedRecipeBuilder builder(ItemLike result, int count, ResourceLocation id) { - return builder(new ItemStack(result, count), id); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result, int count) { + return builder(items, new ItemStack(result.get(), count)); } - public static ShapedRecipeBuilder builder(ItemStack result) { - return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapedRecipeBuilder builder(HolderGetter items, Supplier result, int count, Identifier id) { + return builder(items, new ItemStack(result.get(), count), id); } - public static ShapedRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapedRecipeBuilder(RecipeSerializer.SHAPED_RECIPE, id, result); + public static ShapedRecipeBuilder builder(HolderGetter items, ItemStack result) { + return builder(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static ShapedRecipeBuilder builder(HolderGetter items, ItemStack result, Identifier id) { + return new ShapedRecipeBuilder(id, items, result, ShapedRecipe::new); } // region Custom - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapedRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new ShapedRecipeBuilder(serializer, id, result); + public static ShapedRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new ShapedRecipeBuilder(id, items, result, factory); } // endregion public ShapedRecipeBuilder key(char key, TagKey item) { addAutoCriteria(item); - return keyInternal(key, Ingredient.of(item)); + return keyInternal(key, Ingredient.of(items.getOrThrow(item))); } public ShapedRecipeBuilder key(char key, ItemLike item) { @@ -86,6 +102,11 @@ public ShapedRecipeBuilder key(char key, ItemLike item) { return keyInternal(key, Ingredient.of(item)); } + public ShapedRecipeBuilder key(char key, Supplier item) { + addAutoCriteria(item.get()); + return keyInternal(key, Ingredient.of(item.get())); + } + public ShapedRecipeBuilder key(char key, Ingredient ingredient) { if (generateCriteria) { logger.warn("Criteria not automatically generated for raw ingredient.", new Throwable("Here, have a stack trace")); @@ -112,9 +133,25 @@ public ShapedRecipeBuilder patternLine(String patternIn) { return this; } + public ShapedRecipeBuilder category(CraftingBookCategory category) { + this.category = category; + return this; + } + + public ShapedRecipeBuilder showNotifications(boolean showNotification) { + this.showNotification = showNotification; + return this; + } + @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedShapedRecipe(); + public Recipe _build() { + return factory.build( + group, + category, + ShapedRecipePattern.of(keys, patternLines), + result, + showNotification + ); } @Override @@ -145,20 +182,8 @@ protected void validate() { } } - public class FinishedShapedRecipe extends AbstractItemStackFinishedRecipe { - - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); - JsonArray pattern = new JsonArray(); - patternLines.forEach(pattern::add); - json.add("pattern", pattern); + public interface Factory { - JsonObject key = new JsonObject(); - for (Char2ObjectMap.Entry entry : keys.char2ObjectEntrySet()) { - key.add(String.valueOf(entry.getCharKey()), entry.getValue().toJson()); - } - json.add("key", key); - } + Recipe build(String group, CraftingBookCategory category, ShapedRecipePattern pattern, ItemStack result, boolean showNotification); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java index 4694124c..e3372477 100644 --- a/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java +++ b/src/main/java/codechicken/lib/datagen/recipe/ShapelessRecipeBuilder.java @@ -1,20 +1,21 @@ package codechicken.lib.datagen.recipe; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.core.HolderGetter; +import net.minecraft.core.NonNullList; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.CraftingBookCategory; import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeSerializer; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.ShapelessRecipe; import net.minecraft.world.level.ItemLike; -import net.minecraftforge.registries.ForgeRegistries; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.util.ArrayList; -import java.util.List; +import java.util.function.Supplier; /** * Created by covers1624 on 28/12/20. @@ -23,51 +24,67 @@ public class ShapelessRecipeBuilder extends AbstractItemStackRecipeBuilder ingredients = new ArrayList<>(); + private final Factory factory; + private final NonNullList ingredients = NonNullList.create(); - protected ShapelessRecipeBuilder(RecipeSerializer serializer, ResourceLocation id, ItemStack result) { - super(serializer, id, result); + private CraftingBookCategory category = CraftingBookCategory.MISC; + + protected ShapelessRecipeBuilder(Identifier id, HolderGetter items, ItemStack result, Factory factory) { + super(id, items, result); + this.factory = factory; + } + + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result) { + return builder(items, result, 1); + } + + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result, int count) { + return builder(items, new ItemStack(result, count)); } - public static ShapelessRecipeBuilder builder(ItemLike result) { - return builder(result, 1); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemLike result, int count, Identifier id) { + return builder(items, new ItemStack(result, count), id); } - public static ShapelessRecipeBuilder builder(ItemLike result, int count) { - return builder(new ItemStack(result, count)); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result) { + return builder(items, result.get(), 1); } - public static ShapelessRecipeBuilder builder(ItemLike result, int count, ResourceLocation id) { - return builder(new ItemStack(result, count), id); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result, int count) { + return builder(items, new ItemStack(result.get(), count)); } - public static ShapelessRecipeBuilder builder(ItemStack result) { - return builder(result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapelessRecipeBuilder builder(HolderGetter items, Supplier result, int count, Identifier id) { + return builder(items, new ItemStack(result.get(), count), id); } - public static ShapelessRecipeBuilder builder(ItemStack result, ResourceLocation id) { - return new ShapelessRecipeBuilder(RecipeSerializer.SHAPELESS_RECIPE, id, result); + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemStack result) { + return builder(items, result, BuiltInRegistries.ITEM.getKey(result.getItem())); + } + + public static ShapelessRecipeBuilder builder(HolderGetter items, ItemStack result, Identifier id) { + return new ShapelessRecipeBuilder(id, items, result, ShapelessRecipe::new); } // region Custom - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result) { - return custom(serializer, result, 1); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, Factory factory) { + return custom(items, result, 1, factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count) { - return custom(serializer, new ItemStack(result, count)); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Factory factory) { + return custom(items, new ItemStack(result, count), factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemLike result, int count, ResourceLocation id) { - return custom(serializer, new ItemStack(result, count), id); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemLike result, int count, Identifier id, Factory factory) { + return custom(items, new ItemStack(result, count), id, factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemStack result) { - return custom(serializer, result, ForgeRegistries.ITEMS.getKey(result.getItem())); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemStack result, Factory factory) { + return custom(items, result, BuiltInRegistries.ITEM.getKey(result.getItem()), factory); } - public static ShapelessRecipeBuilder custom(RecipeSerializer serializer, ItemStack result, ResourceLocation id) { - return new ShapelessRecipeBuilder(serializer, id, result); + public static ShapelessRecipeBuilder custom(HolderGetter items, ItemStack result, Identifier id, Factory factory) { + return new ShapelessRecipeBuilder(id, items, result, factory); } // endregion @@ -77,7 +94,20 @@ public ShapelessRecipeBuilder addIngredient(TagKey tag) { public ShapelessRecipeBuilder addIngredient(TagKey tag, int quantity) { addAutoCriteria(tag); - Ingredient ingredient = Ingredient.of(tag); + Ingredient ingredient = Ingredient.of(items.getOrThrow(tag)); + for (int i = 0; i < quantity; ++i) { + ingredients.add(ingredient); + } + return this; + } + + public ShapelessRecipeBuilder addIngredient(Supplier item) { + return addIngredient(item.get(), 1); + } + + public ShapelessRecipeBuilder addIngredient(Supplier item, int quantity) { + addAutoCriteria(item.get()); + Ingredient ingredient = Ingredient.of(item.get()); for (int i = 0; i < quantity; ++i) { ingredients.add(ingredient); } @@ -112,22 +142,23 @@ public ShapelessRecipeBuilder addIngredient(Ingredient ingredient, int quantity) return this; } - @Override - public AbstractItemStackFinishedRecipe _build() { - return new FinishedShapelessRecipe(); + public ShapelessRecipeBuilder category(CraftingBookCategory category) { + this.category = category; + return this; } - public class FinishedShapelessRecipe extends AbstractItemStackFinishedRecipe { + @Override + public Recipe _build() { + return factory.build( + group, + category, + result, + ingredients + ); + } - @Override - public void serializeRecipeData(JsonObject json) { - super.serializeRecipeData(json); + public interface Factory { - JsonArray ingredients = new JsonArray(); - for (Ingredient ingredient : ShapelessRecipeBuilder.this.ingredients) { - ingredients.add(ingredient.toJson()); - } - json.add("ingredients", ingredients); - } + Recipe build(String group, CraftingBookCategory category, ItemStack result, NonNullList ingredients); } } diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java new file mode 100644 index 00000000..a794772f --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/recipe/SpecialCraftingRecipeBuilder.java @@ -0,0 +1,73 @@ +package codechicken.lib.datagen.recipe; + +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.level.ItemLike; + +import java.util.List; +import java.util.function.Supplier; + +/** + * Created by covers1624 on 25/3/21. + */ +public class SpecialCraftingRecipeBuilder implements RecipeBuilder { + + protected final Identifier id; + protected final ResourceKey> key; + + private final Factory factory; + + public SpecialCraftingRecipeBuilder(Identifier id, Factory factory) { + this.id = id; + this.key = ResourceKey.create(Registries.RECIPE, id); + this.factory = factory; + } + + public static SpecialCraftingRecipeBuilder builder(ItemLike id, Factory factory) { + return builder(BuiltInRegistries.ITEM.getKey(id.asItem()), factory); + } + + public static SpecialCraftingRecipeBuilder builder(Supplier id, Factory factory) { + return builder(id.get(), factory); + } + + public static SpecialCraftingRecipeBuilder builder(ItemStack id, Factory factory) { + return builder(id.getItem(), factory); + } + + public static SpecialCraftingRecipeBuilder builder(String id, Factory factory) { + return builder(Identifier.parse(id), factory); + } + + public static SpecialCraftingRecipeBuilder builder(Identifier id, Factory factory) { + return new SpecialCraftingRecipeBuilder(id, factory); + } + + @Override + public final Identifier getId() { + return id; + } + + @Override + public final ResourceKey> getKey() { + return key; + } + + @Override + public BuiltRecipe build() { + return new BuiltRecipe( + factory.build(), + null, + List.of() + ); + } + + public interface Factory { + + Recipe build(); + } +} diff --git a/src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java b/src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java deleted file mode 100644 index 575836c8..00000000 --- a/src/main/java/codechicken/lib/datagen/recipe/SpecialRecipeBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -package codechicken.lib.datagen.recipe; - -import com.google.gson.JsonObject; -import net.minecraft.data.recipes.FinishedRecipe; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.SimpleRecipeSerializer; - -/** - * Created by covers1624 on 25/3/21. - */ -public class SpecialRecipeBuilder implements RecipeBuilder { - - protected final SimpleRecipeSerializer serializer; - protected final ResourceLocation id; - - public SpecialRecipeBuilder(SimpleRecipeSerializer serializer, ResourceLocation id) { - this.serializer = serializer; - this.id = id; - } - - public static SpecialRecipeBuilder builder(SimpleRecipeSerializer serializer, String id) { - return builder(serializer, new ResourceLocation(id)); - } - - public static SpecialRecipeBuilder builder(SimpleRecipeSerializer serializer, ResourceLocation id) { - return new SpecialRecipeBuilder(serializer, id); - } - - @Override - public ResourceLocation getId() { - return id; - } - - @Override - public FinishedRecipe build() { - return new SpecialFinishedRecipe(); - } - - //@formatter:off - protected class SpecialFinishedRecipe implements FinishedRecipe { - @Override public void serializeRecipeData(JsonObject p_218610_1_) { } - @Override public ResourceLocation getId() { return id; } - @Override public RecipeSerializer getType() { return serializer; } - @Override public JsonObject serializeAdvancement() { return null; } - @Override public ResourceLocation getAdvancementId() { return null; } - } - //@formatter:on -} diff --git a/src/main/java/codechicken/lib/datagen/recipe/package-info.java b/src/main/java/codechicken/lib/datagen/recipe/package-info.java new file mode 100644 index 00000000..e7fc155b --- /dev/null +++ b/src/main/java/codechicken/lib/datagen/recipe/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.datagen.recipe; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/fluid/FluidUtils.java b/src/main/java/codechicken/lib/fluid/FluidUtils.java index e1fef24d..77844424 100644 --- a/src/main/java/codechicken/lib/fluid/FluidUtils.java +++ b/src/main/java/codechicken/lib/fluid/FluidUtils.java @@ -2,8 +2,8 @@ import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.Fluids; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; public class FluidUtils { diff --git a/src/main/java/codechicken/lib/fluid/package-info.java b/src/main/java/codechicken/lib/fluid/package-info.java new file mode 100644 index 00000000..b7b2ffd3 --- /dev/null +++ b/src/main/java/codechicken/lib/fluid/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.fluid; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java b/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java deleted file mode 100644 index 71f2ec13..00000000 --- a/src/main/java/codechicken/lib/gui/SimpleCreativeTab.java +++ /dev/null @@ -1,28 +0,0 @@ -package codechicken.lib.gui; - -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nonnull; -import java.util.function.Supplier; - -/** - * Provides a Simple way to create a {@link CreativeModeTab} - *

- * Created by covers1624 on 7/11/2016. - */ -public class SimpleCreativeTab extends CreativeModeTab { - - private final Supplier stackSupplier; - - public SimpleCreativeTab(String label, Supplier stackSupplier) { - super(label); - this.stackSupplier = stackSupplier; - } - - @Nonnull - @Override - public ItemStack makeIcon() { - return stackSupplier.get(); - } -} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGui.java b/src/main/java/codechicken/lib/gui/modular/ModularGui.java new file mode 100644 index 00000000..8e3d26dc --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGui.java @@ -0,0 +1,575 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.gui.modular.lib.DynamicTextures; +import codechicken.lib.gui.modular.lib.GuiProvider; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.world.inventory.Slot; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +/** + * The modular gui system is built around "Gui Elements" but those elements need to be rendered by a base parent element. That's what this class is. + * This class is essentially just a container for the root gui element. + *

+ * Created by brandon3055 on 18/08/2023 + * + * @see GuiProvider + * @see ContainerGuiProvider + */ +public class ModularGui implements GuiParent { + + private static final Logger LOGGER = LogManager.getLogger(); + + private final GuiProvider provider; + private final GuiElement root; + + private boolean guiBuilt = false; + private boolean pauseScreen = false; + private boolean closeOnEscape = true; + private boolean renderBackground = true; + private boolean vanillaSlotRendering = false; + private boolean floatingItemDisablesToolTips = true; + + private Font font; + private Minecraft mc; + private int screenWidth; + private int screenHeight; + private Screen screen; + private Screen parentScreen; + + private Component guiTitle = Component.empty(); + private Identifier newCursor = null; + + private final Map> slotHandlers = new HashMap<>(); + private final List tickListeners = new ArrayList<>(); + private final List resizeListeners = new ArrayList<>(); + private final List closeListeners = new ArrayList<>(); + private final List> preClickListeners = new ArrayList<>(); + private final List> postClickListeners = new ArrayList<>(); + private final List> preKeyPressListeners = new ArrayList<>(); + private final List> postKeyPressListeners = new ArrayList<>(); + + private int jeiHighlightTime = 0; + + /** + * @param provider The gui builder that will be used to construct this modular gui when the screen is initialized. + */ + public ModularGui(GuiProvider provider) { + this.provider = provider; + if (provider instanceof DynamicTextures textures) textures.makeTextures(DynamicTextures.DynamicTexture::guiTexturePath); + Minecraft mc = Minecraft.getInstance(); + updateScreenData(mc, mc.font, mc.getWindow().getGuiScaledWidth(), mc.getWindow().getGuiScaledHeight()); + try { + this.root = provider.createRootElement(this); + } catch (Throwable ex) { + LOGGER.error("An error occurred while constructing a modular gui", ex); + throw ex; + } + } + + public ModularGui(GuiProvider provider, Screen parentScreen) { + this(provider); + this.parentScreen = parentScreen; + } + + public void setScreen(Screen screen) { + this.screen = screen; + } + + public GuiProvider getProvider() { + return provider; + } + + //=== Modular Gui Setup ===// + + public void setGuiTitle(Component guiTitle) { + this.guiTitle = guiTitle; + } + + public Component getGuiTitle() { + return guiTitle; + } + + /** + * @param pauseScreen Should a single-player game pause while this screen is open? + */ + public void setPauseScreen(boolean pauseScreen) { + this.pauseScreen = pauseScreen; + } + + public boolean isPauseScreen() { + return pauseScreen; + } + + public void setCloseOnEscape(boolean closeOnEscape) { + this.closeOnEscape = closeOnEscape; + } + + public boolean closeOnEscape() { + return closeOnEscape; + } + + /** + * Enable / disable the default screen background. (Default Enabled) + * This will be the usual darkened background when in-game, or the dirt background when not in game. + */ + public void renderScreenBackground(boolean renderBackground) { + this.renderBackground = renderBackground; + } + + public boolean renderBackground() { + return renderBackground; + } + + /** + * @return the root element to which content elements should be added. + */ + public GuiElement getRoot() { + return root instanceof ContentElement ? ((ContentElement) root).getContentElement() : root; + } + + public GuiElement getDirectRoot() { + return root; + } + + /** + * Sets up this gui to render like any other standards gui with the specified width and height. + * Meaning, the root element (usually the gui background image) will be centered on the screen, and will have the specified width and height. + *

+ * + * @param guiWidth Gui Width + * @param guiHeight Gui Height + * @see #initFullscreenGui() + */ + public ModularGui initStandardGui(int guiWidth, int guiHeight) { + root.constrain(GeoParam.WIDTH, Constraint.literal(guiWidth)); + root.constrain(GeoParam.HEIGHT, Constraint.literal(guiHeight)); + root.constrain(GeoParam.LEFT, Constraint.midPoint(get(GeoParam.LEFT), get(GeoParam.RIGHT), guiWidth / -2D)); + root.constrain(GeoParam.TOP, Constraint.midPoint(get(GeoParam.TOP), get(GeoParam.BOTTOM), guiHeight / -2D)); + return this; + } + + /** + * Sets up this gui to render as a full screen gui. + * Meaning the root element's geometry will match that of the underlying minecraft screen. + *

+ * + * @see #initStandardGui(int, int) + */ + public ModularGui initFullscreenGui() { + root.constrain(GeoParam.WIDTH, Constraint.match(get(GeoParam.WIDTH))); + root.constrain(GeoParam.HEIGHT, Constraint.match(get(GeoParam.HEIGHT))); + root.constrain(GeoParam.TOP, Constraint.match(get(GeoParam.TOP))); + root.constrain(GeoParam.LEFT, Constraint.match(get(GeoParam.LEFT))); + return this; + } + + /** + * By default, modular gui completely overrides vanillas default slot rendering. + * This ensures slots render within the depth constraint of the slot element and avoids situations where + * stacks in slots render on top of other parts of the gui. + * Meaning you can do things like hide slots by disabling the slot element, Or render elements on top of the slots. + *

+ * This method allow you to return full rendering control to vanilla if you need to for whatever reason. + */ + public void setVanillaSlotRendering(boolean vanillaSlotRendering) { + this.vanillaSlotRendering = vanillaSlotRendering; + } + + public boolean vanillaSlotRendering() { + return vanillaSlotRendering; + } + + //=== Modular Gui Passthrough Methods ===// + + /** + * Primary render method for ModularGui. The screen implementing ModularGui must call this in its render method. + * Followed by the {@link #renderOverlay(GuiGraphics, float)} method to handle overlay rendering. + */ + public void render(GuiGraphics graphics, float partialTicks) { + root.clearGeometryCache(); + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + root.render(graphics, mouseX, mouseY, partialTicks); + } + + /** + * Handles gui overlay rendering. This is where things like tool tips are rendered. + * This should be called immediately after {@link #render(GuiGraphics, float)} + *

+ * The reason this is split out from {@link #render(GuiGraphics, float)} is to allow + * stack tool tips to override gui overlay rendering in {@link ModularGuiContainer} + * + * @return true if an overlay such as a tooltip is currently being drawn. + */ + public boolean renderOverlay(GuiGraphics graphics, float partialTicks) { + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + return root.renderOverlay(graphics, mouseX, mouseY, partialTicks, false); + } + + /** + * Primary update / tick method. Must be called from the tick method of the implementing screen. + */ + public void tick() { + newCursor = null; + double mouseX = computeMouseX(); + double mouseY = computeMouseY(); + root.updateMouseOver(mouseX, mouseY, false); + tickListeners.forEach(Runnable::run); + root.tick(mouseX, mouseY); + CursorHelper.setCursor(newCursor); + if (jeiHighlightTime > 0) jeiHighlightTime--; + } + + /** + * Pass through for the mouseMoved event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX new mouse X position + * @param mouseY new mouse Y position + */ + public void mouseMoved(double mouseX, double mouseY) { + root.mouseMoved(mouseX, mouseY); + } + + /** + * Pass through for the mouseClicked event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @return true if this event has been consumed. + */ + public boolean mouseClicked(MouseButtonEvent event) { + preClickListeners.forEach(e -> e.accept(event)); + boolean consumed = root.mouseClicked(event, false); + if (!consumed) { + postClickListeners.forEach(e -> e.accept(event)); + } + return consumed; + } + + /** + * Pass through for the mouseReleased event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @return true if this event has been consumed. + */ + public boolean mouseReleased(MouseButtonEvent event) { + return root.mouseReleased(event, false); + } + + /** + * Pass through for the keyPressed event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param event The key event. Key, scancode, and modifiers. + * @return true if this event has been consumed. + */ + public boolean keyPressed(KeyEvent event) { + preKeyPressListeners.forEach(e -> e.accept(event)); + boolean consumed = root.keyPressed(event, false); + if (!consumed) { + postKeyPressListeners.forEach(e -> e.accept(event)); + } + return consumed; + } + + /** + * Pass through for the keyReleased event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param event The key event. Key, scancode, and modifiers. + * @return true if this event has been consumed. + */ + public boolean keyReleased(KeyEvent event) { + return root.keyReleased(event, false); + } + + /** + * Pass through for the charTyped event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param event The character event, codepoint and modifiers. + * @return true if this event has been consumed. + */ + public boolean charTyped(CharacterEvent event) { + return root.charTyped(event, false); + } + + /** + * Pass through for the mouseScrolled event. Any screen implementing {@link ModularGui} must pass through this event. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount + * @return true if this event has been consumed. + */ + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return root.mouseScrolled(mouseX, mouseY, scrollX, scrollY, false); + } + + /** + * Must be called by the screen when this gui is closed. + */ + public void onGuiClose() { + CursorHelper.resetCursor(); + closeListeners.forEach(Runnable::run); + } + + //=== Basic Minecraft Stuff ===// + + protected void updateScreenData(Minecraft mc, Font font, int screenWidth, int screenHeight) { + this.mc = mc; + this.font = font; + this.screenWidth = screenWidth; + this.screenHeight = screenHeight; + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + updateScreenData(mc, font, screenWidth, screenHeight); + root.clearGeometryCache(); + try { + root.onScreenInit(mc, font, screenWidth, screenHeight); + if (!guiBuilt) { + guiBuilt = true; + provider.buildGui(this); + } else { + resizeListeners.forEach(Runnable::run); + } + } catch (Throwable ex) { + //Because it seems the default behavior is to just silently consume init errors... Not helpful! + LOGGER.error("An error occurred while building a modular gui", ex); + throw ex; + } + } + + @Override + public Minecraft mc() { + return mc; + } + + @Override + public Font font() { + return font; + } + + @Override + public int scaledScreenWidth() { + return screenWidth; + } + + @Override + public int scaledScreenHeight() { + return screenHeight; + } + + @Override + public ModularGui getModularGui() { + return this; + } + + /** + * Returns the Screen housing this {@link ModularGui} + * With custom ModularGui implementations this may be null. + */ + public Screen getScreen() { + return screen; + } + + @Nullable + public Screen getParentScreen() { + return parentScreen; + } + + //=== Child Elements ===// + + @Override + public List> getChildren() { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void addChild(GuiElement child) { + if (root == null) { //If child is null, we are adding the root element. + child.initElement(this); + return; + } + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public ModularGui addChild(Consumer createChild) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void adoptChild(GuiElement child) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + @Override + public void removeChild(GuiElement child) { + throw new UnsupportedOperationException("Child elements must be managed via the root gui element not the modular gui itself."); + } + + //=== Geometry ===// + //The geometry of the base ModularGui class should always match the underlying minecraft screen. + + @Override + public double xMin() { + return 0; + } + + @Override + public double xMax() { + return screenWidth; + } + + @Override + public double xSize() { + return screenWidth; + } + + @Override + public double yMin() { + return 0; + } + + @Override + public double yMax() { + return screenHeight; + } + + @Override + public double ySize() { + return screenHeight; + } + + //=== Other ===// + + public double computeMouseX() { + return mc.mouseHandler.xpos() * (double) mc.getWindow().getGuiScaledWidth() / (double) mc.getWindow().getScreenWidth(); + } + + public double computeMouseY() { + return mc.mouseHandler.ypos() * (double) mc.getWindow().getGuiScaledHeight() / (double) mc.getWindow().getScreenHeight(); + } + + /** + * Provides a way to later retrieve the gui element responsible for positioning and rendering a slot. + */ + public void setSlotHandler(Slot slot, GuiElement handler) { + if (slotHandlers.containsKey(slot)) throw new IllegalStateException("A gui slot can only have a single handler!"); + slotHandlers.put(slot, handler); + } + + /** + * Returns the gui element responsible for managing a gui slot. + */ + public GuiElement getSlotHandler(Slot slot) { + return slotHandlers.get(slot); + } + + /** + * Sets the current mouse cursor. + * The cursor is reset at the end of each UI tick so this must be set every tick for as long as you want your custom cursor to be active. + */ + public void setCursor(Identifier cursor) { + this.newCursor = cursor; + } + + /** + * By default, tool tips are disabled while where is a floating item on screen. This can be used to re-enable them. + */ + public void setFloatingItemDisablesToolTips(boolean floatingItemDisablesToolTips) { + this.floatingItemDisablesToolTips = floatingItemDisablesToolTips; + } + + public boolean doesFloatingItemDisableToolTips() { + return floatingItemDisablesToolTips; + } + + public List> getJeiExclusions() { + return root.addJeiExclusions(new ArrayList<>()); + } + + public List> getJeiDropTargets() { + return root.addJeiDropTargets(new ArrayList<>()); + } + + public void setJeiHighlightTime(int jeiHighlightTime) { + this.jeiHighlightTime = jeiHighlightTime; + } + + public int getJeiHighlightTime() { + return jeiHighlightTime; + } + + /** + * Allows you to attach a callback that will be fired at the start of each gui tick. + */ + public void onTick(Runnable onTick) { + tickListeners.add(onTick); + } + + /** + * Allows you to attach a callback that will be fired when the parent screen is resized. + */ + public void onResize(Runnable onResize) { + resizeListeners.add(onResize); + } + + public void onClose(Runnable onClose) { + closeListeners.add(onClose); + } + + /** + * Allows you to attach a callback that will be fired on mouse click, before the click is handled by the rest of the gui. + */ + public void onMouseClickPre(Consumer onClick) { + preClickListeners.add(onClick); + } + + /** + * Allows you to attach a callback that will be fired on mouse click, after the click has been handled by the rest of the gui. + * Will only be fired if the event was not consumed by an element. + */ + public void onMouseClickPost(Consumer onClick) { + postClickListeners.add(onClick); + } + + /** + * Allows you to attach a callback that will be fired on key press, before the is handled by the rest of the gui. + */ + public void onKeyPressPre(Consumer preKeyPress) { + preKeyPressListeners.add(preKeyPress); + } + + /** + * Allows you to attach a callback that will be fired on key press, after it has been handled by the rest of the gui. + * Will only be fired if the event was not consumed by an element. + */ + public void onKeyPressPost(Consumer postKeyPress) { + postKeyPressListeners.add(postKeyPress); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java new file mode 100644 index 00000000..9d8a1977 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiContainer.java @@ -0,0 +1,320 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import net.minecraft.ChatFormatting; +import net.minecraft.util.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ClickType; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; + +/** + * Container screen implementation for {@link ModularGui}. + * + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class ModularGuiContainer extends AbstractContainerScreen implements ContainerScreenAccess { + + public final ModularGui modularGui; + /** + * Flag used to disable vanilla slot highlight rendering. + * + */ + private boolean renderingSlots = false; + + public ModularGuiContainer(T containerMenu, Inventory inventory, ContainerGuiProvider provider) { + super(containerMenu, inventory, Component.empty()); + provider.setMenuAccess(this); + this.modularGui = new ModularGui(provider); + this.modularGui.setScreen(this); + addRenderableOnly(this::renderModularGui); + } + + @Override + protected void clearWidgets() { + super.clearWidgets(); + addRenderableOnly(this::renderModularGui); + } + + public ModularGui getModularGui() { + return modularGui; + } + + @Override + public Component getTitle() { + return modularGui.getGuiTitle(); + } + + @Override + public boolean shouldCloseOnEsc() { + return modularGui.closeOnEscape(); + } + + @Override + protected void init() { + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void resize(int width, int height) { + super.resize(width, height); + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + GuiElement root = modularGui.getRoot(); + topPos = (int) root.getValue(GeoParam.TOP); + leftPos = (int) root.getValue(GeoParam.LEFT); + imageWidth = (int) root.getValue(GeoParam.WIDTH); + imageHeight = (int) root.getValue(GeoParam.HEIGHT); + + super.render(graphics, mouseX, mouseY, partialTicks); + + if (!handleFloatingItemRender(graphics, mouseX, mouseY) && !renderHoveredStackToolTip(graphics, mouseX, mouseY)) { + modularGui.renderOverlay(graphics, partialTicks); + } + } + + private void renderModularGui(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + modularGui.render(graphics, partialTicks); + } + + @Override + public void renderBackground(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { + if (modularGui.renderBackground()) { + super.renderBackground(graphics, mouseX, mouseY, partialTick); + } + } + + @Override + public void renderCarriedItem(GuiGraphics guiGraphics, int mouseX, int mouseY) { + if (modularGui.vanillaSlotRendering()) return; + super.renderCarriedItem(guiGraphics, mouseX, mouseY); + } + + @Override + public void renderSnapbackItem(GuiGraphics guiGraphics) { + if (modularGui.vanillaSlotRendering()) return; + super.renderSnapbackItem(guiGraphics); + } + + protected boolean handleFloatingItemRender(GuiGraphics graphics, int mouseX, int mouseY) { + if (modularGui.vanillaSlotRendering()) return false; + boolean ret = false; + + ItemStack stack = draggingItem.isEmpty() ? menu.getCarried() : draggingItem; + if (!stack.isEmpty()) { + int yOffset = draggingItem.isEmpty() ? 8 : 16; + String countOverride = null; + if (!draggingItem.isEmpty() && isSplittingStack) { + stack = stack.copyWithCount(Mth.ceil((float) stack.getCount() / 2.0F)); + } else if (isQuickCrafting && quickCraftSlots.size() > 1) { + stack = stack.copyWithCount(this.quickCraftingRemainder); + if (stack.isEmpty()) { + countOverride = ChatFormatting.YELLOW + "0"; + } + } + renderFloatingItem(graphics, stack, mouseX - 8, mouseY - yOffset, countOverride); + ret = modularGui.doesFloatingItemDisableToolTips(); + } + + if (snapbackData != null) { + float anim = Mth.clamp((float) (Util.getMillis() - snapbackData.time()) / 100.0F, 0F, 1F); + int xDist = snapbackData.end().x - snapbackData.start().x; + int yDist = snapbackData.end().y - snapbackData.start().y; + int xPos = snapbackData.start().x + (int) ((float) xDist * anim); + int yPos = snapbackData.start().y + (int) ((float) yDist * anim); + renderFloatingItem(graphics, snapbackData.item(), xPos + leftPos, yPos + topPos, null); + if (anim >= 1.0F) { + this.snapbackData = null; + } + ret = modularGui.doesFloatingItemDisableToolTips(); + } + + return ret; + } + + protected boolean renderHoveredStackToolTip(GuiGraphics guiGraphics, int mouseX, int mouseY) { + if (this.menu.getCarried().isEmpty() && this.hoveredSlot != null && this.hoveredSlot.hasItem() && showTooltipWithItemInHand(hoveredSlot.getItem())) { + GuiElement handler = modularGui.getSlotHandler(hoveredSlot); + if (handler != null && (handler.blockMouseOver(handler, mouseX, mouseY) || !handler.isMouseOver())) { + return false; + } + ItemStack itemStack = this.hoveredSlot.getItem(); + guiGraphics.setTooltipForNextFrame( + this.font, + this.getTooltipFromContainerItem(itemStack), + itemStack.getTooltipImage(), + itemStack, + mouseX, + mouseY, + itemStack.get(DataComponents.TOOLTIP_STYLE) + ); + return true; + } + return false; + } + + @Override + protected void containerTick() { + modularGui.tick(); + } + + @Override + public void removed() { + super.removed(); + modularGui.onGuiClose(); + } + + //=== Input Pass-though ===// + + @Override + public void mouseMoved(double mouseX, double mouseY) { + modularGui.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + return modularGui.mouseClicked(event) || super.mouseClicked(event, doubleClick); + } + + @Override + public boolean mouseReleased(MouseButtonEvent event) { + return modularGui.mouseReleased(event) || super.mouseReleased(event); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return modularGui.mouseScrolled(mouseX, mouseY, scrollX, scrollY) || super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); + } + + @Override + public boolean keyPressed(KeyEvent event) { + return modularGui.keyPressed(event) || super.keyPressed(event); + } + + @Override + public boolean keyReleased(KeyEvent event) { + return modularGui.keyReleased(event) || super.keyReleased(event); + } + + @Override + public boolean charTyped(CharacterEvent event) { + return modularGui.charTyped(event) || super.charTyped(event); + } + + //=== AbstractContainerMenu Overrides ===// + + @Override + protected void renderBg(GuiGraphics guiGraphics, float f, int i, int j) { + } + + @Override + protected void renderSlot(GuiGraphics guiGraphics, Slot slot, int mouseX, int mouseY) { + if (modularGui.vanillaSlotRendering()) { + super.renderSlot(guiGraphics, slot, mouseX, mouseY); + } else { + renderingSlots = true; + } + } + + //Modular gui friendly version of the slot render + @Override + public void doRenderSlot(GuiGraphics graphics, Slot slot) { + if (modularGui.vanillaSlotRendering()) return; + int slotX = slot.x + leftPos; + int slotY = slot.y + topPos; + ItemStack slotStack = slot.getItem(); + boolean dragingToSlot = false; + boolean dontRenderItem = slot == this.clickedSlot && !this.draggingItem.isEmpty() && !this.isSplittingStack; + + ItemStack carriedStack = this.menu.getCarried(); + String countString = null; + if (slot == this.clickedSlot && !this.draggingItem.isEmpty() && this.isSplittingStack && !slotStack.isEmpty()) { + slotStack = slotStack.copyWithCount(slotStack.getCount() / 2); + } else if (this.isQuickCrafting && this.quickCraftSlots.contains(slot) && !carriedStack.isEmpty()) { + if (this.quickCraftSlots.size() == 1) { + return; + } + + if (AbstractContainerMenu.canItemQuickReplace(slot, carriedStack, true) && this.menu.canDragTo(slot)) { + dragingToSlot = true; + int k = Math.min(carriedStack.getMaxStackSize(), slot.getMaxStackSize(carriedStack)); + int l = slot.getItem().isEmpty() ? 0 : slot.getItem().getCount(); + int m = AbstractContainerMenu.getQuickCraftPlaceCount(this.quickCraftSlots, this.quickCraftingType, carriedStack) + l; + if (m > k) { + m = k; + countString = ChatFormatting.YELLOW.toString() + k; + } + + slotStack = carriedStack.copyWithCount(m); + } else { + this.quickCraftSlots.remove(slot); + this.recalculateQuickCraftRemaining(); + } + } + + if (!dontRenderItem) { + if (dragingToSlot) { + //Highlights slots when doing a drag place operation. + graphics.fill(slotX, slotY, slotX + 16, slotY + 16, 0x80ffffff); + } + renderSlotContents(graphics, slotStack, slot, countString); + } + } + + @Override + public boolean isHovering(Slot pSlot, double pMouseX, double pMouseY) { + boolean ret = super.isHovering(pSlot, pMouseX, pMouseY); + //Override the isHovering check before renderSlotHighlight is called. + if (ret && renderingSlots && pSlot.isActive()) { + //This breaks the default hoveredSlot assignment, so we need to handle that here. + hoveredSlot = pSlot; + return false; + } + return ret; + } + + @Override //Disable vanilla title and inventory name rendering + protected void renderLabels(GuiGraphics guiGraphics, int i, int j) { + renderingSlots = false; + } + + @Nullable + @Override + public Slot getHoveredSlot(double mouseX, double mouseY) { + Slot slot = super.getHoveredSlot(mouseX, mouseY); + if (slot == null) return null; + + GuiElement handler = modularGui.getSlotHandler(slot); + if (handler != null && (!handler.isEnabled() || !handler.isMouseOver())) { + return null; + } + return slot; + } + + @Override + protected void slotClicked(Slot slot, int i, int j, ClickType clickType) { + if (slot != null) { + GuiElement handler = modularGui.getSlotHandler(slot); + if (handler != null && !handler.isEnabled()) return; + } + super.slotClicked(slot, i, j, clickType); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java new file mode 100644 index 00000000..0fa7f79e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/ModularGuiScreen.java @@ -0,0 +1,121 @@ +package codechicken.lib.gui.modular; + +import codechicken.lib.gui.modular.lib.GuiProvider; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +/** + * A simple ModularGui screen implementation. + * This is simply a wrapper for a {@link ModularGui} that takes a {@link GuiProvider} + * This should be suitable for most basic gui screens. + *

+ * Created by brandon3055 on 19/08/2023 + */ +public class ModularGuiScreen extends Screen { + + protected final ModularGui modularGui; + + public ModularGuiScreen(GuiProvider provider) { + super(Component.empty()); + this.modularGui = new ModularGui(provider); + this.modularGui.setScreen(this); + } + + public ModularGuiScreen(GuiProvider builder, Screen parentScreen) { + super(Component.empty()); + this.modularGui = new ModularGui(builder, parentScreen); + this.modularGui.setScreen(this); + } + + public ModularGui getModularGui() { + return modularGui; + } + + @Override + public Component getTitle() { + return modularGui.getGuiTitle(); + } + + @Override + public boolean isPauseScreen() { + return modularGui.isPauseScreen(); + } + + @Override + public boolean shouldCloseOnEsc() { + return modularGui.closeOnEscape(); + } + + @Override + protected void init() { + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void resize(int width, int height) { + super.resize(width, height); + modularGui.onScreenInit(minecraft, font, width, height); + } + + @Override + public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTicks) { + if (modularGui.renderBackground()) { + renderBackground(graphics, mouseX, mouseY, partialTicks); + } + modularGui.render(graphics, partialTicks); + // TODO do we render atop JEI? Whats the event ordering here? + modularGui.renderOverlay(graphics, partialTicks); + } + + @Override + public void tick() { + modularGui.tick(); + } + + @Override + public void removed() { + modularGui.onGuiClose(); + } + + //=== Input Pass-though ===// + + @Override + public void mouseMoved(double mouseX, double mouseY) { + modularGui.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { + return modularGui.mouseClicked(event) || super.mouseClicked(event, doubleClick); + } + + @Override + public boolean mouseReleased(MouseButtonEvent event) { + return modularGui.mouseReleased(event) || super.mouseReleased(event); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return modularGui.mouseScrolled(mouseX, mouseY, scrollX, scrollY) || super.mouseScrolled(mouseX, mouseY, scrollX, scrollY); + } + + @Override + public boolean keyPressed(KeyEvent event) { + return modularGui.keyPressed(event) || super.keyPressed(event); + } + + @Override + public boolean keyReleased(KeyEvent event) { + return modularGui.keyReleased(event) || super.keyReleased(event); + } + + @Override + public boolean charTyped(CharacterEvent event) { + return modularGui.charTyped(event) || super.charTyped(event); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java new file mode 100644 index 00000000..f3ab8c22 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/SpriteSupplier.java @@ -0,0 +1,56 @@ +package codechicken.lib.gui.modular; + +import com.google.common.base.Suppliers; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.Material; +import net.minecraft.data.AtlasIds; +import net.minecraft.resources.Identifier; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * A supplier for sprites. + *

+ * May return null to indicate the sprite is not available. This will usually disable + * the thing being rendered. + *

+ * Created by covers1624 on 4/1/26. + */ +@FunctionalInterface +public interface SpriteSupplier extends Supplier { + + SpriteSupplier EMPTY = () -> null; + + @Override + @Nullable + TextureAtlasSprite get(); + + default void ifPresent(Consumer cons) { + var tex = get(); + if (tex != null) { + cons.accept(tex); + } + } + + static SpriteSupplier gui(Identifier spriteLoc) { + return of(Sheets.GUI_SHEET, spriteLoc); + } + + static SpriteSupplier of(Identifier atlasLoc, Identifier spriteLoc) { + var memo = Suppliers.memoize(() -> Minecraft.getInstance().getAtlasManager().get(new Material(atlasLoc, spriteLoc))); + return memo::get; + } + + static SpriteSupplier gui(Supplier sup) { + return of(() -> new Material(Sheets.GUI_SHEET, sup.get())); + } + + static SpriteSupplier of(Supplier sup) { + var atlasManager = Minecraft.getInstance().getAtlasManager(); + return () -> atlasManager.get(sup.get()); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java new file mode 100644 index 00000000..1e867d06 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiButton.java @@ -0,0 +1,354 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.SpriteSupplier; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.client.resources.sounds.SimpleSoundInstance; +import net.minecraft.core.Holder; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundEvents; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +import static codechicken.lib.CodeChickenLib.MOD_ID; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public class GuiButton extends GuiElement { + + public static final int LEFT_CLICK = 0; + public static final int RIGHT_CLICK = 1; + public static final int MIDDLE_CLICK = 2; + + private final Map onClick = new HashMap<>(); + private final Map onPress = new HashMap<>(); + private boolean pressed = false; + private @Nullable Holder pressSound = SoundEvents.UI_BUTTON_CLICK; + private @Nullable Holder releaseSound = null; + private Supplier disabled = () -> false; + private @Nullable Supplier toggleState; + private @Nullable GuiText label = null; + private boolean resetHoverOnPress = true; + + /** + * In its default state this is a blank, invisible element that can fire callbacks when pressed. + * To make an actual usable button, ether use one of the builtin static create methods, + * Or add your own elements to make this button look and function in a way that meets your needs. + * + * @param parent parent {@link GuiParent}. + */ + public GuiButton(GuiParent parent) { + super(parent); + } + + /** + * Creates a new gui button that looks and acts exactly like a standard vanilla button. + */ + public static GuiButton vanilla(GuiParent parent, @Nullable Component label, Runnable onClick) { + return vanilla(parent, label).onClick(onClick); + } + + /** + * Creates a new gui button that looks and acts exactly like a standard vanilla button. + */ + public static GuiButton vanilla(GuiParent parent, @Nullable Component label) { + GuiButton button = new GuiButton(parent); + GuiTexture texture = new GuiTexture(button, SpriteSupplier.gui(() -> Identifier.fromNamespaceAndPath(MOD_ID, button.toggleState() ? "dynamic/button_highlight" : "dynamic/button_vanilla"))); + texture.dynamicTexture(); + GuiRectangle highlight = new GuiRectangle(button).border(() -> button.hoverTime() > 0 ? 0xFFFFFFFF : 0); + + Constraints.bind(texture, button); + Constraints.bind(highlight, button); + + if (label != null) { + var buttonLabel = new GuiText(button, label); + button.setLabel(buttonLabel); + Constraints.bind(buttonLabel, button, 0, 2, 0, 2); + } + + return button; + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Component label, Runnable onPress) { + return vanillaAnimated(parent, label == null ? null : () -> label, onPress); + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Supplier label, Runnable onPress) { + return vanillaAnimated(parent, label).onPress(onPress); + } + + //TODO Could use a quad-sliced texture for this. + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Component label) { + return vanillaAnimated(parent, label == null ? null : () -> label); + } + + /** + * Creates a vanilla button with a "press" animation. + */ + public static GuiButton vanillaAnimated(GuiParent parent, @Nullable Supplier label) { + GuiButton button = new GuiButton(parent); + GuiTexture texture = new GuiTexture(button, SpriteSupplier.gui(() -> Identifier.fromNamespaceAndPath(MOD_ID, button.toggleState() || button.isPressed() ? "dynamic/button_pressed" : "dynamic/button_vanilla"))); + texture.dynamicTexture(); + GuiRectangle highlight = new GuiRectangle(button).border(() -> button.isMouseOver() ? 0xFFFFFFFF : 0); + + Constraints.bind(texture, button); + Constraints.bind(highlight, button); + + if (label != null) { + button.setLabel(new GuiText(button, label) + .constrain(TOP, Constraint.relative(button.get(TOP), () -> button.isPressed() ? -0.5D : 0.5D).precise()) + .constrain(LEFT, Constraint.relative(button.get(LEFT), () -> button.isPressed() ? 1.5D : 2.5D).precise()) + .constrain(WIDTH, Constraint.relative(button.get(WIDTH), -4)) + .constrain(HEIGHT, Constraint.match(button.get(HEIGHT))) + ); + } + + return button; + } + + /** + * Super simple button that is just a coloured rectangle with a label. + */ + public static GuiButton flatColourButton(GuiParent parent, @Nullable Supplier label, Function buttonColour) { + return flatColourButton(parent, label, buttonColour, null); + } + + /** + * Super simple button that is just a coloured rectangle with a label. + */ + public static GuiButton flatColourButton(GuiParent parent, @Nullable Supplier label, Function buttonColour, @Nullable Function borderColour) { + GuiButton button = new GuiButton(parent); + GuiRectangle background = new GuiRectangle(button) + .fill(() -> buttonColour.apply(button.isMouseOver() || button.toggleState() || button.isPressed())) + .border(borderColour == null ? null : () -> borderColour.apply(button.isMouseOver() || button.toggleState() || button.isPressed())); + Constraints.bind(background, button); + + if (label != null) { + GuiText text = new GuiText(button, label); + button.setLabel(text); + Constraints.bind(text, button, 0, 2, 0, 2); + } + + return button; + } + + /** + * When creating buttons with labels, use this method to store a reference to the label in the button fore easy retrival later. + * + * @param label The button label. + */ + public GuiButton setLabel(@Nullable GuiText label) { + this.label = label; + return this; + } + + /** + * @return The buttons label element, If it has one. + */ + public @Nullable GuiText getLabel() { + return label; + } + + public GuiButton configureLabel(Consumer configure) { + if (label != null) { + configure.accept(label); + } + return this; + } + + /** + * By default, hover time is reset when button is pressed. + * THis allows you to disable that functionality to the tooltip will remain open when button is pressed. + */ + public GuiButton setResetHoverOnPress(boolean resetHoverOnPress) { + this.resetHoverOnPress = resetHoverOnPress; + return this; + } + + /** + * This event is fired immediately when this button is left-clicked. + * This is the logic used by most vanilla gui buttons. + * + * @see #onPress(Runnable) + */ + public GuiButton onClick(Runnable onClick) { + return onClick(onClick, LEFT_CLICK); + } + + /** + * This event is fired immediately when this button is clicked with the specified mouse button. + * This is the logic used by most vanilla gui buttons. + * Note: You can apply one listener per mouse button. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onClick(Runnable onClick, int mouseButton) { + this.onClick.put(mouseButton, onClick); + return this; + } + + /** + * This event is fired when the button is pressed and then released using the left mosue button. + * The event is only fired if the cursor is still over the button when left click is released. + * This is the standard logic for most buttons in the world, but not vanillas. + * Note: You can apply one listener per mouse button. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onPress(Runnable onPress) { + return onPress(onPress, LEFT_CLICK); + } + + /** + * This event is fired when the button is pressed and then released using the specified mouse button. + * The event is only fired if the cursor is still over the button when left click is released. + * This is the standard logic for most buttons in the world, but not vanillas. + * + * @see #onPress(Runnable, int) + */ + public GuiButton onPress(Runnable onPress, int mouseButton) { + this.onPress.put(mouseButton, onPress); + return this; + } + + /** + * Allows set the disabled status of this button + * Note: This is not the same as {@link #setEnabled(boolean)} the "enabled" allows you to completely disable an element. + * This "disabled" status is specific to {@link GuiButton}, + * When disabled via this method a button is still visible but greyed out / not clickable. + */ + public GuiButton setDisabled(boolean disabled) { + this.disabled = () -> disabled; + return this; + } + + /** + * Allows you to install a suppler that controls the disabled state of this button. + * Note: This is not the same as {@link #setEnabled(Supplier)} the "enabled" allows you to completely disable an element. + * This "disabled" status is specific to {@link GuiButton}, + * When disabled via this method a button is still visible but greyed out / not clickable. + */ + public GuiButton setDisabled(Supplier disabled) { + this.disabled = disabled; + return this; + } + + /** + * Allows this button to be used as a toggle or radio button. + * This method allows you to install a suppler that controls the current "selected / toggled" state. + * + * @param toggleState supplier that indicates weather or not this button should currently render as pressed/selected. + */ + public GuiButton setToggleMode(@Nullable Supplier toggleState) { + this.toggleState = toggleState; + return this; + } + + /** + * @return the "disabled" status. + * @see #setDisabled(boolean) + * @see #setDisabled(Supplier) + */ + public boolean isDisabled() { + return disabled.get(); + } + + /** + * @return true if this button is currently pressed by the user (left click held down on button) + */ + public boolean isPressed() { + return pressed && hoverTime() > 0; + } + + public boolean toggleState() { + return toggleState != null && toggleState.get(); + } + + /** + * Sets the sound to be played when this button is pressed. + */ + public GuiButton setPressSound(@Nullable Holder pressSound) { + this.pressSound = pressSound; + return this; + } + + /** + * Sets the sound to be played when this button is released. + */ + public GuiButton setReleaseSound(@Nullable Holder releaseSound) { + this.releaseSound = releaseSound; + return this; + } + + public @Nullable Holder getPressSound() { + return pressSound; + } + + public @Nullable Holder getReleaseSound() { + return releaseSound; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event) { + if (!isMouseOver() || isDisabled()) return false; + Runnable onClick = this.onClick.get(event.button()); + Runnable onPress = this.onPress.get(event.button()); + if (onClick == null && onPress == null) return false; + + pressed = true; + if (resetHoverOnPress) hoverTime = 1; + + if (onClick != null) { + onClick.run(); + } + + if (getPressSound() != null) { + mc().getSoundManager().play(SimpleSoundInstance.forUI(getPressSound(), 1F)); + } + return true; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseReleased(event, consumed); + if (!pressed) return consumed; + Runnable onClick = this.onClick.get(event.button()); + Runnable onPress = this.onPress.get(event.button()); + if (onClick == null && onPress == null) return consumed; + + if (resetHoverOnPress) hoverTime = 1; + + if (!isDisabled() && isMouseOver()) { + if (pressed && onPress != null) { + onPress.run(); + consumed = true; + } + if (getReleaseSound() != null && (toggleState == null || !toggleState.get())) { + mc().getSoundManager().play(SimpleSoundInstance.forUI(getReleaseSound(), 1F)); + } + } + pressed = false; + return consumed; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java new file mode 100644 index 00000000..e4800225 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiColourPicker.java @@ -0,0 +1,264 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.colour.Colour; +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Created by brandon3055 on 17/11/2023 + */ +public class GuiColourPicker extends GuiManipulable { + + private ColourState colourState = ColourState.create(); + private final Colour initialColour; + private boolean blockOutsideClicks = false; + private boolean closeOnOutsideClick = false; + private GuiButton okButton; + private GuiButton cancelButton; + + public GuiColourPicker(GuiParent parent, Colour initialColour) { + super(parent); + this.initialColour = initialColour; + } + + public static GuiColourPicker create(GuiParent guiParent, ColourState colourState) { + return create(guiParent, colourState, true); + } + + public static GuiColourPicker create(GuiParent guiParent, ColourState colourState, boolean hasAlpha) { + GuiColourPicker picker = new GuiColourPicker(guiParent.getModularGui().getRoot(), colourState.getColour()); + picker.setOpaque(true); + picker.setColourState(colourState); + Constraints.size(picker, 80, hasAlpha ? 80 : 70); + + GuiRectangle background = GuiRectangle.toolTipBackground(picker.getContentElement()); + Constraints.bind(background, picker.getContentElement()); + + var hexField = GuiTextField.create(background, 0xFF000000, 0xFF505050, 0xe0e0e0); + hexField.field() + .setTextState(picker.getTextState()) + .setMaxLength(hasAlpha ? 8 : 6) + .setFilter(s -> s.isEmpty() || validHex(s)); + hexField.container() + .setOpaque(true) + .constrain(HEIGHT, literal(12)) + .constrain(TOP, relative(background.get(TOP), 4)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + SliderBG slider = makeSlider(background, 0xFFFF0000, picker.sliderStateRed()) + .constrain(TOP, relative(hexField.container().get(BOTTOM), 2)); + + slider = makeSlider(background, 0xFF00FF00, picker.sliderStateGreen()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + + slider = makeSlider(background, 0xFF0000FF, picker.sliderStateBlue()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + + if (hasAlpha) { + slider = makeSlider(background, 0xFFFFFFFF, picker.sliderStateAlpha()) + .constrain(TOP, relative(slider.get(BOTTOM), 1)); + } else { + colourState.set(colourState.getColour().aF(0)); + } + + ColourPreview preview = new ColourPreview(background, () -> hasAlpha ? colourState.get() : (colourState.get() | 0xFF000000)) + .setOpaque(true) + .constrain(HEIGHT, literal(6)) + .constrain(TOP, relative(slider.get(BOTTOM), 2)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + picker.cancelButton = GuiButton.flatColourButton(background, () -> Component.translatable("gui.cancel"), e -> 0xFF000000, e -> e ? 0xFF777777 : 0xFF555555) + .setOpaque(true) + .onPress(picker::cancel) + .constrain(HEIGHT, literal(10)) + .constrain(TOP, relative(preview.get(BOTTOM), 2)) + .constrain(LEFT, midPoint(background.get(LEFT), background.get(RIGHT), -4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + picker.okButton = GuiButton.flatColourButton(background, () -> Component.translatable("gui.ok"), e -> 0xFF000000, e -> e ? 0xFF777777 : 0xFF555555) + .setOpaque(true) + .onPress(() -> picker.getParent().removeChild(picker)) + .constrain(HEIGHT, literal(10)) + .constrain(TOP, relative(preview.get(BOTTOM), 2)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, dynamic(() -> picker.cancelButton.isEnabled() ? picker.cancelButton.xMin() - 2 : background.xMax() - 4)); + + return picker; + } + + public static SliderBG makeSlider(GuiElement background, int colour, SliderState state) { + SliderBG slideBG = new SliderBG(background, 0xFF505050, 0x30FFFFFF) + .setOpaque(true) + .constrain(HEIGHT, literal(9)) + .constrain(LEFT, relative(background.get(LEFT), 4)) + .constrain(RIGHT, relative(background.get(RIGHT), -4)); + + GuiSlider slider = new GuiSlider(slideBG, Axis.X) + .setSliderState(state); + Constraints.bind(slider, slideBG, 0, 1, 0, 1); + slideBG.slider = slider; + + GuiRectangle handle = new GuiRectangle(slider) + .fill(colour) + .border(0xFF000000) + .borderWidth(0.5) + .constrain(WIDTH, literal(4)); + + slider.installSlider(handle) + .bindSliderWidth(); + + return slideBG; + } + + public GuiColourPicker setBlockOutsideClicks(boolean blockOutsideClicks) { + this.blockOutsideClicks = blockOutsideClicks; + return this; + } + + public GuiColourPicker setCancelOnOutsideClick(boolean closeOnOutsideClick) { + this.closeOnOutsideClick = closeOnOutsideClick; + return this; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + if (closeOnOutsideClick && !getContentElement().getRectangle().contains(event.x(), event.y())) { + cancel(); + } + return super.mouseClicked(event, consumed) || blockOutsideClicks; + } + + public void cancel() { + if (cancelButton != null && cancelButton.isEnabled()) { + colourState.set(initialColour); + } + close(); + } + + public void close() { + getParent().removeChild(this); + } + + private static boolean validHex(String value) { + try { + Integer.parseUnsignedInt(value, 16); + return true; + } catch (Throwable ignored) { + return false; + } + } + + public static class SliderBG extends GuiElement implements BackgroundRender { + + public int colour; + public int highlight; + public GuiSlider slider; + public boolean pressed = false; + + public SliderBG(GuiParent parent, int colour, int highlight) { + super(parent); + this.colour = colour; + this.highlight = highlight; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + pressed = event.button() == 0; + return super.mouseClicked(event, consumed); + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + if (event.button() == 0) pressed = false; + return super.mouseReleased(event, consumed); + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + render.cc$fill(xMin(), yMin(), xMin() + 1, yMax(), colour); + render.cc$fill(xMax() - 1, yMin(), xMax(), yMax(), colour); + render.cc$fill(xMin() + 1, yCenter() - 0.5, xMax() - 1, yCenter() + 0.5, colour); + + if ((isMouseOver() && !pressed) || slider.isDragging()) { + render.cc$fill(getRectangle(), highlight); + } + } + } + + public static class ColourPreview extends GuiElement implements BackgroundRender { + + private final Supplier colour; + public int colourA = 0xFF999999; + public int colourB = 0xFF666666; + + public ColourPreview(GuiParent parent, Supplier colour) { + super(parent); + this.colour = colour; + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + render.cc$enableScissor(xMin(), yMin(), xSize(), ySize()); + for (int x = 0; xMin() + (x * 2) < xMax(); x++) { + for (int y = 0; yMin() + (y * 2) < yMax(); y++) { + int col = (y & 1) == 0 ? ((x & 1) == 0 ? colourA : colourB) : ((x & 1) == 0 ? colourB : colourA); + render.cc$fill(xMin() + (x * 2), yMin() + (y * 2), 2, 2, col); + } + } + render.cc$disableScissor(); + render.cc$fill(getRectangle(), colour.get()); + } + } + + public GuiColourPicker setColourState(ColourState colourState) { + this.colourState = colourState; + return this; + } + + public ColourState getState() { + return colourState; + } + + public SliderState sliderStateAlpha() { + return SliderState.forSlider(() -> (double) colourState.getColour().aF(), e -> colourState.set(colourState.getColour().aF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateRed() { + return SliderState.forSlider(() -> (double) colourState.getColour().rF(), e -> colourState.set(colourState.getColour().rF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateGreen() { + return SliderState.forSlider(() -> (double) colourState.getColour().gF(), e -> colourState.set(colourState.getColour().gF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); + } + + public SliderState sliderStateBlue() { + return SliderState.forSlider(() -> (double) colourState.getColour().bF(), e -> colourState.set(colourState.getColour().bF(e.floatValue())), () -> -1D / (Minecraft.getInstance().hasShiftDown() ? 16 : 64)); + } + + public TextState getTextState() { + return TextState.create(colourState::getHexColour, colourState::setHexColour); + } + + public GuiButton getOkButton() { + return okButton; + } + + /** + * If cancel button is disabled, ok button will automatically resize. + */ + public GuiButton getCancelButton() { + return cancelButton; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java new file mode 100644 index 00000000..6eb4b1d1 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiContextMenu.java @@ -0,0 +1,169 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; + +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Context menus get added to the root element when they are created so as long as no new elements are added after the menu is opened, + * the menu will always be on top. + * It will also automatically close when an option is selected, or when the user clicks outside the context menu. + *

+ * Created by brandon3055 on 21/11/2023 + */ +public class GuiContextMenu extends GuiElement { + + private BiFunction, GuiButton> buttonBuilder = (menu, label) -> GuiButton.flatColourButton(menu, label, hover -> hover ? 0xFF475b6a : 0xFF151515).constrain(HEIGHT, literal(12)); + private final Map, Runnable> options = new LinkedHashMap<>(); + private final Map, Supplier>> tooltips = new HashMap<>(); + private final List buttons = new ArrayList<>(); + private boolean closeOnItemClicked = true; + private boolean closeOnOutsideClick = true; + private boolean actionOnClick = false; + private boolean pressed = false; + + public GuiContextMenu(ModularGui gui) { + super(gui.getRoot()); + jeiExclude(); + setOpaque(true); + } + + public static GuiContextMenu tooltipStyleMenu(GuiParent parent) { + GuiContextMenu menu = new GuiContextMenu(parent.getModularGui()); + Constraints.bind(GuiRectangle.toolTipBackground(menu), menu); + return menu; + } + + public GuiContextMenu setCloseOnItemClicked(boolean closeOnItemClicked) { + this.closeOnItemClicked = closeOnItemClicked; + return this; + } + + public GuiContextMenu setCloseOnOutsideClick(boolean closeOnOutsideClick) { + this.closeOnOutsideClick = closeOnOutsideClick; + return this; + } + + /** + * By default, the option action fires on mouse button release (like pretty much any UI button in existence) + * Calling this will change that to action on mouse button press, (What minecraft uses for its buttons) + */ + public GuiContextMenu actionOnClick() { + this.actionOnClick = true; + rebuildButtons(); + return this; + } + + /** + * Only height should be constrained, with will be set automatically to accommodate the provided label. + */ + public GuiContextMenu setButtonBuilder(BiFunction, GuiButton> buttonBuilder) { + this.buttonBuilder = buttonBuilder; + return this; + } + + public GuiContextMenu addOption(Supplier label, Runnable action) { + options.put(label, action); + rebuildButtons(); + return this; + } + + public GuiContextMenu addOption(Supplier label, Supplier> tooltip, Runnable action) { + options.put(label, action); + tooltips.put(label, tooltip); + rebuildButtons(); + return this; + } + + public GuiContextMenu addOption(Supplier label, List tooltip, Runnable action) { + return addOption(label, () -> tooltip, action); + } + + public GuiContextMenu addOption(Supplier label, Runnable action, Component... tooltip) { + return addOption(label, () -> List.of(tooltip), action); + } + + private void rebuildButtons() { + buttons.forEach(this::removeChild); + buttons.clear(); + + //Menu options can be dynamic so the width constraint needs to be dynamic. + //This is probably a little expensive, but its only while a context menu is open. + constrain(WIDTH, dynamic(() -> options.keySet().stream().mapToInt(e -> font().width(e.get())).max().orElse(0) + 6D + 4D)); + + double height = 3; + for (Supplier label : options.keySet()) { + Runnable action = options.get(label); + GuiButton button = buttonBuilder.apply(this, label) + .constrain(TOP, relative(get(TOP), height)) + .constrain(LEFT, relative(get(LEFT), 3)) + .constrain(RIGHT, relative(get(RIGHT), -3)); + if (actionOnClick) { + button.onClick(action); + } else { + button.onPress(action); + } + if (tooltips.containsKey(label)) { + button.setTooltip(tooltips.get(label)); + } + button.getLabel().setScroll(false); + buttons.add(button); + height += button.ySize(); + } + constrain(HEIGHT, literal(height + 3)); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseClicked(event, consumed); + pressed = isMouseOver(); + if (isMouseOver() || consumed) { + if (actionOnClick) { + if (consumed && closeOnItemClicked) { + close(); + } + return true; + } + } else if (closeOnOutsideClick) { + close(); + return true; + } + + return consumed; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseReleased(event, consumed); + if (isMouseOver() || consumed) { + if (!actionOnClick) { + if (consumed && closeOnItemClicked && pressed) { + close(); + } + pressed = false; + return true; + } + } + pressed = false; + return consumed; + } + + public void close() { + getParent().removeChild(this); + } + + public GuiContextMenu setNormalizedPos(double x, double y) { + constrain(LEFT, dynamic(() -> Math.min(Math.max(x, 0), scaledScreenWidth() - xSize()))); + constrain(TOP, dynamic(() -> Math.min(Math.max(y, 0), scaledScreenHeight() - ySize()))); + return this; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java new file mode 100644 index 00000000..2d119f49 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDVD.java @@ -0,0 +1,97 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.math.MathHelper; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import net.minecraft.client.gui.GuiGraphics; +import org.joml.Vector2d; +import org.jspecify.annotations.Nullable; + +import java.util.Random; +import java.util.function.Consumer; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * Just for fun! + * Created by brandon3055 on 10/09/2023 + */ +public class GuiDVD extends GuiElement implements ContentElement> { + private static final Random randy = new Random(); + + private final GuiElement movingElement; + private double xOffset = 0; + private double yOffset = 0; + private @Nullable Vector2d velocity = null; + private int bounce = 0; + private Consumer onBounce = bounce -> { + }; + + public GuiDVD(GuiParent parent) { + super(parent); + this.movingElement = new GuiElement<>(this) + .constrain(TOP, Constraint.relative(get(TOP), () -> yOffset)) + .constrain(LEFT, Constraint.relative(get(LEFT), () -> xOffset)) + .constrain(WIDTH, Constraint.match(get(WIDTH))) + .constrain(HEIGHT, Constraint.match(get(HEIGHT))); + } + + @Override + public GuiElement getContentElement() { + return movingElement; + } + + public void start() { + if (velocity == null) { + velocity = new Vector2d(randy.nextBoolean() ? 1 : -1, randy.nextBoolean() ? 1 : -1); + velocity.normalize(); + } else { + velocity = null; + xOffset = yOffset = 0; + bounce = 0; + } + } + + public void onBounce(Consumer onBounce) { + this.onBounce = onBounce; + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + } + + @Override + public void render(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + super.render(render, mouseX, mouseY, partialTicks); + if (velocity == null) return; + + double speed = 5 * partialTicks; + xOffset += velocity.x * speed; + yOffset += velocity.y * speed; + Rectangle rect = movingElement.getRectangle(); + + int bounces = 0; + if ((velocity.y < 0 && rect.y() < 0) || (velocity.y > 0 && rect.yMax() > scaledScreenHeight())) { + velocity.y *= -1; + onBounce.accept(bounce++); + bounces++; + } + + if ((velocity.x < 0 && rect.x() < 0) || (velocity.x > 0 && rect.xMax() > scaledScreenWidth())) { + velocity.x *= -1; + onBounce.accept(bounce++); + bounces++; + } + + if (bounce > 0) { + velocity.y += -0.05 + (randy.nextGaussian() * 0.1); + velocity.x += -0.05 + (randy.nextGaussian() * 0.1); + velocity.x = velocity.x > 0 ? MathHelper.clip(velocity.x, 0.4, 0.6) : MathHelper.clip(velocity.x, -0.4, -0.6); + velocity.y = velocity.y > 0 ? MathHelper.clip(velocity.y, 0.4, 0.6) : MathHelper.clip(velocity.y, -0.4, -0.6); + velocity.normalize(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java new file mode 100644 index 00000000..bf535d92 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiDialog.java @@ -0,0 +1,240 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.Nullable; + +import java.util.function.BiFunction; +import java.util.function.Function; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This class is designed to assist with the easy creation of a number of standard dialog windows. + *

+ * Created by brandon3055 on 14/12/2023 + */ +public class GuiDialog extends GuiElement { + + private boolean blockKeyInput = true; + private boolean blockMouseInput = true; + + protected GuiDialog(GuiParent parent) { + super(parent); + } + + /** + * Option dialog builder with pre-configured background and button builders. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width, Option... options) { + return optionsDialog(parent, title, dialogText, GuiRectangle::toolTipBackground, GuiDialog::defaultButton, width, options); + } + + /** + * Option dialog builder with pre-configured background and button builders. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(GuiParent parent, Component dialogText, int width, Option... options) { + return optionsDialog(parent, null, dialogText, width, options); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width, @Nullable Runnable okAction) { + return optionsDialog(parent, title, dialogText, width, neutral(Component.translatable("gui.ok"), okAction)); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(GuiParent parent, @Nullable Component title, Component dialogText, int width) { + return infoDialog(parent, title, dialogText, width, null); + } + + /** + * Creates a simple info dialog for displaying information to the user. + * The dialog has a single "Ok" button that will close the dialog + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param dialogText The main dialog text. + * @param width The dialog width, (Height will automatically adjust based on content.) + */ + public static GuiDialog infoDialog(GuiParent parent, Component dialogText, int width) { + return infoDialog(parent, null, dialogText, width); + } + + /** + * Create a green "Primary" button option. + */ + public static Option primary(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFF44AA44 : 0xFF118811); + } + + /** + * Create a grey "Neutral" button option. + */ + public static Option neutral(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFF909090 : 0xFF505050); + } + + /** + * Create a red "Caution" button option. + */ + public static Option caution(Component text, @Nullable Runnable action) { + return new Option(text, action, hovered -> hovered ? 0xFFAA4444 : 0xFF881111); + } + + /** + * @param blockKeyInput Prevent keyboard inputs from being sent to the rest of the gui while this dialog is open. + * Default: true. + */ + public GuiDialog setBlockKeyInput(boolean blockKeyInput) { + this.blockKeyInput = blockKeyInput; + return this; + } + + /** + * @param blockMouseInput Prevent mouse inputs from being sent to the rest of the gui while this dialog is open. + * Default: true. + */ + public GuiDialog setBlockMouseInput(boolean blockMouseInput) { + this.blockMouseInput = blockMouseInput; + return this; + } + + public void close() { + getParent().removeChild(this); + } + + @Override + public boolean keyPressed(KeyEvent event) { + return blockKeyInput; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event) { + return blockMouseInput; + } + + /** + * This is the core dialog builder method. + * It takes a title text component and a map of Component>Runnable map that is used to define the options. + * Dialog will automatically be centered on the screen. + * + * @param parent Can be any gui element (Will just be used to get the root element) + * @param title Sets a separate title that will be displayed above the main dialog text. (Optional) + * @param dialogText The main dialog text. + * @param backgroundBuilder A function that is used to create the background of the dialog. + * @param buttonBuilder A function that is used to create the dialog buttons. + * @param width The dialog width, (Height will automatically adjust based on content.) + * @param options The list of options for this dialog. + */ + public static GuiDialog optionsDialog(GuiParent parent, @Nullable Component title, Component dialogText, Function> backgroundBuilder, BiFunction buttonBuilder, int width, Option... options) { + if (options.length == 0) throw new IllegalStateException("Can not create gui dialog with no options!"); + ModularGui gui = parent.getModularGui(); + + GuiDialog dialog = new GuiDialog(gui.getRoot()) + .constrain(WIDTH, literal(width)) + .setOpaque(true); + Constraints.bind(backgroundBuilder.apply(dialog), dialog); + + Constraint left = relative(dialog.get(LEFT), 5); + Constraint right = relative(dialog.get(RIGHT), -5); + + if (title != null) { + GuiText titleText = new GuiText(dialog, title) + .setWrap(true) + .constrain(TOP, relative(dialog.get(TOP), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + + GuiText bodyText = new GuiText(dialog, dialogText) + .setWrap(true) + .constrain(TOP, relative(titleText.get(BOTTOM), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + dialog.constrain(HEIGHT, dynamic(() -> 5 + titleText.ySize() + 5 + bodyText.ySize() + 5 + 14 + 5)); + } else { + GuiText bodyText = new GuiText(dialog, dialogText) + .setWrap(true) + .constrain(TOP, relative(dialog.get(TOP), 5)) + .constrain(LEFT, left) + .constrain(RIGHT, right) + .autoHeight(); + dialog.constrain(HEIGHT, dynamic(() -> 5 + bodyText.ySize() + 5 + 14 + 5)); + } + + double totalWidth = FastStream.of(options).doubleSum(e -> dialog.font().width(e.text)); + double pos = 5; + int spacing = 2; + for (Option option : options) { + double fraction = dialog.font().width(option.text) / totalWidth; + double opWidth = (dialog.xSize() - 10 - ((options.length - 1) * spacing)) * fraction; + buttonBuilder.apply(dialog, option) + .constrain(BOTTOM, relative(dialog.get(BOTTOM), -5)) + .constrain(HEIGHT, literal(14)) + .constrain(LEFT, relative(dialog.get(LEFT), pos).precise()) + .constrain(WIDTH, literal(opWidth).precise()); + pos += opWidth + spacing; + } + + dialog.constrain(TOP, midPoint(gui.get(TOP), gui.get(BOTTOM), () -> -(dialog.ySize() / 2D))); + dialog.constrain(LEFT, midPoint(gui.get(LEFT), gui.get(RIGHT), -(width / 2D))); + return dialog; + } + + private static GuiButton defaultButton(GuiDialog dialog, Option option) { + GuiButton button = new GuiButton(dialog); + + GuiRectangle background = new GuiRectangle(button) + .fill(() -> option.colour.apply(button.isMouseOver())); + Constraints.bind(background, button); + + GuiText text = new GuiText(button, option.text()); + button.setLabel(text); + Constraints.bind(text, button, 0, 2, 0, 2); + + button.onPress(() -> { + if (option.action != null) { + option.action.run(); + } + dialog.close(); + }); + + return button; + } + + public record Option(Component text, @Nullable Runnable action, Function colour) { } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java new file mode 100644 index 00000000..6ac44ea9 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiElement.java @@ -0,0 +1,519 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.colour.ColourARGB; +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.lib.*; +import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import codechicken.lib.math.MathHelper; +import com.google.common.collect.Lists; +import com.mojang.blaze3d.vertex.PoseStack; +import net.covers1624.quack.util.SneakyUtils; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; + +import java.security.InvalidParameterException; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This is the Base class for all gui elements in Modular Gui Version 3. + *

+ * In v2 this vas a massive monolithic class that had way too much crammed into it. + * The primary goals of v3 are the following: + * - Build a new, Extremely flexible system for handling element geometry, including relative positions, anchoring, etc. + * This was archived using the new Geometry system. For details see {@link GuiParent} and {@link ConstrainedGeometry} + * - Implement a system to properly handle element z offsets. + * This was archived by giving all elements a 'depth' property which defines an elements size on the z axis. + * This is then used to properly layer elements and child elements when they are rendered. + * - Switch everything over to the new RenderType system. (This is mostly handled behind the scenes. You don't need to mess with it when creating a GUI) + * - Consolidate all the various rendering helper methods into one convenient utility class. + * The new {@link GuiGraphics} system showed me a good way to implement this. + * - Reduce the amount of ambiguity when building GUIs. (Whether I succeeded here is up for debate xD) + * - Cut out a lot of random bloat that was never used in v2. + *

+ *

+ * Created by brandon3055 on 04/07/2023 + */ +public class GuiElement> extends ConstrainedGeometry implements ElementEvents, TooltipHandler { + + private GuiParent parent; + + private final List> addedQueue = new ArrayList<>(); + private final List> removeQueue = new ArrayList<>(); + private final List> childElements = new ArrayList<>(); + private final List> childElementsUnmodifiable = Collections.unmodifiableList(childElements); + private final Map, Integer> reorderMap = new HashMap<>(); + public boolean initialized = false; + + private Minecraft mc; + private Font font; + private int screenWidth; + private int screenHeight; + + protected int hoverTime = 0; + private int hoverTextDelay = 10; + private boolean isMouseOver = false; + private boolean opaque = false; + private boolean removed = true; + private Supplier enabled = () -> true; + private Supplier enableToolTip = () -> true; + private Supplier> toolTip = null; + private Rectangle renderCull = Rectangle.create(Position.create(0, 0), () -> (double) screenWidth, () -> (double) screenHeight); + + private Consumer jeiDropConsumer = null; + private boolean isJeiExcluded = false; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiElement(GuiParent parent) { + this.parent = parent; + this.parent.addChild(this); + } + + @Override + public GuiParent getParent() { + return parent; + } + + //=== Child Element Handling ===// + + @Override + public List> getChildren() { + return childElementsUnmodifiable; + } + + /** + * In Modular GUI v3, The add child method is primarily for internal use, + * Child elements are automatically added to their parent on construction. + * + * @param child The child element to be added. + */ + @Override + public void addChild(GuiElement child) { + if (!initialized) throw new IllegalStateException("Attempted to add a child to an element before that element has been initialised!"); + if (child == this) throw new InvalidParameterException("Attempted to add element to itself as a child element."); + if (child.getParent() != this) throw new UnsupportedOperationException("Attempted to add an already initialized element to a different parent element."); + if (removeQueue.contains(child)) { + removeQueue.remove(child); + if (!childElements.contains(child)) { + addedQueue.add(child); + } + child.initElement(this); + } else if (!childElements.contains(child)) { + addedQueue.add(child); + child.initElement(this); + } + } + + protected void applyQueuedChildUpdates() { + if (!reorderMap.isEmpty()) { + reorderMap.forEach((element, index) -> { + if (!childElements.contains(element)) return; + childElements.remove(element); + childElements.add(Math.min(index, childElements.size()), element); + }); + reorderMap.clear(); + } + + if (!removeQueue.isEmpty()) { + childElements.removeAll(removeQueue); + removeQueue.clear(); + } + + if (!addedQueue.isEmpty()) { + childElements.addAll(addedQueue); + addedQueue.forEach(ConstrainedGeometry::clearGeometryCache); + addedQueue.clear(); + } + } + + /** + * Called immediately after an element is added to its parent, use to initialize the child element. + */ + public void initElement(GuiParent parent) { + removed = false; + updateScreenData(parent.mc(), parent.font(), parent.scaledScreenWidth(), parent.scaledScreenHeight()); + initialized = true; + } + + @Override + public void adoptChild(GuiElement child) { + child.getParent().removeChild(child); + child.parent = this; + addChild(child); + } + + @Override + public void removeChild(GuiElement child) { + if (childElements.contains(child)) { + child.removed = true; + removeQueue.add(child); + } + addedQueue.remove(child); + } + + /** + * Sets a child as the last element in the child lest, meaning it will render over all other elements. + */ + public void bringChildToForeground(GuiElement child) { + sendChildToIndex(child, childElements.size() - 1); + } + + /** + * sends a child to a specific index in the child lest. + */ + public void sendChildToIndex(GuiElement child, int index) { + reorderMap.put(child, index); + } + + /** + * Sets a child as the first element in the child lest, meaning it will render under all other elements. + */ + public void sendChildToBackground(GuiElement child) { + sendChildToIndex(child, 0); + } + + @Override + public boolean isDescendantOf(GuiElement ancestor) { + return ancestor == parent || parent.isDescendantOf(ancestor); + } + + //=== Minecraft Properties / Initialisation ===// + //TODO I can probably just pass these calls all the way up to the root parent... + + @Override + public Minecraft mc() { + return mc; + } + + @Override + public Font font() { + return font; + } + + @Override + public int scaledScreenWidth() { + return screenWidth; + } + + @Override + public int scaledScreenHeight() { + return screenHeight; + } + + @Override + public ModularGui getModularGui() { + return getParent().getModularGui(); + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + updateScreenData(mc, font, screenWidth, screenHeight); + super.onScreenInit(mc, font, screenWidth, screenHeight); + } + + protected void updateScreenData(Minecraft mc, Font font, int screenWidth, int screenHeight) { + this.mc = mc; + this.font = font; + this.screenWidth = screenWidth; + this.screenHeight = screenHeight; + } + + //=== Element Status ===// + + public T setEnabled(boolean enabled) { + this.enabled = () -> enabled; + return SneakyUtils.unsafeCast(this); + } + + public T setEnabled(@Nullable Supplier enabled) { + this.enabled = enabled; + return SneakyUtils.unsafeCast(this); + } + + public boolean isEnabled() { + return !removed && enabled.get(); + } + + public boolean isRemoved() { + return removed; + } + + public T setEnableToolTip(Supplier enableToolTip) { + this.enableToolTip = enableToolTip; + return SneakyUtils.unsafeCast(this); + } + + public boolean isTooltipEnabled() { + return enableToolTip.get(); + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return getParent().blockMouseOver(element, mouseX, mouseY); + } + + @Override + public boolean blockMouseEvents() { + return isMouseOver() && isOpaque(); + } + + /** + * @return True if the cursor is within the bounds of this element, and there is no opaque element above this one obstructing the cursor. + */ + public boolean isMouseOver() { + return isMouseOver; + } + + public boolean isOpaque() { + return opaque; + } + + /** + * If an element is marked as opaque it will consume mouseOver updates, thereby preventing elements bellow from accepting mouseOver input. + * Also prevents mouse events within this element from being passed to elements bellow. + */ + public T setOpaque(boolean opaque) { + this.opaque = opaque; + return SneakyUtils.unsafeCast(this); + } + + /** + * @return the amount of time the cursor has spent inside this element's bounds, + * resets to zero when the cursor leaves this element's bounds. + */ + public int hoverTime() { + return hoverTime; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{" + + "geometry=" + getRectangle() + + '}'; + } + + //=== Render / Update ===// + + /** + * Any child elements completely outside this rectangle will not be rendered at all. + * By default, this is set to the screen bounds (meaning the minecraft window) + * Setting this to null will disable culling. + */ + public T setRenderCull(@Nullable Rectangle renderCull) { + this.renderCull = renderCull; + return SneakyUtils.unsafeCast(this); + } + + /** + * This is the main render method that handles rendering this element and any child elements it may have. + * This method almost never needs to be overridden, instead when creating custom elements with custom rendering, + * your element should implement {@link BackgroundRender} and / or {@link ForegroundRender} in or order to implement + * its rendering. + *

+ * Note: After the render is complete, the poseStack's z pos will be offset by the total depth of this element and its children. + * This is intended behavior, + * + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param partialTicks Partial render ticks + */ + public void render(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + applyQueuedChildUpdates(); + if (this instanceof BackgroundRender bgr) { + bgr.renderBehind(graphics, mouseX, mouseY, partialTicks); + } + + for (GuiElement child : childElements) { + if (child.isEnabled()) { + renderChild(child, graphics, mouseX, mouseY, partialTicks); + } + } + + if (this instanceof ForegroundRender fgr) { + fgr.renderInFront(graphics, mouseX, mouseY, partialTicks); + } + } + + protected boolean renderChild(GuiElement child, GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + if (renderCull != null && !renderCull.intersects(child.getRectangle())) return false; + child.render(graphics, mouseX, mouseY, partialTicks); + return true; + } + + /** + * Used to render overlay's such as hover text. Anything rendered in this method will be rendered on top of everything else on the screen. + * Only one overlay should be rendered at a time, When an element renders content via the overlay method it must return true to indicate the render call has been 'consumed' + * If the render call has already been consumed (Check via the consumed boolean) then this element should avoid rendering its overlay. + *

+ * When rendering overlay content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * This stack will already have the correct Z translation to ensure the overlay renders above everything else on the screen. + *

+ * To check if the cursor is over this element, use 'render.hoveredElement() == this' + * {@link #isMouseOver()} Will also work, but may be problematic when multiple, stacked elements have overlay content. + * + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + * @param partialTicks Partial render ticks + * @param consumed Will be true if the overlay render call has already been consumed by another element. + * @return true if the render call has been consumed. + */ + public boolean renderOverlay(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.renderOverlay(graphics, mouseX, mouseY, partialTicks, consumed); + } + } + return consumed || (showToolTip() && renderTooltip(graphics, Minecraft.getInstance().font, mouseX, mouseY)); + } + + /** + * @return true if all conditions are bet for this element to be rendering its tool tip. + * Meaning mouse is over the element, hover time has elapsed and tooltip is enabled. + */ + public boolean showToolTip() { + return isMouseOver() && isTooltipEnabled() && hoverTime() >= getTooltipDelay(); + } + + /** + * Called every tick to update the element. Note this is called regardless of weather or not the element is actually enabled. + * + * @param mouseX Current mouse X position + * @param mouseY Current mouse Y position + */ + public void tick(double mouseX, double mouseY) { + if (isMouseOver()) { + hoverTime++; + } else { + hoverTime = 0; + } + + for (GuiElement childElement : childElements) { + childElement.tick(mouseX, mouseY); + } + } + + /** + * Called at the start of each tick to update the 'mouseOver' state of each element. + * If the cursor is over an element that is marked as opaque, the update will be consumed. + * This ensures no elements below the opaque element will have their mouseOver flag set to true. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param consumed True if mouseover event has been consumed. + * @return true if this event has been consumed. + */ + public boolean updateMouseOver(double mouseX, double mouseY, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.updateMouseOver(mouseX, mouseY, consumed); + } + } + + isMouseOver = !consumed && MathHelper.isInRect(xMin(), yMin(), xSize(), ySize(), mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY); + return consumed || (isMouseOver && isOpaque()); + } + + //=== Hover Text ===// + + @Override + public Supplier> getTooltip() { + return toolTip; + } + + @Override + public T setTooltipDelay(int tooltipDelay) { + this.hoverTextDelay = tooltipDelay; + return SneakyUtils.unsafeCast(this); + } + + @Override + public int getTooltipDelay() { + return hoverTextDelay; + } + + @Override + public T setTooltip(@Nullable Supplier> tooltip) { + this.toolTip = tooltip; + return SneakyUtils.unsafeCast(this); + } + + //=== JEI Integration ===// + + /** + * Add this element to the list of jei exclusions. + * Use this for any elements that render outside the normal gui bounds. + * This will ensure JEI does not try to render on top of these elements. + */ + public T jeiExclude() { + isJeiExcluded = true; + return SneakyUtils.unsafeCast(this); + } + + public T setJeiExcluded(boolean jeiExcluded) { + isJeiExcluded = jeiExcluded; + return SneakyUtils.unsafeCast(this); + } + + public boolean isJeiExcluded() { + return isJeiExcluded; + } + + /** + * Allows you get notified when a player drags and drops an ItemStack from jai onto this element. + * If using the standard highlight then you should call this after adding any other required child elements to ensure the highlight is on top. + */ + public T setJeiDropTarget(Consumer onDrop, boolean installStandardHighlight) { + jeiDropConsumer = onDrop; + if (installStandardHighlight) { + GuiRectangle highlight = new GuiRectangle(this) + .setEnabled(() -> getModularGui().getJeiHighlightTime() > 0) + .fill(() -> ColourARGB.packARGB(0, 0xFF, 0, Math.min(getModularGui().getJeiHighlightTime() * 2, 0x50))); + Constraints.bind(highlight, this); + } + return SneakyUtils.unsafeCast(this); + } + + public Consumer getJeiDropConsumer() { + return jeiDropConsumer; + } + + public boolean isJeiDropTarget() { + return jeiDropConsumer != null; + } + + public List> addJeiExclusions(List> list) { + if (isJeiExcluded()) { + list.add(this); + } + for (GuiElement child : childElements) { + if (child.isEnabled()) { + child.addJeiExclusions(list); + } + } + return list; + } + + public List> addJeiDropTargets(List> list) { + if (isJeiDropTarget()) { + list.add(this); + } + for (GuiElement child : childElements) { + if (child.isEnabled()) { + child.addJeiDropTargets(list); + } + } + return list; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java new file mode 100644 index 00000000..1e8f5ec6 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEnergyBar.java @@ -0,0 +1,143 @@ +//package codechicken.lib.gui.modular.elements; +// +//import codechicken.lib.gui.modular.lib.BackgroundRender; +//import codechicken.lib.gui.modular.lib.Constraints; +//import codechicken.lib.gui.modular.lib.geometry.GuiParent; +//import codechicken.lib.gui.modular.sprite.GuiTextures; +//import codechicken.lib.gui.modular.sprite.SpriteSupplier; +//import codechicken.lib.util.FormatUtil; +//import net.minecraft.client.Minecraft; +//import net.minecraft.client.gui.GuiGraphics; +//import net.minecraft.network.chat.Component; +// +//import java.text.DecimalFormat; +//import java.text.DecimalFormatSymbols; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Locale; +//import java.util.function.BiFunction; +//import java.util.function.Supplier; +// +//import static net.minecraft.ChatFormatting.*; +// +///** +// * Created by brandon3055 on 10/09/2023 +// */ +//public class GuiEnergyBar extends GuiElement implements BackgroundRender { +// +// public static final DecimalFormat COMMA_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); +// public static final SpriteSupplier EMPTY = GuiTextures.CCL.get("widgets/energy_empty"); +// public static final SpriteSupplier FULL = GuiTextures.CCL.get("widgets/energy_full"); +// +// private Supplier energy = () -> 0L; +// private Supplier capacity = () -> 0L; +// private SpriteSupplier emptyTexture = EMPTY; +// private SpriteSupplier fullTexture = FULL; +// private BiFunction> toolTipFormatter; +// +// public GuiEnergyBar(GuiParent parent) { +// super(parent); +// setTooltipDelay(0); +// setToolTipFormatter(defaultFormatter()); +// } +// +// /** +// * Creates a simple energy bar using a simple slot as a background to make it look nice. +// */ +// public static EnergyBar simpleBar(GuiParent parent) { +// GuiRectangle container = GuiRectangle.vanillaSlot(parent); +// GuiEnergyBar energyBar = new GuiEnergyBar(container); +// Constraints.bind(energyBar, container, 1); +// return new EnergyBar(container, energyBar); +// } +// +// public static BiFunction> defaultFormatter() { +// return (energy, capacity) -> { +// List tooltip = new ArrayList<>(); +// tooltip.add(Component.translatable("ccl.energy_bar.energy_storage").withStyle(DARK_AQUA)); +// boolean shift = Minecraft.getInstance().hasShiftDown(); +// tooltip.add(Component.translatable("ccl.energy_bar.capacity") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(shift ? FormatUtil.addCommas(capacity) : FormatUtil.formatNumber(capacity)) +// .withStyle(GRAY) +// .append(" ") +// .append(Component.translatable("ccl.energy_bar.rf") +// .withStyle(GRAY) +// ) +// ) +// ); +// tooltip.add(Component.translatable("ccl.energy_bar.stored") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(shift ? FormatUtil.addCommas(energy) : FormatUtil.formatNumber(energy)) +// .withStyle(GRAY) +// ) +// .append(" ") +// .append(Component.translatable("ccl.energy_bar.rf") +// .withStyle(GRAY) +// ) +// .append(Component.literal(String.format(" (%.2f%%)", ((double) energy / (double) capacity) * 100D)) +// .withStyle(GRAY) +// ) +// ); +// return tooltip; +// }; +// } +// +// public GuiEnergyBar setEmptyTexture(SpriteSupplier emptyTexture) { +// this.emptyTexture = emptyTexture; +// return this; +// } +// +// public GuiEnergyBar setFullTexture(SpriteSupplier fullTexture) { +// this.fullTexture = fullTexture; +// return this; +// } +// +// public GuiEnergyBar setCapacity(long capacity) { +// return setCapacity(() -> capacity); +// } +// +// public GuiEnergyBar setCapacity(Supplier capacity) { +// this.capacity = capacity; +// return this; +// } +// +// public GuiEnergyBar setEnergy(long energy) { +// return setEnergy(() -> energy); +// } +// +// public GuiEnergyBar setEnergy(Supplier energy) { +// this.energy = energy; +// return this; +// } +// +// public long getEnergy() { +// return energy.get(); +// } +// +// public long getCapacity() { +// return capacity.get(); +// } +// +// /** +// * Install a custom formatter to control how the energy tool tip renders. +// */ +// public GuiEnergyBar setToolTipFormatter(BiFunction> toolTipFormatter) { +// this.toolTipFormatter = toolTipFormatter; +// setTooltip(() -> this.toolTipFormatter.apply(getEnergy(), getCapacity())); +// return this; +// } +// +// @Override +// public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { +// float p = 1 / 128F; +// float height = getCapacity() <= 0 ? 0 : (float) ySize() * (getEnergy() / (float) getCapacity()); +// float texHeight = height * p; +// graphics.partialSprite(EMPTY.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), EMPTY.sprite(), 0F, 1F - (p * (float) ySize()), p * (float) xSize(), 1F, 0xFFFFFFFF); +// graphics.partialSprite(FULL.renderType(GuiRender::texColType), xMin(), yMin() + (ySize() - height), xMax(), yMax(), FULL.sprite(), 0F, 1F - texHeight, p * (float) xSize(), 1F, 0xFFFFFFFF); +// } +// +// public record EnergyBar(GuiRectangle container, GuiEnergyBar bar) { } +//} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java new file mode 100644 index 00000000..b4eeee2c --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEntityRenderer.java @@ -0,0 +1,202 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import codechicken.lib.render.CCRenderEventHandler; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.InventoryScreen; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.LivingEntity; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 15/11/2023 + */ +public class GuiEntityRenderer extends GuiElement implements BackgroundRender { + + public static final Logger LOGGER = LogManager.getLogger(); + private static final Map entityCache = new HashMap<>(); + private static final List invalidEntities = new ArrayList<>(); + + private Supplier rotationSpeed = () -> 1F; + private Supplier lockedRotation = () -> 0F; + private @Nullable Entity entity; + private @Nullable Identifier entityName; + private boolean invalidEntity = false; + private Supplier rotationLocked = () -> false; + private Supplier trackMouse = () -> false; + private Supplier drawName = () -> false; + public boolean force2dSize = false; + + public GuiEntityRenderer(GuiParent parent) { + super(parent); + } + + public GuiEntityRenderer setEntity(Entity entity) { + this.entity = entity; + if (this.entity == null) { + invalidEntity = true; + return this; + } + + this.entityName = BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()); + invalidEntity = invalidEntities.contains(entityName); + return this; + } + + public GuiEntityRenderer setEntity(Identifier entity) { + this.entityName = entity; + this.entity = entityCache.computeIfAbsent(entity, resourceLocation -> { + EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(entity); + return type.create(mc().level, EntitySpawnReason.SPAWNER); + }); + + invalidEntity = this.entity == null; + if (invalidEntities.contains(entityName)) { + invalidEntity = true; + } + + return this; + } + + public GuiEntityRenderer setRotationSpeed(float rotationSpeed) { + this.rotationSpeed = () -> rotationSpeed; + return this; + } + + public GuiEntityRenderer setRotationSpeed(Supplier rotationSpeed) { + this.rotationSpeed = rotationSpeed; + return this; + } + + public float getRotationSpeed() { + return rotationSpeed.get(); + } + + public GuiEntityRenderer setLockedRotation(float lockedRotation) { + this.lockedRotation = () -> lockedRotation; + return this; + } + + public GuiEntityRenderer setLockedRotation(Supplier lockedRotation) { + this.lockedRotation = lockedRotation; + return this; + } + + public float getLockedRotation() { + return lockedRotation.get(); + } + + public GuiEntityRenderer setRotationLocked(boolean rotationLocked) { + this.rotationLocked = () -> rotationLocked; + return this; + } + + public GuiEntityRenderer setRotationLocked(Supplier rotationLocked) { + this.rotationLocked = rotationLocked; + return this; + } + + public boolean isRotationLocked() { + return rotationLocked.get(); + } + + public GuiEntityRenderer setTrackMouse(boolean trackMouse) { + this.trackMouse = () -> trackMouse; + return this; + } + + public GuiEntityRenderer setTrackMouse(Supplier trackMouse) { + this.trackMouse = trackMouse; + return this; + } + + public boolean isTrackMouse() { + return trackMouse.get(); + } + + public GuiEntityRenderer setDrawName(boolean drawName) { + this.drawName = () -> drawName; + return this; + } + + public GuiEntityRenderer setDrawName(Supplier drawName) { + this.drawName = drawName; + return this; + } + + public boolean isDrawName() { + return drawName.get(); + } + + public GuiEntityRenderer setForce2dSize(boolean force2dSize) { + this.force2dSize = force2dSize; + return this; + } + + @Override + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + if (invalidEntity) return; + + try { + if (entity != null) { + Rectangle rect = getRectangle(); + float scale = (float) (force2dSize ? (Math.min(rect.height() / entity.getBbHeight(), rect.width() / entity.getBbWidth())) : rect.height() / entity.getBbHeight()); + float xPos = (float) (rect.x() + (rect.width() / 2D)); + float yPos = (float) ((yMin() + (ySize() / 2)) + (rect.height() / 2)); + float rotation = rotationLocked.get() ? lockedRotation.get() : (CCRenderEventHandler.renderTime + partialTicks) * rotationSpeed.get(); + if (entity instanceof LivingEntity living) { + int eyeOffset = (int) ((entity.getEyeHeight()) * scale); + if (trackMouse.get()) { + InventoryScreen.renderEntityInInventoryFollowsMouse( + graphics, + (int) rect.x(), (int) rect.y(), + (int) rect.xMax(), (int) rect.yMax(), + (int) scale, + 0f, + (float) mouseX, + (float) mouseY - eyeOffset, + living + ); + } else { + // TODO always tracks mouse for now, need math + InventoryScreen.renderEntityInInventoryFollowsMouse( + graphics, + (int) rect.x(), (int) rect.y(), + (int) rect.xMax(), (int) rect.yMax(), + (int) scale, + 0f, + (float) mouseX, + (float) mouseY - eyeOffset, + living + ); + } + } else { + // TODO not supported without custom submit. +// Quaternionf quaternionf = new Quaternionf().rotateZ((float) Math.PI); +// Quaternionf quaternionf1 = Axis.YP.rotationDegrees(rotation); +// quaternionf.mul(quaternionf1); +// renderEntityInInventory(graphics, xPos, yPos, scale, force2dSize, quaternionf, quaternionf1, entity); + } + } + } catch (Throwable e) { + invalidEntity = true; + invalidEntities.add(entityName); + LOGGER.error("Failed to render entity in GUI. This is not a bug there are just some entities that can not be rendered like this."); + LOGGER.error("Entity: {}", entity, e); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java new file mode 100644 index 00000000..59368659 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiEventProvider.java @@ -0,0 +1,133 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +/** + * Created by brandon3055 on 15/11/2023 + */ +public class GuiEventProvider extends GuiElement { + + private boolean ignoreConsumed = false; + private final List> clickListeners = new ArrayList<>(); + private final List> releaseListeners = new ArrayList<>(); + private final List movedListeners = new ArrayList<>(); + private final List scrollListeners = new ArrayList<>(); + private final List> keyPressListeners = new ArrayList<>(); + private final List> keyReleaseListeners = new ArrayList<>(); + private final List> charTypedListeners = new ArrayList<>(); + + public GuiEventProvider(GuiParent parent) { + super(parent); + } + + public GuiEventProvider setIgnoreConsumed(boolean ignoreConsumed) { + this.ignoreConsumed = ignoreConsumed; + return this; + } + + public GuiEventProvider onMouseClick(Consumer listener) { + clickListeners.add(listener); + return this; + } + + public GuiEventProvider onMouseRelease(Consumer listener) { + releaseListeners.add(listener); + return this; + } + + public GuiEventProvider onMouseMove(MouseMoveListener listener) { + movedListeners.add(listener); + return this; + } + + public GuiEventProvider onScroll(ScrollListener listener) { + scrollListeners.add(listener); + return this; + } + + public GuiEventProvider onKeyPress(Consumer listener) { + keyPressListeners.add(listener); + return this; + } + + public GuiEventProvider onKeyRelease(Consumer listener) { + keyReleaseListeners.add(listener); + return this; + } + + public GuiEventProvider onCharTyped(Consumer listener) { + charTypedListeners.add(listener); + return this; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + if (ignoreConsumed || !consumed) { + clickListeners.forEach(e -> e.accept(event)); + } + return super.mouseClicked(event, consumed); + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + if (ignoreConsumed || !consumed) { + releaseListeners.forEach(e -> e.accept(event)); + } + return super.mouseReleased(event, consumed); + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + movedListeners.forEach(e -> e.onMoved(mouseX, mouseY)); + super.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, boolean consumed) { + if (ignoreConsumed || !consumed) { + scrollListeners.forEach(e -> e.onScrolled(mouseX, mouseY, scrollX, scrollY)); + } + return super.mouseScrolled(mouseX, mouseY, scrollX, scrollY, consumed); + } + + @Override + public boolean keyPressed(KeyEvent event, boolean consumed) { + if (ignoreConsumed || !consumed) { + keyPressListeners.forEach(e -> e.accept(event)); + } + return super.keyPressed(event, consumed); + } + + @Override + public boolean keyReleased(KeyEvent event, boolean consumed) { + if (ignoreConsumed || !consumed) { + keyReleaseListeners.forEach(e -> e.accept(event)); + } + return super.keyReleased(event, consumed); + } + + @Override + public boolean charTyped(CharacterEvent event, boolean consumed) { + if (ignoreConsumed || !consumed) { + charTypedListeners.forEach(e -> e.accept(event)); + } + return super.charTyped(event, consumed); + } + + public interface MouseMoveListener { + + void onMoved(double mouseX, double mouseY); + } + + public interface ScrollListener { + + void onScrolled(double mouseX, double mouseY, double scrollX, double scrollY); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java new file mode 100644 index 00000000..46b58f06 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiFluidTank.java @@ -0,0 +1,251 @@ +//package codechicken.lib.gui.modular.elements; +// +//import codechicken.lib.gui.modular.lib.BackgroundRender; +//import codechicken.lib.gui.modular.lib.Constraints; +//import codechicken.lib.gui.modular.lib.geometry.GuiParent; +//import codechicken.lib.gui.modular.sprite.GuiTextures; +//import codechicken.lib.gui.modular.sprite.SpriteSupplier; +//import codechicken.lib.util.FormatUtil; +//import net.minecraft.client.Minecraft; +//import net.minecraft.client.gui.GuiGraphics; +//import net.minecraft.client.renderer.texture.TextureAtlasSprite; +//import net.minecraft.network.chat.Component; +//import net.minecraft.network.chat.Style; +//import net.minecraft.resources.ResourceLocation; +//import net.minecraft.world.level.material.Fluid; +//import net.minecraft.world.level.material.Fluids; +//import net.neoforged.neoforge.client.ClientHooks; +//import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +//import net.neoforged.neoforge.fluids.FluidStack; +//import org.jetbrains.annotations.Nullable; +// +//import java.util.ArrayList; +//import java.util.List; +//import java.util.function.BiFunction; +//import java.util.function.Supplier; +// +//import static net.minecraft.ChatFormatting.*; +// +///** +// * When implementing this tank, you must specify the tank capacity in mb, +// * And then you have two options for specifying the tank contents. +// * You can set the fluid and the amount stored, +// * Or you can provide a {@link FluidStack} +// *

+// * Created by brandon3055 on 11/09/2023 +// */ +//public class GuiFluidTank extends GuiElement implements BackgroundRender { +// +// //TODO make a better texture, This feels a little too.. cluttered. +// public static final SpriteSupplier DEFAULT_WINDOW = GuiTextures.CCL.get("widgets/tank_window"); +// +// private int gaugeColour = 0xFF909090; +// private boolean drawGauge = true; +// private SpriteSupplier window = SpriteSupplier.EMPTY; +// private Supplier capacity = () -> 10000L; +// private Supplier fluidStack = () -> FluidStack.EMPTY; +// +// private BiFunction> toolTipFormatter; +// +// public GuiFluidTank(GuiParent parent) { +// super(parent); +// setTooltipDelay(0); +// setToolTipFormatter(defaultFormatter()); +// } +// +// /** +// * Creates a simple tank using a simple slot as a background to make it look nice. +// */ +// public static FluidTank simpleTank(GuiParent parent) { +// GuiRectangle container = GuiRectangle.vanillaSlot(parent); +// GuiFluidTank energyBar = new GuiFluidTank(container); +// Constraints.bind(energyBar, container, 1); +// return new FluidTank(container, energyBar); +// } +// +// /** +// * Sets the capacity of this tank in milli-buckets. +// */ +// public GuiFluidTank setCapacity(long capacity) { +// return setCapacity(() -> capacity); +// } +// +// /** +// * Supply the capacity of this tank in milli-buckets. +// */ +// public GuiFluidTank setCapacity(Supplier capacity) { +// this.capacity = capacity; +// return this; +// } +// +// /** +// * Allows you to set the current stored fluid stack. +// */ +// public GuiFluidTank setFluidStack(FluidStack fluidStack) { +// return setFluidStack(() -> fluidStack); +// } +// +// /** +// * Allows you to supply the current stored fluid stack. +// */ +// public GuiFluidTank setFluidStack(Supplier fluidStack) { +// this.fluidStack = fluidStack; +// return this; +// } +// +// /** +// * Install a custom formatter to control how the fluid tool tip renders. +// */ +// public GuiFluidTank setToolTipFormatter(BiFunction> toolTipFormatter) { +// this.toolTipFormatter = toolTipFormatter; +// setTooltip(() -> this.toolTipFormatter.apply(getFluidStack(), getCapacity())); +// return this; +// } +// +// /** +// * Sets the tank window texture, Will be tiled to fit the tank size. +// * +// * @param window New window texture or null for no window texture. +// */ +// public GuiFluidTank setWindow(SpriteSupplier window) { +// this.window = window; +// return this; +// } +// +// /** +// * Enable the built-in fluid gauge lines. +// */ +// public GuiFluidTank setDrawGauge(boolean drawGauge) { +// this.drawGauge = drawGauge; +// return this; +// } +// +// /** +// * Sets the colour of the built-in fluid gauge lines +// */ +// public GuiFluidTank setGaugeColour(int gaugeColour) { +// this.gaugeColour = gaugeColour; +// return this; +// } +// +// public Long getCapacity() { +// return capacity.get(); +// } +// +// public FluidStack getFluidStack() { +// return fluidStack.get(); +// } +// +// @Override +// public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { +// FluidStack stack = getFluidStack(); +// var fluidStill = getStillTexture(stack); +// +// if (!stack.isEmpty() && fluidStill != null) { +// int fluidColor = getColour(stack); +// float height = getCapacity() <= 0 ? 0 : (float) ySize() * (stack.getAmount() / (float) getCapacity()); +// graphics.tileSprite(fluidStill.renderType(GuiRender::texColType), xMin(), yMax() - height, xMax(), yMax(), fluidStill, fluidColor); +// } +// window.ifPresent(icon -> { +// graphics.tileSprite(window.renderType(GuiRender::texColType), xMin(), yMin(), xMax(), yMax(), icon, 0xFFFFFFFF); +// }); +// +// gaugeColour = 0xFF000000; +// if (drawGauge) { +// double spacing = computeGaugeSpacing(); +// if (spacing == 0) return; +// +// double pos = spacing; +// while (pos + 1 < ySize()) { +// double width = xSize() / 4; +// double yPos = yMax() - 1 - pos; +// graphics.cc$fill(xMax() - width, yPos, xMax(), yPos + 1, gaugeColour); +// pos += spacing; +// } +// } +// } +// +// private double computeGaugeSpacing() { +// double ySize = ySize(); +// double capacity = getCapacity(); +// if (ySize / (capacity / 100D) > 3) return ySize / (capacity / 100D); +// if (ySize / (capacity / 500D) > 3) return ySize / (capacity / 500D); +// if (ySize / (capacity / 1000D) > 3) return ySize / (capacity / 1000D); +// if (ySize / (capacity / 5000D) > 3) return ySize / (capacity / 5000D); +// if (ySize / (capacity / 10000D) > 3) return ySize / (capacity / 10000D); +// if (ySize / (capacity / 50000D) > 3) return ySize / (capacity / 50000D); +// if (ySize / (capacity / 100000D) > 3) return ySize / (capacity / 100000D); +// return 0; +// } +// +// public static BiFunction> defaultFormatter() { +// return (fluidStack, capacity) -> { +// List tooltip = new ArrayList<>(); +// tooltip.add(Component.translatable("ccl.fluid_tank.fluid_storage").withStyle(DARK_AQUA)); +// if (!fluidStack.isEmpty()) { +// tooltip.add(Component.translatable("ccl.fluid_tank.contains") +// .withStyle(GOLD) +// .append(" ") +// .append(fluidStack.getHoverName().copy() +// .setStyle(Style.EMPTY +// .withColor(getColour(fluidStack)) +// ) +// ) +// ); +// } +// +// tooltip.add(Component.translatable("ccl.fluid_tank.capacity") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(FormatUtil.addCommas(capacity)) +// .withStyle(GRAY) +// .append(" ") +// .append(Component.translatable("ccl.fluid_tank.mb") +// .withStyle(GRAY) +// ) +// ) +// ); +// tooltip.add(Component.translatable("ccl.fluid_tank.stored") +// .withStyle(GOLD) +// .append(" ") +// .append(Component.literal(FormatUtil.addCommas(fluidStack.getAmount())) +// .withStyle(GRAY) +// ) +// .append(" ") +// .append(Component.translatable("ccl.fluid_tank.mb") +// .withStyle(GRAY) +// ) +// .append(Component.literal(String.format(" (%.2f%%)", ((double) fluidStack.getAmount() / (double) capacity) * 100D)) +// .withStyle(GRAY) +// ) +// ); +// return tooltip; +// }; +// } +// +// //TODO These could maybe go in FluidUtils? but they are client side only so... +// +// public static int getColour(FluidStack fluidStack) { +// return fluidStack.getFluid() == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluidStack.getFluid()).getTintColor(fluidStack); +// } +// +// public static int getColour(Fluid fluid) { +// return fluid == Fluids.EMPTY ? -1 : IClientFluidTypeExtensions.of(fluid).getTintColor(); +// } +// +// @Nullable +// public static TextureAtlasSprite getStillTexture(FluidStack stack) { +// if (stack.getFluid() == Fluids.EMPTY) return null; +// ResourceLocation texture = IClientFluidTypeExtensions.of(stack.getFluid()).getStillTexture(stack); +// return Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(texture)); +// } +// +// @Nullable +// public static TextureAtlasSprite getStillTexture(Fluid fluid) { +// if (fluid == Fluids.EMPTY) return null; +// ResourceLocation texture = IClientFluidTypeExtensions.of(fluid).getStillTexture(); +// return Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(texture)); +// } +// +// public record FluidTank(GuiRectangle container, GuiFluidTank tank) { } +//} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java new file mode 100644 index 00000000..80235694 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiItemStack.java @@ -0,0 +1,125 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.component.DataComponents; +import net.minecraft.world.item.ItemStack; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.HEIGHT; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.WIDTH; + +/** + * A simple gui element that renders an item stack. + * This width and height of this element should be constrained to the same value, + * The stack size is based on the element size. + * constrain size to 16x16 for the standard gui stack size. + *

+ * Created by brandon3055 on 03/09/2023 + */ +public class GuiItemStack extends GuiElement implements BackgroundRender { + private Supplier stack; + private Supplier decorate = () -> true; + private Supplier toolTip = () -> true; + + public GuiItemStack(GuiParent parent) { + this(parent, () -> ItemStack.EMPTY); + } + + public GuiItemStack(GuiParent parent, ItemStack itemStack) { + super(parent); + setStack(itemStack); + } + + public GuiItemStack(GuiParent parent, Supplier provider) { + super(parent); + setStack(provider); + } + + public GuiItemStack setStack(Supplier stackProvider) { + this.stack = stackProvider; + return this; + } + + public GuiItemStack setStack(ItemStack stack) { + this.stack = () -> stack; + return this; + } + + /** + * Enable item stack decorations. + * Meaning, Damage bar, Stack size, Item cool down, etc. (Default Enabled) + */ + public GuiItemStack enableStackDecoration(boolean enableDecoration) { + return enableStackDecoration(() -> enableDecoration); + } + + /** + * Enable item stack decorations. + * Meaning, Damage bar, Stack size, Item cool down, etc. (Default Enabled) + */ + public GuiItemStack enableStackDecoration(Supplier enableDecoration) { + this.decorate = enableDecoration; + return this; + } + + /** + * Enable the default item stack tooltip. (Default Enabled) + * Note: If the {@link GuiItemStack} element has a tooltip applied via one of the element #setTooltip methods, + * That will override the item stack tool tip. + */ + public GuiItemStack enableStackToolTip(boolean enableToolTip) { + return enableStackToolTip(() -> enableToolTip); + } + + /** + * Enable the default item stack tooltip. (Default Enabled) + * Note: If the {@link GuiItemStack} element has a tooltip applied via one of the element #setTooltip methods, + * That will override the item stack tool tip. + */ + public GuiItemStack enableStackToolTip(Supplier enableToolTip) { + this.toolTip = enableToolTip; + return this; + } + + //=== Internal methods ===// + + private double getStackSize() { + return Math.max(getValue(WIDTH), getValue(HEIGHT)); + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + ItemStack stack = this.stack.get(); + if (stack.isEmpty()) return; + + // TODO size needs to be applied via pose transform + render.cc$renderItem(stack, xMin(), yMin(), (int) (xMin() + (xSize() * yMin()))); + if (decorate.get()) { + render.cc$renderItemDecorations(Minecraft.getInstance().font, stack, xMin(), yMin()); + } + } + + @Override + public boolean renderOverlay(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks, boolean consumed) { + if (super.renderOverlay(graphics, mouseX, mouseY, partialTicks, consumed)) return true; + var stack = this.stack.get(); + if (isMouseOver() && !stack.isEmpty() && toolTip.get()) { + graphics.setTooltipForNextFrame( + font(), + Screen.getTooltipFromItem(Minecraft.getInstance(), stack), + stack.getTooltipImage(), + stack, + (int) mouseX, + (int) mouseY, + stack.get(DataComponents.TOOLTIP_STYLE) + ); + return true; + } + return false; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java new file mode 100644 index 00000000..44158abc --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiList.java @@ -0,0 +1,232 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.SliderState; +import codechicken.lib.gui.modular.lib.geometry.*; +import codechicken.lib.math.MathHelper; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; + +import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Predicate; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * GuiList, as the name suggests allows you to display a list of objects. + * The list type can be whatever you want, and you can install a converter to + * map list objects to elements for display. + *

+ * The default converter simply displays the toString() value of the object. + *

+ * Element width will be fixed to the width of the GuiList, element height can be whatever you want. + *

+ * Note on adding child elements to this: + * If any child elements extend beyond the bounds of this element, that part will be culled. + * Also, child elements will always end up bellow the list items when the list is updated. + *

+ * Created by brandon3055 on 21/09/2023 + */ +public class GuiList extends GuiElement> { + + /** + * This is made available primarily for debugging purposes where it can be useful to see what's going on behind the scenes. + */ + public boolean enableScissor = true; + private double yScrollPos = 0; + private double lastWidth = 0; + private double contentHeight = 0; + private double itemSpacing = 1; + private boolean rebuild = true; + private GuiSlider hiddenBar = null; + + private final List listContent = new ArrayList<>(); + private final Map> elementMap = new HashMap<>(); + private final LinkedList> visible = new LinkedList<>(); + private Predicate filter = e -> true; + + private BiFunction, E, ? extends GuiElement> displayBuilder = (parent, e) -> { + GuiText text = new GuiText(parent, () -> Component.literal(String.valueOf(e))).setWrap(true); + text.constrain(GeoParam.HEIGHT, Constraint.dynamic(() -> (double) font().wordWrapHeight(text.getText(), (int) text.xSize()))); + return text; + }; + + public GuiList(GuiParent parent) { + super(parent); + this.setRenderCull(getRectangle()); + } + + public boolean add(E e) { + rebuild = true; + return listContent.add(e); + } + + public boolean remove(E e) { + rebuild = true; + return listContent.remove(e); + } + + /** + * You are allowed to modify this list directly, but if you do you must call + * {@link #markDirty()} otherwise the display elements will not get updated. + */ + public List getList() { + return listContent; + } + + public void markDirty() { + this.rebuild = true; + } + + public GuiList setDisplayBuilder(BiFunction, E, ? extends GuiElement> displayBuilder) { + this.displayBuilder = displayBuilder; + return this; + } + + public GuiList setFilter(Predicate filter) { + this.filter = filter; + return this; + } + + public GuiList setItemSpacing(double itemSpacing) { + this.itemSpacing = itemSpacing; + return this; + } + + public SliderState scrollState() { + return SliderState.forScrollBar(() -> yScrollPos, e -> { + yScrollPos = e; + updateVisible(); + }, () -> MathHelper.clip(ySize() / contentHeight, 0, 1)); + } + + /** + * You can choose to attach a scroll bar to this element the same way you would a {@link GuiScrolling} + * But sometimes you just want to be able to mouse-wheel scroll without an actual scroll bar. + *

+ * This method will add a hidden scroll bar to enable mouse wheel scrolling and middle-click dragging without the need for an actual scroll bar. + * The scroll bar will be an invisible zero width element on the right side of this list. + */ + public GuiList addHiddenScrollBar() { + if (hiddenBar != null) removeChild(hiddenBar); + hiddenBar = new GuiSlider(this, Axis.Y) + .setSliderState(scrollState()) + .setScrollableElement(this) + .constrain(TOP, match(get(TOP))) + .constrain(LEFT, relative(get(RIGHT), -5)) + .constrain(BOTTOM, match(get(BOTTOM))) + .constrain(RIGHT, match(get(RIGHT))); + return this; + } + + public GuiList removeHiddenScrollBar() { + if (hiddenBar != null) removeChild(hiddenBar); + return this; + } + + //=== Internal Logic ===// + + public double hiddenSize() { + return Math.max(contentHeight - ySize(), 0); + } + + @Override + public void tick(double mouseX, double mouseY) { + if (lastWidth != xSize()) { + lastWidth = xSize(); + markDirty(); + } + if (rebuild) { + rebuildElements(); + } + super.tick(mouseX, mouseY); + } + + public void rebuildElements() { + elementMap.values().forEach(this::removeChild); + elementMap.clear(); + + for (E item : listContent) { + if (!filter.test(item)) continue; + GuiElement next = displayBuilder.apply(this, item); + next.constrain(LEFT, match(get(LEFT))); + next.constrain(RIGHT, match(get(RIGHT))); + removeChild(next); + elementMap.put(item, next); + } + rebuild = false; + updateVisible(); + } + + public Map> getElementMap() { + return elementMap; + } + + public void scrollTo(E scrollTo) { + if (rebuild) { + rebuild = false; + rebuildElements(); + } + + if (elementMap.containsKey(scrollTo)) { + scrollState().setPos(0); + double yMax = yMin(); + + for (E item : getList()) { + GuiElement e = elementMap.get(item); + if (e != null) { + yMax += e.ySize() + 1; + if (item.equals(scrollTo)) break; + } + } + + if (yMax > yMax()) { + double move = yMax - yMax(); + scrollState().setPos(move / hiddenSize()); + } + } + } + + private void updateVisible() { + visible.forEach(this::removeChild); + visible.clear(); + contentHeight = 0; + if (listContent.isEmpty()) return; + + for (GuiElement item : elementMap.values()) { + contentHeight += item.ySize() + itemSpacing; + } + contentHeight -= itemSpacing; + + double winTop = yMin(); + double winBottom = yMax(); + + double yPos = winTop + (yScrollPos * -hiddenSize()); + for (E item : listContent) { + GuiElement element = elementMap.get(item); + if (element == null) continue; + double top = yPos; + double bottom = yPos + element.ySize(); + + if ((top >= winTop && top <= winBottom) || (bottom >= winTop && bottom <= winBottom)) { + addChild(element); + visible.add(element); + element.constrain(TOP, literal(top)); + } + yPos = bottom + itemSpacing; + } + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return super.blockMouseOver(element, mouseX, mouseY) || (element.isDescendantOf(this) && !isMouseOver()); + } + + @Override + public void render(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + if (enableScissor) render.cc$enableScissor(getRectangle()); + super.render(render, mouseX, mouseY, partialTicks); + if (enableScissor) render.cc$disableScissor(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java new file mode 100644 index 00000000..ee532a1f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiManipulable.java @@ -0,0 +1,465 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.input.MouseButtonEvent; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.literal; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This element can be used to create movable/resizable guis of gui elements. + * This is achieved via a "contentElement" to which all child elements should eb attached. + * Initially the bounds of the content element will match the parent {@link GuiManipulable} element. + * However, depending on which features are enabled, it is possible for the user to resize the + * content element by clicking and dragging the edges, or move the element by clicking and dragging + * a specified "dragArea". + *

+ * It should be noted that the constraints on the underlying {@link GuiManipulable} should be fairly rigid. + * Things like dynamic constraint changes will not translate through to the contentElement, + *

+ * If a UI resize occurs the content element's bounds will be reset to default. + * You can also trigger a manual reset by calling {@link #resetBounds()} + *

+ * Created by brandon3055 on 13/11/2023 + */ +public class GuiManipulable extends GuiElement implements ContentElement> { + + private final GuiElement contentElement; + + private int dragXOffset = 0; + private int dragYOffset = 0; + private boolean isDragging = false; + private boolean dragPos = false; + private boolean dragTop = false; + private boolean dragLeft = false; + private boolean dragBottom = false; + private boolean dragRight = false; + private boolean enableCursors = false; + private boolean resetOnUiInit = true; + + //Made available for external position restraints + public int xMin = 0; + public int xMax = 0; + public int yMin = 0; + public int yMax = 0; + + protected Rectangle minSize = Rectangle.create(0, 0, 50, 50); + protected Rectangle maxSize = Rectangle.create(0, 0, 256, 256); + protected Consumer onMovedCallback = null; + protected Consumer onResizedCallback = null; + protected PositionRestraint positionRestraint = draggable -> { + if (xMin < 0) { + int move = -xMin; + xMin += move; + xMax += move; + } else if (xMax > scaledScreenWidth()) { + int move = xMax - scaledScreenWidth(); + xMin -= move; + xMax -= move; + } + if (yMin < 0) { + int move = -yMin; + yMin += move; + yMax += move; + } else if (yMax > scaledScreenHeight()) { + int move = yMax - scaledScreenHeight(); + yMin -= move; + yMax -= move; + } + }; + + private GuiElement moveHandle; + private GuiElement leftHandle; + private GuiElement rightHandle; + private GuiElement topHandle; + private GuiElement bottomHandle; + + public GuiManipulable(GuiParent parent) { + super(parent); + this.contentElement = new ContentElement(this) + .constrain(LEFT, Constraint.dynamic(() -> (double) xMin)) + .constrain(RIGHT, Constraint.dynamic(() -> (double) xMax)) + .constrain(TOP, Constraint.dynamic(() -> (double) yMin)) + .constrain(BOTTOM, Constraint.dynamic(() -> (double) yMax)); + moveHandle = new GuiRectangle(contentElement); + leftHandle = new GuiRectangle(contentElement); + rightHandle = new GuiRectangle(contentElement); + topHandle = new GuiRectangle(contentElement); + bottomHandle = new GuiRectangle(contentElement); + } + + public GuiManipulable resetBounds() { + xMin = (int) xMin(); + xMax = (int) xMax(); + yMin = (int) yMin(); + yMax = (int) yMax(); + return this; + } + + @Override + public GuiManipulable constrain(GeoParam param, @Nullable Constraint constraint) { + return super.constrain(param, constraint).resetBounds(); //TODO, This will break if strict constraints are enabled... + } + + @Override + public void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + super.onScreenInit(mc, font, screenWidth, screenHeight); + if (resetOnUiInit) resetBounds(); + } + + /** + * @param resetOnUiInit If true, element bounds will be reset on UI init. (Default: true) + */ + public GuiManipulable setResetOnUiInit(boolean resetOnUiInit) { + this.resetOnUiInit = resetOnUiInit; + return this; + } + + @Override + public GuiElement getContentElement() { + return contentElement; + } + + public GuiManipulable addResizeHandles(int handleSize, boolean includeTopHandle) { + if (includeTopHandle) addTopHandle(handleSize); + addLeftHandle(handleSize); + addRightHandle(handleSize); + addBottomHandle(handleSize); + return this; + } + + public GuiManipulable addTopHandle(int handleSize) { + this.topHandle + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + public GuiManipulable setTopHandle(GuiElement topHandle) { + this.topHandle = topHandle; + return this; + } + + public GuiManipulable addBottomHandle(int handleSize) { + this.bottomHandle + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + public GuiManipulable setBottomHandle(GuiElement bottomHandle) { + this.bottomHandle = bottomHandle; + return this; + } + + public GuiManipulable addLeftHandle(int handleSize) { + this.leftHandle + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(WIDTH, literal(handleSize)); + return this; + } + + public GuiManipulable setLeftHandle(GuiElement leftHandle) { + this.leftHandle = leftHandle; + return this; + } + + public GuiManipulable addRightHandle(int handleSize) { + this.rightHandle + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(BOTTOM, match(contentElement.get(BOTTOM))) + .constrain(WIDTH, literal(handleSize)); + return this; + } + + public GuiManipulable setRightHandle(GuiElement rightHandle) { + this.rightHandle = rightHandle; + return this; + } + + public GuiManipulable addMoveHandle(int handleSize) { + this.moveHandle + .constrain(TOP, match(contentElement.get(TOP))) + .constrain(LEFT, match(contentElement.get(LEFT))) + .constrain(RIGHT, match(contentElement.get(RIGHT))) + .constrain(HEIGHT, literal(handleSize)); + return this; + } + + public GuiManipulable setMoveHandle(GuiElement moveHandle) { + this.moveHandle = moveHandle; + return this; + } + + /** + * You can use this to retrieve the current move handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getMoveHandle() { + return moveHandle; + } + + /** + * You can use this to retrieve the current left resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getLeftHandle() { + return leftHandle; + } + + /** + * You can use this to retrieve the current right resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getRightHandle() { + return rightHandle; + } + + /** + * You can use this to retrieve the current top resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getTopHandle() { + return topHandle; + } + + /** + * You can use this to retrieve the current bottom resize handle. + * You are free to update the constraints on this handle, but it must be constrained relative to the content element. + */ + public GuiElement getBottomHandle() { + return bottomHandle; + } + + /** + * Enables rendering of custom mouse cursors when hovering over a draggable handle. + */ + public GuiManipulable enableCursors(boolean enableCursors) { + this.enableCursors = enableCursors; + return this; + } + + public GuiManipulable setOnMovedCallback(Runnable onMovedCallback) { + this.onMovedCallback = finished -> onMovedCallback.run(); + return this; + } + + public GuiManipulable setOnMovedCallback(Consumer onMovedCallback) { + this.onMovedCallback = onMovedCallback; + return this; + } + + public GuiManipulable setOnResizedCallback(Runnable onResizedCallback) { + this.onResizedCallback = finished -> onResizedCallback.run(); + return this; + } + + public GuiManipulable setOnResizedCallback(Consumer onResizedCallback) { + this.onResizedCallback = onResizedCallback; + return this; + } + + public GuiManipulable setPositionRestraint(PositionRestraint positionRestraint) { + this.positionRestraint = positionRestraint; + return this; + } + + public void setMinSize(Rectangle minSize) { + this.minSize = minSize; + } + + public void setMaxSize(Rectangle maxSize) { + this.maxSize = maxSize; + } + + public Rectangle getMinSize() { + return minSize; + } + + public Rectangle getMaxSize() { + return maxSize; + } + + @Override + public void tick(double mouseX, double mouseY) { + if (enableCursors) { + boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); + boolean topFlag = topHandle != null && topHandle.isMouseOver(); + boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); + boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); + boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); + boolean any = posFlag || topFlag || leftFlag || bottomFlag || rightFlag; + + if (any) { + if (posFlag) { + getModularGui().setCursor(CursorHelper.DRAG); + } else if ((topFlag && leftFlag) || (bottomFlag && rightFlag)) { + getModularGui().setCursor(CursorHelper.RESIZE_TLBR); + } else if ((topFlag && rightFlag) || (bottomFlag && leftFlag)) { + getModularGui().setCursor(CursorHelper.RESIZE_TRBL); + } else if (topFlag || bottomFlag) { + getModularGui().setCursor(CursorHelper.RESIZE_V); + } else { + getModularGui().setCursor(CursorHelper.RESIZE_H); + } + } + } + + super.tick(mouseX, mouseY); + } + + public void startDragging() { + double mouseX = getModularGui().computeMouseX(); + double mouseY = getModularGui().computeMouseY(); + dragXOffset = (int) (mouseX - xMin); + dragYOffset = (int) (mouseY - yMin); + isDragging = true; + dragPos = true; + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + if (isDragging) { + int xMove = (int) (mouseX - dragXOffset) - xMin; + int yMove = (int) (mouseY - dragYOffset) - yMin; + if (dragPos) { + xMin += xMove; + xMax += xMove; + yMin += yMove; + yMax += yMove; + validatePosition(false); + onMoved(false); + } else { + Rectangle min = getMinSize(); + Rectangle max = getMaxSize(); + if (dragTop) { + yMin += yMove; + if (yMax - yMin < min.height()) yMin = yMax - (int) min.height(); + if (yMax - yMin > max.height()) yMin = yMax - (int) max.height(); + if (yMin < 0) yMin = 0; + } + if (dragLeft) { + xMin += xMove; + if (xMax - xMin < min.width()) xMin = xMax - (int) min.width(); + if (xMax - xMin > max.width()) xMin = xMax - (int) max.width(); + if (xMin < 0) xMin = 0; + } + if (dragBottom) { + yMax = yMin + (dragYOffset + yMove); + if (yMax - yMin < min.height()) yMax = yMin + (int) min.height(); + if (yMax - yMin > max.height()) yMax = yMin + (int) max.height(); + if (yMax > scaledScreenHeight()) yMax = scaledScreenHeight(); + } + if (dragRight) { + xMax = xMin + (dragXOffset + xMove); + if (xMax - xMin < min.width()) xMax = xMin + (int) min.width(); + if (xMax - xMin > max.width()) xMax = xMin + (int) max.width(); + if (xMax > scaledScreenWidth()) xMax = scaledScreenWidth(); + } + validatePosition(false); + onResized(false); + } + } + super.mouseMoved(mouseX, mouseY); + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + if (isMoving()) { + validatePosition(true); + onMoved(true); + } + if (isResizing()) { + onResized(true); + } + isDragging = dragPos = dragTop = dragLeft = dragBottom = dragRight = false; + return super.mouseReleased(event, consumed); + } + + protected void validatePosition(boolean finished) { + double x = xMin; + double y = yMin; + positionRestraint.restrainPosition(this); + if ((x != xMin || y != yMin)) { + onMoved(finished); + } + } + + protected void onMoved(boolean finished) { + if (onMovedCallback != null) { + onMovedCallback.accept(finished); + } + } + + protected void onResized(boolean finished) { + if (onResizedCallback != null) { + onResizedCallback.accept(finished); + } + } + + public boolean isMoving() { + return dragPos; + } + + public boolean isResizing() { + return dragTop || dragLeft || dragBottom || dragRight; + } + + public interface PositionRestraint { + + void restrainPosition(GuiManipulable draggable); + } + + private class ContentElement extends GuiElement { + + public ContentElement(GuiParent parent) { + super(parent); + } + + @Override + public boolean mouseClicked(MouseButtonEvent event) { + if (super.mouseClicked(event)) return true; + + boolean posFlag = moveHandle != null && moveHandle.isMouseOver(); + boolean topFlag = topHandle != null && topHandle.isMouseOver(); + boolean leftFlag = leftHandle != null && leftHandle.isMouseOver(); + boolean bottomFlag = bottomHandle != null && bottomHandle.isMouseOver(); + boolean rightFlag = rightHandle != null && rightHandle.isMouseOver(); + + if (posFlag || topFlag || leftFlag || bottomFlag || rightFlag) { + dragXOffset = (int) (event.x() - xMin); + dragYOffset = (int) (event.y() - yMin); + isDragging = true; + if (posFlag) { + dragPos = true; + } else { + dragTop = topFlag; + dragLeft = leftFlag; + dragBottom = bottomFlag; + dragRight = rightFlag; + } + return true; + } + + return false; + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java new file mode 100644 index 00000000..82294538 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiProgressIcon.java @@ -0,0 +1,139 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.Direction; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.SpriteSupplier; +import codechicken.lib.math.MathHelper; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; + +import java.util.function.Supplier; + +/** + * This can be used to create a simple progress indicator like those used in machines like furnaces. + *

+ * The background texture (if one is used) and the animated texture must be the same shape and size, + * They must be designed so that the animated texture can be rendered directly on top of the background texture with no offset. + * The animated texture should not have any empty space on ether end as the entire width of the texture is used in the animation. + *

+ * Texture must be designed for left to right animation, + *

+ * Created by brandon3055 on 04/09/2023 + */ +public class GuiProgressIcon extends GuiElement implements BackgroundRender { + + private SpriteSupplier background = SpriteSupplier.EMPTY; + private SpriteSupplier animated = SpriteSupplier.EMPTY; + private Supplier progress = () -> 0D; + private boolean rotateToDirection = true; + private Direction direction = Direction.RIGHT; + + public GuiProgressIcon(GuiParent parent) { + this(parent, SpriteSupplier.EMPTY, SpriteSupplier.EMPTY); + } + + public GuiProgressIcon(GuiParent parent, SpriteSupplier animated) { + this(parent, SpriteSupplier.EMPTY, animated); + } + + public GuiProgressIcon(GuiParent parent, SpriteSupplier background, SpriteSupplier animated) { + super(parent); + this.background = background; + this.animated = animated; + } + + /** + * The expected default direction for a progress texture is left-to-right e.g. furnace arrow. + * The texture will then be rotated to the direction specified via {@link #setDirection(Direction)} + * If you do not want the texture to be rotated then set this to false. + */ + public GuiProgressIcon setRotateToDirection(boolean rotateToDirection) { + this.rotateToDirection = rotateToDirection; + return this; + } + + /** + * Set the direction this progress icon is pointing, Default is RIGHT + */ + public GuiProgressIcon setDirection(Direction direction) { + this.direction = direction; + return this; + } + + /** + * Sets the background texture, aka the "empty" texture. + */ + public GuiProgressIcon setBackground(SpriteSupplier background) { + this.background = background; + return this; + } + + /** + * Sets the texture that will be animated. + */ + public GuiProgressIcon setAnimated(SpriteSupplier animated) { + this.animated = animated; + return this; + } + + /** + * Set the current progress to a fixed value. + * + * @see #setProgress(Supplier) + */ + public GuiProgressIcon setProgress(double progress) { + return setProgress(() -> progress); + } + + /** + * Attach a supplier that returns the current progress value for this progress icon (0 to 1) + */ + public GuiProgressIcon setProgress(Supplier progress) { + this.progress = progress; + return this; + } + + public double getProgress() { + return progress.get(); + } + + @Override + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + if (rotateToDirection) { + graphics.pose().pushMatrix(); + + double width = direction.getAxis() == Axis.X ? xSize() : ySize(); + double height = direction.getAxis() == Axis.X ? ySize() : xSize(); + + graphics.pose().translate((float) (xMin() + (xSize() / 2)), (float) (yMin() + (ySize() / 2))); + graphics.pose().rotate((float) (Direction.RIGHT.rotationTo(direction) * MathHelper.torad)); + + double halfWidth = width / 2; + double halfHeight = height / 2; + background.ifPresent(sprite -> { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, -halfWidth, -halfHeight, halfWidth, halfHeight); + }); + + animated.ifPresent(sprite -> { + float progress = (float) getProgress(); + graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, -halfWidth, -halfHeight, -halfWidth + (width * progress), -halfHeight + height, sprite, 0F, 0F, progress, 1F, 0xFFFFFFFF); + }); + graphics.pose().popMatrix(); + } else { + background.ifPresent(sprite -> { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, getRectangle()); + }); + animated.ifPresent(sprite -> { + float progress = (float) getProgress(); + switch (direction) { + case UP -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMax() - (ySize() * progress), xMax(), yMax(), sprite, 0F, 1F - progress, 1F, 1F); + case LEFT -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMax() - (xSize() * progress), yMin(), xMax(), yMax(), sprite, 1F - progress, 0F, 1F, 1F); + case DOWN -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMin(), xMax(), yMin() + (ySize() * progress), sprite, 0F, 0F, 1F, progress); + case RIGHT -> graphics.cc$blitPartialSprite(RenderPipelines.GUI_TEXTURED, xMin(), yMin(), xMin() + (xSize() * progress), yMax(), sprite, 0F, 0F, progress, 1F); + } + }); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java new file mode 100644 index 00000000..d02209ad --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiRectangle.java @@ -0,0 +1,174 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.colour.Colour; +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.gui.GuiGraphics; +import org.jetbrains.annotations.Nullable; + +import java.util.function.DoubleSupplier; +import java.util.function.IntSupplier; + +import static java.util.Objects.requireNonNull; + +/** + * Used to draw a simple rectangle on the screen. + * Can specify separate (or no) border colours and fill colours. + * Can also render using the "shadedRectangle" render type. + *

+ * Created by brandon3055 on 28/08/2023 + */ +public class GuiRectangle extends GuiElement implements BackgroundRender { + + private @Nullable IntSupplier fill = null; + private @Nullable IntSupplier border = null; + + private DoubleSupplier borderWidth = () -> 1D; + + private @Nullable IntSupplier shadeTopLeft; + private @Nullable IntSupplier shadeBottomRight; + private @Nullable IntSupplier shadeCorners; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiRectangle(GuiParent parent) { + super(parent); + } + + /** + * Creates a rectangle that mimics the appearance of a vanilla inventory slot. + * Uses shadedRect to create the 3D "inset" look. + */ + public static GuiRectangle vanillaSlot(GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFF373737, 0xFFffffff, 0xFF8b8b8b, 0xFF8b8b8b); + } + + /** + * Creates a rectangle that mimics the appearance of a vanilla inventory slot, except inverted + * Uses shadedRect to create the 3D "popped out" appearance + */ + public static GuiRectangle invertedSlot(GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFFffffff, 0xFF373737, 0xFF8b8b8b, 0xFF8b8b8b); + } + + /** + * Creates a rectangle similar in appearance to a vanilla button, but with no texture and no black border. + */ + public static GuiRectangle planeButton(GuiParent parent) { + return new GuiRectangle(parent).shadedRect(0xFFaaaaaa, 0xFF545454, 0xFF6f6f6f); + } + + public static GuiRectangle toolTipBackground(GuiParent parent) { + return toolTipBackground(parent, 0xF0100010, 0x505000FF, 0x5028007f); + } + + public static GuiRectangle toolTipBackground(GuiParent parent, int backgroundColour, int borderColourTop, int borderColourBottom) { + return toolTipBackground(parent, backgroundColour, backgroundColour, borderColourTop, borderColourBottom); + } + + public static GuiRectangle toolTipBackground(GuiParent parent, int backgroundColourTop, int backgroundColourBottom, int borderColourTop, int borderColourBottom) { + return new GuiRectangle(parent) { + @Override + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + graphics.cc$tooltipBackground(xMin(), yMin(), xSize(), ySize(), backgroundColourTop, backgroundColourBottom, borderColourTop, borderColourBottom, false); + } + }; + } + + public GuiRectangle border(int border) { + return border(() -> border); + } + + public GuiRectangle border(@Nullable IntSupplier border) { + this.border = border; + return this; + } + + public GuiRectangle fill(int fill) { + return fill(() -> fill); + } + + public GuiRectangle fill(IntSupplier fill) { + this.fill = fill; + return this; + } + + public GuiRectangle rectangle(int fill, int border) { + return rectangle(() -> fill, () -> border); + } + + public GuiRectangle rectangle(IntSupplier fill, IntSupplier border) { + this.fill = fill; + this.border = border; + return this; + } + + public GuiRectangle shadedRect(int topLeft, int bottomRight, int fill) { + return shadedRect(() -> topLeft, () -> bottomRight, () -> fill); + } + + public GuiRectangle shadedRect(IntSupplier topLeft, IntSupplier bottomRight, IntSupplier fill) { + return shadedRect(topLeft, bottomRight, () -> Colour.mid(topLeft.getAsInt(), bottomRight.getAsInt()), fill); + } + + public GuiRectangle shadedRect(int topLeft, int bottomRight, int cornerMix, int fill) { + return shadedRect(() -> topLeft, () -> bottomRight, () -> cornerMix, () -> fill); + } + + public GuiRectangle shadedRect(IntSupplier topLeft, IntSupplier bottomRight, IntSupplier cornerMix, IntSupplier fill) { + this.fill = fill; + this.shadeTopLeft = topLeft; + this.shadeBottomRight = bottomRight; + this.shadeCorners = cornerMix; + return this; + } + + public GuiRectangle setShadeTopLeft(IntSupplier shadeTopLeft) { + this.shadeTopLeft = shadeTopLeft; + return this; + } + + public GuiRectangle setShadeBottomRight(IntSupplier shadeBottomRight) { + this.shadeBottomRight = shadeBottomRight; + return this; + } + + public GuiRectangle setShadeCorners(IntSupplier shadeCorners) { + this.shadeCorners = shadeCorners; + return this; + } + + public GuiRectangle setShadeCornersAuto() { + this.shadeCorners = () -> { + var topLeft = requireNonNull(shadeTopLeft, "shadeTopLeft required for corners.").getAsInt(); + var bottomRight = requireNonNull(shadeBottomRight, "shadeBottomRight required for corners.").getAsInt(); + return Colour.mid(topLeft, bottomRight); + }; + return this; + } + + public GuiRectangle borderWidth(double borderWidth) { + return borderWidth(() -> borderWidth); + } + + public GuiRectangle borderWidth(DoubleSupplier borderWidth) { + this.borderWidth = borderWidth; + return this; + } + + public double getBorderWidth() { + return borderWidth.getAsDouble(); + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + if (shadeTopLeft != null && shadeBottomRight != null && shadeCorners != null) { + render.cc$shadedRect(getRectangle(), getBorderWidth(), shadeTopLeft.getAsInt(), shadeBottomRight.getAsInt(), shadeCorners.getAsInt(), fill == null ? 0 : fill.getAsInt()); + } else if (border != null) { + render.cc$borderRect(getRectangle(), getBorderWidth(), fill == null ? 0 : fill.getAsInt(), border.getAsInt()); + } else if (fill != null) { + render.cc$fill(getRectangle(), fill.getAsInt()); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java new file mode 100644 index 00000000..24238383 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiScrolling.java @@ -0,0 +1,219 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.ContentElement; +import codechicken.lib.gui.modular.lib.SliderState; +import codechicken.lib.gui.modular.lib.geometry.Axis; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.math.MathHelper; +import net.minecraft.client.gui.GuiGraphics; +import org.jetbrains.annotations.Nullable; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * So the logic behind this element is as follows. + * This element contains a base "Content Element" that holds all the scrollable content. + * The content element's position is controlled by the {@link GuiScrolling} + * But its {@link GeoParam#WIDTH} and {@link GeoParam#HEIGHT} constraints can be set by the user, + * Or they can be set to dynamically adjust to the child elements added to it. + *

+ * The bounds of the {@link GuiScrolling} represent the "view window" + * When scrolling up/down, left/right the Content Element is effectively just moving around behind the view window + * and everything outside the view window is scissored off. + * Any events that occur outside the view window are not propagated to scroll element. + * Calls to {@link #isMouseOver()} from an area of an element that is outside the view window will return false. + *

+ * Elements that are completely outside the view window will not be rendered at all for efficiency. + *

+ * Created by brandon3055 on 01/09/2023 + */ +public class GuiScrolling extends GuiElement implements ContentElement> { + + /** + * This is made available primarily for debugging purposes where it can be useful to see what's going on behind the scenes. + */ + public boolean enableScissor = true; + private GuiElement contentElement; + private double xScrollPos = 0; + private double yScrollPos = 0; + private double contentWidth = 0; + private double contentHeight = 0; + private boolean setup = false; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiScrolling(GuiParent parent) { + super(parent); + installContainerElement(new ContentElement(this)); + } + + //=== Scroll element setup ===// + + /** + * Retrieves the content element that holds all the scrolling elements. + * You must add all of your scrolling content to this element. + * Scrolling content must also be constrained relative to this element. + *

+ * The {@link GeoParam#TOP} and {@link GeoParam#LEFT} constraints for this element are set by the {@link GuiScrolling} and must not be overridden. + * These are used to control the 'scrolling' of the element. + *

+ * By default, the {@link GeoParam#WIDTH} and {@link GeoParam#HEIGHT} (and therefor also BOTTOM, RIGHT) are dynamically constrained to match the outer bounds of the scrolling elements. + * So attempting to constrain the content to any of these dynamic parameters would result in a stack overflow. + * You can however override the WIDTH and HEIGHT constraints if you wish. + * This can be useful if you wish to create something like a fixed width scrolling list where the width of each scrolling element is bound to the width of the list. + *

+ * The most important thing to note, Especially when manually constraining the WIDTH and HEIGHT of the content element, + * All scrolling elements must be withing the bounds of the content element. Anything outside the content element's bounds will not be visible. + * + * @return The content element. + */ + @Override + public GuiElement getContentElement() { + return contentElement; + } + + /** + * This allows you to install a custom container element. + * The elements constraints will automatically be set by this method. + *

+ * After calling this method you may override the container element WIDTH and HEIGHT constraints as described in the documentation for {@link #getContentElement()} + * But you must not touch the TOP or LEFT constraints. + *

+ * Important thing to note, By default the container element is preinstalled before any children can be added, meaning any children added to the {@link GuiScrolling} + * will render on top of the scrolling content. + * As this method allows you to set a new child as the container element, any children added before the new content element, will render under the content element. + * + * @param element The new container element. + */ + public void installContainerElement(GuiElement element) { + if (element.getParent() != this) throw new IllegalStateException("Content element must be a child of the GuiScrollingBase it is being installed in"); + if (contentElement != null) removeChild(contentElement); + setup = true; + contentElement = element; + contentElement.setRenderCull(getRectangle()); + contentElement.constrain(TOP, Constraint.relative(get(TOP), () -> yScrollPos * -hiddenSize(Axis.Y))); + contentElement.constrain(LEFT, Constraint.relative(get(LEFT), () -> xScrollPos * -hiddenSize(Axis.X))); + contentElement.constrain(WIDTH, Constraint.dynamic(() -> contentElement.getChildBounds().xMax() - contentElement.xMin())); + contentElement.constrain(HEIGHT, Constraint.dynamic(() -> contentElement.getChildBounds().yMax() - contentElement.yMin())); + setup = false; + } + + /** + * @return a {@link SliderState} that can be used to get or control the scroll position of the specified axis. + */ + public SliderState scrollState(Axis axis) { + return switch (axis) { + case X -> SliderState.forScrollBar(() -> xScrollPos, e -> xScrollPos = e, () -> MathHelper.clip(xSize() / contentElement.xSize(), 0, 1)); + case Y -> SliderState.forScrollBar(() -> yScrollPos, e -> yScrollPos = e, () -> MathHelper.clip(ySize() / contentElement.ySize(), 0, 1)); + }; + } + + //=== Internal logic ===// + + /** + * @return the total content size / length for the given axis + */ + public double totalSize(Axis axis) { + return switch (axis) { + case X -> contentWidth; + case Y -> contentHeight; + }; + } + + /** + * @return the hidden content size / length for the given axis (How much of the content is outside the view area) + */ + public double hiddenSize(Axis axis) { + return switch (axis) { + case X -> Math.max(contentWidth - xSize(), 0); + case Y -> Math.max(contentHeight - ySize(), 0); + }; + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + //These can not be generated dynamically, Doing so would result in a calculation loop, aka a stack overflow. + contentWidth = contentElement.xSize(); + contentHeight = contentElement.ySize(); + } + + @Override + public boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return super.blockMouseOver(element, mouseX, mouseY) || (element.isDescendantOf(contentElement) && !this.isMouseOver()); + } + + //=== Rendering ===// + + @Override + protected boolean renderChild(GuiElement child, GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + boolean scissor = child == contentElement && enableScissor; + if (scissor) render.cc$enableScissor(getRectangle()); + boolean ret = super.renderChild(child, render, mouseX, mouseY, partialTicks); + if (scissor) render.cc$disableScissor(); + return ret; + } + + private class ContentElement extends GuiElement { + + /** + * @param parent parent {@link GuiParent}. + */ + public ContentElement(GuiParent parent) { + super(parent); + } + + @Override + public ContentElement constrain(GeoParam param, @Nullable Constraint constraint) { + if (!setup && (param == TOP || param == LEFT)) throw new IllegalStateException("Can not override TOP or LEFT constraints on content element, These are used to control the scrolling behavior!"); + return super.constrain(param, constraint); + } + } + + public static ScrollWindow simpleScrollWindow(GuiParent parent, boolean verticalScrollBar, boolean horizontalScrollBar) { + GuiElement container = new GuiElement<>(parent); + GuiRectangle background = GuiRectangle.vanillaSlot(container) + .constrain(TOP, match(container.get(TOP))) + .constrain(LEFT, match(container.get(LEFT))) + .constrain(BOTTOM, relative(container.get(BOTTOM), horizontalScrollBar ? -10 : 0)) + .constrain(RIGHT, relative(container.get(RIGHT), verticalScrollBar ? -10 : 0)); + + GuiScrolling scroll = new GuiScrolling(background); + Constraints.bind(scroll, background, 1); + + GuiSlider.ScrollBar verticalBar = null; + if (verticalScrollBar) { + verticalBar = GuiSlider.vanillaScrollBar(container, Axis.Y); + verticalBar.container() + .constrain(TOP, match(container.get(TOP))) + .constrain(BOTTOM, relative(container.get(BOTTOM), horizontalScrollBar ? -10 : 0)) + .constrain(RIGHT, match(container.get(RIGHT))) + .constrain(WIDTH, Constraint.literal(9)); + verticalBar.slider() + .setSliderState(scroll.scrollState(Axis.Y)) + .setScrollableElement(scroll); + } + GuiSlider.ScrollBar horizontalBar = null; + if (horizontalScrollBar) { + horizontalBar = GuiSlider.vanillaScrollBar(container, Axis.X); + horizontalBar.container() + .constrain(BOTTOM, match(container.get(BOTTOM))) + .constrain(LEFT, match(container.get(LEFT))) + .constrain(RIGHT, relative(container.get(RIGHT), verticalScrollBar ? -10 : 0)) + .constrain(HEIGHT, Constraint.literal(9)); + horizontalBar.slider() + .setSliderState(scroll.scrollState(Axis.X)) + .setScrollableElement(scroll); + } + return new ScrollWindow(container, scroll, verticalBar, horizontalBar); + } + + public record ScrollWindow(GuiElement container, GuiScrolling scrolling, @Nullable GuiSlider.ScrollBar verticalBar, @Nullable GuiSlider.ScrollBar horizontalBar) { + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java new file mode 100644 index 00000000..cb3763c3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlider.java @@ -0,0 +1,268 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.Constraints; +import codechicken.lib.gui.modular.lib.SliderState; +import codechicken.lib.gui.modular.lib.geometry.*; +import codechicken.lib.math.MathHelper; +import net.minecraft.client.input.MouseButtonEvent; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This can be used as the base for anything that requires the linear movement of an element between two position. + * e.g. Scroll bars, Slide controls and slide indicators. + *

+ * Implementation is simple, Simply install a "Slide Element", this will be the moving element, + * The movement of this element is confined to the bounds og the {@link GuiSlider} + *

+ * The position of the slider is managed via the installed {@link SliderState} + *

+ * Created by brandon3055 on 02/09/2023 + */ +public class GuiSlider extends GuiElement { + + private final Axis axis; + private SliderState state = SliderState.create(0.1); + private GuiElement slider; + private double outOfBoundsDist = 50; + private GuiElement scrollableElement; + + private int dragButton = GuiButton.LEFT_CLICK; + private int scrollDragButton = GuiButton.MIDDLE_CLICK; + private boolean middleClickScroll = false; + /** + * This should theoretically never be needed, But just in case... + */ + public boolean invertDragScroll = false; + + private boolean dragging = false; + private double slideStartPos = 0; + private Position clickPos = Position.create(0, 0); + private boolean scrollableDragging = false; + + /** + * Creates a basic gui slider that moves along the specified axis. + * This includes a default slider element the width of which is bound to the GuiSlider, + * And the length of which is controlled by {@link SliderState#sliderRatio()} + */ + public GuiSlider(GuiParent parent, Axis axis) { + super(parent); + this.axis = axis; + installSlider(new GuiElement<>(this)); + bindSliderLength(); + bindSliderWidth(); + } + + public GuiSlider(GuiParent parent, Axis axis, GuiElement slider) { + super(parent); + this.axis = axis; + installSlider(slider); + } + + /** + * Vanilla does not really seem to have a standard for its scroll bars, + * But this is something that should at least fit in to a typical vanilla gui. + */ + public static ScrollBar vanillaScrollBar(GuiElement parent, Axis axis) { + GuiRectangle background = GuiRectangle.vanillaSlot(parent); + + GuiSlider slider = new GuiSlider(background, axis); + Constraints.bind(slider, background, 1); + + slider.installSlider(GuiRectangle.planeButton(slider)) + .bindSliderLength() + .bindSliderWidth(); + + GuiRectangle sliderHighlight = new GuiRectangle(slider.getSlider()) + .fill(0x5000b6FF) + .setEnabled(() -> slider.getSlider().isMouseOver()); + + Constraints.bind(sliderHighlight, slider.getSlider()); + + return new ScrollBar(background, slider, sliderHighlight); + } + + /** + * Set the slider state used by this slider element. + * The slider state is used to get and set the slider position. + * It also controls scroll speed. + */ + public GuiSlider setSliderState(SliderState state) { + this.state = state; + return this; + } + + /** + * For use cases where this slider is controlling something like a scroll element. + * This enables scrolling when the cursor is over the scrollable element. + * It can also enable scrolling via middle-click + drag. + */ + public GuiSlider setScrollableElement(GuiElement scrollableElement) { + return setScrollableElement(scrollableElement, true); + } + + /** + * For use cases where this slider is controlling something like a scroll element. + * This enables scrolling when the cursor is over the scrollable element. + * It can also enable scrolling via middle-click + drag. + */ + public GuiSlider setScrollableElement(GuiElement scrollableElement, boolean middleClickScroll) { + this.scrollableElement = scrollableElement; + this.middleClickScroll = middleClickScroll; + return this; + } + + /** + * Install an element to be used as the sliding element. + * The sliders minimum position (meaning either LEFT or TOP) on the moving axis will be constrained the {@link GuiSlider} + * Attempting to override this constraint after installing the slider element will break the slider. + *

+ * The size constraints, and position constraint for the non-moving axis need to be set by the implementor. + * + * @see #bindSliderLength() + * @see #bindSliderWidth() + */ + public GuiSlider installSlider(GuiElement slider) { + if (slider.getParent() != this) throw new IllegalStateException("slider element must be a child of the GuiSlider it is being installed in"); + if (this.slider != null) removeChild(this.slider); + this.slider = slider; + switch (axis) { + case X -> slider.constrain(LEFT, Constraint.relative(get(LEFT), () -> (getValue(WIDTH) - slider.getValue(WIDTH)) * state.getPos())); + case Y -> slider.constrain(TOP, Constraint.relative(get(TOP), () -> (getValue(HEIGHT) - slider.getValue(HEIGHT)) * state.getPos())); + } + return this; + } + + /** + * Sets up constraints to automatically control the slider element length. + * The slider element length will be controlled by {@link SliderState#sliderRatio()} + * This is used for things like gui scroll bars where the bar length changes based on the ratio of content in view. + */ + public GuiSlider bindSliderLength() { + switch (axis) {//Ensure we don't accidentally over-constrain + case X -> slider.constrain(RIGHT, null).constrain(WIDTH, Constraint.dynamic(() -> getValue(WIDTH) * state.sliderRatio())); + case Y -> slider.constrain(BOTTOM, null).constrain(HEIGHT, Constraint.dynamic(() -> getValue(HEIGHT) * state.sliderRatio())); + } + return this; + } + + /** + * Binds the sliders position and size on the non-moving axis to the width and pos of the {@link GuiSlider} + */ + public GuiSlider bindSliderWidth() { + switch (axis) {//Ensure we don't accidentally over-constrain + case X -> slider.constrain(HEIGHT, null).constrain(TOP, Constraint.match(get(TOP))).constrain(BOTTOM, Constraint.match(get(BOTTOM))); + case Y -> slider.constrain(WIDTH, null).constrain(LEFT, Constraint.match(get(LEFT))).constrain(RIGHT, Constraint.match(get(RIGHT))); + } + return this; + } + + /** + * @return the installed slider element. + */ + public GuiElement getSlider() { + return slider; + } + + /** + * @return True if the slider is currently being dragged by the user. + */ + public boolean isDragging() { + return dragging; + } + + /** + * Set the out-of-bounds distance, + * If the cursor is dragged more than this distance from the slider bounds on the no-moving axis, + * the slider will snap back to its original position until the cursor moves back into bounds. + * Default is 50, -1 will disable the snap-back functionality. + */ + public GuiSlider setOutOfBoundsDist(double outOfBoundsDist) { + this.outOfBoundsDist = outOfBoundsDist; + return this; + } + + /** + * @param dragButton The mouse button used to drag this slider (Default {@link GuiButton#LEFT_CLICK}) + */ + public GuiSlider setDragButton(int dragButton) { + this.dragButton = dragButton; + return this; + } + + /** + * @param scrollDragButton The button used to scroll by clicking and dragging the defined scrollableElement (Default {@link GuiButton#MIDDLE_CLICK}) + * @see #setScrollableElement(GuiElement, boolean) + */ + public GuiSlider setScrollDragButton(int scrollDragButton) { + this.scrollDragButton = scrollDragButton; + return this; + } + + @Override + public boolean mouseClicked(MouseButtonEvent event) { + dragging = false; + clickPos = Position.create(event.x(), event.y()); + slideStartPos = state.getPos(); + if (event.button() == dragButton && isMouseOver()) { + if (!slider.isMouseOver()) { + clickPos = Position.create(slider.xCenter(), slider.yCenter()); + handleDrag(event.x(), event.y()); + } + dragging = true; + return true; + } + if (event.button() == scrollDragButton && scrollableElement != null && scrollableElement.isMouseOver()) { + scrollableDragging = true; + } + return false; + } + + @Override + public boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + dragging = scrollableDragging = false; + return super.mouseReleased(event, consumed); + } + + @Override + public void mouseMoved(double mouseX, double mouseY) { + if (dragging || (scrollableDragging && scrollableElement != null)) { + handleDrag(mouseX, mouseY); + } + super.mouseMoved(mouseX, mouseY); + } + + private void handleDrag(double mouseX, double mouseY) { + Position mousePos = Position.create(mouseX, mouseY); + Rectangle rect = dragging || scrollableElement == null ? getRectangle() : scrollableElement.getRectangle(); + + if (dragging && outOfBoundsDist >= -1 && rect.distance(axis.opposite(), mousePos) > outOfBoundsDist) { + state.setPos(slideStartPos); + return; + } + + double travel = rect.size(axis) - slider.getRectangle().size(axis); + if (travel <= 0) return; + double clickPos = this.clickPos.get(axis); + double currentPos = mousePos.get(axis); + double movement = (currentPos - clickPos) / travel; + + if (scrollableDragging) { + movement *= invertDragScroll ? state.sliderRatio() : -state.sliderRatio(); + } + + state.setPos(MathHelper.clip(slideStartPos + movement, 0, 1)); + } + + @Override + public boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + if (isMouseOver() || (scrollableElement != null && scrollableElement.isMouseOver())) { + if (!state.canScroll(axis)) return false; + state.setPos(MathHelper.clip(state.getPos() + (state.scrollSpeed() * -scrollY), 0, 1)); + return true; + } + return false; + } + + public record ScrollBar(GuiRectangle container, GuiSlider slider, GuiRectangle highlight) { } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java new file mode 100644 index 00000000..fee6ad0b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiSlots.java @@ -0,0 +1,403 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.container.SlotGroup; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; +import codechicken.lib.gui.modular.SpriteSupplier; +import codechicken.lib.math.MathHelper; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.Sheets; +import net.minecraft.client.renderer.texture.TextureAtlas; +import net.minecraft.data.AtlasIds; +import net.minecraft.resources.Identifier; +import net.minecraft.world.inventory.Slot; +import org.apache.logging.log4j.util.TriConsumer; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; + +import static codechicken.lib.CodeChickenLib.MOD_ID; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.match; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This element is used to manage and render a grid of inventory slots in a GUI. + * The width and height of this element are automatically constrained based on the slot configuration. + * However, you can override those constraints, The slot grid will always render in the center of the element nomater the element size. + *

+ * This can be used to render all slots in a {@link SlotGroup} or a sub-set of slots within a group. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class GuiSlots extends GuiElement implements BackgroundRender { + + public static final SpriteSupplier[] ARMOR_SLOTS = new SpriteSupplier[] { + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_helmet")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_chestplate")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_leggings")), + SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_boots")) + }; + public static final SpriteSupplier OFF_HAND_SLOT = SpriteSupplier.of(TextureAtlas.LOCATION_ITEMS, Identifier.withDefaultNamespace("item/empty_armor_slot_shield")); + + private final int firstSlot; + private final int slotCount; + private final int columns; + private final SlotGroup slots; + private final ContainerScreenAccess screenAccess; + + private Function slotTexture = slot -> SpriteSupplier.gui(Identifier.fromNamespaceAndPath(MOD_ID, "widgets/slot")); + private Function slotIcons = slot -> SpriteSupplier.EMPTY; + private Function highlightColour = slot -> 0x80ffffff; + private @Nullable TriConsumer slotOverlay = null; + private int xSlotSpacing = 0; + private int ySlotSpacing = 0; + + /** + * @param slots The slot group containing the slots that this element will manage. + * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) + */ + public GuiSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int gridColumns) { + this(parent, screenAccess, slots, 0, slots.size(), gridColumns); + } + + /** + * @param slots The slot group containing the slots that this element will manage. + * @param firstSlot Index of the fist slot within the slot group. + * @param slotCount The number of slots that this element will manage. + * @param gridColumns The width of the inventory grid (Typically 9 for standard player or chest inventories) + */ + public GuiSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int firstSlot, int slotCount, int gridColumns) { + super(parent); + this.screenAccess = screenAccess; + this.slots = slots; + this.firstSlot = firstSlot; + this.slotCount = slotCount; + this.columns = gridColumns; + if (firstSlot + slotCount > slots.size()) { + throw new IllegalStateException("Specified slot range is out of bounds, Last slot in group is at index " + (slots.size() - 1) + " Specified range is from index " + firstSlot + " to " + (firstSlot + slotCount - 1)); + } + int columns = Math.min(gridColumns, slotCount); + this.constrain(WIDTH, Constraint.dynamic(() -> (double) (columns * 18) + ((columns - 1) * xSlotSpacing))); + int rows = Math.max(1, slotCount / gridColumns); + this.constrain(GeoParam.HEIGHT, Constraint.dynamic(() -> (double) (rows * 18) + ((rows - 1) * ySlotSpacing))); + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + getModularGui().setSlotHandler(slot, this); + } + + updateSlots(parent.getModularGui().getRoot()); + } + + //=== Construction Helpers ===// + + public static GuiSlots singleSlot(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots) { + return singleSlot(parent, screenAccess, slots, 0); + } + + public static GuiSlots singleSlot(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup slots, int index) { + return new GuiSlots(parent, screenAccess, slots, index, 1, 1); + } + + public static Player player(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots) { + return player(parent, screenAccess, mainSlots, hotBarSlots, 3); + } + + public static Player player(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, int hotBarSpacing) { + int width = 18 * 9; + int height = 18 * 4 + hotBarSpacing; + GuiElement container = new GuiElement<>(parent) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), hotBarSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + return new Player(container, main, bar); + } + + public static PlayerWithArmor playerWithArmor(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots) { + return playerWithArmor(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, 3, true); + } + + public static PlayerWithArmor playerWithArmor(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, int groupSpacing, boolean slotIcons) { + int width = 18 * 10 + groupSpacing; + int height = 18 * 4 + groupSpacing; + GuiElement container = new GuiElement<>(parent) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) + .setYSlotSpacing(groupSpacing / 3) + .setEmptyIconI(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, match(armor.get(TOP))) + .constrain(LEFT, relative(armor.get(RIGHT), groupSpacing)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), groupSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + + return new PlayerWithArmor(container, main, bar, armor); + } + + public static PlayerAll playerAllSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots) { + return playerAllSlots(parent, screenAccess, mainSlots, hotBarSlots, armorSlots, offhandSlots, 3, true); + } + + public static PlayerAll playerAllSlots(GuiParent parent, ContainerScreenAccess screenAccess, SlotGroup mainSlots, SlotGroup hotBarSlots, SlotGroup armorSlots, SlotGroup offhandSlots, int groupSpacing, boolean slotIcons) { + int width = 18 * 11 + groupSpacing * 2; + int height = 18 * 4 + groupSpacing; + GuiElement container = new GuiElement<>(parent) + .constrain(WIDTH, Constraint.literal(width)) + .constrain(HEIGHT, Constraint.literal(height)); + + GuiSlots armor = new GuiSlots(container, screenAccess, armorSlots, 1) + .setYSlotSpacing(groupSpacing / 3) + .setEmptyIconI(index -> slotIcons ? ARMOR_SLOTS[index] : null) + .constrain(TOP, Constraint.midPoint(container.get(TOP), container.get(BOTTOM), height / -2D)) + .constrain(LEFT, Constraint.midPoint(container.get(LEFT), container.get(RIGHT), width / -2D)); + + GuiSlots main = new GuiSlots(container, screenAccess, mainSlots, 9) + .constrain(TOP, match(armor.get(TOP))) + .constrain(LEFT, relative(armor.get(RIGHT), groupSpacing)); + + GuiSlots bar = new GuiSlots(container, screenAccess, hotBarSlots, 9) + .constrain(TOP, relative(main.get(BOTTOM), groupSpacing)) + .constrain(LEFT, match(main.get(LEFT))); + + GuiSlots offHand = new GuiSlots(container, screenAccess, offhandSlots, 1) + .setEmptyIconI(index -> slotIcons ? OFF_HAND_SLOT : null) + .constrain(TOP, match(bar.get(TOP))) + .constrain(LEFT, relative(bar.get(RIGHT), groupSpacing)); + + return new PlayerAll(container, main, bar, armor, offHand); + } + + //=== Slots Setup ===// + + /** + * Allows you to use a custom slot texture, The default is the standard vanilla slot. + */ + public GuiSlots setSlotTexture(SpriteSupplier slotTexture) { + this.slotTexture = e -> slotTexture; + return this; + } + + /** + * Allows you to use a custom per-slot slot textures, The default is the standard vanilla texture for all slots. + */ + public GuiSlots setSlotTexture(Function slotTexture) { + this.slotTexture = slotTexture; + return this; + } + + /** + * Allows you to use a custom per-slot slot textures, The default is the standard vanilla texture for all slots. + *

+ * Similar to {@link #setSlotTexture(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + */ + public GuiSlots setSlotTextureI(Function slotTexture) { + this.slotTexture = slot -> slotTexture.apply(slots.indexOf(slot) - firstSlot); + return this; + } + + /** + * Sets a custom slot highlight colour (The highlight you get when your cursor is over a slot.) + */ + public GuiSlots setHighlightColour(int highlightColour) { + return setHighlightColour(slot -> highlightColour); + } + + /** + * Allows you to set per-slot highlight colours, The integer passed to the function is the + * index of the slot within the {@link SlotGroup} + */ + public GuiSlots setHighlightColour(Function highlightColour) { + this.highlightColour = highlightColour; + return this; + } + + /** + * Allows you to set per-slot highlight colours, The integer passed to the function is the + * index of the slot within the {@link SlotGroup} + *

+ * Similar to {@link #setHighlightColour(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + */ + public GuiSlots setHighlightColourI(Function highlightColour) { + this.highlightColour = slot -> highlightColour.apply(slots.indexOf(slot) - firstSlot); + return this; + } + + /** + * Applies a single empty slot icon to all slots. + * Recommended texture size is 16x16 + */ + public GuiSlots setEmptyIcon(SpriteSupplier texture) { + return setEmptyIcon(index -> texture); + } + + /** + * Allows you to provide a texture to be rendered in each slot when the slot is empty. + * Recommended texture size is 16x16 + * + * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. + */ + public GuiSlots setEmptyIcon(Function slotIcons) { + this.slotIcons = slotIcons; + return this; + } + + /** + * Allows you to provide a texture to be rendered in each slot when the slot is empty. + * Recommended texture size is 16x16 + *

+ * Similar to {@link #setEmptyIcon(Function)} except you are given the index of the slot within the {@link GuiSlots} element. + * + * @param slotIcons A function that is given the slot index within the {@link SlotGroup}, and should return a material or null. + */ + public GuiSlots setEmptyIconI(Function slotIcons) { + this.slotIcons = slot -> slotIcons.apply(slots.indexOf(slot) - firstSlot); + return this; + } + + /** + * Allows you to attach an overlay renderer that will get called for each slot, after all slots have been rendered. + * This can be used to render pretty much anything you want to overtop the slot. + * + * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. + */ + public GuiSlots setSlotOverlay(TriConsumer slotOverlay) { + this.slotOverlay = slotOverlay; + return this; + } + + /** + * Allows you to attach an overlay renderer that will get called for each slot, after all slots have been rendered. + * This can be used to render pretty much anything you want to overtop the slot. + *

+ * Similar to {@link #setSlotOverlay(TriConsumer)} except you are given the index of the slot within the {@link GuiSlots} element. + * + * @param slotOverlay Render callback providing the slot, screen position of the slot (top-left corner) and the active GuiRender. + */ + public GuiSlots setSlotOverlayI(TriConsumer slotOverlay) { + this.slotOverlay = (slot, position, render) -> slotOverlay.accept(slots.indexOf(slot) - firstSlot, position, render); + return this; + } + + public GuiSlots setXSlotSpacing(int xSlotSpacing) { + this.xSlotSpacing = xSlotSpacing; + return this; + } + + public GuiSlots setYSlotSpacing(int ySlotSpacing) { + this.ySlotSpacing = ySlotSpacing; + return this; + } + + public GuiSlots setSlotSpacing(int xSlotSpacing, int ySlotSpacing) { + this.xSlotSpacing = xSlotSpacing; + this.ySlotSpacing = ySlotSpacing; + return this; + } + + //=== Internal Methods ===// + + private void updateSlots(GuiElement root) { + int columns = Math.min(this.columns, slotCount); + int rows = Math.max(1, slotCount / columns); + double width = (columns * 18) + (columns - 1) * xSlotSpacing; + double height = (rows * 18) + (rows - 1) * ySlotSpacing; + int top = (int) (yCenter() - (height / 2) - root.yMin()); + int left = (int) (xCenter() - (width / 2) - root.xMin()); + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + int x = index % columns; + int y = index / columns; + slot.x = left + (x * 18) + 1 + (x * xSlotSpacing); + slot.y = top + (y * 18) + 1 + (y * ySlotSpacing); + } + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + GuiElement root = getModularGui().getRoot(); + updateSlots(root); + + Slot highlightSlot = null; + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + slotTexture.apply(slot).ifPresent(icon -> { + render.cc$blitSprite(RenderPipelines.GUI_TEXTURED, icon, slot.x + root.xMin() - 1, slot.y + root.yMin() - 1, 18, 18); + }); + } + + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + if (!slot.isActive()) continue; + if (!slot.hasItem()) { + slotIcons.apply(slot).ifPresent(icon -> { + render.cc$blitSprite(RenderPipelines.GUI_TEXTURED, icon, slot.x + root.xMin(), slot.y + root.yMin(), 16, 16); + }); + } + + screenAccess.doRenderSlot(render, slot); + if (MathHelper.isInRect(slot.x + root.xMin(), slot.y + root.yMin(), 16, 16, mouseX, mouseY) && !blockMouseOver(this, mouseX, mouseY) && isMouseOver()) { + highlightSlot = slot; + } + } + + if (slotOverlay != null) { + for (int index = 0; index < slotCount; index++) { + Slot slot = slots.getSlot(index + firstSlot); + if (!slot.isActive()) continue; + slotOverlay.accept(slot, Position.create(slot.x + root.xMin(), slot.y + root.yMin()), render); + } + } + + if (highlightSlot != null) { + render.cc$fill(highlightSlot.x + root.xMin(), highlightSlot.y + root.yMin(), 16, 16, highlightColour.apply(highlightSlot)); + } + } + + public record Player(GuiElement container, GuiSlots main, GuiSlots hotBar) { + + public FastStream stream() { + return FastStream.of(main, hotBar); + } + } + + public record PlayerWithArmor(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor) { + + public FastStream stream() { + return FastStream.of(main, hotBar, armor); + } + } + + public record PlayerAll(GuiElement container, GuiSlots main, GuiSlots hotBar, GuiSlots armor, GuiSlots offHand) { + + public FastStream stream() { + return FastStream.of(main, hotBar, armor, offHand); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java new file mode 100644 index 00000000..7e947f60 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiText.java @@ -0,0 +1,268 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ForegroundRender; +import codechicken.lib.gui.modular.lib.geometry.Align; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.lib.geometry.Position; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.util.FormattedCharSequence; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Align.MAX; +import static codechicken.lib.gui.modular.lib.geometry.Align.MIN; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.dynamic; +import static java.util.Objects.requireNonNull; + +/** + * Created by brandon3055 on 31/08/2023 + */ +public class GuiText extends GuiElement implements ForegroundRender { + + private Supplier text; + private Supplier shadow = () -> true; + private Supplier textColour = () -> 0xFFFFFFFF; + private @Nullable Supplier rotation = null; + private Position rotatePoint = Position.create(() -> xSize() / 2, () -> ySize() / 2); + private boolean trim = false; + private boolean wrap = false; + private boolean scroll = true; + private Align alignment = Align.CENTER; + //TODO, Arbitrary rotation is fun, But may want to switch to Axis, with option for "reverse" + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(GuiParent parent) { + this(parent, () -> null); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(GuiParent parent, @Nullable Component text) { + this(parent, () -> text); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiText(GuiParent parent, Supplier<@Nullable Component> text) { + super(parent); + this.text = text; + } + + /** + * Apply a dynamic height constraint that sets the height based on text height (accounting for wrapping) + */ + public GuiText autoHeight() { + constrain(GeoParam.HEIGHT, dynamic(() -> wrap ? (double) font().wordWrapHeight(requireNonNull(getText()), (int) xSize()) : font().lineHeight)); + return this; + } + + public GuiText autoWidth() { + constrain(GeoParam.WIDTH, dynamic(() -> (double) font().width(requireNonNull(getText())))); + return this; + } + + public GuiText setTextSupplier(Supplier<@Nullable Component> textSupplier) { + this.text = textSupplier; + return this; + } + + public GuiText setText(@Nullable Component text) { + this.text = () -> text; + return this; + } + + public GuiText setText(String text) { + this.text = () -> Component.literal(text); + return this; + } + + public GuiText setTranslatable(String translationKey) { + this.text = () -> Component.translatable(translationKey); + return this; + } + + @Nullable + public Component getText() { + return text.get(); + } + + public GuiText setAlignment(Align alignment) { + this.alignment = alignment; + return this; + } + + public Align getAlignment() { + return alignment; + } + + /** + * If set to true the text will be trimmed if it is too long to fit within the bounds on the element. + * Default disabled. + * Setting this to true will automatically disable wrap and scroll ether are enabled. + */ + public GuiText setTrim(boolean trim) { + this.trim = trim; + if (trim) wrap = scroll = false; + return this; + } + + public boolean getTrim() { + return trim; + } + + /** + * Set to true the text will be wrapped (rendered as multiple lines of text) if it is too long to fit within the size of the element. + * Default disabled. + * Setting this to true will automatically disable trim and scroll ether are enabled. + */ + public GuiText setWrap(boolean wrap) { + this.wrap = wrap; + if (wrap) trim = scroll = false; + return this; + } + + public boolean getWrap() { + return wrap; + } + + /** + * Set to true the text scroll using the same logic as vanillas widgets if the text is too long to fit within the elements bounds + * Default enabled. + * Setting this to true will automatically disable trim and wrap ether are enabled. + */ + public GuiText setScroll(boolean scroll) { + this.scroll = scroll; + if (scroll) trim = wrap = false; + return this; + } + + public boolean getScroll() { + return scroll; + } + + public GuiText setShadow(Supplier shadow) { + this.shadow = shadow; + return this; + } + + public GuiText setShadow(boolean shadow) { + this.shadow = () -> shadow; + return this; + } + + public boolean getShadow() { + return shadow.get(); + } + + public GuiText setTextColour(Supplier textColour) { + this.textColour = textColour; + return this; + } + + public GuiText setTextColour(int textColour) { + this.textColour = () -> textColour; + return this; + } + + public int getTextColour() { + return textColour.get(); + } + + /** + * Set rotation angle in degrees + * //TODO, Does not work when text scroll is used + */ + public GuiText setRotation(double rotation) { + return setRotation(() -> rotation); + } + + /** + * Dynamic rotation control, Set to null to disable rotation. + * Rotation angle is in degrees + * //TODO, Does not work when text scroll is used + */ + public GuiText setRotation(@Nullable Supplier rotation) { + this.rotation = rotation; + return this; + } + + /** + * Sets the point around which the text rotates relative to the top left of the element. + * Default rotation point is a dynamic point set to the dead center of the element. + */ + public GuiText setRotatePoint(Position rotatePoint) { + this.rotatePoint = rotatePoint; + return this; + } + + @Override + public void renderInFront(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + Component component = getText(); + if (component == null) return; + Font font = Minecraft.getInstance().font; + + int textHeight = font.lineHeight; + int textWidth = font.width(component); + boolean tooLong = textWidth > xSize(); + double yPos = (yMin() + ySize() / 2 - textHeight / 2D) + 1; //Adding 1 here makes the text look 'visually' centered, Text height includes the height of the optional underline. + + var pose = graphics.pose(); + if (rotation != null) { + pose.pushMatrix(); + pose.translate((float) (xMin() + rotatePoint.x()), (float) (yMin() + rotatePoint.y())); + pose.rotate(rotation.get().floatValue()); + pose.translate((float) (-xMin() - rotatePoint.x()), (float) (-yMin() - rotatePoint.y())); + } + + //Draw Trimmed + if (tooLong && getTrim()) { + Component tail = Component.literal("...").setStyle(getText().getStyle()); + FormattedText head = font.getSplitter().headByWidth(component, (int) xSize() - font.width(tail), getText().getStyle()); + FormattedCharSequence formatted = Language.getInstance().getVisualOrder(FormattedText.composite(head, tail)); + textWidth = font.width(formatted); + + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + graphics.cc$drawString(font, formatted, xPos, yPos, getTextColour(), getShadow()); + } + //Draw Wrapped + else if ((tooLong || font().split(component, Integer.MAX_VALUE).size() > 1) && wrap) { + textHeight = font.wordWrapHeight(component, (int) xSize()); + List list = font.split(component, (int) xSize()); + + yPos = yMin() + ySize() / 2 - textHeight / 2D; + for (FormattedCharSequence line : list) { + int lineWidth = font.width(line); + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - lineWidth : xMin() + xSize() / 2 - lineWidth / 2D; + graphics.cc$drawString(font, line, xPos, yPos, getTextColour(), getShadow()); + yPos += font.lineHeight; + } + } + //Draw Scrolling + else if (tooLong && scroll) { + graphics.cc$enableScissor(getRectangle()); + graphics.cc$drawScrollingString(font, component, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + graphics.cc$disableScissor(); + } + //Draw + else { + double xPos = alignment == MIN ? xMin() : alignment == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + graphics.cc$drawString(font, component, xPos, yPos, getTextColour(), getShadow()); + } + + if (rotation != null) { + pose.popMatrix(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java new file mode 100644 index 00000000..14498a2b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextField.java @@ -0,0 +1,669 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.TextState; +import codechicken.lib.gui.modular.lib.geometry.Constraint; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import com.mojang.blaze3d.platform.InputConstants; +import net.minecraft.util.Util; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import net.minecraft.util.StringUtil; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.glfw.GLFW; + +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * TODO, Re write this, Its currently mostly pulled from the TextField in Gui v2 + *

+ * Created by brandon3055 on 03/09/2023 + */ +public class GuiTextField extends GuiElement implements BackgroundRender { + + private int tick; + private int cursorPos; + private int maxLength = 32; + private int displayPos; + private int highlightPos; + private boolean focused; + private boolean shiftPressed; + + private Supplier isEditable = () -> true; + private Supplier isFocusable = () -> true; + private Supplier canLoseFocus = () -> true; + + private Runnable onEditComplete = null; + private Runnable onEnterPressed = null; + + private TextState textState = TextState.simpleState(""); + private Supplier shadow = () -> true; + private Supplier textColor = () -> 0xe0e0e0; + + private Supplier suggestion = null; + private Supplier suggestionColour = () -> 0x7f7f80; + private Supplier suggestionShadow = () -> true; + + private Predicate filter = Objects::nonNull; + private BiFunction formatter = (string, pos) -> FormattedCharSequence.forward(string, Style.EMPTY); + + public GuiTextField(GuiParent parent) { + super(parent); + } + + /** + * Creates a simple text box with a simple bordered background. + * Using colours 0xFF000000, 0xFFFFFFFF, 0xE0E0E0 will get you a text box identical to the one in a command block + */ + public static TextField create(GuiElement parent, int backgroundColour, int borderColour, int textColour) { + GuiRectangle background = new GuiRectangle(parent) + .rectangle(backgroundColour, borderColour); + + GuiTextField textField = new GuiTextField(background) + .setTextColor(textColour) + .constrain(TOP, Constraint.relative(background.get(TOP), 1)) + .constrain(BOTTOM, Constraint.relative(background.get(BOTTOM), -1)) + .constrain(LEFT, Constraint.relative(background.get(LEFT), 4)) + .constrain(RIGHT, Constraint.relative(background.get(RIGHT), -4)); + + return new TextField(background, textField); + } + + //=== Text field setup ===// + + /** + * Called when the user clicks outside the text box, or when they press enter + */ + public GuiTextField setOnEditComplete(Runnable onEditComplete) { + this.onEditComplete = onEditComplete; + return this; + } + + /** + * Called when the user presses enter key (Including numpad enter) with the text box ion focus + */ + public GuiTextField setEnterPressed(Runnable onEnterPressed) { + this.onEnterPressed = onEnterPressed; + return this; + } + + /** + * The {@link TextState} is an accessor for the current text value. + * It simply contains string getter and setter methods. + * You can use this to link the text field to some external value. + */ + public GuiTextField setTextState(TextState textState) { + this.textState = textState; + return this; + } + + public TextState getTextState() { + return textState; + } + + public GuiTextField setTextColor(Supplier textColor) { + this.textColor = textColor; + return this; + } + + public GuiTextField setTextColor(int textColor) { + return setTextColor(() -> textColor); + } + + /** + * Should the text be rendered with a shadow? + */ + public GuiTextField setShadow(Supplier shadow) { + this.shadow = shadow; + return this; + } + + /** + * Should the text be rendered with a shadow? + */ + public GuiTextField setShadow(boolean shadow) { + return setShadow(() -> shadow); + } + + /** + * Set the "suggestion" text that is displayed when the text field is empty. + */ + public GuiTextField setSuggestion(Component suggestion) { + return setSuggestion(suggestion == null ? null : () -> suggestion); + } + + /** + * Set the "suggestion" text that is displayed when the text field is empty. + */ + public GuiTextField setSuggestion(@Nullable Supplier suggestion) { + this.suggestion = suggestion; + return this; + } + + /** + * Set the colour of the suggestion text. + */ + public GuiTextField setSuggestionColour(Supplier suggestionColour) { + this.suggestionColour = suggestionColour; + return this; + } + + public GuiTextField setSuggestionColour(int suggestionColour) { + this.suggestionColour = () -> suggestionColour; + return this; + } + + public GuiTextField setSuggestionShadow(Supplier suggestionShadow) { + this.suggestionShadow = suggestionShadow; + return this; + } + + public GuiTextField setSuggestionShadow(boolean suggestionShadow) { + this.suggestionShadow = () -> suggestionShadow; + return this; + } + + /** + * Allows you to apply a fielder to this text field. + * Whenever this field's value is updated, If the new value does not pass this filter + * It will not be applied. + */ + public GuiTextField setFilter(Predicate filter) { + this.filter = filter; + return this; + } + + /** + * Formats the current text value for display to the user. + * The integer is the current display start position within the current field value. + */ + public GuiTextField setFormatter(BiFunction formatter) { + this.formatter = formatter; + return this; + } + + /** + * If set to false, it will not be possible for the text field to lose focus via normal means. + * Focus can still be set via {@link #setFocus(boolean)} + */ + public GuiTextField setCanLoseFocus(boolean canLoseFocus) { + return setCanLoseFocus(() -> canLoseFocus); + } + + /** + * If set to false, it will not be possible for the text field to lose focus via normal means. + * Focus can still be set via {@link #setFocus(boolean)} + */ + public GuiTextField setCanLoseFocus(Supplier canLoseFocus) { + this.canLoseFocus = canLoseFocus; + return this; + } + + /** + * If false, It will not be possible to focus this element by clicking on it. + */ + public GuiTextField setFocusable(boolean focusable) { + return setFocusable(() -> focusable); + } + + /** + * If false, It will not be possible to focus this element by clicking on it. + */ + public GuiTextField setFocusable(Supplier focusable) { + this.isFocusable = focusable; + return this; + } + + /** + * If false, It will not be possible for the user to edit the value of this text field. + */ + public GuiTextField setEditable(boolean editable) { + return setEditable(() -> editable); + } + + /** + * If false, It will not be possible for the user to edit the value of this text field. + */ + public GuiTextField setEditable(Supplier editable) { + this.isEditable = editable; + return this; + } + + /** + * Sets the maximum allowed text length + */ + public GuiTextField setMaxLength(int newWidth) { + String value = getValue(); + maxLength = newWidth; + if (value.length() > newWidth) { + textState.setText(value.substring(0, newWidth)); + } + return this; + } + + private int getMaxLength() { + return maxLength; + } + + //=== Text field logic ===// + + /** + * Note, Initial value should be set after element is constrained, + * If element width is zero when set, nothing will render until the field is updated. + * TODO, I need to fix this. Element size should be able to change dynamically without things breaking. + */ + public GuiTextField setValue(String newValue) { + if (this.filter.test(newValue)) { + if (newValue.length() > maxLength) { + textState.setText(newValue.substring(0, maxLength)); + } else { + textState.setText(newValue); + } + moveCursorToEnd(); + setHighlightPos(cursorPos); + } + return this; + } + + public String getValue() { + return textState.getText(); + } + + public String getHighlighted() { + int i = Math.min(cursorPos, highlightPos); + int j = Math.max(cursorPos, highlightPos); + return getValue().substring(i, j); + } + + public void insertText(String text) { + String value = getValue(); + int selectStart = Math.min(cursorPos, highlightPos); + int selectEnd = Math.max(cursorPos, highlightPos); + int freeSpace = maxLength - value.length() - (selectStart - selectEnd); + String toInsert = StringUtil.filterText(text); + int insertLen = toInsert.length(); + if (freeSpace < insertLen) { + toInsert = toInsert.substring(0, freeSpace); + insertLen = freeSpace; + } + + String newValue = (new StringBuilder(value)).replace(selectStart, selectEnd, toInsert).toString(); + if (filter.test(newValue)) { + textState.setText(newValue); + setCursorPosition(selectStart + insertLen); + setHighlightPos(cursorPos); + } + } + + private void deleteText(int i) { + if (Minecraft.getInstance().hasControlDown()) { + deleteWords(i); + } else { + deleteChars(i); + } + } + + public void deleteWords(int i) { + if (!getValue().isEmpty()) { + if (highlightPos != cursorPos) { + insertText(""); + } else { + deleteChars(getWordPosition(i) - cursorPos); + } + } + } + + public void deleteChars(int i1) { + String value = getValue(); + if (!value.isEmpty()) { + if (highlightPos != cursorPos) { + insertText(""); + } else { + int i = getCursorPos(i1); + int j = Math.min(i, cursorPos); + int k = Math.max(i, cursorPos); + if (j != k) { + String s = (new StringBuilder(value)).delete(j, k).toString(); + if (filter.test(s)) { + textState.setText(s); + moveCursorTo(j); + } + } + } + } + } + + public int getWordPosition(int i) { + return getWordPosition(i, getCursorPosition()); + } + + private int getWordPosition(int i, int i1) { + return getWordPosition(i, i1, true); + } + + private int getWordPosition(int i1, int i2, boolean b) { + String value = getValue(); + int i = i2; + boolean flag = i1 < 0; + int j = Math.abs(i1); + + for (int k = 0; k < j; ++k) { + if (!flag) { + int l = value.length(); + i = value.indexOf(32, i); + if (i == -1) { + i = l; + } else { + while (b && i < l && value.charAt(i) == ' ') { + ++i; + } + } + } else { + while (b && i > 0 && value.charAt(i - 1) == ' ') { + --i; + } + while (i > 0 && value.charAt(i - 1) != ' ') { + --i; + } + } + } + + return i; + } + + public void moveCursor(int pos) { + moveCursorTo(getCursorPos(pos)); + } + + private int getCursorPos(int i) { + return Util.offsetByCodepoints(getValue(), cursorPos, i); + } + + public void moveCursorTo(int pos, boolean notify) { + setCursorPosition(pos); + if (!shiftPressed) { + setHighlightPos(cursorPos); + } + } + + public void moveCursorTo(int pos) { + moveCursorTo(pos, true); + } + + public void setCursorPosition(int pos) { + cursorPos = Mth.clamp(pos, 0, getValue().length()); + } + + public void moveCursorToStart() { + moveCursorTo(0); + } + + public void moveCursorToEnd(boolean notify) { + moveCursorTo(getValue().length(), notify); + } + + public void moveCursorToEnd() { + moveCursorToEnd(true); + } + + public boolean isEditable() { + return isEditable.get(); + } + + public void setFocus(boolean focused) { + if (this.focused && !focused && onEditComplete != null) { + onEditComplete.run(); + } + this.focused = focused; + } + + public boolean isFocused() { + return focused; + } + + public int getCursorPosition() { + return cursorPos; + } + + public void setHighlightPos(int newPos) { + String value = getValue(); + int length = value.length(); + highlightPos = Mth.clamp(newPos, 0, length); + + if (displayPos > length) { + displayPos = length; + } + + int width = (int) xSize(); + String visibleText = font().plainSubstrByWidth(value.substring(displayPos), width); + int endPos = displayPos + visibleText.length(); + if (highlightPos == displayPos) { + displayPos -= font().plainSubstrByWidth(value, width, true).length(); + } + + if (highlightPos > endPos) { + displayPos += highlightPos - endPos; + } else if (highlightPos <= displayPos) { + displayPos -= displayPos - highlightPos; + } + + displayPos = Mth.clamp(displayPos, 0, length); + } + + //=== Input Handling ===// + + @Override + public boolean keyPressed(KeyEvent event) { + if (!canConsumeInput()) { + return false; + } else { + shiftPressed = event.hasShiftDown(); + if (event.isSelectAll()) { + moveCursorToEnd(); + setHighlightPos(0); + return true; + } else if (event.isCopy()) { + Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); + return true; + } else if (event.isPaste()) { + if (isEditable()) { + insertText(Minecraft.getInstance().keyboardHandler.getClipboard()); + } + + return true; + } else if (event.isCut()) { + Minecraft.getInstance().keyboardHandler.setClipboard(getHighlighted()); + if (isEditable()) { + insertText(""); + } + + return true; + } else { + switch (event.key()) { + case InputConstants.KEY_BACKSPACE: + if (isEditable()) { + shiftPressed = false; + deleteText(-1); + shiftPressed = event.hasShiftDown(); + } + + return true; + case InputConstants.KEY_NUMPADENTER: + case InputConstants.KEY_RETURN: { + if (onEditComplete != null) { + onEditComplete.run(); + } + if (onEnterPressed != null) { + onEnterPressed.run(); + } + } + case InputConstants.KEY_INSERT: + case InputConstants.KEY_DOWN: + case InputConstants.KEY_UP: + case InputConstants.KEY_PAGEUP: + case InputConstants.KEY_PAGEDOWN: + default: + //Consume key presses when we are typing so we dont do something dumb like close the screen when you type e + return event.key() != GLFW.GLFW_KEY_ESCAPE; + case InputConstants.KEY_DELETE: + if (isEditable()) { + shiftPressed = false; + deleteText(1); + shiftPressed = event.hasShiftDown(); + } + return true; + case InputConstants.KEY_RIGHT: + if (event.hasControlDown()) { + moveCursorTo(getWordPosition(1)); + } else { + moveCursor(1); + } + return true; + case InputConstants.KEY_LEFT: + if (event.hasControlDown()) { + moveCursorTo(getWordPosition(-1)); + } else { + moveCursor(-1); + } + return true; + case InputConstants.KEY_HOME: + moveCursorToStart(); + return true; + case InputConstants.KEY_END: + moveCursorToEnd(); + return true; + } + } + } + } + + public boolean canConsumeInput() { + return isFocused() && isEditable() && isEnabled(); + } + + @Override + public boolean keyReleased(KeyEvent event, boolean consumed) { + this.shiftPressed = event.hasShiftDown(); + return super.keyReleased(event, consumed); + } + + @Override + public boolean charTyped(CharacterEvent event) { + if (!canConsumeInput()) { + return false; + } else if (StringUtil.isAllowedChatCharacter(event.codepoint())) { + if (isEditable()) { + insertText(event.codepointAsString()); + } + return true; + } else { + return false; + } + } + + @Override + public boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + consumed = super.mouseClicked(event, consumed); + + boolean mouseOver = isMouseOver(); + if (isFocused() && !mouseOver) { + setFocus(isFocusable.get() && !canLoseFocus.get()); + } + + if (consumed) return true; + + if (canLoseFocus.get()) { + setFocus(mouseOver && isFocusable.get()); + } else { + setFocus(isFocusable.get()); + } + + if (isFocused() && mouseOver && event.button() == 0) { + int i = (int) (Mth.floor(event.x()) - xMin()); + String s = font().plainSubstrByWidth(getValue().substring(displayPos), (int) xSize()); + moveCursorTo(font().plainSubstrByWidth(s, i).length() + displayPos); + return true; + } else { + return false; + } + } + + @Override + public void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + var font = Minecraft.getInstance().font; + String value = getValue(); + int colour = textColor.get(); + + int textStart = cursorPos - displayPos; + int highlightStart = highlightPos - displayPos; + String displayText = font().plainSubstrByWidth(value.substring(displayPos), (int) xSize()); + boolean flag = textStart >= 0 && textStart <= displayText.length(); + boolean cursorBlink = isFocused() && tick / 6 % 2 == 0 && flag; + double drawX = xMin(); + double drawY = yMin() + ((ySize() - 8) / 2); + int drawEnd = (int) drawX; + + if (highlightStart > displayText.length()) { + highlightStart = displayText.length(); + } + + if (!displayText.isEmpty()) { + String drawString = flag ? displayText.substring(0, textStart) : displayText; + var formatted = formatter.apply(drawString, displayPos); + render.cc$drawString(font, formatted, drawX, drawY, colour, shadow.get()); + drawEnd += font.width(formatted) + 1; + } + + boolean flag2 = cursorPos < value.length() || value.length() >= getMaxLength(); + int k1 = drawEnd; + + if (!flag) { + k1 = (int) (textStart > 0 ? drawX + xSize() : drawX); + } else if (flag2) { + k1 = drawEnd - 1; + --drawEnd; + } + + if (!displayText.isEmpty() && flag && textStart < displayText.length()) { + render.cc$drawString(font, formatter.apply(displayText.substring(textStart), cursorPos), drawEnd, drawY, colour, shadow.get()); + } + + if (suggestion != null && value.isEmpty()) { + render.cc$drawString(font, suggestion.get(), (float) (k1 - 1), (float) drawY, suggestionColour.get(), suggestionShadow.get()); + } + + if (cursorBlink) { + if (flag2) { + render.cc$fill(k1, drawY - 1, k1 + 1, drawY + 1 + 9, -3092272); + } else { + render.cc$drawString(font, "_", (float) k1, (float) drawY, colour, shadow.get()); + } + } + + if (highlightStart != textStart) { + int l1 = (int) (drawX + font().width(displayText.substring(0, highlightStart))); + render.cc$textHighlight(k1, drawY - 1, l1 - 1, drawY + 1 + 9); + } + } + + @Override + public void tick(double mouseX, double mouseY) { + super.tick(mouseX, mouseY); + tick++; + } + + public record TextField(GuiRectangle container, GuiTextField field) { } +} + diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java new file mode 100644 index 00000000..b74febc4 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTextList.java @@ -0,0 +1,169 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.ForegroundRender; +import codechicken.lib.gui.modular.lib.geometry.Align; +import codechicken.lib.gui.modular.lib.geometry.GeoParam; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.network.chat.Component; + +import java.util.List; +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Align.MAX; +import static codechicken.lib.gui.modular.lib.geometry.Align.MIN; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.dynamic; + +/** + * Created by brandon3055 on 10/10/2023 + */ +public class GuiTextList extends GuiElement implements ForegroundRender { + + private Supplier> text; + private Supplier shadow = () -> true; + private Supplier textColour = () -> 0xFFFFFFFF; + private boolean scroll = true; + private Align horizontalAlign = Align.CENTER; + private Align verticalAlign = Align.TOP; + private int lineSpacing = 0; + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(GuiParent parent) { + this(parent, () -> null); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(GuiParent parent, List text) { + this(parent, () -> text); + } + + /** + * @param parent parent {@link GuiParent}. + */ + public GuiTextList(GuiParent parent, Supplier> text) { + super(parent); + this.text = text; + } + + /** + * Apply a dynamic height constraint that sets the height based on text height (accounting for wrapping) + */ + public GuiTextList autoHeight() { + constrain(GeoParam.HEIGHT, dynamic(() -> (double) ((font().lineHeight + lineSpacing) * getText().size()) - 1)); + return this; + } + + public GuiTextList setTextSupplier(Supplier> textSupplier) { + this.text = textSupplier; + return this; + } + + public GuiTextList setText(List text) { + this.text = () -> text; + return this; + } + + public List getText() { + return text.get(); + } + + public GuiTextList setHorizontalAlign(Align horizontalAlign) { + this.horizontalAlign = horizontalAlign; + return this; + } + + public GuiTextList setVerticalAlign(Align verticalAlign) { + this.verticalAlign = verticalAlign; + return this; + } + + public Align getHorizontalAlign() { + return horizontalAlign; + } + + public Align getVerticalAlign() { + return verticalAlign; + } + + public GuiTextList setLineSpacing(int lineSpacing) { + this.lineSpacing = lineSpacing; + return this; + } + + public int getLineSpacing() { + return lineSpacing; + } + + /** + * Set to true the text scroll using the same logic as vanillas widgets if the text is too long to fit within the elements bounds + * Default enabled. + * Setting this to true will automatically disable trim and wrap ether are enabled. + */ + public GuiTextList setScroll(boolean scroll) { + this.scroll = scroll; + return this; + } + + public boolean getScroll() { + return scroll; + } + + public GuiTextList setShadow(Supplier shadow) { + this.shadow = shadow; + return this; + } + + public GuiTextList setShadow(boolean shadow) { + this.shadow = () -> shadow; + return this; + } + + public boolean getShadow() { + return shadow.get(); + } + + public GuiTextList setTextColour(Supplier textColour) { + this.textColour = textColour; + return this; + } + + public GuiTextList setTextColour(int textColour) { + this.textColour = () -> textColour; + return this; + } + + public int getTextColour() { + return textColour.get(); + } + + @Override + public void renderInFront(GuiGraphics render, double mouseX, double mouseY, float partialTicks) { + List list = getText(); + if (list.isEmpty()) return; + Font font = Minecraft.getInstance().font; + + double height = (list.size() * (font.lineHeight + lineSpacing)) - lineSpacing; + double yPos = verticalAlign == MIN ? yMin() : verticalAlign == MAX ? yMax() - height : (yCenter() - (height / 2)) + 1; + for (Component line : list) { + int textWidth = font.width(line); + boolean tooLong = textWidth > xSize(); + + if (tooLong && scroll) { + render.cc$enableScissor(getRectangle()); + render.cc$drawScrollingString(font, line, xMin(), yPos, xMax(), getTextColour(), getShadow(), false); + render.cc$disableScissor(); + } else { + double xPos = horizontalAlign == MIN ? xMin() : horizontalAlign == MAX ? xMax() - textWidth : xMin() + xSize() / 2 - textWidth / 2D; + render.cc$drawString(font, line, xPos, yPos, getTextColour(), getShadow()); + } + + yPos += font.lineHeight + lineSpacing; + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java new file mode 100644 index 00000000..f61aa21c --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/GuiTexture.java @@ -0,0 +1,116 @@ +package codechicken.lib.gui.modular.elements; + +import codechicken.lib.gui.modular.lib.BackgroundRender; +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.gui.modular.SpriteSupplier; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.RenderPipelines; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public class GuiTexture extends GuiElement implements BackgroundRender { + + private SpriteSupplier spriteSupplier = SpriteSupplier.EMPTY; + private Supplier colour = () -> 0xFFFFFFFF; + private @Nullable Borders dynamicBorders = null; + private Supplier rotation = () -> 0; + + public GuiTexture(GuiParent parent) { + this(parent, SpriteSupplier.EMPTY); + } + + public GuiTexture(GuiParent parent, SpriteSupplier spriteSupplier) { + super(parent); + setMaterial(spriteSupplier); + } + + public GuiTexture setMaterial(SpriteSupplier spriteSupplier) { + this.spriteSupplier = spriteSupplier; + return this; + } + + public SpriteSupplier getSprite() { + return spriteSupplier; + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * This method uses the standard border with of 5 pixels on all sides. + */ + public GuiTexture dynamicTexture() { + return dynamicTexture(5); + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * The border parameters indicate the width of border around the texture that must be maintained during the cutting and tiling process. + * For standardisation purposes the border width should be >= 5 + */ + public GuiTexture dynamicTexture(int textureBorders) { + return dynamicTexture(Borders.create(textureBorders)); + } + + /** + * Enables dynamic texture resizing though the use of cutting and tiling. + * Only works with textures that can be cut up and tiled without issues, e.g. background textures or button textures. + * The border parameters indicate the width of border around the texture that must be maintained during the cutting and tiling process. + * For standardisation purposes the border width should be >= 5 + */ + public GuiTexture dynamicTexture(@Nullable Borders textureBorders) { + dynamicBorders = textureBorders; + return this; + } + + /** + * Allows you to set an argb colour. + * This colour will be applied when rendering the texture. + */ + public GuiTexture setColour(int colourARGB) { + return setColour(() -> colourARGB); + } + + /** + * Allows you to set an argb colour provider. + * This colour will be applied when rendering the texture. + */ + public GuiTexture setColour(Supplier colour) { + this.colour = colour; + return this; + } + + /** + * Sets the texture rotation, each integer increment will rotate the texture by 90 degrees. + * (Not compatible with dynamic textures) + */ + public GuiTexture setRotation(Supplier rotation) { + this.rotation = rotation; + return this; + } + + /** + * Sets the texture rotation, each integer increment will rotate the texture by 90 degrees. + * (Not compatible with dynamic textures) + */ + public GuiTexture setRotation(int rotation) { + this.rotation = () -> rotation; + return this; + } + + @Override + public void renderBehind(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks) { + getSprite().ifPresent(sprite -> { + if (dynamicBorders != null) { + graphics.cc$blitDynamicSprite(RenderPipelines.GUI_TEXTURED, sprite, getRectangle(), dynamicBorders, colour.get()); + } else { + graphics.cc$blitSprite(RenderPipelines.GUI_TEXTURED, sprite, rotation.get(), getRectangle(), colour.get()); + } + }); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/elements/package-info.java b/src/main/java/codechicken/lib/gui/modular/elements/package-info.java new file mode 100644 index 00000000..0fff58bb --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/elements/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.elements; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java new file mode 100644 index 00000000..4836da56 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/BackgroundRender.java @@ -0,0 +1,23 @@ +package codechicken.lib.gui.modular.lib; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.GuiGraphics; + +/** + * Allows a Gui Elements to render content behind child elements. + * This is the default render mode for the majority of elements. + *

+ * Created by brandon3055 on 07/08/2023 + */ +public interface BackgroundRender { + + /** + * Used to render content behind this elements child elements. + * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * Where applicable, always use push/pop to ensure the stack is returned to its original state after your rendering is complete. + * + * @param render Contains gui context information as well as essential render methods/utils including the PoseStack. + */ + void renderBehind(GuiGraphics render, double mouseX, double mouseY, float partialTicks); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java b/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java new file mode 100644 index 00000000..850e0f14 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ColourState.java @@ -0,0 +1,72 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.colour.Colour; +import codechicken.lib.colour.ColourARGB; + +import java.util.Locale; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 19/11/2023 + */ +public interface ColourState { + + int get(); + + default ColourARGB getColour() { + return new ColourARGB(get()); + } + + void set(int colour); + + default void set(Colour colour) { + set(colour.argb()); + } + + default String getHexColour() { + return Integer.toHexString(get()).toUpperCase(Locale.ROOT); + } + + default void setHexColour(String hexColour) { + try { + set(Integer.parseUnsignedInt(hexColour, 16)); + } catch (Throwable e) { + set(0); + } + } + + static ColourState create() { + return create(null); + } + + static ColourState create(Consumer listener) { + return new ColourState() { + int colour = 0; + @Override + public int get() { + return colour; + } + + @Override + public void set(int colour) { + this.colour = colour; + if (listener != null) listener.accept(colour); + } + }; + } + + static ColourState create(Supplier getter, Consumer setter) { + return new ColourState() { + @Override + public int get() { + return getter.get(); + } + + @Override + public void set(int colour) { + setter.accept(colour); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java new file mode 100644 index 00000000..6399df5e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/Constraints.java @@ -0,0 +1,172 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.ConstrainedGeometry; +import net.covers1624.quack.annotation.ReplaceWithExpr; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.*; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This class contains a bunch of static helper methods that can be used to quickly apply common constraints. + * The plan is to keep adding common constraints to this class as they pop up. + *

+ * Created by brandon3055 on 28/08/2023 + */ +public class Constraints { + + /** + * Bind an elements geometry to a reference element. + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference) { + bind(element, reference, 0.0); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, double borders) { + bind(element, reference, borders, borders, borders, borders); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * + * @param element The element to be bound. + * @param reference The element to be bound to. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, double top, double left, double bottom, double right) { + element.constrain(TOP, relative(reference.get(TOP), top)); + element.constrain(LEFT, relative(reference.get(LEFT), left)); + element.constrain(BOTTOM, relative(reference.get(BOTTOM), -bottom)); + element.constrain(RIGHT, relative(reference.get(RIGHT), -right)); + } + + /** + * Bind an elements geometry to a reference element with border offsets. (Border offsets may be positive or negative) + * The border offsets are dynamic, meaning if the values stored in the {@link Borders} object are updated, this binding will reflect those changes automatically. + * + * @param element The element to be bound. + * @param reference The element to be bound to. + * @param borders Border offsets. + */ + public static void bind(ConstrainedGeometry element, ConstrainedGeometry reference, Borders borders) { + element.constrain(TOP, relative(reference.get(TOP), borders::top)); + element.constrain(LEFT, relative(reference.get(LEFT), borders::left)); + element.constrain(BOTTOM, relative(reference.get(BOTTOM), () -> -borders.bottom())); + element.constrain(RIGHT, relative(reference.get(RIGHT), () -> -borders.right())); + } + + public static void size(ConstrainedGeometry element, double width, double height) { + element.constrain(WIDTH, literal(width)); + element.constrain(HEIGHT, literal(height)); + } + + public static void size(ConstrainedGeometry element, Supplier width, Supplier height) { + element.constrain(WIDTH, dynamic(width)); + element.constrain(HEIGHT, dynamic(height)); + } + + public static void pos(ConstrainedGeometry element, double left, double top) { + element.constrain(LEFT, literal(left)); + element.constrain(TOP, literal(top)); + } + + public static void pos(ConstrainedGeometry element, Supplier left, Supplier top) { + element.constrain(LEFT, dynamic(left)); + element.constrain(TOP, dynamic(top)); + } + + public static void center(ConstrainedGeometry element, ConstrainedGeometry centerOn) { + element.constrain(TOP, midPoint(centerOn.get(TOP), centerOn.get(BOTTOM), () -> element.ySize() / -2)); + element.constrain(LEFT, midPoint(centerOn.get(LEFT), centerOn.get(RIGHT), () -> element.xSize() / -2)); + } + + public static void center(ConstrainedGeometry element, ConstrainedGeometry centerOn, double xOffset, double yOffset) { + element.constrain(TOP, midPoint(centerOn.get(TOP), centerOn.get(BOTTOM), () -> (element.ySize() / -2) + yOffset)); + element.constrain(LEFT, midPoint(centerOn.get(LEFT), centerOn.get(RIGHT), () -> (element.xSize() / -2) + xOffset)); + } + + /** + * Constrain the specified element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + */ + @Deprecated + @ReplaceWithExpr ("target.placeInside") + public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { + target.placeInside(reference, position); + } + + /** + * Constrain the specified element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + @Deprecated + @ReplaceWithExpr ("target.placeInside") + public static void placeInside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { + target.placeInside(reference, position, xOffset, yOffset); + } + + /** + * Constrain the specified element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + */ + @Deprecated + @ReplaceWithExpr ("target.placeOutside") + public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position) { + target.placeOutside(reference, position); + } + + /** + * Constrain the specified element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param target The element whose position we are setting. + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + @Deprecated + @ReplaceWithExpr ("target.placeOutside") + public static void placeOutside(ConstrainedGeometry target, ConstrainedGeometry reference, LayoutPos position, double xOffset, double yOffset) { + target.placeOutside(reference, position, xOffset, yOffset); + } + + public enum LayoutPos { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + MIDDLE_RIGHT, + MIDDLE_LEFT, + BOTTOM_RIGHT, + BOTTOM_CENTER, + BOTTOM_LEFT + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java b/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java new file mode 100644 index 00000000..6db976a5 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ContentElement.java @@ -0,0 +1,14 @@ +package codechicken.lib.gui.modular.lib; + + +import codechicken.lib.gui.modular.elements.GuiElement; + +/** + * Implemented by elements that have a separate child element to which content should be added. + * e.g. scroll element, manipulable element etc... + * Created by brandon3055 on 13/11/2023 + */ +public interface ContentElement> { + + T getContentElement(); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java new file mode 100644 index 00000000..c073addf --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/CursorHelper.java @@ -0,0 +1,100 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.CodeChickenLib; +import net.minecraft.client.Minecraft; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.Resource; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.lwjgl.BufferUtils; +import org.lwjgl.glfw.GLFW; +import org.lwjgl.glfw.GLFWImage; +import org.lwjgl.system.MemoryUtil; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Created by brandon3055 on 11/5/20. + */ +public class CursorHelper { + public static final Logger LOGGER = LogManager.getLogger(); + + public static final Identifier DRAG = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/drag.png"); + public static final Identifier RESIZE_H = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_h.png"); + public static final Identifier RESIZE_V = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_v.png"); + public static final Identifier RESIZE_TRBL = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_trbl.png"); + public static final Identifier RESIZE_TLBR = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "textures/gui/cursors/resize_diag_tlbr.png"); + + private static final Map cursors = new HashMap<>(); + private static Identifier active = null; + + private static long createCursor(Identifier cursorTexture) { + try { + Resource resource = Minecraft.getInstance().getResourceManager().getResource(cursorTexture).orElse(null); + if (resource == null) return MemoryUtil.NULL; + BufferedImage bufferedimage = ImageIO.read(resource.open()); + GLFWImage glfwImage = imageToGLFWImage(bufferedimage); + return GLFW.glfwCreateCursor(glfwImage, 16, 16); + } catch (Exception e) { + LOGGER.warn("An error occurred while creating cursor", e); + } + return 0; + } + + private static GLFWImage imageToGLFWImage(BufferedImage image) { + if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) { + final BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); + final Graphics2D graphics = convertedImage.createGraphics(); + final int targetWidth = image.getWidth(); + final int targetHeight = image.getHeight(); + graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null); + graphics.dispose(); + image = convertedImage; + } + final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4); + for (int i = 0; i < image.getHeight(); i++) { + for (int j = 0; j < image.getWidth(); j++) { + int colorSpace = image.getRGB(j, i); + buffer.put((byte) ((colorSpace << 8) >> 24)); + buffer.put((byte) ((colorSpace << 16) >> 24)); + buffer.put((byte) ((colorSpace << 24) >> 24)); + buffer.put((byte) (colorSpace >> 24)); + } + } + buffer.flip(); + final GLFWImage result = GLFWImage.create(); + result.set(image.getWidth(), image.getHeight(), buffer); + return result; + } + + public static void setCursor(@Nullable Identifier cursor) { + if (cursor != active) { + active = cursor; + long window = Minecraft.getInstance().getWindow().handle(); + long newCursor = active == null ? 0 : cursors.computeIfAbsent(cursor, CursorHelper::createCursor); + GLFW.glfwSetCursor(window, newCursor); + } + } + + public static void resetCursor() { + if (active != null) { + setCursor(null); + } + } + + public static void onResourceReload() { + cursors.values().forEach(cursor -> { + if (cursor != MemoryUtil.NULL) { + GLFW.glfwDestroyCursor(cursor); + } + }); + cursors.clear(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java new file mode 100644 index 00000000..77c167e1 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/DynamicTextures.java @@ -0,0 +1,30 @@ +package codechicken.lib.gui.modular.lib; + +import net.minecraft.resources.Identifier; + +import java.util.function.Function; + +/** + * Designed for use with DynamicTextureProvider + *

+ * Created by brandon3055 on 07/09/2023 + */ +public interface DynamicTextures { + + void makeTextures(Function textures); + + default String dynamicTexture(Function textures, Identifier dynamicInput, Identifier outputLocation, int width, int height, int border) { + return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, border, border, border, border)); + } + + default String dynamicTexture(Function textures, Identifier dynamicInput, Identifier outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + return textures.apply(new DynamicTexture(dynamicInput, outputLocation, width, height, topBorder, leftBorder, bottomBorder, rightBorder)); + } + + record DynamicTexture(Identifier dynamicInput, Identifier outputLocation, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + public String guiTexturePath() { + return outputLocation.getPath().replace("textures/gui/", "").replace(".gui", ""); + } + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java new file mode 100644 index 00000000..66f36548 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ElementEvents.java @@ -0,0 +1,259 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.elements.GuiElement; +import com.google.common.collect.Lists; +import net.minecraft.client.input.CharacterEvent; +import net.minecraft.client.input.KeyEvent; +import net.minecraft.client.input.MouseButtonEvent; + +import java.util.List; + +/** + * This class defines the default implementation for all Screen events. + * Input events in Modular GUI v2 work similar to v2, events are passed to all elements recursively in a top-down order, + * and if any element 'consumes' the event, it will not be passed any further down the chain. + * However, this approach had issues in v2, because there are certain situations where an element needs to receive an event even if it has been consumed. + * To deal with that we now have two methods for each event, the main handler method that will always get called, and uses a 'consumed' flag to track whether the event has been consumed, + * as well as a simpler convenience method that will only get called if the event has not already been canceled, and does not require you to call super. + *

+ * Created by brandon3055 on 09/08/2023 + */ +public interface ElementEvents { + + /** + * @return An unmodifiable list of all assigned child elements assigned to this parent. The list should be sorted in the order they were added. + */ + List> getChildren(); + + //=== Mouse Events ==// + + /** + * Called whenever the cursor position changes. + * Vanillas mouseDragged is not passed through because it is redundant. + * All mouse drag functionality can be archived using available events. + * + * @param mouseX new mouse X position + * @param mouseY new mouse Y position + */ + default void mouseMoved(double mouseX, double mouseY) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + child.mouseMoved(mouseX, mouseY); + } + } + } + + /** + * Override this method to implement handling for the mouseClicked event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseClicked(MouseButtonEvent, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @return true to consume event. + */ + default boolean mouseClicked(MouseButtonEvent event) { + return false; + } + + /** + * Root handler for mouseClick event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseClick handling should be implemented via {@link #mouseClicked(MouseButtonEvent)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseClicked(MouseButtonEvent event, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseClicked(event, consumed); + } + } + return consumed || mouseClicked(event) || blockMouseEvents(); + } + + /** + * Override this method to implement handling for the mouseReleased event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseReleased(MouseButtonEvent, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @return true to consume event. + */ + default boolean mouseReleased(MouseButtonEvent event) { + return false; + } + + /** + * Root handler for mouseReleased event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseReleased handling should be implemented via {@link #mouseReleased(MouseButtonEvent)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param event The mouse button event. Position, Key, and modifiers. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseReleased(MouseButtonEvent event, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseReleased(event, consumed); + } + } + return consumed || mouseReleased(event) || blockMouseEvents(); + } + + /** + * Override this method to implement handling for the mouseScrolled event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #mouseScrolled(double, double, double, double, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount + * @return true to consume event. + */ + default boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY) { + return false; + } + + /** + * Root handler for mouseScrolled event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of mouseScrolled handling should be implemented via {@link #mouseScrolled(double, double, double, double)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param mouseX Mouse X position + * @param mouseY Mouse Y position + * @param scrollX Scroll direction and amount + * @param scrollY Scroll direction and amount + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean mouseScrolled(double mouseX, double mouseY, double scrollX, double scrollY, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.mouseScrolled(mouseX, mouseY, scrollX, scrollY, consumed); + } + } + return consumed || mouseScrolled(mouseX, mouseY, scrollX, scrollY) || blockMouseEvents(); + } + + /** + * @return True to prevent mouse events from being passed to elements bellow this element. + */ + default boolean blockMouseEvents() { + return false; + } + + //=== Keyboard Events ==// + + /** + * Override this method to implement handling for the keyPressed event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyPressed(KeyEvent, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param event The key event. Key, scancode, and modifiers. + * @return true to consume event. + */ + default boolean keyPressed(KeyEvent event) { + return false; + } + + /** + * Root handler for keyPressed event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of keyPressed handling should be implemented via {@link #keyPressed(KeyEvent)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param event The key event. Key, scancode, and modifiers. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean keyPressed(KeyEvent event, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.keyPressed(event, consumed); + } + } + return consumed || keyPressed(event); + } + + /** + * Override this method to implement handling for the keyReleased event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #keyReleased(KeyEvent, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param event The key event. Key, scancode, and modifiers. + * @return true to consume event. + */ + default boolean keyReleased(KeyEvent event) { + return false; + } + + /** + * Root handler for keyReleased event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of keyReleased handling should be implemented via {@link #keyReleased(KeyEvent)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param event The key event. Key, scancode, and modifiers. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean keyReleased(KeyEvent event, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.keyReleased(event, consumed); + } + } + return consumed || keyReleased(event); + } + + /** + * Override this method to implement handling for the charTyped event. + * This event propagates through the entire gui element stack from top to bottom, If eny element consumes the event it will not propagate any further. + * For rare cases where you need to receive this even if it has been consumed, you can override {@link #charTyped(CharacterEvent, boolean)} + *

+ * Note: You do not need to call super when overriding this interface method. + * + * @param event The character event, codepoint and modifiers. + * @return true to consume event. + */ + default boolean charTyped(CharacterEvent event) { + return false; + } + + /** + * Root handler for charTyped event. This method will always be called for all elements even if the event has already been consumed. + * There are a few uses for this method, but the fast majority of charTyped handling should be implemented via {@link #charTyped(CharacterEvent)} + *

+ * Note: If overriding this method, do so with caution, You must either return true (if you wish to consume the event) or you must return the result of the super call. + * + * @param event The character event, codepoint and modifiers. + * @param consumed Will be true if this action has already been consumed. + * @return true if this event has been consumed. + */ + default boolean charTyped(CharacterEvent event, boolean consumed) { + for (GuiElement child : Lists.reverse(getChildren())) { + if (child.isEnabled()) { + consumed |= child.charTyped(event, consumed); + } + } + return consumed || charTyped(event); + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java new file mode 100644 index 00000000..2e51189f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ForegroundRender.java @@ -0,0 +1,22 @@ +package codechicken.lib.gui.modular.lib; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.gui.GuiGraphics; + +/** + * Allows a Gui Elements to render content in front of child elements. + * Note: Most elements should use {@link BackgroundRender} to render their content. + *

+ * Created by brandon3055 on 07/08/2023 + */ +public interface ForegroundRender { + + /** + * Used to render content in front of this elements child elements. + * When rendering element content, always use the {@link PoseStack} available via the provided {@link GuiRender} + * Where applicable, always use push/pop to ensure the stack is returned to its original state after your rendering is complete. + * + * @param graphics Contains gui context information as well as essential render methods/utils including the PoseStack. + */ + void renderInFront(GuiGraphics graphics, double mouseX, double mouseY, float partialTicks); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java b/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java new file mode 100644 index 00000000..32dbcbb5 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/GuiProvider.java @@ -0,0 +1,42 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.container.ContainerGuiProvider; + +/** + * This interface is used to build modular gui Screens. + * For modular gui container screens use {@link ContainerGuiProvider} + * + * Created by brandon3055 on 19/08/2023 + */ +public interface GuiProvider { + + /** + * Override this to defile a custom root gui element. + * Useful if you want to use something like a background texture or a manipulable element as the root element. + * + * @param gui The modular GUI. + * @return the root gui element. + */ + default GuiElement createRootElement(ModularGui gui) { + return new GuiElement<>(gui); + } + + /** + * Use this method to build the modular gui. + *

+ * Initialize the gui root element with {@link ModularGui#initStandardGui(int, int)}, {@link ModularGui#initFullscreenGui()} + * This applies bindings to fix the size and position of the root element, you can also do this manually for custom configurations. + *

+ * Build your gui by adding and configuring your desired gui elements. + * Elements must be added to the root gui element which is obtainable via gui.getRoot() + *

+ * Note: gui elements are added on construction, meaning you do not need to use element.addChild. + * Instead, just construct the elements, and pass in the root element (or any other initialized element) as the parent. + * + * @param gui The modular gui instance. + */ + void buildGui(ModularGui gui); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java new file mode 100644 index 00000000..b8138094 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/ScissorHandler.java @@ -0,0 +1,75 @@ +package codechicken.lib.gui.modular.lib; + +import com.google.common.collect.Queues; +import com.mojang.blaze3d.platform.Window; +import com.mojang.blaze3d.systems.RenderSystem; +import net.minecraft.client.Minecraft; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.Deque; + +/** + * Created by brandon3055 on 29/06/2023 + */ +public class ScissorHandler { + public static final Logger LOGGER = LogManager.getLogger(); + private final Deque stack = Queues.newArrayDeque(); + + public void pushGuiScissor(double x, double y, double width, double height) { + Window window = Minecraft.getInstance().getWindow(); + int windowHeight = window.getHeight(); + double scale = window.getGuiScale(); + double scX = x * scale; + double scY = (double) windowHeight - (y + height) * scale; + double scW = Math.max(width * scale, 0); + double scH = Math.max(height * scale, 0); + pushScissor((int) scX, (int) scY, (int) scW, (int) scH); + } + + public void pushScissor(int x, int y, int width, int height) { + int xMax = x + width; + int yMax = y + height; + stack.addLast(ScissorState.createState(x, y, xMax, yMax, stack.peekLast()).apply()); + } + + public void popScissor() { + if (stack.isEmpty()) { + LOGGER.error("Scissor stack underflow"); + } + stack.removeLast(); + ScissorState active = stack.peekLast(); + if (active != null) { + active.apply(); + } else { +// RenderSystem.disableScissor(); + } + } + + private record ScissorState(int x, int y, int xMax, int yMax) { + + private ScissorState apply() { +// RenderSystem.enableScissor(x, y, xMax - x, yMax - y); + return this; + } + + private static ScissorState createState(int newX, int newY, int newXMax, int newYMax, ScissorState prevState) { + if (prevState != null) { + int x = Math.max(prevState.x, newX); + int y = Math.max(prevState.y, newY); + int xMax = Math.min(prevState.xMax, newXMax); + int yMax = Math.min(prevState.yMax, newYMax); + Minecraft mc = Minecraft.getInstance(); + if (x < 0) x = 0; + if (y < 0) y = 0; + if (xMax > mc.getWindow().getScreenWidth()) xMax = mc.getWindow().getScreenWidth(); + if (yMax > mc.getWindow().getScreenHeight()) yMax = mc.getWindow().getScreenHeight(); + if (xMax < x) xMax = x; + if (yMax < y) yMax = y; + return new ScissorState(x, y, xMax, yMax); + } else { + return new ScissorState(newX, newY, newXMax, newYMax); + } + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java new file mode 100644 index 00000000..f4f16055 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/SliderState.java @@ -0,0 +1,139 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.lib.geometry.Axis; +import net.minecraft.client.Minecraft; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The primary interface for managing getting and setting the position of slider elements. + *

+ * Created by brandon3055 on 01/09/2023 + */ +public interface SliderState { + + /** + * @return the current position. (Between 0 and 1) + */ + double getPos(); + + /** + * Set the current slide position, + * When using this method, make sure the provided value can not go outside the valid range of 0 to 1. + * + * @param pos Set the current position (Between 0 and 1) + */ + void setPos(double pos); + + /** + * The slider ratio is computed by dividing the length of the slider element by the total length of the slider track. + * This is primarily for things like setting the size of scroll bar sliders, and calibrating scrolling via middle-click + drag. + * + * @return scroll ratio, viewable content size / total content size (Range 0 to 1) + */ + default double sliderRatio() { + return 0.1; + } + + /** + * For controlling a slider via mouse scroll wheel. + * You can return a negative value to invert the scroll direction. + * + * @return The amount added to the position per scroll increment. + */ + default double scrollSpeed() { + double ratio = sliderRatio(); + return ratio < 0.1 ? ratio * 0.1 : ratio * ratio; + } + + /** + * @param scrollAxis The moving axis of the slider element. + * @return true if the current scroll wheel event should affect this slider. + */ + default boolean canScroll(Axis scrollAxis) { + return true; + } + + /** + * Creates a basic slide state which stores its position internally. + * Useful for things like simple slide control elements. + */ + static SliderState create(double speed) { + return create(speed, null); + } + + /** + * Creates a basic slide state which stores its position internally. + * And allows you to attach a change listener. + * Useful for things like simple slide control elements. + */ + static SliderState create(double speed, @Nullable Consumer changeListener) { + return new SliderState() { + double pos = 0; + + @Override + public double getPos() { + return pos; + } + + @Override + public void setPos(double pos) { + this.pos = pos; + if (changeListener != null) { + changeListener.accept(pos); + } + } + + @Override + public double scrollSpeed() { + return speed; + } + }; + } + + static SliderState forScrollBar(Supplier getPos, Consumer setPos, Supplier getRatio) { + return new SliderState() { + @Override + public double getPos() { + return getPos.get(); + } + + @Override + public void setPos(double pos) { + setPos.accept(pos); + } + + @Override + public double sliderRatio() { + return getRatio.get(); + } + + @Override + public boolean canScroll(Axis scrollAxis) { + //Controls scrolling left and right when shift key is down. + return (scrollAxis == Axis.Y) != Minecraft.getInstance().hasShiftDown(); + } + }; + } + + static SliderState forSlider(Supplier getPos, Consumer setPos, Supplier getSpeed) { + return new SliderState() { + @Override + public double getPos() { + return getPos.get(); + } + + @Override + public void setPos(double pos) { + setPos.accept(pos); + } + + @Override + public double scrollSpeed() { + return getSpeed.get(); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TextState.java b/src/main/java/codechicken/lib/gui/modular/lib/TextState.java new file mode 100644 index 00000000..f92af296 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/TextState.java @@ -0,0 +1,56 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.elements.GuiTextField; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * The primary interface for managing getting and setting the text in a {@link GuiTextField} + *

+ * Created by brandon3055 on 03/09/2023 + */ +public interface TextState { + + String getText(); + + void setText(String text); + + static TextState simpleState(String defaultValue) { + return simpleState(defaultValue, null); + } + + static TextState simpleState(String defaultValue, @Nullable Consumer changeListener) { + return new TextState() { + private String value = defaultValue; + + @Override + public String getText() { + return value; + } + + @Override + public void setText(String text) { + this.value = text; + if (changeListener != null) { + changeListener.accept(value); + } + } + }; + } + + static TextState create(Supplier getValue, Consumer setValue) { + return new TextState() { + @Override + public String getText() { + return getValue.get(); + } + + @Override + public void setText(String text) { + setValue.accept(text); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java new file mode 100644 index 00000000..3e56c1c0 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/TooltipHandler.java @@ -0,0 +1,124 @@ +package codechicken.lib.gui.modular.lib; + +import codechicken.lib.gui.modular.elements.GuiElement; +import net.covers1624.quack.collection.FastStream; +import net.covers1624.quack.util.SneakyUtils; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; +import net.minecraft.client.gui.screens.inventory.tooltip.DefaultTooltipPositioner; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import org.jetbrains.annotations.Nullable; + +import java.util.Collections; +import java.util.List; +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 01/09/2023 + */ +public interface TooltipHandler> { + + Supplier> getTooltip(); + + /** + * Set a delay before element tooltip is displayed. + * Default delay is 10 ticks. + */ + T setTooltipDelay(int tooltipDelay); + + int getTooltipDelay(); + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param Tooltip A single tooltip text component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltipSingle(@Nullable Component Tooltip) { + return setTooltip(Tooltip == null ? null : () -> Collections.singletonList(Tooltip)); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param Tooltip A single tooltip text component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltip(Component... Tooltip) { + return setTooltip(Tooltip == null ? null : () -> List.of(Tooltip)); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip A single line tooltip component supplier. + * @see #setTooltipDelay(int) + */ + default T setTooltipSingle(@Nullable Supplier tooltip) { + return setTooltip(tooltip == null ? null : () -> Collections.singletonList(tooltip.get())); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or empty, hover text will be disabled + * @see #setTooltipDelay(int) + */ + default T setTooltip(@Nullable List tooltip) { + return setTooltip(tooltip == null ? null : () -> tooltip); + } + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. (with a delay of 10 ticks) + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or the returned list is empty, hover text will be disabled + * @see #setTooltipDelay(int) + */ + T setTooltip(@Nullable Supplier> tooltip); + + /** + * Add hover text that is to be displayed when the user hovers their cursor over this element. + * If you have multiple stacked elements with tooltips, only the top most element under the cursor will display its hover text. + * + * @param tooltip The tooltip lines. If null or the returned list is empty, hover text will be disabled + * @param tooltipDelay Delay before hover text is shown. + */ + default T setTooltip(@Nullable Supplier> tooltip, int tooltipDelay) { + setTooltip(tooltip); + setTooltipDelay(tooltipDelay); + return SneakyUtils.unsafeCast(this); + } + + /** + * The method responsible for rendering element tool tips. + * Called from {@link GuiElement#renderOverlay(GuiGraphics, double, double, float, boolean)} + */ + default boolean renderTooltip(GuiGraphics graphics, Font font, double mouseX, double mouseY) { + Supplier> supplier = getTooltip(); + if (supplier == null) return false; + List list = supplier.get(); + if (list.isEmpty()) return false; + + graphics.renderTooltip( + font, + FastStream.of(list) + //Run all components though split to account for newline characters in translations + .flatMap(e -> font.getSplitter().splitLines(e, Integer.MAX_VALUE, e.getStyle())) + .map(Language.getInstance()::getVisualOrder) + .map(ClientTooltipComponent::create) + .toList(), + (int) mouseX, + (int) mouseY, + DefaultTooltipPositioner.INSTANCE, + null + ); + return true; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java new file mode 100644 index 00000000..92282ee8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerGuiProvider.java @@ -0,0 +1,33 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.ModularGuiContainer; +import codechicken.lib.gui.modular.lib.GuiProvider; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.world.inventory.AbstractContainerMenu; + +/** + * Created by brandon3055 on 08/09/2023 + */ +public abstract class ContainerGuiProvider implements GuiProvider { + + private ContainerScreenAccess screenAccess; + + public void setMenuAccess(ContainerScreenAccess screenAccess) { + this.screenAccess = screenAccess; + } + + @Override + public final void buildGui(ModularGui gui) { + buildGui(gui, screenAccess); + } + + /** + * This is the same as {@link GuiProvider#buildGui(ModularGui)} except you have access to the {@link MenuAccess} + * The given menu accessor should always be the parent screen unless your using some custom modular gui implementation. + * + * @param gui The modular gui instance. + * @param screenAccess The screen access (This will be a gui class that extends {@link ModularGuiContainer} + */ + public abstract void buildGui(ModularGui gui, ContainerScreenAccess screenAccess); +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java new file mode 100644 index 00000000..8bab19f7 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/ContainerScreenAccess.java @@ -0,0 +1,22 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.elements.GuiSlots; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.screens.inventory.MenuAccess; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; + +/** + * Used by {@link ContainerGuiProvider} + * Provides access to the ContainerMenu as well as some essential functions. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public interface ContainerScreenAccess extends MenuAccess { + + /** + * This is the modular gui friendly method used by elements such as {@link GuiSlots} to render inventory item stacks. + */ + void doRenderSlot(GuiGraphics render, Slot slot); + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java new file mode 100644 index 00000000..8745a71e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/DataSync.java @@ -0,0 +1,50 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.inventory.container.data.AbstractDataStore; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; + +import java.util.function.Supplier; + +/** + * This class provides a convenient way to synchronize server side data with a client side screen via the ContainerMenu + *

+ * Created by brandon3055 on 09/09/2023 + */ +public class DataSync { + + public static final int PKT_SEND_CHANGES = 255; + private final ModularGuiContainerMenu containerMenu; + private final AbstractDataStore dataStore; + private final Supplier valueGetter; + + public DataSync(ModularGuiContainerMenu containerMenu, AbstractDataStore dataStore, Supplier valueGetter) { + this.containerMenu = containerMenu; + this.dataStore = dataStore; + this.valueGetter = valueGetter; + containerMenu.dataSyncs.add(this); + } + + public T get() { + return dataStore.get(); + } + + /** + * This should only ever be called server side! + */ + public void detectAndSend() { + if (dataStore.isSameValue(valueGetter.get())) { + return; + } + dataStore.set(valueGetter.get()); + containerMenu.sendPacketToClient(PKT_SEND_CHANGES, buf -> { + buf.writeByte((byte) containerMenu.dataSyncs.indexOf(this)); + dataStore.toBytes(buf); + }); + } + + public void handleSyncPacket(RegistryFriendlyByteBuf buf) { + dataStore.fromBytes(buf); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java new file mode 100644 index 00000000..9a5ddaa3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/SlotGroup.java @@ -0,0 +1,128 @@ +package codechicken.lib.gui.modular.lib.container; + +import codechicken.lib.gui.modular.elements.GuiSlots; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import codechicken.lib.inventory.container.modular.ModularSlot; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.world.Container; +import net.minecraft.world.entity.EquipmentSlot; +import net.minecraft.world.entity.Mob; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.EnchantmentEffectComponents; +import net.minecraft.world.item.enchantment.EnchantmentHelper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * Used to configure slots a set of slots in a ContainerMenu. + * The SlotGroup can then be passed to ModularGui elements such as {@link GuiSlots} in order to give the gui control over slot positioning and rendering. + *

+ * Ideally you should use a separate SlotGroup for each 'group' of slots, Meaning the players main inventory and hot bar should be separate ranges. + * That said, if you have multiple slots spread out across something like a machine gui, You can add them all to one SlotGroup then + * pass each individual slot from that range to a {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} + *

+ * Created by brandon3055 on 08/09/2023 + */ +public class SlotGroup { + + private static final EquipmentSlot[] ARMOR_SLOTS = new EquipmentSlot[] { + EquipmentSlot.HEAD, + EquipmentSlot.CHEST, + EquipmentSlot.LEGS, + EquipmentSlot.FEET + }; + + public final int zone; + public final List quickMoveTo; + + private final ModularGuiContainerMenu containerMenu; + private final List slots = new ArrayList<>(); + + public SlotGroup(ModularGuiContainerMenu containerMenu, int zone, int... quickMoveTo) { + this.zone = zone; + this.containerMenu = containerMenu; + this.quickMoveTo = Arrays.stream(quickMoveTo).boxed().toList(); + } + + public ModularSlot addSlot(ModularSlot slot) { + slots.add(slot); + containerMenu.addSlot(slot); + containerMenu.mapSlot(slot, this); + return slot; + } + + /** + * Convenient method for adding multiple slots. + * + * @param slotCount The number of slots to be added. + * @param startIndex Slot starting index. + * @param makeSlot Builder used to create the slots, Input integer will start at startIndex and increment by one for each slot. + */ + public void addSlots(int slotCount, int startIndex, Function makeSlot) { + for (int index = startIndex; index < startIndex + slotCount; index++) { + addSlot(makeSlot.apply(index)); + } + } + + public void addAllSlots(Container container) { + addAllSlots(container, ModularSlot::new); + } + + public void addAllSlots(Container container, BiFunction makeSlot) { + for (int index = 0; index < container.getContainerSize(); index++) { + addSlot(makeSlot.apply(container, index)); + } + } + + public void addPlayerMain(Inventory inventory) { + addSlots(27, 9, index -> new ModularSlot(inventory, index)); + } + + public void addPlayerBar(Inventory inventory) { + addSlots(9, 0, index -> new ModularSlot(inventory, index)); + } + + public void addPlayerArmor(Inventory inventory) { + for (int i = 0; i < 4; ++i) { + EquipmentSlot slot = ARMOR_SLOTS[i]; + addSlot(new ModularSlot(inventory, 39 - i) + .onSet((oldStack, newStack) -> onEquipItem(inventory, slot, newStack, oldStack)) + .setStackLimit(stack -> 1) + .setValidator(stack -> slot == inventory.player.getEquipmentSlotForItem(stack)) + .setCanRemove((player, stack) -> stack.isEmpty() || player.isCreative() || !EnchantmentHelper.has(stack, EnchantmentEffectComponents.PREVENT_ARMOR_CHANGE)) + ); + } + } + + public void addPlayerOffhand(Inventory inventory) { + addSlot(new ModularSlot(inventory, 40).onSet((oldStack, newStack) -> onEquipItem(inventory, EquipmentSlot.OFFHAND, newStack, oldStack))); + } + + static void onEquipItem(Inventory inventory, EquipmentSlot slot, ItemStack newStack, ItemStack oldStack) { + inventory.player.onEquipItem(slot, oldStack, newStack); + } + + public int size() { + return slots.size(); + } + + public ModularSlot getSlot(int index) { + return slots.get(index); + } + + public int indexOf(Slot slot) { + return slots.indexOf(slot); + } + + public List slots() { + return Collections.unmodifiableList(slots); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java new file mode 100644 index 00000000..3e54103f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/container/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.lib.container; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java new file mode 100644 index 00000000..c38b84b3 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Align.java @@ -0,0 +1,14 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 31/08/2023 + */ +public enum Align { + MIN, + CENTER, + MAX; + public static Align LEFT = MIN; + public static Align RIGHT = MAX; + public static Align TOP = MIN; + public static Align BOTTOM = MAX; +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java new file mode 100644 index 00000000..7f4ac8f2 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Axis.java @@ -0,0 +1,13 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 02/09/2023 + */ +public enum Axis { + X, + Y; + + public Axis opposite() { + return this == X ? Y : X; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java new file mode 100644 index 00000000..5fbd204b --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/AxisConfig.java @@ -0,0 +1,96 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import org.apache.commons.lang3.function.TriFunction; +import org.jetbrains.annotations.Nullable; + +/** + * Denies how each of the three axis parameters are computed based on the available constraints. + * Note: If both min and max are defined, size is ignored. + */ +public enum AxisConfig { + //@formatter:off + // | Compute Axis Min | Compute Axis Max | Compute Axis Size | + /** + * If nothing is constrained. + * min=0, max=0, size=0 + * */ + NONE (0, (min, max, size) -> 0D, (min, max, size) -> 0D, (min, max, size) -> 0D), + /** + * If only Min is constrained. + * min=min, max=min, size=0 + * */ + MIN_ONLY (1, (min, max, size) -> min.get(), (min, max, size) -> min.get(), (min, max, size) -> 0D), + /** + * If only Max is constrained. + * min=max, max=max, size=0 + * */ + MAX_ONLY (1, (min, max, size) -> max.get(), (min, max, size) -> max.get(), (min, max, size) -> 0D), + /** + * If only Size is constrained. + * min=0, max=size, size=size + * */ + SIZE_ONLY (1, (min, max, size) -> 0D, (min, max, size) -> size.get(), (min, max, size) -> size.get()), + /** + * If Min and Size are constrained . + * min=min, max=min+size, size=size + * */ + MIN_SIZE (2, (min, max, size) -> min.get(), (min, max, size) -> min.get() + size.get(), (min, max, size) -> size.get()), + /** + * If Max and Size are constrained. + * min=max-size, max=max, size=size + * */ + MAX_SIZE (2, (min, max, size) -> max.get() - size.get(), (min, max, size) -> max.get(), (min, max, size) -> size.get()), + /** + * If Min and Max are constrained. + * min=min, max=max, size=max-min + * */ + MIN_MAX (2, (min, max, size) -> min.get(), (min, max, size) -> max.get(), (min, max, size) -> max.get() - min.get()), + /** + * If Min, Max and Size are constrained the Size is ignored. + * min=min, max=max, size=max-min + * */ + MIN_MAX_SIZE(3, (min, max, size) -> min.get(), (min, max, size) -> max.get(), (min, max, size) -> max.get() - min.get()); + //@formatter:on + + public final int constraints; + public final TriFunction min; + public final TriFunction max; + public final TriFunction size; + //[min][max][size] TODO, I Clean this up once i confirm everything works correctly. + private static final AxisConfig[][][] LOOKUP = new AxisConfig[][][]{ + { //Min = 0 + { //Max = 0 + NONE, //Size = 0 + SIZE_ONLY //Size = 1 + }, + { //Max = 1 + MAX_ONLY, //Size = 0 + MAX_SIZE //Size = 1 + } + }, + { //Min = 1 + { //Max = 0 + MIN_ONLY, //Size = 0 + MIN_SIZE //Size = 1 + }, + { //Max = 1 + MIN_MAX, //Size = 0 + MIN_MAX_SIZE//Size = 1 + } + } + }; + + AxisConfig(int constraints, + TriFunction min, + TriFunction max, + TriFunction size) { + this.constraints = constraints; + this.min = min; + this.max = max; + this.size = size; + } + + public static AxisConfig getConfigFor(@Nullable Constraint min, @Nullable Constraint max, @Nullable Constraint size) { + return LOOKUP[min != null ? 1 : 0][max != null ? 1 : 0][size != null ? 1 : 0]; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java new file mode 100644 index 00000000..d9ef9ce7 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Borders.java @@ -0,0 +1,118 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.Objects; + +/** + * Created by brandon3055 on 28/08/2023 + */ +public final class Borders { + public double top; + public double left; + public double bottom; + public double right; + + public Borders(double top, double left, double bottom, double right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + } + + public static Borders create(double borders) { + return create(borders, borders); + } + + public static Borders create(double leftRight, double topBottom) { + return create(topBottom, leftRight, topBottom, leftRight); + } + + public static Borders create(double top, double left, double bottom, double right) { + return new Borders(top, left, bottom, right); + } + + public double top() { + return top; + } + + public double left() { + return left; + } + + public double bottom() { + return bottom; + } + + public double right() { + return right; + } + + public Borders top(double top) { + this.top = top; + return this; + } + + public Borders left(double left) { + this.left = left; + return this; + } + + public Borders bottom(double bottom) { + this.bottom = bottom; + return this; + } + + public Borders right(double right) { + this.right = right; + return this; + } + + public Borders setTopBottom(double topBottom) { + return top(topBottom).bottom(topBottom); + } + + public Borders setLeftRight(double leftRight) { + return left(leftRight).setLeftRight(leftRight); + } + + public Borders setBorders(double borders) { + return setBorders(borders, borders); + } + + public Borders setBorders(double topBottom, double leftRight) { + return setBorders(topBottom, leftRight, topBottom, leftRight); + } + + public Borders setBorders(double top, double left, double bottom, double right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + return this; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) return true; + if (obj == null || obj.getClass() != this.getClass()) return false; + var that = (Borders) obj; + return Double.doubleToLongBits(this.top) == Double.doubleToLongBits(that.top) && + Double.doubleToLongBits(this.left) == Double.doubleToLongBits(that.left) && + Double.doubleToLongBits(this.bottom) == Double.doubleToLongBits(that.bottom) && + Double.doubleToLongBits(this.right) == Double.doubleToLongBits(that.right); + } + + @Override + public int hashCode() { + return Objects.hash(top, left, bottom, right); + } + + @Override + public String toString() { + return "Borders[" + + "top=" + top + ", " + + "left=" + left + ", " + + "bottom=" + bottom + ", " + + "right=" + right + ']'; + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java new file mode 100644 index 00000000..8cc6e914 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstrainedGeometry.java @@ -0,0 +1,469 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import codechicken.lib.gui.modular.elements.GuiElement; +import codechicken.lib.gui.modular.lib.Constraints; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +import static codechicken.lib.gui.modular.lib.geometry.Constraint.midPoint; +import static codechicken.lib.gui.modular.lib.geometry.Constraint.relative; +import static codechicken.lib.gui.modular.lib.geometry.GeoParam.*; + +/** + * This is the base class used to define the size and position of a GuiElement. + *

+ * The geometry system is designed to be very user-friendly, yet very powerful, with the ability to do all sorts of fun and interesting things. + * But if all you want is the ability to set simple size and position values, then there is no need to read any further. + * Just use the basic setters setXPos, setYPos, setWidth, setHeight and everything should just work. + * If you want to dive deeper, read on. + *

+ * The geometry system is based around 6 core parameters: xMin, xMax, xSize, yMin, yMax and ySize. See: {@link GeoParam}
+ * These parameters are defined using 'Constraints' See: {@link Constraint}
+ * When properly constrained, it will be possible to request values for any of these 6 parameters.
+ * For each axis (x and y) there are 3 constraints: min, max and size.
+ * In order for an axis to be properly defined 2 of these constraints need to be set.
+ * e.g. (xMin and xSize) or (xMin and xMax) or (xMax and xSize)
+ * Using any of these combinations the position and size of an axis can be computed. + *

+ * Look at {@link AxisConfig} for details on the values that get returned when too few constraints are set.
+ * TLDR: We will always try to return "reasonable" default values. e.g. if only size is constrained, xMin will default + * to 0 and xMax will default to 0 + xSize.
+ * If all three constraints are set then the size constraint will be ignored.
+ * You can use {@link #strictMode(boolean)} to change this behavior. + *

+ * There are a number of different types of constraints that can be used, including completely custom constraints.
+ * Take a look at the {@link Constraint} class for a detailed list with explanations. + *

+ * Note: + * All position and size values in ModularGui use doubles. This is because floating point position and size values + * can be very useful at times. But they can also cause a lot of ugly visual artifacts when not used properly. + * So by default, all the builtin constraints will cast their outputs to an integer value. + * If you need floating point precision, you can enable it by calling .precise() on any of the builtin constraints. + *

+ * Created by brandon3055 on 29/06/2023 + */ +public abstract class ConstrainedGeometry> implements GuiParent { + + private Constraint xMin = null; + private Constraint xMax = null; + private Constraint xSize = null; + private AxisConfig xAxis = AxisConfig.NONE; + + private Constraint yMin = null; + private Constraint yMax = null; + private Constraint ySize = null; + private AxisConfig yAxis = AxisConfig.NONE; + + //Permanently bound immutable position and rectangle elements. + private final Position position = Position.create(this); + private final Rectangle rectangle = Rectangle.create(this); + private final Rectangle.Mutable childBounds = getRectangle().mutable(); + + private boolean strictMode = false; + + public abstract GuiParent getParent(); + + public GeoRef getParent(GeoParam param) { + return getParent().get(param); + } + + //=== Simple Setters ===// + + /** + * Simple method for setting the x position of this element. + *

+ * Constrains the left side of this element, to the left side of the parent element, + * with an offset that is calculated by subtracting parent's current x pos from the given x pos. + *

+ * In other words, if the parent element's position changes, this element will move with it. + * + * @param x The X position in screen space. + * @return This Element. + */ + public T setXPos(double x) { + GeoRef parentLeft = getParent(LEFT); + return constrain(LEFT, Constraint.relative(parentLeft, x - parentLeft.get())); + } + + /** + * Simple method for setting the y position of this element. + *

+ * Constrains the top side of this element, to the top side of the parent element, + * with an offset that is calculated by subtracting parent's current y pos from the given y pos. + *

+ * In other words, if the parent element's position changes, this element will move with it. + * + * @param y The Y position in screen space. + * @return This Element. + */ + public T setYPos(double y) { + GeoRef parentTop = getParent(LEFT); + return constrain(LEFT, Constraint.relative(parentTop, y - parentTop.get())); + } + + /** + * Convenience method for setting both x and y positions. + * + * @param x The X position in screen space. + * @param y The Y position in screen space. + * @return This Element. + * @see #setXPos(double) + * @see #setYPos(double) + */ + public T setPos(double x, double y) { + return setXPos(x).setYPos(y); + } + + /** + * Simple method for setting the width of this element. + * + * @param width The width to apply. + * @return This Element. + */ + public T setWidth(double width) { + return constrain(WIDTH, Constraint.literal(width)); + } + + /** + * Simple method for setting the height of this element. + * + * @param height The height to apply. + * @return This Element. + */ + public T setHeight(double height) { + return constrain(HEIGHT, Constraint.literal(height)); + } + + /** + * Convenience method for setting both width and height. + * + * @param width The width to apply. + * @param height The height to apply. + * @return This Element. + * @see #setWidth(double) + * @see #setHeight(double) + */ + public T setSize(double width, double height) { + return setWidth(width).setHeight(height); + } + + //=== Everything related to constraint based geometry ===// + + /** + * @return The position of the Left edge of this element. + */ + @Override + public double xMin() { + return xAxis.min.apply(xMin, xMax, xSize); + } + + /** + * @return The position of the Right edge of this element. + */ + @Override + public double xMax() { + return xAxis.max.apply(xMin, xMax, xSize); + } + + /** + * @return The Width of this element. + */ + @Override + public double xSize() { + return xAxis.size.apply(xMin, xMax, xSize); + } + + /** + * @return The position of the Top edge of this element. + */ + @Override + public double yMin() { + return yAxis.min.apply(yMin, yMax, ySize); + } + + /** + * @return The position of the Bottom edge of this element. + */ + @Override + public double yMax() { + return yAxis.max.apply(yMin, yMax, ySize); + } + + /** + * @return The Height of this element. + */ + @Override + public double ySize() { + return yAxis.size.apply(yMin, yMax, ySize); + } + + /** + * Returns a reference to the specified geometry parameter. + * This is primarily used when defining geometry constraints. + * But it can also be used as a simple {@link Supplier} + * that will return the current parameter value when requested. + *

+ * Note: The returned geometry reference will always be valid + * + * @param param The geometry parameter. + * @return A Geometry Reference + */ + @Override + public GeoRef get(GeoParam param) { + return new GeoRef(this, param); + } + + @SuppressWarnings ("unchecked") + private T self() { + return (T) this; + } + + /** + * @param param The geometry parameter to be constrained. + * @param constraint The constraint to apply + * @return This Element. + */ + public T constrain(GeoParam param, @Nullable Constraint constraint) { + if (constraint != null && constraint.axis() != null && constraint.axis() != param.axis) { + throw new IllegalStateException("Attempted to apply constraint for axis: " + constraint.axis() + ", to Parameter: " + param); + } + if (param.axis == Axis.X) { + constrainX(param, constraint); + } else if (param.axis == Axis.Y) { + constrainY(param, constraint); + } + return self(); + } + + /** + * Clear any configured constraints and reset this element to default unconstrained state. + * Convenient when reconfiguring an elements constraints or applying constraints to an element + * with an existing, unknown constraint configuration. + */ + public T clearConstraints() { + xMin = xMax = xSize = yMin = yMax = ySize = null; + xAxis = yAxis = AxisConfig.NONE; + return self(); + } + + private void constrainX(GeoParam param, @Nullable Constraint constraint) { + if (param == GeoParam.LEFT) { + xMin = constraint; + } else if (param == GeoParam.RIGHT) { + xMax = constraint; + } else if (param == WIDTH) { + xSize = constraint; + } + xAxis = AxisConfig.getConfigFor(xMin, xMax, xSize); + validate(); + } + + private void constrainY(GeoParam param, @Nullable Constraint constraint) { + if (param == GeoParam.TOP) { + yMin = constraint; + } else if (param == GeoParam.BOTTOM) { + yMax = constraint; + } else if (param == GeoParam.HEIGHT) { + ySize = constraint; + } + yAxis = AxisConfig.getConfigFor(yMin, yMax, ySize); + validate(); + } + + /** + * Strict mode is intended to help catch potential mistakes when writing modular GUIs + *

+ * Enforces a strict requirement for each exist to have two and only two constraints. + * Any attempt to over-constrain an axis will throw an immediate fatal exception. + * If an axis is under-constrained then a fatal exception will be thrown when a value from the axis is queried. + *

+ * Strict mode applies to this element, and recursively to all children of this element. + * + * @param strictMode Enable strict mode. + * @return the geometry object. + */ + public T strictMode(boolean strictMode) { + this.strictMode = strictMode; + //TODO Propagate to children (Will be handled in the base GuiElement) + return self(); + } + + //TODO This needs to be called from the parent element somewhere. Possibly on tick or render + //Ideally i would like to find a way to only call it once. we need to account for constraints being modified after initial element construction. + public void validate() { + if (strictMode) { + if (xAxis.constraints != 2) { + throw new IllegalStateException(String.format("X axis of element: %s is %s constrained!", getParent(), xAxis.constraints < 2 ? "under" : "over")); + } else if (yAxis.constraints != 2) { + throw new IllegalStateException(String.format("Y axis of element: %s is %s constrained!", getParent(), yAxis.constraints < 2 ? "under" : "over")); + } + } + } + + public void clearGeometryCache() { + if (xMin != null) xMin.markDirty(); + if (xMax != null) xMax.markDirty(); + if (xSize != null) xSize.markDirty(); + if (yMin != null) yMin.markDirty(); + if (yMax != null) yMax.markDirty(); + if (ySize != null) ySize.markDirty(); + getChildren().forEach(ConstrainedGeometry::clearGeometryCache); + } + + //=== Geometry Utilities ===// + + /** + * Returns a {@link Position} that is permanently bound to this element. + */ + public Position getPosition() { + return position; + } + + /** + * Returns a {@link Rectangle} that is permanently bound to this element. + */ + public Rectangle getRectangle() { + return rectangle; + } + + public double xCenter() { + return xMin() + (xSize() / 2); + } + + public double yCenter() { + return yMin() + (ySize() / 2); + } + + /** + * Returns a new {@link Rectangle} the bounds of which will enclose this element and all of its child + * elements recursively. + */ + public Rectangle.Mutable getEnclosingRect() { + return addBoundsToRect(getRectangle().mutable()); + } + + /** + * Expands the bounds of the given rectangle (if needed) so that they enclose this element. + * And all of its child elements recursively. + */ + public Rectangle.Mutable addBoundsToRect(Rectangle.Mutable enclosingRect) { + enclosingRect.combine(getRectangle()); + for (GuiElement element : getChildren()) { + if (element.isEnabled()) { + element.addBoundsToRect(enclosingRect); + } + } + return enclosingRect; + } + + /** + * @return a rectangle, the bounds of which enclose all enabled child elements. + * If there are no enabled child elements the returned rect will have the position of this element, with zero size. + */ + public Rectangle.Mutable getChildBounds() { + boolean set = false; + for (GuiElement element : getChildren()) { + if (element.isEnabled()) { + if (!set) { + childBounds.set(element.getRectangle()); + set = true; + } else { + element.addBoundsToRect(childBounds); + } + } + } + if (!set) childBounds.setPos(xMin(), yMin()).setSize(0, 0); + return childBounds; + } + + //=== Layout Utilities ===// + + /** + * Constrain this element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + */ + public T placeInside(ConstrainedGeometry reference, Constraints.LayoutPos position) { + return placeInside(reference, position, 0, 0); + } + + /** + * Constrain this element to a position inside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/e89a6 + * + * @param reference The reference element, the element that target will be placed inside. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public T placeInside(ConstrainedGeometry reference, Constraints.LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case TOP_RIGHT -> constrain(TOP, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> constrain(BOTTOM, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(LEFT), xOffset)); + } + return self(); + } + + /** + * Constrain this element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + */ + public T placeOutside(ConstrainedGeometry reference, Constraints.LayoutPos position) { + return placeOutside(reference, position, 0, 0); + } + + /** + * Constrain this element to a position outside the specified targetElement. + * See the following image for an example of what each LayoutPos does: + * https://ss.brandon3055.com/baa7c + * + * @param reference The reference element, the element that target will be placed outside of. + * @param position The layout position. + * @param xOffset Optional X offset to be applied to the final position. + * @param yOffset Optional Y offset to be applied to the final position. + */ + public T placeOutside(ConstrainedGeometry reference, Constraints.LayoutPos position, double xOffset, double yOffset) { + switch (position) { + case TOP_LEFT -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case TOP_CENTER -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case TOP_RIGHT -> constrain(BOTTOM, relative(reference.get(TOP), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case MIDDLE_RIGHT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_RIGHT -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, relative(reference.get(RIGHT), xOffset)); + case BOTTOM_CENTER -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(LEFT, midPoint(reference.get(LEFT), reference.get(RIGHT), () -> (xSize() / -2) + xOffset)); + case BOTTOM_LEFT -> constrain(TOP, relative(reference.get(BOTTOM), yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + case MIDDLE_LEFT -> constrain(TOP, midPoint(reference.get(TOP), reference.get(BOTTOM), () -> (ySize() / -2) + yOffset)) + .constrain(RIGHT, relative(reference.get(LEFT), xOffset)); + } + return self(); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java new file mode 100644 index 00000000..a3fb6acf --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Constraint.java @@ -0,0 +1,186 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Constraints are used to define an elements position and shape by constraining the elements geometry parameters. {@link GeoParam} + * Constraints can be as simple as literal values representing an elements exact position and / or size in screen space, + * They can be relative coordinates, (Relative to another element's Geometry) + * Or they can be used to supply completely custom dynamic values. + *

+ * All the built-in constraints are implemented and documented in this class. + *

+ * Created by brandon3055 on 30/06/2023 + * + * @see ConstrainedGeometry + */ +public sealed interface Constraint permits ConstraintImpl { + + /** + * This method will return the current value of this constraint. + * This could be a fixed stored value, or a dynamically computed value + * depending on the type of constraint. + *

+ * All position and size values in ModularGui are doubles. + * However, by default, all the builtin constraints will cast their outputs to integer values. + * This avoids a lot of random visual artifacts that can occur when using floating point values in MC Screens. + *

+ * If you need floating-point precision, it can be enabled calling .precise() on any of the builtin constraints. + * + * @return The computed or stored value of this constraint. + */ + double get(); + + /** + * @return the axis this constraint applies to, Ether X, Y or null for undefined. + */ + @Nullable + Axis axis(); + + /** + * This is part of a late addition to improve performance. + * Rather than computing a constraint value every single time it is queried, which can be many, many times per render frame, + * We now cache the constraint value, and that cache is cleared at the start of each render frame. + */ + void markDirty(); + + /** + * This is the most basic constraint. It constrains a parameter to a single fixed value. + * + * @param value The fixed value that will be returned by this constraint. + */ + static ConstraintImpl.Literal literal(double value) { + return new ConstraintImpl.Literal(value); + } + + /** + * Constrains a parameter to the value provided by the given supplier. + * + * @param valueSupplier The dynamic value supplier. + */ + static ConstraintImpl.Dynamic dynamic(Supplier valueSupplier) { + return new ConstraintImpl.Dynamic(valueSupplier); + } + + /** + * Contains a parameter to the exact value of the given reference. + * This is effectively a relative constraint with no offset. + * + * @param relativeTo The relative geometry. + */ + static ConstraintImpl.Relative match(GeoRef relativeTo) { + return new ConstraintImpl.Relative(relativeTo, 0); + } + + /** + * Contains a parameter to the given reference plus the provided fixed offset. + * + * @param relativeTo The relative geometry. + * @param offset The offset to apply. + */ + static ConstraintImpl.Relative relative(GeoRef relativeTo, double offset) { + return new ConstraintImpl.Relative(relativeTo, offset); + } + + /** + * Contains a parameter to the given reference plus the provided dynamic offset. + * + * @param relativeTo The relative geometry. + * @param offset The dynamic offset to apply. + */ + static ConstraintImpl.RelativeDynamic relative(GeoRef relativeTo, Supplier offset) { + return new ConstraintImpl.RelativeDynamic(relativeTo, offset); + } + + /** + * Contains a parameter to a fixed position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + * + * @param start The Start position. + * @param end The End position. + * @param position The position between start and end. (0=start to 1=end) + */ + static ConstraintImpl.Between between(GeoRef start, GeoRef end, double position) { + return new ConstraintImpl.Between(start, end, position); + } + + /** + * Contains a parameter to a fixed position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + *

+ * This variant also allows a pixel offset. + * + * @param start The Start position. + * @param end The End position. + * @param position The position between start and end. (0=start to 1=end) + * @param offset position offset in pixels + */ + static ConstraintImpl.BetweenOffset between(GeoRef start, GeoRef end, double position, double offset) { + return new ConstraintImpl.BetweenOffset(start, end, position, offset); + } + + /** + * Contains a parameter to a dynamic position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + * + * @param start The Start position. + * @param end The End position. + * @param position The dynamic position between start and end. (0=start to 1=end) + */ + static ConstraintImpl.BetweenDynamic between(GeoRef start, GeoRef end, Supplier position) { + return new ConstraintImpl.BetweenDynamic(start, end, position); + } + + /** + * Contains a parameter to a dynamic position between the two provided references. + * Note: it is possible to go outside the given range if the given position is greater than 1 or less than 0. + * To prevent this call .clamp() on the returned constraint. + *

+ * This variant also allows a pixel offset. + * + * @param start The Start position. + * @param end The End position. + * @param position The dynamic position between start and end. (0=start to 1=end) + * @param offset Dynamic position offset in pixels + */ + static ConstraintImpl.BetweenDynamic between(GeoRef start, GeoRef end, Supplier position, Supplier offset) { + return new ConstraintImpl.BetweenOffsetDynamic(start, end, position, offset); + } + + /** + * Contains a parameter to the mid-point between the two provided references. + * + * @param start The Start position. + * @param end The End position. + */ + static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end) { + return new ConstraintImpl.MidPoint(start, end, 0); + } + + /** + * Contains a parameter to the mid-point between the two provided references with a fixed offset. + * + * @param start The Start position. + * @param end The End position. + * @param offset offset distance. + */ + static ConstraintImpl.MidPoint midPoint(GeoRef start, GeoRef end, double offset) { + return new ConstraintImpl.MidPoint(start, end, offset); + } + + /** + * Contains a parameter to the mid-point between the two provided references with a dynamic offset. + * + * @param start The Start position. + * @param end The End position. + * @param offset offset distance suppler. + */ + static ConstraintImpl.MidPointDynamic midPoint(GeoRef start, GeoRef end, Supplier offset) { + return new ConstraintImpl.MidPointDynamic(start, end, offset); + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java new file mode 100644 index 00000000..258437d0 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/ConstraintImpl.java @@ -0,0 +1,322 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import net.minecraft.util.Mth; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 04/07/2023 + */ +public abstract non-sealed class ConstraintImpl> implements Constraint { + + protected boolean precise = false; + protected Axis axis = null; + private double value; + private boolean isDirty = true; + + /** + * @return True if precise mode is enabled. + * @see #precise() + */ + public boolean isPrecise() { + return precise; + } + + /** + * By default, all constraint values are cast to (int). + * This helps avoid a lot of visual artifacts that can occur when using floating point positions in MC Screens. + *

+ * Calling this enables precise mode, which allows floating point precision to be used. + * + * @return The Constraint. + */ + @SuppressWarnings("unchecked") + public T precise() { + this.precise = true; + return (T) this; + } + + @Override + public double get() { + if (isDirty) { + value = isPrecise() ? getImpl() : (int) getImpl(); + isDirty = false; + } + return value; + } + + @Override + public @Nullable Axis axis() { + return axis; + } + + @SuppressWarnings("unchecked") + public T setAxis(@Nullable Axis axis) { + this.axis = axis; + return (T) this; + } + + @Override + public void markDirty() { + isDirty = true; + } + + protected abstract double getImpl(); + + public static class Literal extends ConstraintImpl { + protected final double value; + + /** + * Returns the literal value supplied. + */ + public Literal(double value) { + this.value = value; + } + + @Override + protected double getImpl() { + return value; + } + } + + public static class Dynamic extends ConstraintImpl { + protected final Supplier value; + + /** + * Returns a dynamic value that will be retrieved from the provided supplier. + */ + public Dynamic(Supplier value) { + this.value = value; + } + + @Override + protected double getImpl() { + return value.get(); + } + } + + public static class Relative extends ConstraintImpl { + protected final GeoRef relTo; + protected final double offset; + + /** + * Returns the value of the provided reference plus the given offset. + */ + public Relative(GeoRef relTo, double offset) { + this.setAxis(relTo.parameter.axis); + this.relTo = relTo; + this.offset = offset; + } + + @Override + protected double getImpl() { + return relTo.get() + getOffset(); + } + + public double getOffset() { + return offset; + } + } + + public static class RelativeDynamic extends ConstraintImpl { + protected final GeoRef relTo; + protected final Supplier offset; + + /** + * Returns the value of the provided reference plus the given dynamic offset. + */ + public RelativeDynamic(GeoRef relTo, Supplier offset) { + this.setAxis(relTo.parameter.axis); + this.relTo = relTo; + this.offset = offset; + } + + @Override + protected double getImpl() { + return relTo.get() + getOffset(); + } + + public double getOffset() { + return offset.get(); + } + } + + public static class Between extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final double pos; + protected boolean clamp = false; + + public Between(GeoRef start, GeoRef end, double pos) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'Between' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.pos = pos; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) * getPos()); + } + + public double getPos() { + return clamp ? Mth.clamp(pos, 0, 1) : pos; + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + + /** + * Ensure the output can not go bellow the min reference or above the max reference. + */ + public Between clamp() { + this.clamp = true; + return this; + } + } + + public static class BetweenDynamic extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final Supplier pos; + protected boolean clamp = false; + + public BetweenDynamic(GeoRef start, GeoRef end, Supplier pos) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'Between' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.pos = pos; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) * getPos()); + } + + public double getPos() { + return clamp ? Mth.clamp(pos.get(), 0, 1) : pos.get(); + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + + /** + * Ensure the output can not go bellow the min reference or above the max reference. + */ + public BetweenDynamic clamp() { + this.clamp = true; + return this; + } + } + + public static class BetweenOffset extends Between { + private final double offset; + + public BetweenOffset(GeoRef start, GeoRef end, double pos, double offset) { + super(start, end, pos); + this.offset = offset; + } + + @Override + protected double getImpl() { + return super.getImpl() + offset; + } + } + + public static class BetweenOffsetDynamic extends BetweenDynamic { + private final Supplier offset; + + public BetweenOffsetDynamic(GeoRef start, GeoRef end, Supplier pos, Supplier offset) { + super(start, end, pos); + this.offset = offset; + } + + @Override + protected double getImpl() { + return super.getImpl() + offset.get(); + } + } + + public static class MidPoint extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final double offset; + + public MidPoint(GeoRef start, GeoRef end, double offset) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'MidPoint' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.offset = offset; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) / 2) + getOffset(); + } + + public double getOffset() { + return offset; + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + } + + public static class MidPointDynamic extends ConstraintImpl { + protected final GeoRef start; + protected final GeoRef end; + protected final Supplier offset; + + public MidPointDynamic(GeoRef start, GeoRef end, Supplier offset) { + this.setAxis(start.parameter.axis); + if (start.parameter.axis != end.parameter.axis) { + throw new IllegalStateException("Attempted to define a 'MidPoint' Constraint with parameters on different axes."); + } + this.start = start; + this.end = end; + this.offset = offset; + } + + @Override + protected double getImpl() { + return start.get() + ((end.get() - start.get()) / 2) + getOffset(); + } + + public double getOffset() { + return offset.get(); + } + + public double getStart() { + return start.get(); + } + + public double getEnd() { + return end.get(); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java new file mode 100644 index 00000000..9e2513e8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Direction.java @@ -0,0 +1,40 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Created by brandon3055 on 04/09/2023 + */ +public enum Direction { + UP(Axis.Y), + LEFT(Axis.X), + DOWN(Axis.Y), + RIGHT(Axis.X); + + private static Direction[] VALUES = values(); + + private final Axis axis; + + Direction(Axis axis) { + this.axis = axis; + } + + public Axis getAxis() { + return axis; + } + + public Direction opposite() { + if (axis == Axis.X) return this == LEFT ? RIGHT : LEFT; + else return this == UP ? DOWN : UP; + } + + public Direction rotateCW() { + return values()[(ordinal() + VALUES.length - 1) % VALUES.length]; + } + + public Direction rotateCCW() { + return values()[(ordinal() + 1) % VALUES.length]; + } + + public double rotationTo(Direction other) { + return (this.ordinal() - other.ordinal()) * 90; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java new file mode 100644 index 00000000..0f37720f --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoParam.java @@ -0,0 +1,32 @@ +package codechicken.lib.gui.modular.lib.geometry; + +/** + * Used to define the 6 core parameters that make up an elements geometry + * These are named Left, Right, Width, Top, Bottom, Height. + * These names were chosen for ease of use, and to make it clear what they represent. + * Internally they are known as xMin, xMax, xSize, yMin, yMax, ySize. + *

+ * Created by brandon3055 on 30/06/2023 + */ +public enum GeoParam { + /** X_MIN */ + LEFT(Axis.X), + /** X_MAX */ + RIGHT(Axis.X), + /** X_SIZE */ + WIDTH(Axis.X), + + /** Y_MIN */ + TOP(Axis.Y), + /** Y_MAX */ + BOTTOM(Axis.Y), + /** Y_SIZE */ + HEIGHT(Axis.Y); + + public final Axis axis; + + GeoParam(Axis axis) { + this.axis = axis; + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java new file mode 100644 index 00000000..93ebf68e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GeoRef.java @@ -0,0 +1,36 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.function.Supplier; + +/** + * Used to access one of the 6 core parameters that make up an element's geometry. + *

+ * The primary purpose of this class is to provide a convenient way to reference a geometry + * parameter when defining constraints. + * It also helps make the code more debuggable. + * I could just make literally everything a lambda, but that makes debugging kinda painful when things break. + *

+ * Created by brandon3055 on 30/06/2023 + */ +public class GeoRef implements Supplier { + public final GuiParent geometry; + public final GeoParam parameter; + + public GeoRef(GuiParent geometry, GeoParam parameter) { + this.geometry = geometry; + this.parameter = parameter; + } + + @Override + public Double get() { + return geometry.getValue(parameter); + } + + @Override + public String toString() { + return "GeoReference{" + + "geometry=" + geometry + + ", parameter=" + parameter + + '}'; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java new file mode 100644 index 00000000..9a2b8d77 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/GuiParent.java @@ -0,0 +1,190 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.elements.GuiElement; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import org.jetbrains.annotations.ApiStatus; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** + * This is the base interface that allows an element or screen to define its basic geometry. + * As well as defining the primary methods for handling child elements. + *

+ * It also provides a way to access some common minecraft fields. + *

+ * Created by brandon3055 on 29/06/2023 + */ +public interface GuiParent> { + + /** + * @return The position of the Left edge of this element. + */ + double xMin(); + + /** + * @return The position of the Right edge of this element. + */ + double xMax(); + + /** + * @return The Width of this element. + */ + double xSize(); + + /** + * @return The position of the Top edge of this element. + */ + double yMin(); + + /** + * @return The position of the Bottom edge of this element. + */ + double yMax(); + + /** + * @return The Height of this element. + */ + double ySize(); + + /** + * Returns a reference to the specified geometry parameter. + * This is primarily used when defining geometry constraints. + * But it can also be used as a simple {@link Supplier} + * that will return the current parameter value when requested. + *

+ * Note: The returned geometry reference will always be valid + * + * @param param The geometry parameter. + * @return A Geometry Reference + */ + default GeoRef get(GeoParam param) { + return new GeoRef(this, param); + } + + /** + * @param param The geometry parameter. + * @return The current value of the specified parameter. + */ + default double getValue(GeoParam param) { + return switch (param) { + case LEFT -> xMin(); + case RIGHT -> xMax(); + case WIDTH -> xSize(); + case TOP -> yMin(); + case BOTTOM -> yMax(); + case HEIGHT -> ySize(); + }; + } + + /** + * @return An unmodifiable list of all assigned child elements assigned to this parent. The list should be sorted in the order they were added. + */ + List> getChildren(); + + /** + * Adds a new child element to this parent. + * You should almost never need to use this because this is handled automatically when an element is created. + *

+ * Note: Due to the way relative coordinates work with the new geometry system, + * Transferring an element to a different parent can have unpredictable results. + * Therefor, to help avoid confusion it is not possible to transfer a child to a new parent using this method. + * + * @param child The child element to be added. + * @throws UnsupportedOperationException - If child has previously been assigned to a different parent. + * @see #adoptChild(GuiElement) + */ + void addChild(GuiElement child); + + /** + * This meant to be a convenience method that allows builder style addition of a child element. + * I'm not sure how useful it will be yet, so it may or may not stay. + * + * @param createChild A consumer that is given this element to be used in the construction of the child element. + * @return The parent element + */ + @ApiStatus.Experimental + @SuppressWarnings ("unchecked") + default T addChild(Consumer createChild) { + createChild.accept((T) this); + return (T) this; + } + + /** + * This method can be used to transfer an already initialized child to this parent element. + * This automatically handles removing the element from its previous parent, adds it to this element. + * Note: This will most likely break any relative constraints on the child's geometry. + * To fix this you will need to re-apply geometry constraints after the transfer. + * + * @param child The child element to be adopted. + */ + void adoptChild(GuiElement child); + + /** + * Allows the removal of a child element. + * Child removal is not instantaneous, Instead all removals occur at the end of the current screen thick. + * This is to avoid any possible concurrency issues. + * + * @param child The child element to be removed. + */ + void removeChild(GuiElement child); + + /** + * Checks if this element is a descendant of the specified. + * @return true if the specified element is a parent or grandparent etc... of this element. + */ + default boolean isDescendantOf(GuiElement ancestor) { + return false; + } + + /** + * @return The minecraft instance. + */ + Minecraft mc(); + + /** + * @return The active font instance. + */ + Font font(); + + /** + * @return The current gui screen width, As returned by mc.getWindow().getGuiScaledWidth() + */ + int scaledScreenWidth(); + + /** + * @return The current gui screen height, As returned by mc.getWindow().getGuiScaledHeight() + */ + int scaledScreenHeight(); + + /** + * @return the parent ModularGui instance. + */ + ModularGui getModularGui(); + + /** + * Called when the minecraft Screen is initialised or resized. + * + * @param mc The Minecraft instance. + * @param font The active font. + * @param screenWidth The current guiScaledWidth. + * @param screenHeight The current guiScaledHeight. + */ + default void onScreenInit(Minecraft mc, Font font, int screenWidth, int screenHeight) { + getChildren().forEach(e -> e.onScreenInit(mc, font, screenWidth, screenHeight)); + } + + /** + * Allows an element to override the {@link GuiElement#isMouseOver()} method of its children. + * This is primarily used for things like scroll elements where mouseover interactions need to be blocked outside the view area. + * + * @param element The element on which isMouseOver is getting called. + * @return true if mouse-over interaction should be blocked for this child element. + */ + default boolean blockMouseOver(GuiElement element, double mouseX, double mouseY) { + return false; + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java new file mode 100644 index 00000000..df430507 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Position.java @@ -0,0 +1,103 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 24/08/2023 + */ +public interface Position { + + double x(); + + double y(); + + default Position offset(double x, double y) { + return create(x() + x, y() + y); + } + + /** + * Returns the position value for the given axis. + */ + default double get(Axis axis) { + return axis == Axis.X ? x() : y(); + } + + static Position create(double x, double y) { + return new Immutable(x, y); + } + + static Position create(Supplier getX, Supplier getY) { + return new Dynamic(getX, getY); + } + + /** + * Creates a new position, bound to the specified parent's position. + * */ + static Position create(GuiParent parent) { + return new Dynamic(parent::xMin, parent::yMin); + } + + record Immutable(@Override double x, @Override double y) implements Position { } + + record Dynamic(Supplier getX, Supplier getY) implements Position { + @Override + public double x() { + return getX.get(); + } + + @Override + public double y() { + return getY.get(); + } + + @Override + public String toString() { + return "Dynamic{" + + "x=" + x() + + ", y=" + y() + + '}'; + } + } + + static class Mutable implements Position { + private double x; + private double y; + + public Mutable(double x, double y) { + this.x = x; + this.y = y; + } + + @Override + public double x() { + return x; + } + + @Override + public double y() { + return y; + } + + @Override + public Position offset(double x, double y) { + this.x += x; + this.y += y; + return this; + } + + public Position set(double x, double y) { + this.x = x; + this.y = y; + return this; + } + + @Override + public String toString() { + return "Mutable{" + + "x=" + x() + + ", y=" + y() + + '}'; + } + } + +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java new file mode 100644 index 00000000..d770073d --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/Rectangle.java @@ -0,0 +1,313 @@ +package codechicken.lib.gui.modular.lib.geometry; + +import net.minecraft.client.renderer.Rect2i; + +import java.util.function.Supplier; + +/** + * Created by brandon3055 on 14/08/2023 + */ +public interface Rectangle { + + Position pos(); + + default double x() { + return pos().x(); + } + + default double y() { + return pos().y(); + } + + double width(); + + double height(); + + default double xMax() { + return x() + width(); + } + + default double yMax() { + return y() + height(); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle offsetPos(double xAmount, double yAmount) { + return create(x() + xAmount, y() + yAmount, width(), height()); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle setPos(double newX, double newY) { + return create(newX, newY, width(), height()); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle setSize(double width, double height) { + return create(x(), y(), width, height); + } + + /** + * Returns a new rectangle with this operation applied + */ + default Rectangle offsetSize(double xAmount, double yAmount) { + return create(x(), y(), width() + xAmount, height() + yAmount); + } + + default Rect2i toRect2i() { + return new Rect2i((int) x(), (int) y(), (int) width(), (int) height()); + } + + default boolean intersects(double x, double y, double w, double h) { + double x0 = x(); + double y0 = y(); + return (x + w > x0 && y + h > y0 && x < x0 + width() && y < y0 + height()); + } + + default boolean intersects(Rectangle other) { + double x0 = x(); + double y0 = y(); + return (other.x() + other.width() > x0 && other.y() + other.height() > y0 && other.x() < x0 + width() && other.y() < y0 + height()); + } + + /** + * Returns a new rectangle that represents the intersection area between the two inputs + */ + default Rectangle intersect(Rectangle other) { + double left = Math.max(x(), other.x()); + double right = Math.min(xMax(), other.xMax()); + if (right > left) { + double top = Math.max(y(), other.y()); + double bottom = Math.min(yMax(), other.yMax()); + if (bottom > top) { + return create(left, top, right - left, bottom - top); + } + } + return create(0, 0, 0, 0); + } + + /** + * Returns a new rectangle, the bounds of which enclose all the input rectangles. + * + * @param combineWith Rectangles to combine with the start rectangle + */ + default Rectangle combine(Rectangle... combineWith) { + double x = x(); + double y = y(); + double maxX = xMax(); + double maxY = yMax(); + for (Rectangle other : combineWith) { + x = Math.min(x, other.x()); + y = Math.min(y, other.y()); + maxX = Math.max(maxX, other.xMax()); + maxY = Math.max(maxY, other.yMax()); + } + return create(x, y, maxX - x, maxY - y); + } + + default boolean contains(double x, double y) { + return x >= x() && x <= x() + width() && y >= y() && y <= y() + height(); + } + + /** + * @return the size of this rectangle on the given axis. + */ + default double size(Axis axis) { + return axis == Axis.X ? width() : height(); + } + + /** + * @return the min value the specified axis (meaning x() or y()) + */ + default double min(Axis axis) { + return axis == Axis.X ? x() : y(); + } + + /** + * @return the max value the specified axis (meaning x() + width() or y() + height()) + */ + default double max(Axis axis) { + return axis == Axis.X ? xMax() : yMax(); + } + + /** + * Return the distance the given position is from this rectangle on the specified axis. + * Will return 0 if position is inside this rectangle on the given axis. + */ + default double distance(Axis axis, Position position) { + double pos = position.get(axis); + double min = min(axis); + double max = max(axis); + return pos < min ? min - pos : pos > max ? pos - max : 0; + } + + static Rectangle create(Position position, double width, double height) { + return new Immutable(position, width, height); + } + + static Rectangle create(double x, double y, double width, double height) { + return new Immutable(Position.create(x, y), width, height); + } + + /** + * Returns a new rectangle bound to the specified parent's geometry. + */ + static Rectangle create(GuiParent parent) { + return new Dynamic(Position.create(parent), parent::xSize, parent::ySize); + } + + static Rectangle create(Position position, Supplier getWidth, Supplier getHeight) { + return new Dynamic(position, getWidth, getHeight); + } + + default Mutable mutable() { + return new Mutable(new Position.Mutable(x(), y()), width(), height()); + } + + /** + * Should not be created directly + */ + record Immutable(Position position, double xSize, double ySize) implements Rectangle { + @Override + public Position pos() { + return position; + } + + @Override + public double width() { + return xSize; + } + + @Override + public double height() { + return ySize; + } + + @Override + public String toString() { + return "Immutable{" + + "pos=" + pos() + + ", width=" + width() + + ", height=" + height() + + '}'; + } + } + + record Dynamic(Position position, Supplier getWidth, Supplier getHeight) implements Rectangle { + @Override + public Position pos() { + return position; + } + + @Override + public double width() { + return getWidth.get(); + } + + @Override + public double height() { + return getHeight.get(); + } + + @Override + public String toString() { + return "Dynamic{" + + "pos=" + pos() + + ", width=" + width() + + ", height=" + height() + + '}'; + } + } + + class Mutable implements Rectangle { + private Position.Mutable pos; + private double width; + private double height; + + public Mutable(Position.Mutable pos, double width, double height) { + this.pos = pos; + this.width = width; + this.height = height; + } + + @Override + public Position pos() { + return pos; + } + + @Override + public double width() { + return width; + } + + @Override + public double height() { + return height; + } + + @Override + public Rectangle offsetPos(double xAmount, double yAmount) { + pos.offset(xAmount, yAmount); + return this; + } + + @Override + public Rectangle setPos(double newX, double newY) { + pos.set(newX, newY); + return this; + } + + @Override + public Rectangle setSize(double width, double height) { + this.width = width; + this.height = height; + return this; + } + + @Override + public Rectangle offsetSize(double xAmount, double yAmount) { + this.width += xAmount; + this.height += yAmount; + return this; + } + + @Override + public Rectangle intersect(Rectangle other) { + double x = Math.max(x(), other.x()); + double y = Math.max(y(), other.y()); + width = Math.max(0, Math.min(xMax(), other.xMax()) - x()); + height = Math.max(0, Math.min(yMax(), other.yMax()) - y()); + return setPos(x, y); + } + + public void set(Rectangle rectangle) { + this.pos.set(rectangle.x(), rectangle.y()); + this.width = rectangle.width(); + this.height = rectangle.height(); + } + + @Override + public Rectangle combine(Rectangle... combineWith) { + double x = x(); + double y = y(); + double maxX = xMax(); + double maxY = yMax(); + for (Rectangle other : combineWith) { + x = Math.min(x, other.x()); + y = Math.min(y, other.y()); + maxX = Math.max(maxX, other.xMax()); + maxY = Math.max(maxY, other.yMax()); + } + return setPos(x, y).setSize(maxX - x, maxY - y); + } + + public Immutable immutable() { + return new Immutable(Position.create(x(), y()), width(), height()); + } + } +} diff --git a/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java new file mode 100644 index 00000000..ee9de084 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/geometry/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.lib.geometry; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/lib/package-info.java b/src/main/java/codechicken/lib/gui/modular/lib/package-info.java new file mode 100644 index 00000000..d757f46a --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/lib/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular.lib; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/modular/package-info.java b/src/main/java/codechicken/lib/gui/modular/package-info.java new file mode 100644 index 00000000..1a87becf --- /dev/null +++ b/src/main/java/codechicken/lib/gui/modular/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.modular; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java b/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java new file mode 100644 index 00000000..8f99c0b8 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/CCCustomRenderState.java @@ -0,0 +1,32 @@ +package codechicken.lib.gui.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.gui.navigation.ScreenRectangle; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.GuiElementRenderState; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix3x2f; + +/** + * Created by covers1624 on 4/11/26. + */ +public record CCCustomRenderState( + RenderPipeline pipeline, + TextureSetup textureSetup, + Matrix3x2f pose, + @Nullable ScreenRectangle scissorArea, + @Nullable ScreenRectangle bounds, + VertBuilder builder +) implements GuiElementRenderState { + + @Override + public void buildVertices(VertexConsumer consumer) { + builder.buildVertices(consumer, pose); + } + + public interface VertBuilder { + + void buildVertices(VertexConsumer consumer, Matrix3x2f pose); + } +} diff --git a/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java new file mode 100644 index 00000000..63bb6398 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/GuiGraphicsExtension.java @@ -0,0 +1,442 @@ +package codechicken.lib.gui.render; + +import codechicken.lib.colour.Colour; +import codechicken.lib.gui.modular.lib.geometry.Borders; +import codechicken.lib.gui.modular.lib.geometry.Rectangle; +import com.mojang.blaze3d.pipeline.RenderPipeline; +import net.minecraft.client.gui.Font; +import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.gui.render.TextureSetup; +import net.minecraft.client.gui.render.state.BlitRenderState; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.locale.Language; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.FormattedText; +import net.minecraft.resources.Identifier; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.util.Mth; +import net.minecraft.util.Util; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; + +/** + * An extension interface providing many various GUI rendering helpers. + * + * @see GuiGraphics + */ +// TODO document all these, they mostly came from the old GuiRender class from ModularGui, and all had documentation. +public interface GuiGraphicsExtension { + + private GuiGraphics self() { + return (GuiGraphics) this; + } + + default void cc$fillGradientH(Rectangle rect, int col1, int col2) { + cc$fillGradientH(rect.x(), rect.y(), rect.xMax(), rect.yMax(), col1, col2); + } + + default void cc$fillGradientH(double xMin, double yMin, double xMax, double yMax, int col1, int col2) { + cc$fillGradient(xMin, yMin, xMax, yMax, col1, col2, true); + } + + default void cc$fillGradientV(Rectangle rect, int col1, int col2) { + cc$fillGradientV(rect.x(), rect.y(), rect.xMax(), rect.yMax(), col1, col2); + } + + default void cc$fillGradientV(double xMin, double yMin, double xMax, double yMax, int col1, int col2) { + cc$fillGradient(xMin, yMin, xMax, yMax, col1, col2, true); + } + + default void cc$fill(Rectangle rect, int color) { + cc$fill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), color); + } + + default void cc$fill(double xMin, double yMin, double xMax, double yMax, int color) { + cc$fillGradient(xMin, yMin, xMax, yMax, color, color, false); + } + + default void cc$fill(RenderPipeline pipeline, double xMin, double yMin, double xMax, double yMax, int color) { + cc$fillGradient(pipeline, xMin, yMin, xMax, yMax, color, color, false); + } + + default void cc$fillGradient(double xMin, double yMin, double xMax, double yMax, int col1, int col2, boolean hoz) { + cc$fillGradient(RenderPipelines.GUI, xMin, yMin, xMax, yMax, col1, col2, hoz); + } + + default void cc$fillGradient(RenderPipeline pipeline, double xMin, double yMin, double xMax, double yMax, int col1, int col2, boolean hoz) { + cc$submitColoredRectangle(pipeline, TextureSetup.noTexture(), + xMin, xMax, + yMin, yMax, + col1, col2, + hoz + ); + } + + private void cc$submitColoredRectangle(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, int col1, int col2, boolean hoz) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> { + if (hoz) { + RenderStateUtils.fillGradientH(consumer, pose, x0, x1, y0, y1, col1, col2); + } else { + RenderStateUtils.fillGradientV(consumer, pose, x0, x1, y0, y1, col1, col2); + } + } + ); + } + + default void cc$borderRect(Rectangle rect, double border, int fillColor, int borderColor) { + cc$borderFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, fillColor, borderColor); + } + + default void cc$borderRect(double x, double y, double width, double height, double border, int fillColor, int borderColor) { + cc$borderFill(x, y, x + width, y + height, border, fillColor, borderColor); + } + + default void cc$borderFill(double xMin, double yMin, double xMax, double yMax, double border, int fillColor, int borderColor) { + cc$submitBorderFill(RenderPipelines.GUI, TextureSetup.noTexture(), xMin, xMax, yMin, yMax, border, fillColor, borderColor); + } + + private void cc$submitBorderFill(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, double border, int fillColor, int borderColor) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.borderFill( + consumer, pose, + x0, x1, + y0, y1, + border, + borderColor, + fillColor + ) + ); + } + + default void cc$shadedRect(Rectangle rect, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, topLeftColor, bottomRightColor, fillColor); + } + + default void cc$shadedRect(Rectangle rect, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$shadedFill(rect.x(), rect.y(), rect.xMax(), rect.yMax(), border, topLeftColor, bottomRightColor, cornerMixColor, fillColor); + } + + default void cc$shadedRect(double x, double y, double width, double height, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(x, y, x + width, y + height, border, topLeftColor, bottomRightColor, fillColor); + } + + default void cc$shadedRect(double x, double y, double width, double height, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$shadedFill(x, y, x + width, y + height, border, topLeftColor, bottomRightColor, cornerMixColor, fillColor); + } + + default void cc$shadedFill(double xMin, double yMin, double xMax, double yMax, double border, int topLeftColor, int bottomRightColor, int fillColor) { + cc$shadedFill(xMin, yMin, xMax, yMax, border, topLeftColor, bottomRightColor, Colour.mid(topLeftColor, bottomRightColor), fillColor); + } + + default void cc$shadedFill(double xMin, double yMin, double xMax, double yMax, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$submitShadedFill(RenderPipelines.GUI, TextureSetup.noTexture(), + xMin, xMax, + yMin, yMax, + border, + topLeftColor, bottomRightColor, + cornerMixColor, fillColor + ); + } + + private void cc$submitShadedFill(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + cc$submitCustom( + pipeline, texture, + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.shadedFill( + consumer, pose, + x0, x1, + y0, y1, + border, + topLeftColor, bottomRightColor, + cornerMixColor, fillColor + ) + ); + } + + default void cc$tooltipBackground(double x, double y, double width, double height, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$tooltipBackground(RenderPipelines.GUI, TextureSetup.noTexture(), x, y, width, height, bgColorTop, bgColorBottom, borderColorTop, borderColorBottom, empty); + } + + default void cc$tooltipBackground(RenderPipeline pipeline, TextureSetup texture, double x, double y, double width, double height, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$submitTooltipBackground(pipeline, texture, x, x + width, y, y + height, bgColorTop, bgColorBottom, borderColorTop, borderColorBottom, empty); + } + + private void cc$submitTooltipBackground(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, int bgColorTop, int bgColorBottom, int borderColorTop, int borderColorBottom, boolean empty) { + cc$submitCustom(pipeline, texture, x0, x1, y0, y1, (consumer, pose) -> { + RenderStateUtils.fill(consumer, pose, x0 + 1, y0, x1 - 1, y0 + 1, bgColorTop); // Top + RenderStateUtils.fill(consumer, pose, x0 + 1, y1 - 1, x1 - 1, y1, bgColorBottom); // Bottom + RenderStateUtils.fillGradientV(consumer, pose, x0, x0 + 1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Left + RenderStateUtils.fillGradientV(consumer, pose, x1 - 1, x1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Right + if (!empty) { + RenderStateUtils.fillGradientV(consumer, pose, x0 + 1, x1 - 1, y0 + 1, y1 - 1, bgColorTop, bgColorBottom); // Fill + } + RenderStateUtils.fillGradientV(consumer, pose, x0 + 1, x0 + 2, y0 + 1, y1 - 1, borderColorTop, borderColorBottom); // Left Accent + RenderStateUtils.fillGradientV(consumer, pose, x1 - 2, x1 - 1, y0 + 1, y1 - 1, borderColorTop, borderColorBottom); // Right Accent + RenderStateUtils.fill(consumer, pose, x0 + 2, y0 + 1, x1 - 2, y0 + 2, borderColorTop); // Top Accent + RenderStateUtils.fill(consumer, pose, x0 + 2, y1 - 2, x1 - 2, y1 - 1, borderColorBottom); // Bottom Accent + }); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect) { + cc$blitSprite(pipeline, sprite, rect, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int argb) { + cc$blitSprite(pipeline, sprite, rect.x(), rect.y(), rect.width(), rect.height(), argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, double x, double y, double width, double height) { + cc$blitSprite(pipeline, sprite, x, y, width, height, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, double x, double y, double width, double height, int argb) { + cc$blitSprite(pipeline, sprite, 0, x, y, width, height, argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, Rectangle rect) { + cc$blitSprite(pipeline, sprite, rotation, rect, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, Rectangle rect, int argb) { + cc$blitSprite(pipeline, sprite, rotation, rect.x(), rect.y(), rect.width(), rect.height(), argb); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, double x, double y, double width, double height) { + cc$blitSprite(pipeline, sprite, rotation, x, y, width, height, 0xFFFFFFFF); + } + + default void cc$blitSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int rotation, double x, double y, double width, double height, int argb) { + cc$blit( + pipeline, sprite.atlasLocation(), + x, x + width, + y, y + height, + rotation, + sprite.getU0(), sprite.getU1(), + sprite.getV0(), sprite.getV1(), + argb + ); + } + + default void cc$blitPartialSprite(RenderPipeline pipeline, double x0, double y0, double x1, double y1, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax) { + cc$blitPartialSprite(pipeline, x0, y0, x1, y1, sprite, uMin, vMin, uMax, vMax, 0xFFFFFFFF); + } + + default void cc$blitPartialSprite(RenderPipeline pipeline, double x0, double y0, double x1, double y1, TextureAtlasSprite sprite, float uMin, float vMin, float uMax, float vMax, int argb) { + float u0 = sprite.getU0(); + float v0 = sprite.getV0(); + float u1 = sprite.getU1(); + float v1 = sprite.getV1(); + float ul = u1 - u0; + float vl = v1 - v0; + cc$blit( + pipeline, + sprite.atlasLocation(), + x0, x1, + y0, y1, + 0, + u0 + (uMin * ul), + u0 + (uMax * ul), + v0 + (vMin * vl), + v0 + (vMax * vl), + argb + ); + } + + private void cc$blit(RenderPipeline pipeline, Identifier atlas, + double x0, double x1, + double y0, double y1, + int rotation, + float u0, float u1, + float v0, float v1, + int color) { + var texture = self().minecraft.getTextureManager().getTexture(atlas); + cc$submitCustom( + pipeline, TextureSetup.singleTexture(texture.getTextureView(), texture.getSampler()), + x0, x1, + y0, y1, + (consumer, pose) -> RenderStateUtils.blit( + consumer, pose, + x0, x1, + y0, y1, + rotation, + u0, u1, + v0, v1, + color + ) + ); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, Borders borders) { + cc$blitDynamicSprite(pipeline, sprite, rect, borders, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, Borders borders, int color) { + cc$blitDynamicSprite(pipeline, sprite, (int) rect.x(), (int) rect.y(), (int) rect.width(), (int) rect.height(), (int) borders.top(), (int) borders.left(), (int) borders.bottom(), (int) borders.right(), color); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + cc$blitDynamicSprite(pipeline, sprite, rect, topBorder, leftBorder, bottomBorder, rightBorder, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, Rectangle rect, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int color) { + cc$blitDynamicSprite(pipeline, sprite, (int) rect.x(), (int) rect.y(), (int) rect.width(), (int) rect.height(), topBorder, leftBorder, bottomBorder, rightBorder, color); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, int x, int y, int width, int height, int topBorder, int leftBorder, int bottomBorder, int rightBorder) { + cc$blitDynamicSprite(pipeline, sprite, x, y, width, height, topBorder, leftBorder, bottomBorder, rightBorder, 0xFFFFFFFF); + } + + default void cc$blitDynamicSprite(RenderPipeline pipeline, TextureAtlasSprite sprite, + int x, int y, + int width, int height, + int topBorder, int leftBorder, + int bottomBorder, int rightBorder, + int color) { + var texture = self().minecraft.getTextureManager().getTexture(sprite.atlasLocation()); + cc$submitCustom( + pipeline, + TextureSetup.singleTexture(texture.getTextureView(), texture.getSampler()), + x, x + width, + y, y + height, + (consumer, pose) -> RenderStateUtils.blitDynamic( + consumer, pose, + sprite, + x, y, + width, height, + topBorder, leftBorder, + bottomBorder, rightBorder, + color + ) + ); + } + + private void cc$submitCustom(RenderPipeline pipeline, TextureSetup texture, double x0, double x1, double y0, double y1, CCCustomRenderState.VertBuilder builder) { + var pose = self().pose(); + var scissor = self().peekScissorStack(); + var bounds = BlitRenderState.getBounds((int) x0, (int) y0, (int) x1, (int) y1, pose, scissor); + self().submitGuiElementRenderState(new CCCustomRenderState( + pipeline, + texture, + pose, + scissor, bounds, + builder + )); + } + + default void cc$drawCenteredString(Font font, String text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, String text, double x, double y, int color, boolean drawShadow) { + cc$drawCenteredString(font, Language.getInstance().getVisualOrder(FormattedText.of(text)), x, y, color, drawShadow); + } + + default void cc$drawCenteredString(Font font, Component text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, Component text, double x, double y, int color, boolean drawShadow) { + cc$drawCenteredString(font, text.getVisualOrderText(), x, y, color, drawShadow); + } + + default void cc$drawCenteredString(Font font, FormattedCharSequence text, double x, double y, int color) { + cc$drawCenteredString(font, text, x, y, color, true); + } + + default void cc$drawCenteredString(Font font, FormattedCharSequence text, double x, double y, int color, boolean drawShadow) { + cc$drawString(font, text, x - (double) font.width(text) / 2, y, color, drawShadow); + } + + default void cc$drawString(Font font, @Nullable String text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, @Nullable String text, double x, double y, int color, boolean drawShadow) { + if (text == null) return; + + cc$drawString(font, Language.getInstance().getVisualOrder(FormattedText.of(text)), x, y, color, drawShadow); + } + + default void cc$drawString(Font font, Component text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, Component text, double x, double y, int color, boolean drawShadow) { + cc$drawString(font, text.getVisualOrderText(), x, y, color, drawShadow); + } + + default void cc$drawString(Font font, FormattedCharSequence text, double x, double y, int color) { + cc$drawString(font, text, x, y, color, true); + } + + default void cc$drawString(Font font, FormattedCharSequence text, double x, double y, int color, boolean drawShadow) { + self().drawString(font, text, (int) x, (int) y, color, drawShadow); + } + + default void cc$drawScrollingString(Font font, Component text, double x, double y, double maxX, int color, boolean shadow, boolean scissor) { + int textWidth = font.width(text); + double width = maxX - x; + if (textWidth > width) { + double outside = textWidth - width; + double anim = (double) Util.getMillis() / 1000.0; + double e = Math.max(outside * 0.5, 3.0); + double f = Math.sin(1.5707963267948966 * Math.cos(6.283185307179586 * anim / e)) / 2.0 + 0.5; + double offset = Mth.lerp(f, 0.0, outside); + if (scissor) cc$enableScissor(x, y - 1, maxX, y + font.lineHeight + 1); + cc$drawString(font, text, x - offset, y, color, shadow); + if (scissor) cc$disableScissor(); + } else { + cc$drawCenteredString(font, text, (x + maxX) / 2, y, color, shadow); + } + } + + default void cc$textHighlight(double minX, double minY, double maxX, double maxY) { + cc$fill(RenderPipelines.GUI_INVERT, minX, minY, maxX, maxY, -1); + cc$fill(RenderPipelines.GUI_TEXT_HIGHLIGHT, minX, minY, maxX, maxY, -16776961); + } + + default void cc$enableScissor(Rectangle rect) { + cc$enableScissor(rect.x(), rect.y(), rect.xMax(), rect.yMax()); + } + + default void cc$enableScissor(double minX, double minY, double maxX, double maxY) { + self().enableScissor((int) minX, (int) minY, (int) maxX, (int) maxY); + } + + /** + * Only exists for visual symetry for cc$enableScissor. + */ + default void cc$disableScissor() { + self().disableScissor(); + } + + default void cc$renderItem(ItemStack stack, double x, double y, int rand) { + self().renderItem(stack, (int) x, (int) y, rand); + } + + default void cc$renderItem(@Nullable LivingEntity entity, ItemStack stack, double x, double y, int rand) { + if (entity == null) { + self().renderItem(stack, (int) x, (int) y, rand); + } else { + self().renderItem(entity, stack, (int) x, (int) y, rand); + } + } + + default void cc$renderItemDecorations(Font font, ItemStack stack, double x, double y) { + cc$renderItemDecorations(font, stack, x, y, null); + } + + default void cc$renderItemDecorations(Font font, ItemStack stack, double x, double y, @Nullable String text) { + self().renderItemDecorations(font, stack, (int) x, (int) y, text); + } +} diff --git a/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java b/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java new file mode 100644 index 00000000..1e27b096 --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/RenderStateUtils.java @@ -0,0 +1,141 @@ +package codechicken.lib.gui.render; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.joml.Matrix3x2f; + +/** + * Created by covers1624 on 4/11/26. + */ +public class RenderStateUtils { + + public static void fill(VertexConsumer consumer, Matrix3x2f pose, double xMin, double yMin, double xMax, double yMax, int color) { + if (xMax < xMin) { + double min = xMax; + xMax = xMin; + xMin = min; + } + if (yMax < yMin) { + double min = yMax; + yMax = yMin; + yMin = min; + } + + consumer.addVertexWith2DPose(pose, (float) xMax, (float) yMax).setColor(color); //R-B + consumer.addVertexWith2DPose(pose, (float) xMax, (float) yMin).setColor(color); //R-T + consumer.addVertexWith2DPose(pose, (float) xMin, (float) yMin).setColor(color); //L-T + consumer.addVertexWith2DPose(pose, (float) xMin, (float) yMax).setColor(color); //L-B + } + + public static void fillGradientH(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int col1, int col2) { + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setColor(col2); + } + + public static void fillGradientV(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int col1, int col2) { + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setColor(col1); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setColor(col2); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setColor(col1); + } + + public static void borderFill(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, double border, int borderColor, int fillColor) { + RenderStateUtils.fill(consumer, pose, x0, y0, x1, y0 + border, borderColor); //Top + RenderStateUtils.fill(consumer, pose, x0, y0 + border, x0 + border, y1 - border, borderColor); //Left + RenderStateUtils.fill(consumer, pose, x0, y1 - border, x1, y1, borderColor); //Bottom + RenderStateUtils.fill(consumer, pose, x1 - border, y0 + border, x1, y1 - border, borderColor); //Right + + //No point rendering fill if there is no fill color + if (fillColor != 0) { + RenderStateUtils.fill(consumer, pose, x0 + border, y0 + border, x1 - border, y1 - border, fillColor); //Fill + } + } + + public static void shadedFill(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, double border, int topLeftColor, int bottomRightColor, int cornerMixColor, int fillColor) { + fill(consumer, pose, x0, y0, x1 - border, y0 + border, topLeftColor); //Top + fill(consumer, pose, x0, y0 + border, x0 + border, y1 - border, topLeftColor); //Left + fill(consumer, pose, x0 + border, -border, x1, y1, bottomRightColor); //Bottom + fill(consumer, pose, x1 - border, y0 + border, x1, y1 - border, bottomRightColor); //Right + fill(consumer, pose, x1 - border, y0, x1, y0 + border, cornerMixColor); //Top Right Corner + fill(consumer, pose, x0, y1 - border, x0 + border, y1, cornerMixColor); //Bottom Left Corner + + //No point rendering fill if there is no fill color + if (fillColor != 0) { + fill(consumer, pose, x0 + border, y0 + border, x1 - border, y1 - border, fillColor); //Fill + } + } + + public static void blit(VertexConsumer consumer, Matrix3x2f pose, double x0, double x1, double y0, double y1, int rotation, float u0, float u1, float v0, float v1, int color) { + float[] u = { u1, u0, u0, u1 }; + float[] v = { v0, v0, v1, v1 }; + consumer.addVertexWith2DPose(pose, (float) x0, (float) y0).setUv(u[(1 + rotation) % 4], v[(1 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x0, (float) y1).setUv(u[(2 + rotation) % 4], v[(2 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y1).setUv(u[(3 + rotation) % 4], v[(3 + rotation) % 4]).setColor(color); + consumer.addVertexWith2DPose(pose, (float) x1, (float) y0).setUv(u[(0 + rotation) % 4], v[(0 + rotation) % 4]).setColor(color); + } + + public static void blitDynamic(VertexConsumer consumer, Matrix3x2f pose, TextureAtlasSprite sprite, int xPos, int yPos, int xSize, int ySize, int topBorder, int leftBorder, int bottomBorder, int rightBorder, int color) { + SpriteContents contents = sprite.contents(); + int texWidth = contents.width(); + int texHeight = contents.height(); + int trimWidth = texWidth - leftBorder - rightBorder; + int trimHeight = texHeight - topBorder - bottomBorder; + if (xSize <= texWidth) trimWidth = Math.min(trimWidth, xSize - rightBorder); + if (xSize <= 0 || ySize <= 0 || trimWidth <= 0 || trimHeight <= 0) return; + + for (int x = 0; x < xSize; ) { + int rWidth = Math.min(xSize - x, trimWidth); + int trimU = 0; + if (x != 0) { + if (x + leftBorder + trimWidth <= xSize) { + trimU = leftBorder; + } else { + trimU = (texWidth - (xSize - x)); + } + } + + //Top & Bottom trim + emitQuad(consumer, pose, sprite, xPos + x, yPos, trimU, 0, rWidth, topBorder, color); + emitQuad(consumer, pose, sprite, xPos + x, yPos + ySize - bottomBorder, trimU, texHeight - bottomBorder, rWidth, bottomBorder, color); + + rWidth = Math.min(xSize - x - leftBorder - rightBorder, trimWidth); + for (int y = 0; y < ySize; ) { + int rHeight = Math.min(ySize - y - topBorder - bottomBorder, trimHeight); + int trimV; + if (y + (texHeight - topBorder - bottomBorder) <= ySize) { + trimV = topBorder; + } else { + trimV = texHeight - (ySize - y); + } + + //Left & Right trim + if (x == 0 && y + topBorder < ySize - bottomBorder) { + emitQuad(consumer, pose, sprite, xPos, yPos + y + topBorder, 0, trimV, leftBorder, rHeight, color); + emitQuad(consumer, pose, sprite, xPos + xSize - rightBorder, yPos + y + topBorder, trimU + texWidth - rightBorder, trimV, rightBorder, rHeight, color); + } + + //Core + if (y + topBorder < ySize - bottomBorder && x + leftBorder < xSize - rightBorder) { + emitQuad(consumer, pose, sprite, xPos + x + leftBorder, yPos + y + topBorder, leftBorder, topBorder, rWidth, rHeight, color); + } + y += trimHeight; + } + x += trimWidth; + } + } + + public static void emitQuad(VertexConsumer builder, Matrix3x2f pose, TextureAtlasSprite sprite, int x, int y, float textureX, float textureY, int width, int height, int color) { + int w = sprite.contents().width(); + int h = sprite.contents().height(); + + //@formatter:off + builder.addVertexWith2DPose(pose, x, y + height).setUv(sprite.getU(textureX / w), sprite.getV((textureY + height) / h)).setColor(color); + builder.addVertexWith2DPose(pose, x + width, y + height).setUv(sprite.getU((textureX + width) / w), sprite.getV((textureY + height) / h)).setColor(color); + builder.addVertexWith2DPose(pose, x + width, y ).setUv(sprite.getU((textureX + width) / w), sprite.getV((textureY / h)) ).setColor(color); + builder.addVertexWith2DPose(pose, x, y ).setUv(sprite.getU(textureX / w), sprite.getV((textureY / h)) ).setColor(color); + //@formatter:on + } +} diff --git a/src/main/java/codechicken/lib/gui/render/package-info.java b/src/main/java/codechicken/lib/gui/render/package-info.java new file mode 100644 index 00000000..9beba10e --- /dev/null +++ b/src/main/java/codechicken/lib/gui/render/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.gui.render; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/CCLNetwork.java b/src/main/java/codechicken/lib/internal/CCLNetwork.java new file mode 100644 index 00000000..e264f5fc --- /dev/null +++ b/src/main/java/codechicken/lib/internal/CCLNetwork.java @@ -0,0 +1,39 @@ +package codechicken.lib.internal; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import codechicken.lib.packet.StreamNetworkChannel; +import codechicken.lib.packet.StreamNetworkChannel.BidirectionalPacketHandle; +import codechicken.lib.packet.StreamNetworkChannel.ConfigurationPacketHandle; +import codechicken.lib.render.particle.CustomParticleHandler; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.neoforge.network.handling.IPayloadContext; + +import static codechicken.lib.CodeChickenLib.MOD_ID; + +/** + * Created by covers1624 on 28/10/19. + */ +public class CCLNetwork { + + protected static final StreamNetworkChannel CHANNEL = new StreamNetworkChannel(MOD_ID) + .optional(); + + public static final BidirectionalPacketHandle GUI_SYNC = CHANNEL.playBidirectional("gui_sync", ModularGuiContainerMenu::handlePacketFromClient); + public static final BidirectionalPacketHandle TILE_MESSAGE = CHANNEL.playBidirectional("tile_message", CCLNetwork::handleTileMessageServer); + + public static final ConfigurationPacketHandle CONFIG_SYNC = CHANNEL.configurationToClient("config_sync", ConfigSyncManager.ConfigSyncConfigurationTask::new); + + public static void init(IEventBus modBus, ModContainer container) { + CHANNEL.init(modBus, container); + } + + private static void handleTileMessageServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { + tile.onInternalServerPacket(packet, ctx); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/CCLNetworkClient.java b/src/main/java/codechicken/lib/internal/CCLNetworkClient.java new file mode 100644 index 00000000..6c0cdd26 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/CCLNetworkClient.java @@ -0,0 +1,26 @@ +package codechicken.lib.internal; + +import codechicken.lib.block.ModularBlockEntity; +import codechicken.lib.config.ConfigSyncManager; +import codechicken.lib.inventory.container.modular.ModularGuiContainerMenu; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.handling.IPayloadContext; + +/** + * Created by covers1624 on 11/4/26. + */ +public class CCLNetworkClient extends CCLNetwork { + + public static void initClient() { + CHANNEL.assignClientHandler(GUI_SYNC, ModularGuiContainerMenu::handlePacketFromServer); + CHANNEL.assignClientHandler(TILE_MESSAGE, CCLNetworkClient::handleTileMessageClient); + + CHANNEL.assignClientHandler(CONFIG_SYNC, ConfigSyncManager::readSyncPacket); + } + + private static void handleTileMessageClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + if (ctx.player().level().getBlockEntity(packet.readBlockPos()) instanceof ModularBlockEntity tile) { + tile.onInternalClientPacket(packet, ctx); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/ClientInit.java b/src/main/java/codechicken/lib/internal/ClientInit.java new file mode 100644 index 00000000..08a12f99 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/ClientInit.java @@ -0,0 +1,57 @@ +package codechicken.lib.internal; + +import codechicken.lib.CodeChickenLib; +import codechicken.lib.config.ConfigCategory; +import codechicken.lib.gui.modular.lib.CursorHelper; +import codechicken.lib.render.CCRenderEventHandler; +import codechicken.lib.render.CCRenderPipelines; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; +import net.neoforged.neoforge.client.event.RegisterRenderPipelinesEvent; + +import static codechicken.lib.CodeChickenLib.MOD_ID; + +/** + * Created by covers1624 on 8/9/23. + */ +public class ClientInit { + + private static final CrashLock LOCK = new CrashLock("Already Initialized."); + + public static void init(IEventBus modBus) { + LOCK.lock(); + + CCLNetworkClient.initClient(); + + loadClientConfig(); + CCRenderEventHandler.init(); + HighlightHandler.init(); + + modBus.addListener(ClientInit::onResourceReload); + modBus.addListener(ClientInit::onRegisterPipelines); + } + + private static void loadClientConfig() { + ConfigCategory clientTag = CodeChickenLib.config.getCategory("client"); + clientTag.delete("block_renderer_dispatcher_misc"); + clientTag.delete("catchItemRenderExceptions"); + clientTag.delete("attemptRecoveryOnItemRenderException"); + clientTag.delete("catchBlockRenderExceptions"); + clientTag.delete("messagePlayerOnRenderExceptionCaught"); + + clientTag.save(); + } + + private static void onResourceReload(AddClientReloadListenersEvent event) { + event.addListener(Identifier.fromNamespaceAndPath(MOD_ID, "cursor_helper"), (ResourceManagerReloadListener) e -> CursorHelper.onResourceReload()); + } + + private static void onRegisterPipelines(RegisterRenderPipelinesEvent event) { + event.registerPipeline(CCRenderPipelines.SOLID_TRIANGLES); + event.registerPipeline(CCRenderPipelines.POSITION_COLOR); + event.registerPipeline(CCRenderPipelines.POSITION_COLOR_NO_DEPTH); + } +} diff --git a/src/main/java/codechicken/lib/internal/DataGenerators.java b/src/main/java/codechicken/lib/internal/DataGenerators.java index 91638b65..f4ee4ce8 100644 --- a/src/main/java/codechicken/lib/internal/DataGenerators.java +++ b/src/main/java/codechicken/lib/internal/DataGenerators.java @@ -2,75 +2,82 @@ import codechicken.lib.datagen.LanguageProvider; import codechicken.lib.util.CCLTags; -import net.minecraft.data.DataGenerator; -import net.minecraft.data.tags.BlockTagsProvider; -import net.minecraft.data.tags.ItemTagsProvider; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.core.HolderLookup; +import net.minecraft.data.PackOutput; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Blocks; -import net.minecraftforge.common.data.ExistingFileHelper; -import net.minecraftforge.data.event.GatherDataEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.common.data.BlockTagsProvider; +import net.neoforged.neoforge.common.data.ItemTagsProvider; +import net.neoforged.neoforge.data.event.GatherDataEvent; + +import java.util.concurrent.CompletableFuture; import static codechicken.lib.CodeChickenLib.MOD_ID; /** * Created by covers1624 on 13/12/20. */ -@Mod.EventBusSubscriber (modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD) public class DataGenerators { - @SubscribeEvent - public static void gatherDataGenerators(GatherDataEvent event) { - DataGenerator gen = event.getGenerator(); - ExistingFileHelper files = event.getExistingFileHelper(); - BlockTags blockTagsProvider = new BlockTags(gen, files); - gen.addProvider(event.includeServer(), blockTagsProvider); - gen.addProvider(event.includeServer(), new ItemTags(gen, blockTagsProvider, files)); - gen.addProvider(event.includeClient() || event.includeServer(), new LangUS(gen, LanguageProvider.getDist(event))); + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + + public static void init(IEventBus modBus) { + LOCK.lock(); + if (FMLEnvironment.getDist().isClient()) { + modBus.addListener(DataGenerators::gatherDataGenerators); + } + } + + private static void gatherDataGenerators(GatherDataEvent.Client event) { + event.createProvider(BlockTags::new); + event.createProvider(ItemTags::new); + event.createProvider(LangUS::new); } private static class BlockTags extends BlockTagsProvider { - public BlockTags(DataGenerator generatorIn, ExistingFileHelper files) { - super(generatorIn, MOD_ID, files); + public BlockTags(PackOutput output, CompletableFuture lookupProvider) { + super(output, lookupProvider, MOD_ID); } @Override - protected void addTags() { - tag(CCLTags.Blocks.WOOL) - .addTag(CCLTags.Blocks.WOOL_WHITE) - .addTag(CCLTags.Blocks.WOOL_ORANGE) - .addTag(CCLTags.Blocks.WOOL_MAGENTA) - .addTag(CCLTags.Blocks.WOOL_LIGHT_BLUE) - .addTag(CCLTags.Blocks.WOOL_YELLOW) - .addTag(CCLTags.Blocks.WOOL_LIME) - .addTag(CCLTags.Blocks.WOOL_PINK) - .addTag(CCLTags.Blocks.WOOL_GRAY) - .addTag(CCLTags.Blocks.WOOL_LIGHT_GRAY) - .addTag(CCLTags.Blocks.WOOL_CYAN) - .addTag(CCLTags.Blocks.WOOL_PURPLE) - .addTag(CCLTags.Blocks.WOOL_BLUE) - .addTag(CCLTags.Blocks.WOOL_BROWN) - .addTag(CCLTags.Blocks.WOOL_GREEN) - .addTag(CCLTags.Blocks.WOOL_RED) - .addTag(CCLTags.Blocks.WOOL_BLACK); - tag(CCLTags.Blocks.WOOL_WHITE).add(Blocks.WHITE_WOOL); - tag(CCLTags.Blocks.WOOL_ORANGE).add(Blocks.ORANGE_WOOL); - tag(CCLTags.Blocks.WOOL_MAGENTA).add(Blocks.MAGENTA_WOOL); - tag(CCLTags.Blocks.WOOL_LIGHT_BLUE).add(Blocks.LIGHT_BLUE_WOOL); - tag(CCLTags.Blocks.WOOL_YELLOW).add(Blocks.YELLOW_WOOL); - tag(CCLTags.Blocks.WOOL_LIME).add(Blocks.LIME_WOOL); - tag(CCLTags.Blocks.WOOL_PINK).add(Blocks.PINK_WOOL); - tag(CCLTags.Blocks.WOOL_GRAY).add(Blocks.GRAY_WOOL); - tag(CCLTags.Blocks.WOOL_LIGHT_GRAY).add(Blocks.LIGHT_GRAY_WOOL); - tag(CCLTags.Blocks.WOOL_CYAN).add(Blocks.CYAN_WOOL); - tag(CCLTags.Blocks.WOOL_PURPLE).add(Blocks.PURPLE_WOOL); - tag(CCLTags.Blocks.WOOL_BLUE).add(Blocks.BLUE_WOOL); - tag(CCLTags.Blocks.WOOL_BROWN).add(Blocks.BROWN_WOOL); - tag(CCLTags.Blocks.WOOL_GREEN).add(Blocks.GREEN_WOOL); - tag(CCLTags.Blocks.WOOL_RED).add(Blocks.RED_WOOL); - tag(CCLTags.Blocks.WOOL_BLACK).add(Blocks.BLACK_WOOL); + protected void addTags(HolderLookup.Provider pProvider) { + tag(CCLTags.Blocks.WOOLS) + .addTag(CCLTags.Blocks.WOOLS_WHITE) + .addTag(CCLTags.Blocks.WOOLS_ORANGE) + .addTag(CCLTags.Blocks.WOOLS_MAGENTA) + .addTag(CCLTags.Blocks.WOOLS_LIGHT_BLUE) + .addTag(CCLTags.Blocks.WOOLS_YELLOW) + .addTag(CCLTags.Blocks.WOOLS_LIME) + .addTag(CCLTags.Blocks.WOOLS_PINK) + .addTag(CCLTags.Blocks.WOOLS_GRAY) + .addTag(CCLTags.Blocks.WOOLS_LIGHT_GRAY) + .addTag(CCLTags.Blocks.WOOLS_CYAN) + .addTag(CCLTags.Blocks.WOOLS_PURPLE) + .addTag(CCLTags.Blocks.WOOLS_BLUE) + .addTag(CCLTags.Blocks.WOOLS_BROWN) + .addTag(CCLTags.Blocks.WOOLS_GREEN) + .addTag(CCLTags.Blocks.WOOLS_RED) + .addTag(CCLTags.Blocks.WOOLS_BLACK); + tag(CCLTags.Blocks.WOOLS_WHITE).add(Blocks.WHITE_WOOL); + tag(CCLTags.Blocks.WOOLS_ORANGE).add(Blocks.ORANGE_WOOL); + tag(CCLTags.Blocks.WOOLS_MAGENTA).add(Blocks.MAGENTA_WOOL); + tag(CCLTags.Blocks.WOOLS_LIGHT_BLUE).add(Blocks.LIGHT_BLUE_WOOL); + tag(CCLTags.Blocks.WOOLS_YELLOW).add(Blocks.YELLOW_WOOL); + tag(CCLTags.Blocks.WOOLS_LIME).add(Blocks.LIME_WOOL); + tag(CCLTags.Blocks.WOOLS_PINK).add(Blocks.PINK_WOOL); + tag(CCLTags.Blocks.WOOLS_GRAY).add(Blocks.GRAY_WOOL); + tag(CCLTags.Blocks.WOOLS_LIGHT_GRAY).add(Blocks.LIGHT_GRAY_WOOL); + tag(CCLTags.Blocks.WOOLS_CYAN).add(Blocks.CYAN_WOOL); + tag(CCLTags.Blocks.WOOLS_PURPLE).add(Blocks.PURPLE_WOOL); + tag(CCLTags.Blocks.WOOLS_BLUE).add(Blocks.BLUE_WOOL); + tag(CCLTags.Blocks.WOOLS_BROWN).add(Blocks.BROWN_WOOL); + tag(CCLTags.Blocks.WOOLS_GREEN).add(Blocks.GREEN_WOOL); + tag(CCLTags.Blocks.WOOLS_RED).add(Blocks.RED_WOOL); + tag(CCLTags.Blocks.WOOLS_BLACK).add(Blocks.BLACK_WOOL); } @Override @@ -81,45 +88,45 @@ public String getName() { private static class ItemTags extends ItemTagsProvider { - public ItemTags(DataGenerator generatorIn, BlockTags blockTagProvider, ExistingFileHelper files) { - super(generatorIn, blockTagProvider, MOD_ID, files); + public ItemTags(PackOutput output, CompletableFuture lookupProvider) { + super(output, lookupProvider, MOD_ID); } @Override - protected void addTags() { - tag(CCLTags.Items.WOOL) - .addTag(CCLTags.Items.WOOL_WHITE) - .addTag(CCLTags.Items.WOOL_ORANGE) - .addTag(CCLTags.Items.WOOL_MAGENTA) - .addTag(CCLTags.Items.WOOL_LIGHT_BLUE) - .addTag(CCLTags.Items.WOOL_YELLOW) - .addTag(CCLTags.Items.WOOL_LIME) - .addTag(CCLTags.Items.WOOL_PINK) - .addTag(CCLTags.Items.WOOL_GRAY) - .addTag(CCLTags.Items.WOOL_LIGHT_GRAY) - .addTag(CCLTags.Items.WOOL_CYAN) - .addTag(CCLTags.Items.WOOL_PURPLE) - .addTag(CCLTags.Items.WOOL_BLUE) - .addTag(CCLTags.Items.WOOL_BROWN) - .addTag(CCLTags.Items.WOOL_GREEN) - .addTag(CCLTags.Items.WOOL_RED) - .addTag(CCLTags.Items.WOOL_BLACK); - tag(CCLTags.Items.WOOL_WHITE).add(Items.WHITE_WOOL); - tag(CCLTags.Items.WOOL_ORANGE).add(Items.ORANGE_WOOL); - tag(CCLTags.Items.WOOL_MAGENTA).add(Items.MAGENTA_WOOL); - tag(CCLTags.Items.WOOL_LIGHT_BLUE).add(Items.LIGHT_BLUE_WOOL); - tag(CCLTags.Items.WOOL_YELLOW).add(Items.YELLOW_WOOL); - tag(CCLTags.Items.WOOL_LIME).add(Items.LIME_WOOL); - tag(CCLTags.Items.WOOL_PINK).add(Items.PINK_WOOL); - tag(CCLTags.Items.WOOL_GRAY).add(Items.GRAY_WOOL); - tag(CCLTags.Items.WOOL_LIGHT_GRAY).add(Items.LIGHT_GRAY_WOOL); - tag(CCLTags.Items.WOOL_CYAN).add(Items.CYAN_WOOL); - tag(CCLTags.Items.WOOL_PURPLE).add(Items.PURPLE_WOOL); - tag(CCLTags.Items.WOOL_BLUE).add(Items.BLUE_WOOL); - tag(CCLTags.Items.WOOL_BROWN).add(Items.BROWN_WOOL); - tag(CCLTags.Items.WOOL_GREEN).add(Items.GREEN_WOOL); - tag(CCLTags.Items.WOOL_RED).add(Items.RED_WOOL); - tag(CCLTags.Items.WOOL_BLACK).add(Items.BLACK_WOOL); + protected void addTags(HolderLookup.Provider pProvider) { + tag(CCLTags.Items.WOOLS) + .addTag(CCLTags.Items.WOOLS_WHITE) + .addTag(CCLTags.Items.WOOLS_ORANGE) + .addTag(CCLTags.Items.WOOLS_MAGENTA) + .addTag(CCLTags.Items.WOOLS_LIGHT_BLUE) + .addTag(CCLTags.Items.WOOLS_YELLOW) + .addTag(CCLTags.Items.WOOLS_LIME) + .addTag(CCLTags.Items.WOOLS_PINK) + .addTag(CCLTags.Items.WOOLS_GRAY) + .addTag(CCLTags.Items.WOOLS_LIGHT_GRAY) + .addTag(CCLTags.Items.WOOLS_CYAN) + .addTag(CCLTags.Items.WOOLS_PURPLE) + .addTag(CCLTags.Items.WOOLS_BLUE) + .addTag(CCLTags.Items.WOOLS_BROWN) + .addTag(CCLTags.Items.WOOLS_GREEN) + .addTag(CCLTags.Items.WOOLS_RED) + .addTag(CCLTags.Items.WOOLS_BLACK); + tag(CCLTags.Items.WOOLS_WHITE).add(Items.WHITE_WOOL); + tag(CCLTags.Items.WOOLS_ORANGE).add(Items.ORANGE_WOOL); + tag(CCLTags.Items.WOOLS_MAGENTA).add(Items.MAGENTA_WOOL); + tag(CCLTags.Items.WOOLS_LIGHT_BLUE).add(Items.LIGHT_BLUE_WOOL); + tag(CCLTags.Items.WOOLS_YELLOW).add(Items.YELLOW_WOOL); + tag(CCLTags.Items.WOOLS_LIME).add(Items.LIME_WOOL); + tag(CCLTags.Items.WOOLS_PINK).add(Items.PINK_WOOL); + tag(CCLTags.Items.WOOLS_GRAY).add(Items.GRAY_WOOL); + tag(CCLTags.Items.WOOLS_LIGHT_GRAY).add(Items.LIGHT_GRAY_WOOL); + tag(CCLTags.Items.WOOLS_CYAN).add(Items.CYAN_WOOL); + tag(CCLTags.Items.WOOLS_PURPLE).add(Items.PURPLE_WOOL); + tag(CCLTags.Items.WOOLS_BLUE).add(Items.BLUE_WOOL); + tag(CCLTags.Items.WOOLS_BROWN).add(Items.BROWN_WOOL); + tag(CCLTags.Items.WOOLS_GREEN).add(Items.GREEN_WOOL); + tag(CCLTags.Items.WOOLS_RED).add(Items.RED_WOOL); + tag(CCLTags.Items.WOOLS_BLACK).add(Items.BLACK_WOOL); } @Override @@ -130,8 +137,8 @@ public String getName() { public static class LangUS extends LanguageProvider { - public LangUS(DataGenerator gen, Side side) { - super(gen, MOD_ID, "en_us", side); + public LangUS(PackOutput output) { + super(output, MOD_ID, "en_us"); } @Override @@ -145,6 +152,16 @@ protected void addTranslations() { addServer("ccl.commands.killall.success.line", "Killed %s"); addServer("ccl.commands.count.fail", "Found no entities."); addServer("ccl.commands.count.total", "Found %s entities."); + + addServer("ccl.energy_bar.energy_storage", "Energy Storage"); + addServer("ccl.energy_bar.capacity", "Capacity:"); + addServer("ccl.energy_bar.stored", "Stored:"); + addServer("ccl.energy_bar.rf", "RF"); + addServer("ccl.fluid_tank.fluid_storage", "Fluid Storage"); + addServer("ccl.fluid_tank.capacity", "Capacity:"); + addServer("ccl.fluid_tank.stored", "Stored:"); + addServer("ccl.fluid_tank.mb", "mB"); + addServer("ccl.fluid_tank.contains", "Contains:"); } } } diff --git a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java b/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java deleted file mode 100644 index 9048b023..00000000 --- a/src/main/java/codechicken/lib/internal/ExceptionMessageEventHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.internal; - -import codechicken.lib.CodeChickenLib; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod.EventBusSubscriber; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -/** - * Created by covers1624 on 25/07/18. - */ -@EventBusSubscriber (value = Dist.CLIENT, modid = CodeChickenLib.MOD_ID) -public class ExceptionMessageEventHandler { - - public static Set exceptionMessageCache = new HashSet<>(); - private static long lastExceptionClear; - - @SubscribeEvent - public static void clientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - //Clear the known exceptions every 5 seconds. - long time = System.nanoTime(); - if (TimeUnit.NANOSECONDS.toSeconds(time - lastExceptionClear) > 5) { - lastExceptionClear = time; - exceptionMessageCache.clear(); - } - } - } - -} diff --git a/src/main/java/codechicken/lib/internal/HighlightHandler.java b/src/main/java/codechicken/lib/internal/HighlightHandler.java index b223bc6d..7f701887 100644 --- a/src/main/java/codechicken/lib/internal/HighlightHandler.java +++ b/src/main/java/codechicken/lib/internal/HighlightHandler.java @@ -1,34 +1,32 @@ package codechicken.lib.internal; -import codechicken.lib.CodeChickenLib; import codechicken.lib.colour.EnumColour; +import codechicken.lib.render.CCRenderPipelines; import codechicken.lib.render.RenderUtils; import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.vec.Cuboid6; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexFormat; +import net.covers1624.quack.util.CrashLock; import net.minecraft.client.Camera; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.rendertype.RenderSetup; +import net.minecraft.client.renderer.rendertype.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.client.event.RenderLevelLastEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.common.Mod; +import net.neoforged.neoforge.client.event.RenderLevelStageEvent; +import net.neoforged.neoforge.common.NeoForge; import org.jetbrains.annotations.Nullable; -import static net.minecraft.client.renderer.RenderStateShard.*; +import static codechicken.lib.CodeChickenLib.MOD_ID; /** * Created by covers1624 on 9/06/18. */ -@Mod.EventBusSubscriber (value = Dist.CLIENT, modid = CodeChickenLib.MOD_ID) public class HighlightHandler { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + private static final Cuboid6 BOX = Cuboid6.full.copy().expand(0.02); private static final float[] RED = EnumColour.RED.getColour(128).packArray(); @@ -36,34 +34,29 @@ public class HighlightHandler { public static BlockPos highlight; public static boolean useDepth = true; - private static final RenderType box = RenderType.create("ccl:box_depth", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, false, true, RenderType.CompositeState.builder() - .setShaderState(POSITION_COLOR_SHADER) - .setTransparencyState(TRANSLUCENT_TRANSPARENCY) - .setWriteMaskState(COLOR_WRITE) - .createCompositeState(false) + private static final RenderType box = RenderType.create( + MOD_ID + ":box", + RenderSetup.builder(CCRenderPipelines.POSITION_COLOR) + .createRenderSetup() ); - private static final DepthTestStateShard DISABLE_DEPTH = new DepthTestStateShard("none", 519) { - @Override - public void setupRenderState() { - RenderSystem.disableDepthTest(); - } - }; - - private static final RenderType boxNoDepth = RenderType.create("ccl:box_no_depth", DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS, 256, false, true, RenderType.CompositeState.builder() - .setShaderState(POSITION_COLOR_SHADER) - .setTransparencyState(TRANSLUCENT_TRANSPARENCY) - .setWriteMaskState(COLOR_WRITE) - .setDepthTestState(DISABLE_DEPTH) - .createCompositeState(false) + // TODO depth toggle is broken + private static final RenderType boxNoDepth = RenderType.create( + MOD_ID + ":box_no_depth", + RenderSetup.builder(CCRenderPipelines.POSITION_COLOR_NO_DEPTH) + .createRenderSetup() ); - @SubscribeEvent - public static void renderLevelLast(RenderLevelLastEvent event) { + public static void init() { + LOCK.lock(); + NeoForge.EVENT_BUS.addListener(HighlightHandler::renderLevelLast); + } + + private static void renderLevelLast(RenderLevelStageEvent.AfterParticles event) { if (highlight != null) { MultiBufferSource.BufferSource source = Minecraft.getInstance().renderBuffers().bufferSource(); Camera camera = Minecraft.getInstance().gameRenderer.getMainCamera(); - Vec3 cameraPos = camera.getPosition(); + Vec3 cameraPos = camera.position(); PoseStack pStack = event.getPoseStack(); pStack.pushPose(); diff --git a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java index 8afe90e5..934c6d98 100644 --- a/src/main/java/codechicken/lib/internal/ItemFileRenderer.java +++ b/src/main/java/codechicken/lib/internal/ItemFileRenderer.java @@ -1,32 +1,40 @@ package codechicken.lib.internal; +import com.google.common.base.Suppliers; import com.mojang.blaze3d.pipeline.RenderTarget; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.platform.NativeImage; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; +import com.mojang.blaze3d.vertex.VertexSorting; import net.covers1624.quack.image.AnimatedGifEncoder; import net.covers1624.quack.io.IOUtils; -import net.covers1624.quack.util.SneakyUtils; +import net.covers1624.quack.platform.OperatingSystem; import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.item.ItemStack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; +import org.joml.Matrix4f; +import org.joml.Matrix4fStack; import org.lwjgl.opengl.GL11; import javax.imageio.ImageIO; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import java.util.function.Supplier; + +import static java.util.Objects.requireNonNull; /** * Mostly internal, intended for developer use. @@ -41,143 +49,282 @@ public class ItemFileRenderer { private static final Logger LOGGER = LogManager.getLogger(); private static final LinkedList tasks = new LinkedList<>(); - private static final List gifTasks = new LinkedList<>(); - - public static void addRenderTask(ItemStack stack, Path file, int resolution) { - tasks.add(new RenderTask(stack, file, resolution)); - } + private static final Path OUTPUT = Paths.get("exports"); + private static @Nullable RenderTarget target; - public static void addGifRenderTask(ItemStack stack, Path file, int resolution, int fps, int duration) { - gifTasks.add(new GifRenderTask(stack, file, resolution, fps, duration)); + public static void renderStatic(ItemStack stack, String file, int resolution) { + tasks.add(new StaticRenderTask(stack, resolution, OUTPUT.resolve(file))); } - public static void tick() { - renderStackToFile(); - renderGifs(); + public static void addGifRenderTask(ItemStack stack, String file, int resolution, int fps, int duration) { + tasks.add(new GifRenderTask(stack, resolution, OUTPUT.resolve(file), fps, duration)); } - private static void renderStackToFile() { - if (tasks.isEmpty()) return; + public static boolean addWebpRenderTask(ItemStack stack, String file, int resolution, int fps, int duration) { + if (!WebpRenderTask.isFfmpegAvailable()) return false; - RenderTask task = tasks.pop(); - takeItemScreenshot(task.stack, task.resolution, image -> { - try { - image.writeToFile(IOUtils.makeParents(task.file)); - } catch (IOException ex) { - LOGGER.error("Failed to write image to file.", ex); - } - }); + tasks.add(new WebpRenderTask(stack, resolution, OUTPUT.resolve(file), fps, duration)); + return true; } - private static void renderGifs() { - gifTasks.removeIf(GifRenderTask::render); + public static void tick() { + RenderTask task = tasks.peek(); + if (task != null && guardRender(task)) { + tasks.pop(); + } } - private static void takeItemScreenshot(ItemStack stack, int res, Consumer cons) { - Minecraft mc = Minecraft.getInstance(); - RenderTarget mainTarget = mc.getMainRenderTarget(); - PoseStack pStack = RenderSystem.getModelViewStack(); - if (mainTarget.width < res || mainTarget.height < res) { - // TODO explode instead? - LOGGER.warn("Window is not at least 512x512 make it bigger! Your image is probably cropped a bit."); + private static boolean guardRender(RenderTask task) { + try { + return task.render(); + } catch (Throwable ex) { + LOGGER.error("Failed to render.", ex); + return true; } + } - Matrix4f ortho = Matrix4f.orthographic(0, mainTarget.width * 16F / res, 0, mainTarget.height * 16F / res, -3000, 3000); - RenderSystem.setProjectionMatrix(ortho); - - pStack.pushPose(); - pStack.setIdentity(); - RenderSystem.applyModelViewMatrix(); + private static abstract class RenderTask { - mainTarget.bindWrite(true); - GL11.glClearColor(0, 0, 0, 0); - GL11.glClearDepth(1.0); - GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); + private static final boolean DEBUG = Boolean.getBoolean("ccl.ItemFileRenderer.debug"); - Lighting.setupFor3DItems(); - RenderSystem.enableTexture(); - RenderSystem.enableCull(); + protected final ItemStack stack; - mc.getItemRenderer().renderGuiItem(stack, 0, 0); + protected final int resolution; + protected final Path path; - try (NativeImage fullScreenshot = new NativeImage(mainTarget.width, mainTarget.height, false); - NativeImage subImage = new NativeImage(res, res, false)) { - RenderSystem.bindTexture(mainTarget.getColorTextureId()); - fullScreenshot.downloadTexture(0, false); - fullScreenshot.flipY(); - fullScreenshot.resizeSubRectTo(0, 0, res, res, subImage); - cons.accept(subImage); + private RenderTask(ItemStack stack, int resolution, Path path) { + this.stack = stack; + this.resolution = resolution; + this.path = path; } - pStack.popPose(); - RenderSystem.applyModelViewMatrix(); - mainTarget.unbindWrite(); + /** + * Perform the render operation. + * + * @return If the render operation is complete. + */ + protected abstract boolean render() throws IOException; + + protected NativeImage takeItemScreenshot() { +// long start = System.nanoTime(); +// Minecraft mc = Minecraft.getInstance(); +// Matrix4fStack pStack = RenderSystem.getModelViewStack(); +// GuiGraphics guiGraphics = new GuiGraphics(mc, mc.renderBuffers().bufferSource()); +// +// if (target == null || target.width < resolution || target.height < resolution) { +// if (target == null) { +// target = new RenderTarget(true) { }; +// } +// target.resize(resolution, resolution, Minecraft.ON_OSX); +// } +// +// Matrix4f ortho = new Matrix4f().setOrtho(0, resolution * 16F / resolution, resolution * 16F / resolution, 0, -3000, 3000); +// RenderSystem.setProjectionMatrix(ortho, VertexSorting.ORTHOGRAPHIC_Z); +// +// pStack.pushMatrix(); +// pStack.identity(); +// RenderSystem.applyModelViewMatrix(); +// target.bindWrite(true); +// +// GL11.glClearColor(0, 0, 0, 0); +// GL11.glClearDepth(1.0); +// GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); +// +// Lighting.setupFor3DItems(); +// RenderSystem.enableCull(); +// long preRender = System.nanoTime(); +// if (DEBUG) LOGGER.info("Setup: {}ns", preRender - start); +// +// guiGraphics.renderItem(stack, 0, 0); +// +// long postRender = System.nanoTime(); +// if (DEBUG) LOGGER.info("Render: {}ns", postRender - preRender); +// +// NativeImage image = new NativeImage(resolution, resolution, false); +// target.bindRead(); +// image.downloadTexture(0, false); +// image.flipY(); +// if (DEBUG) LOGGER.info("Screenshot: {}ns", System.nanoTime() - postRender); +// +// pStack.popMatrix(); +// RenderSystem.applyModelViewMatrix(); +// +// target.unbindWrite(); +// return image; + return null; + } } - private record RenderTask(ItemStack stack, Path file, int resolution) { + private static class StaticRenderTask extends RenderTask { + + private StaticRenderTask(ItemStack stack, int resolution, Path path) { + super(stack, resolution, path); + } + + @Override + protected boolean render() throws IOException { + try (NativeImage image = takeItemScreenshot()) { + image.writeToFile(IOUtils.makeParents(path)); + } + return true; + } } - private static final class GifRenderTask { + private static abstract class AnimatedRenderTask extends RenderTask { - public final ItemStack stack; - public final Path file; - private final int resolution; - public final int fps; - public final long targetDuration; + protected final int fps; + protected final long targetDuration; - public final List frames; - public final long frameDelay; + protected final List frames; + protected final long frameDelay; - public long startTime = -1; - public long lastFrame; + protected long startTime = -1; + protected long lastFrame; - private GifRenderTask(ItemStack stack, Path file, int resolution, int fps, int targetDuration) { - this.stack = stack; - this.file = file; - this.resolution = resolution; + private @Nullable CompletableFuture finalizeTask; + + private AnimatedRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path); this.fps = fps; - this.targetDuration = TimeUnit.SECONDS.toMillis(targetDuration); + this.targetDuration = TimeUnit.SECONDS.toMillis(duration); - frames = new ArrayList<>(targetDuration * fps); + frames = new ArrayList<>(duration * fps); frameDelay = (long) ((1F / fps) * 1000F); } - public boolean render() { + @Override + protected boolean render() { long currTime = System.currentTimeMillis(); if (startTime == -1) { startTime = currTime; } if (startTime + targetDuration <= currTime) { - CompletableFuture.runAsync(this::finishGif); - return true; + if (finalizeTask == null) { + finalizeTask = CompletableFuture.runAsync(() -> { + try { + serialize(); + } catch (Throwable ex) { + LOGGER.error("Failed to serialize item render task.", ex); + } + }); + } + return finalizeTask.isDone(); } // Wait more for next frame. if (lastFrame + frameDelay > currTime) return false; lastFrame = currTime; - takeItemScreenshot(stack, resolution, SneakyUtils.sneak(e -> frames.add(e.asByteArray()))); - LOGGER.info("Captured gif frame {} / {}", frames.size(), ((targetDuration / 1000) * fps)); + frames.add(takeItemScreenshot()); + LOGGER.info("Captured frame {} / {}", frames.size(), ((targetDuration / 1000) * fps)); return false; } - private void finishGif() { - LOGGER.info("Writing gif.."); - try (OutputStream os = Files.newOutputStream(file)) { + protected abstract void serialize() throws IOException; + } + + private static class GifRenderTask extends AnimatedRenderTask { + + private GifRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path, fps, duration); + } + + @Override + protected void serialize() throws IOException { + try (OutputStream os = Files.newOutputStream(IOUtils.makeParents(path))) { AnimatedGifEncoder encoder = new AnimatedGifEncoder(); encoder.start(os); encoder.setDelay((int) frameDelay); encoder.setRepeat(0); // Always repeat. encoder.setQuality(1); // Best quality possible. for (int i = 0; i < frames.size(); i++) { - byte[] frame = frames.get(i); LOGGER.info("Encoding Frame {} / {}", i + 1, frames.size()); - encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame))); + NativeImage frame = frames.get(i); + try (frame) { +// encoder.addFrame(ImageIO.read(new ByteArrayInputStream(frame.asByteArray()))); + } } encoder.finish(); LOGGER.info("Finished writing gif."); + } + } + } + + private static class WebpRenderTask extends AnimatedRenderTask { + + public static final Supplier<@Nullable String> FFMPEG_BINARY = Suppliers.memoize(() -> { + String ffmpeg = System.getProperty("ccl.ffmpeg", "ffmpeg" + (OperatingSystem.current().isWindows() ? ".exe" : "")); + LOGGER.info("Probing for ffmpeg with {}", ffmpeg); + try { + int ret = runFfmpeg(List.of(ffmpeg, "-version"), LOGGER::info); + if (ret == 0) { + LOGGER.info("ffmpeg available via {}", ffmpeg); + return ffmpeg; + } + LOGGER.error("Failed to find working ffmpeg. Got exit code: {}", ret); } catch (IOException ex) { - LOGGER.error("Failed to write gif.", ex); + LOGGER.error("Failed to find ffmpeg. Exception whilst running command.", ex); + } + return null; + }); + + public static boolean isFfmpegAvailable() { + return FFMPEG_BINARY.get() != null; + } + + private WebpRenderTask(ItemStack stack, int resolution, Path path, int fps, int duration) { + super(stack, resolution, path, fps, duration); + } + + @Override + protected void serialize() throws IOException { + Path tempDir = path.getParent().resolve(path.getFileName() + ".tmp"); + Files.createDirectories(tempDir); + LOGGER.info("Dumping frames to temp directory.."); + int i = 0; + List tempFiles = new ArrayList<>(frames.size() + 1); + for (NativeImage frame : frames) { + try (frame) { + Path file = tempDir.resolve(i++ + ".png"); + LOGGER.info("Dumping: {}", file); + tempFiles.add(file); + frame.writeToFile(file); + } + } + tempFiles.add(tempDir); + + int ret = runFfmpeg( + List.of( + requireNonNull(FFMPEG_BINARY.get()), + "-y", + "-framerate", String.valueOf(fps), + "-i", tempDir.toAbsolutePath() + "/%d.png", + "-loop", "0", + "-lossless", "1", + "-compression_level", "0", + path.toAbsolutePath().toString() + ), + LOGGER::info + ); + if (ret != 0) { + LOGGER.error("ffmpeg exited with exit code {}", ret); + } else { + LOGGER.info("ffmpeg success!"); + } + + for (Path tempFile : tempFiles) { + Files.deleteIfExists(tempFile); + } + } + + private static int runFfmpeg(List args, Consumer out) throws IOException { + ProcessBuilder pb = new ProcessBuilder(args); + pb.redirectErrorStream(true); + Process proc = pb.start(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8))) { + reader.lines().forEach(out); } + proc.onExit().join(); + return proc.exitValue(); } } } diff --git a/src/main/java/codechicken/lib/world/TileChunkLoadHook.java b/src/main/java/codechicken/lib/internal/TileChunkLoadHook.java similarity index 64% rename from src/main/java/codechicken/lib/world/TileChunkLoadHook.java rename to src/main/java/codechicken/lib/internal/TileChunkLoadHook.java index beef0c80..87ad09df 100644 --- a/src/main/java/codechicken/lib/world/TileChunkLoadHook.java +++ b/src/main/java/codechicken/lib/internal/TileChunkLoadHook.java @@ -1,28 +1,25 @@ -package codechicken.lib.world; +package codechicken.lib.internal; +import codechicken.lib.world.IChunkLoadTile; +import net.covers1624.quack.util.CrashLock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ImposterProtoChunk; import net.minecraft.world.level.chunk.LevelChunk; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.level.ChunkEvent; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.level.ChunkEvent; public class TileChunkLoadHook { - private static boolean init; + private static final CrashLock LOCK = new CrashLock("Already Initialized."); public static void init() { - if (init) { - return; - } - init = true; + LOCK.lock(); - MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook()); + NeoForge.EVENT_BUS.addListener(TileChunkLoadHook::onChunkLoad); } - @SubscribeEvent - public void onChunkLoad(ChunkEvent.Load event) { + private static void onChunkLoad(ChunkEvent.Load event) { ChunkAccess iChunk = event.getChunk(); LevelChunk chunk; if (iChunk instanceof LevelChunk) { diff --git a/src/main/java/codechicken/lib/internal/command/CCLCommands.java b/src/main/java/codechicken/lib/internal/command/CCLCommands.java index ec462243..ea5eec69 100644 --- a/src/main/java/codechicken/lib/internal/command/CCLCommands.java +++ b/src/main/java/codechicken/lib/internal/command/CCLCommands.java @@ -9,10 +9,11 @@ import codechicken.lib.internal.command.dev.DevCommands; import com.mojang.brigadier.CommandDispatcher; import net.covers1624.quack.util.CrashLock; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; -import net.minecraftforge.client.event.RegisterClientCommandsEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.RegisterCommandsEvent; /** * Created by covers1624 on 17/9/20. @@ -24,16 +25,17 @@ public class CCLCommands { public static void init() { LOCK.lock(); - MinecraftForge.EVENT_BUS.addListener(CCLCommands::registerServerCommands); - MinecraftForge.EVENT_BUS.addListener(CCLCommands::registerClientCommands); + NeoForge.EVENT_BUS.addListener(CCLCommands::registerServerCommands); + NeoForge.EVENT_BUS.addListener(CCLCommands::registerClientCommands); } private static void registerServerCommands(RegisterCommandsEvent event) { CommandDispatcher dispatcher = event.getDispatcher(); - CountCommand.register(dispatcher); - KillAllCommand.register(dispatcher); - MiscCommands.register(dispatcher); - DevCommands.register(dispatcher); + CommandBuildContext context = event.getBuildContext(); + CountCommand.register(dispatcher, context); + KillAllCommand.register(dispatcher, context); + MiscCommands.register(dispatcher, context); + DevCommands.register(dispatcher, context); } private static void registerClientCommands(RegisterClientCommandsEvent event) { @@ -42,5 +44,4 @@ private static void registerClientCommands(RegisterClientCommandsEvent event) { ItemInfoCommand.register(dispatcher); RenderItemToFileCommand.register(dispatcher); } - } diff --git a/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java b/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java deleted file mode 100644 index 636816c6..00000000 --- a/src/main/java/codechicken/lib/internal/command/EntityTypeArgument.java +++ /dev/null @@ -1,32 +0,0 @@ -package codechicken.lib.internal.command; - -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.arguments.ResourceKeyArgument; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.EntityType; - -import static codechicken.lib.CodeChickenLib.MOD_ID; -import static net.minecraft.commands.arguments.ResourceKeyArgument.getRegistryKeyType; - -/** - * Created by covers1624 on 17/9/20. - */ -public class EntityTypeArgument { - - private static final DynamicCommandExceptionType MISSING = new DynamicCommandExceptionType(p -> - Component.translatable(MOD_ID + ":argument.entity_type.invalid", p) - ); - - public static ResourceKeyArgument> entityType() { - return ResourceKeyArgument.key(Registry.ENTITY_TYPE_REGISTRY); - } - - public static Holder> getEntityType(CommandContext stack, String name) throws CommandSyntaxException { - return getRegistryKeyType(stack, name, Registry.ENTITY_TYPE_REGISTRY, MISSING); - } -} diff --git a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java index 693a8076..c377d159 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/CountCommand.java @@ -4,12 +4,16 @@ import com.mojang.brigadier.context.CommandContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.EntityType; -import net.minecraftforge.registries.ForgeRegistries; import java.util.ArrayList; import java.util.Comparator; @@ -17,8 +21,6 @@ import java.util.function.Predicate; import java.util.stream.StreamSupport; -import static codechicken.lib.internal.command.EntityTypeArgument.entityType; -import static codechicken.lib.internal.command.EntityTypeArgument.getEntityType; import static codechicken.lib.math.MathHelper.floor; import static net.minecraft.ChatFormatting.*; import static net.minecraft.commands.Commands.argument; @@ -29,13 +31,13 @@ */ public class CountCommand { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("count") - .requires(e -> e.hasPermission(2)) - .then(argument("entity", entityType()) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return countAllEntities(ctx, e -> e.equals(entityType)); }) ) @@ -64,14 +66,15 @@ private static int countAllEntities(CommandContext ctx, Pred int total = 0; for (EntityType type : order) { int count = counts.getInt(type); - String name = ForgeRegistries.ENTITY_TYPES.getKey(type).toString(); - ctx.getSource().sendSuccess(Component.literal(GREEN + name + RESET + " x " + AQUA + count), false); + String name = BuiltInRegistries.ENTITY_TYPE.getKey(type).toString(); + ctx.getSource().sendSuccess(() -> Component.literal(GREEN + name + RESET + " x " + AQUA + count), false); total += count; } - if (order.size() == 0) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.count.fail"), false); + if (order.isEmpty()) { + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.count.fail"), false); } else if (order.size() > 1) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.count.total", AQUA.toString() + total + RESET), false); + int finalTotal = total; + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.count.total", AQUA.toString() + finalTotal + RESET), false); } return total; diff --git a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java index 389cf6ac..2ae06e65 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java +++ b/src/main/java/codechicken/lib/internal/command/admin/KillAllCommand.java @@ -4,27 +4,28 @@ import com.mojang.brigadier.context.CommandContext; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap; -import net.covers1624.quack.collection.StreamableIterable; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; -import net.minecraft.core.Holder; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.ResourceArgument; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.monster.Enemy; -import net.minecraftforge.registries.ForgeRegistries; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; -import java.util.function.Consumer; +import java.util.function.BiConsumer; import java.util.function.Predicate; -import static codechicken.lib.internal.command.EntityTypeArgument.entityType; -import static codechicken.lib.internal.command.EntityTypeArgument.getEntityType; import static codechicken.lib.math.MathHelper.floor; import static net.minecraft.ChatFormatting.*; import static net.minecraft.commands.Commands.argument; @@ -35,21 +36,21 @@ */ public class KillAllCommand { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("killall") - .requires(e -> e.hasPermission(2)) - .then(argument("entity", entityType()) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return killallForce(ctx, entityType, e -> Objects.equals(e.getType(), entityType)); }) ) .executes(ctx -> killallForce(ctx, null, e -> e instanceof Enemy)) .then(literal("gracefully") - .then(argument("entity", entityType()) + .then(argument("entity", ResourceArgument.resource(context, Registries.ENTITY_TYPE)) .executes(ctx -> { - EntityType entityType = getEntityType(ctx, "entity").value(); + EntityType entityType = ResourceArgument.getEntityType(ctx, "entity").value(); return killAllGracefully(ctx, entityType, e -> Objects.equals(e.getType(), entityType)); }) ) @@ -60,16 +61,18 @@ public static void register(CommandDispatcher dispatcher) { } private static int killAllGracefully(CommandContext ctx, @Nullable EntityType type, Predicate predicate) { - return killEntities(ctx, type, predicate, Entity::kill); + return killEntities(ctx, type, predicate, (l, e) -> e.kill(l)); } private static int killallForce(CommandContext ctx, @Nullable EntityType type, Predicate predicate) { - return killEntities(ctx, type, predicate, Entity::discard); + return killEntities(ctx, type, predicate, (l, e) -> e.discard()); } - private static int killEntities(CommandContext ctx, @Nullable EntityType type, Predicate predicate, Consumer killFunc) { + private static int killEntities(CommandContext ctx, @Nullable EntityType type, Predicate predicate, BiConsumer killFunc) { if (type == EntityType.PLAYER) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), false); + ctx.getSource().sendSuccess( + () -> Component.translatable("ccl.commands.killall.fail.player").withStyle(RED), + false); return 0; } CommandSourceStack source = ctx.getSource(); @@ -77,13 +80,14 @@ private static int killEntities(CommandContext ctx, @Nullabl ServerChunkCache provider = world.getChunkSource(); Object2IntMap> counts = new Object2IntOpenHashMap<>(); counts.defaultReturnValue(0); - StreamableIterable entities = StreamableIterable.of(world.getEntities().getAll()) + List entities = FastStream.of(world.getEntities().getAll()) .filter(Objects::nonNull) .filter(predicate) - .filter(e -> provider.hasChunk(floor(e.getX()) >> 4, floor(e.getZ()) >> 4)); + .filter(e -> provider.hasChunk(floor(e.getX()) >> 4, floor(e.getZ()) >> 4)) + .toList(); for (Entity e : entities) { - killFunc.accept(e); + killFunc.accept(world, e); int count = counts.getInt(e.getType()); counts.put(e.getType(), count + 1); } @@ -94,14 +98,15 @@ private static int killEntities(CommandContext ctx, @Nullabl int total = 0; for (EntityType t : order) { int count = counts.getInt(t); - String name = ForgeRegistries.ENTITY_TYPES.getKey(t).toString(); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.success.line", RED + name + RESET + " x " + AQUA + count), false); + String name = BuiltInRegistries.ENTITY_TYPE.getKey(t).toString(); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.success.line", RED + name + RESET + " x " + AQUA + count), false); total += count; } - if (order.size() == 0) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.fail"), false); + if (order.isEmpty()) { + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.fail"), false); } else if (order.size() > 1) { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.killall.success", AQUA.toString() + total + RESET), false); + int finalTotal = total; + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.killall.success", AQUA.toString() + finalTotal + RESET), false); } return total; } diff --git a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java index 3ea6edb3..84e14b44 100644 --- a/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java +++ b/src/main/java/codechicken/lib/internal/command/admin/MiscCommands.java @@ -2,7 +2,9 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.network.chat.Component; import static net.minecraft.commands.Commands.literal; @@ -12,20 +14,20 @@ */ public class MiscCommands { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("meminfo") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(MiscCommands::printMemInfo) ) .then(literal("gc") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(ctx -> { - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.before"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.before"), true); printMemInfo(ctx, true); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.performing"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.performing"), true); System.gc(); - ctx.getSource().sendSuccess(Component.translatable("ccl.commands.gc.after"), true); + ctx.getSource().sendSuccess(() -> Component.translatable("ccl.commands.gc.after"), true); printMemInfo(ctx, true); return 0; }) @@ -48,8 +50,10 @@ private static int printMemInfo(CommandContext ctx, boolean mem = " " + mem; allocated = " " + allocated; } - ctx.getSource().sendSuccess(Component.literal(mem), true); - ctx.getSource().sendSuccess(Component.literal(allocated), true); + String finalMem = mem; + String finalAllocated = allocated; + ctx.getSource().sendSuccess(() -> Component.literal(finalMem), true); + ctx.getSource().sendSuccess(() -> Component.literal(finalAllocated), true); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/admin/package-info.java b/src/main/java/codechicken/lib/internal/command/admin/package-info.java new file mode 100644 index 00000000..0424575b --- /dev/null +++ b/src/main/java/codechicken/lib/internal/command/admin/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.command.admin; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java index 18f7ffbe..e93769e9 100644 --- a/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/HighlightCommand.java @@ -10,6 +10,7 @@ import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.coordinates.BlockPosArgument; import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.block.Block; @@ -17,9 +18,7 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; -import net.minecraftforge.registries.ForgeRegistries; -import static codechicken.lib.util.LambdaUtils.tryOrNull; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @@ -66,10 +65,10 @@ private static int setHighlightArg(CommandContext ctx) throw private static int setHighlight(CommandContext ctx, BlockPos pos) { CommandSourceStack source = ctx.getSource(); if (HighlightHandler.highlight == null) { - source.sendSuccess(Component.literal("Set highlight at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); + source.sendSuccess(() -> Component.literal("Set highlight at " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); } else { BlockPos prev = HighlightHandler.highlight; - source.sendSuccess(Component.literal("Moved highlight from " + prev.getX() + ", " + prev.getY() + ", " + prev.getZ() + " to " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); + source.sendSuccess(() -> Component.literal("Moved highlight from " + prev.getX() + ", " + prev.getY() + ", " + prev.getZ() + " to " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()), false); } HighlightHandler.highlight = pos; return 0; @@ -83,7 +82,7 @@ private static int clearHighlight(CommandContext ctx) { } HighlightHandler.highlight = null; HighlightHandler.useDepth = true; - source.sendSuccess(Component.literal("Highlight position cleared."), false); + source.sendSuccess(() -> Component.literal("Highlight position cleared."), false); return 0; } @@ -97,9 +96,9 @@ private static int toggleDepth(CommandContext ctx) { HighlightHandler.useDepth = !HighlightHandler.useDepth; if (HighlightHandler.useDepth) { - source.sendSuccess(Component.literal("Enabled highlight depth."), false); + source.sendSuccess(() -> Component.literal("Enabled highlight depth."), false); } else { - source.sendSuccess(Component.literal("Disabled highlight depth."), false); + source.sendSuccess(() -> Component.literal("Disabled highlight depth."), false); } return 0; } @@ -120,14 +119,14 @@ private static int dumpInfo(CommandContext ctx) { BlockEntity tile = level.getBlockEntity(pos); StringBuilder builder = new StringBuilder("\nBlock info:\n"); builder.append(" BlockPos: ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n"); - builder.append(" Block Class: ").append(tryOrNull(() -> block.getClass())).append("\n"); - builder.append(" Registry Name: ").append(tryOrNull(() -> ForgeRegistries.BLOCKS.getKey(block))).append("\n"); + builder.append(" Block Class: ").append(block.getClass()).append("\n"); + builder.append(" Registry Name: ").append(BuiltInRegistries.BLOCK.getKey(block)).append("\n"); builder.append(" State: ").append(state).append("\n"); builder.append("Tile at position\n"); - builder.append(" Tile Class: ").append(tryOrNull(() -> tile.getClass())).append("\n"); - builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); - builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithoutMetadata())).append("\n"); - source.sendSuccess(Component.literal(builder.toString()), false); + builder.append(" Tile Class: ").append(tile != null ? tile.getClass() : null).append("\n"); + builder.append(" Tile Id: ").append(tile != null ? BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(tile.getType()) : null).append("\n"); + builder.append(" Tile NBT: ").append(tile != null ? tile.saveWithoutMetadata(tile.getLevel().registryAccess()) : null).append("\n"); + source.sendSuccess(() -> Component.literal(builder.toString()), false); return 0; } diff --git a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java index d1702c30..44c2f1d6 100644 --- a/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/ItemInfoCommand.java @@ -3,10 +3,11 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.EquipmentSlot; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.registries.ForgeRegistries; import static net.minecraft.commands.Commands.literal; @@ -26,15 +27,11 @@ public static void register(CommandDispatcher dispatcher) { private static int execute(CommandContext command) { CommandSourceStack ctx = command.getSource(); Player player = command.getSource().getPlayer(); - ItemStack stack = player.getMainHandItem(); - if (stack.isEmpty()) { - stack = player.getOffhandItem(); - } + ItemStack stack = player.hasItemInSlot(EquipmentSlot.MAINHAND) ? player.getMainHandItem() : player.getOffhandItem(); if (stack.isEmpty()) return 0; - String tag = stack.hasTag() ? stack.getTag().toString() : "Item has no NBT."; - ctx.sendSuccess(Component.literal("Registry Name: " + ForgeRegistries.ITEMS.getKey(stack.getItem())), false); - ctx.sendSuccess(Component.literal("NBT : " + tag), false); + ctx.sendSuccess(() -> Component.literal("Registry Name: " + BuiltInRegistries.ITEM.getKey(stack.getItem())), false); + ctx.sendSuccess(() -> Component.literal("Components : " + stack.getComponents()), false); return 0; } } diff --git a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java index 60536a6f..9102f0fe 100644 --- a/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java +++ b/src/main/java/codechicken/lib/internal/command/client/RenderItemToFileCommand.java @@ -5,17 +5,16 @@ import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import com.mojang.brigadier.exceptions.DynamicCommandExceptionType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; -import net.minecraft.commands.CommandRuntimeException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; -import java.nio.file.Path; -import java.nio.file.Paths; - +import static java.util.Objects.requireNonNull; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; @@ -24,9 +23,11 @@ */ public class RenderItemToFileCommand { + private static final DynamicCommandExceptionType ERROR_INVALID = new DynamicCommandExceptionType(p_311534_ -> (Component) p_311534_); + public static void register(CommandDispatcher dispatcher) { dispatcher.register(literal("ccl") - .then(literal("render_held_to_file") + .then(literal("render_held") .then(argument("resolution", IntegerArgumentType.integer(16)) .then(argument("name", StringArgumentType.greedyString()) .executes(e -> renderToFile(e, getResolution(e))) @@ -36,16 +37,16 @@ public static void register(CommandDispatcher dispatcher) { .executes(e -> renderToFile(e, ItemFileRenderer.DEFAULT_RES)) ) ) - .then(literal("render_held_to_gif") + .then(literal("render_held_anim") .then(argument("fps", IntegerArgumentType.integer(5, 75)) .then(argument("duration", IntegerArgumentType.integer()) .then(argument("resolution", IntegerArgumentType.integer(16)) .then(argument("name", StringArgumentType.greedyString()) - .executes(e -> renderToGif(e, getResolution(e))) + .executes(e -> renderAnim(e, getResolution(e))) ) ) .then(argument("name", StringArgumentType.greedyString()) - .executes(e -> renderToGif(e, ItemFileRenderer.DEFAULT_RES)) + .executes(e -> renderAnim(e, ItemFileRenderer.DEFAULT_RES)) ) ) ) @@ -53,52 +54,76 @@ public static void register(CommandDispatcher dispatcher) { ); } - private static int renderToFile(CommandContext ctx, int resolution) { - Path path = getPath(ctx, "png"); + private static int renderToFile(CommandContext ctx, int resolution) throws CommandSyntaxException { + String path = getPath(ctx); ItemStack held = getHeldItem(); - ctx.getSource().sendSuccess(Component.literal("Queued item render to file: " + path), false); - ItemFileRenderer.addRenderTask(held, path, resolution); + ctx.getSource().sendSuccess(() -> Component.literal("Queued item render to file: " + path), false); + ItemFileRenderer.renderStatic(held, path, resolution); return 0; } - private static int renderToGif(CommandContext ctx, int resolution) { + private static int renderAnim(CommandContext ctx, int resolution) throws CommandSyntaxException { CommandSourceStack src = ctx.getSource(); int fps = IntegerArgumentType.getInteger(ctx, "fps"); int duration = IntegerArgumentType.getInteger(ctx, "duration"); - Path path = getPath(ctx, "gif"); + String path = getPath(ctx); ItemStack held = getHeldItem(); - src.sendSuccess(Component.literal("Queued item render to gif: " + path), false); - ItemFileRenderer.addGifRenderTask(held, path, resolution, fps, duration); + int lastSlash = path.lastIndexOf('/'); + int lastDot = path.lastIndexOf('.', lastSlash != -1 ? lastSlash : path.length() - 1); + String ext = lastDot != -1 ? path.substring(lastDot + 1) : ""; + + String finalPath; + if (ext.isEmpty()) { + ext = "gif"; + finalPath = path + ".gif"; + } else { + finalPath = path; + } + + switch (ext) { + case "gif" -> { + ItemFileRenderer.addGifRenderTask(held, finalPath, resolution, fps, duration); + src.sendSuccess(() -> Component.literal("Queued item render to gif: " + finalPath), false); + } + case "webp" -> { + if (!ItemFileRenderer.addWebpRenderTask(held, path, resolution, fps, duration)) { + src.sendFailure(Component.literal("Failed to queue render for webp, ffmpeg is not accessible. Either make it accessible on PATH, or set the `ccl.ffmpeg` system property.")); + } else { + src.sendSuccess(() -> Component.literal("Queued item render to webp: " + path), false); + } + } + } + return 0; } - private static Path getPath(CommandContext ctx, String extension) { + private static String getPath(CommandContext ctx) throws CommandSyntaxException { String str = StringArgumentType.getString(ctx, "name"); if (str.contains("..")) { - throw new CommandRuntimeException(Component.literal("'..' is not allowed in name.")); + throw ERROR_INVALID.create(Component.literal("'..' is not allowed in name.")); } - return Paths.get("exports", str + "." + extension); + return str; } - public static int getResolution(CommandContext ctx) { + public static int getResolution(CommandContext ctx) throws CommandSyntaxException { int res = IntegerArgumentType.getInteger(ctx, "resolution"); if ((res & res - 1) != 0) { - throw new CommandRuntimeException(Component.literal("Resolution must be a power of 2. 16, 32, 64...")); + throw ERROR_INVALID.create(Component.literal("Resolution must be a power of 2. 16, 32, 64...")); } return res; } - private static ItemStack getHeldItem() { - LocalPlayer player = Minecraft.getInstance().player; + private static ItemStack getHeldItem() throws CommandSyntaxException { + LocalPlayer player = requireNonNull(Minecraft.getInstance().player); ItemStack held = player.getItemInHand(InteractionHand.MAIN_HAND); if (held.isEmpty()) { held = player.getItemInHand(InteractionHand.OFF_HAND); } if (held.isEmpty()) { - throw new CommandRuntimeException(Component.literal("You are not holding anything.")); + throw ERROR_INVALID.create(Component.literal("You are not holding anything.")); } return held; } diff --git a/src/main/java/codechicken/lib/internal/command/client/package-info.java b/src/main/java/codechicken/lib/internal/command/client/package-info.java index eefafb3f..9ec1c645 100644 --- a/src/main/java/codechicken/lib/internal/command/client/package-info.java +++ b/src/main/java/codechicken/lib/internal/command/client/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.internal.command.client; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java index 911a5bc3..ced8febb 100644 --- a/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java +++ b/src/main/java/codechicken/lib/internal/command/dev/DevCommands.java @@ -2,10 +2,12 @@ import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.context.CommandContext; +import net.minecraft.commands.CommandBuildContext; import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.GameRules; +import net.minecraft.world.level.gamerules.GameRules; import static net.minecraft.commands.Commands.literal; @@ -14,10 +16,10 @@ */ public class DevCommands { - public static void register(CommandDispatcher dispatcher) { + public static void register(CommandDispatcher dispatcher, CommandBuildContext context) { dispatcher.register(literal("ccl") .then(literal("setup_dev_world") - .requires(e -> e.hasPermission(4)) + .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) .executes(DevCommands::setupWorld) ) ); @@ -26,18 +28,15 @@ public static void register(CommandDispatcher dispatcher) { private static int setupWorld(CommandContext ctx) { CommandSourceStack source = ctx.getSource(); MinecraftServer server = source.getServer(); - GameRules gameRules = server.getGameRules(); + GameRules gameRules = server.getWorldData().getGameRules(); for (ServerLevel level : server.getAllLevels()) { level.setWeatherParameters(6000, 0, false, false); } - gameRules.getRule(GameRules.RULE_DAYLIGHT) - .set(false, server); - gameRules.getRule(GameRules.RULE_WEATHER_CYCLE) - .set(false, server); - gameRules.getRule(GameRules.RULE_DO_TRADER_SPAWNING) - .set(false, server); + gameRules.set(GameRules.ADVANCE_TIME, false, server); + gameRules.set(GameRules.ADVANCE_WEATHER, false, server); + gameRules.set(GameRules.SPAWN_WANDERING_TRADERS, false, server); return 0; } } diff --git a/src/main/java/codechicken/lib/internal/command/dev/package-info.java b/src/main/java/codechicken/lib/internal/command/dev/package-info.java new file mode 100644 index 00000000..228f9ba4 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/command/dev/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.command.dev; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java new file mode 100644 index 00000000..1358fa3e --- /dev/null +++ b/src/main/java/codechicken/lib/internal/compat/JEIPlugin.java @@ -0,0 +1,93 @@ +package codechicken.lib.internal.compat; + +import codechicken.lib.CodeChickenLib; +import codechicken.lib.gui.modular.ModularGui; +import codechicken.lib.gui.modular.ModularGuiContainer; +import codechicken.lib.gui.modular.elements.GuiElement; +import mezz.jei.api.IModPlugin; +import mezz.jei.api.JeiPlugin; +import mezz.jei.api.constants.VanillaTypes; +import mezz.jei.api.gui.handlers.IGhostIngredientHandler; +import mezz.jei.api.gui.handlers.IGuiContainerHandler; +import mezz.jei.api.ingredients.ITypedIngredient; +import mezz.jei.api.registration.IGuiHandlerRegistration; +import net.covers1624.quack.collection.FastStream; +import net.minecraft.client.renderer.Rect2i; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.ItemStack; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static net.covers1624.quack.util.SneakyUtils.unsafeCast; + +/** + * Created by brandon3055 on 31/12/2023 + */ +@JeiPlugin +public class JEIPlugin implements IModPlugin { + + private static final Identifier ID = Identifier.fromNamespaceAndPath(CodeChickenLib.MOD_ID, "jei_plugin"); + + public JEIPlugin() { + } + + @Override + public Identifier getPluginUid() { + return ID; + } + + @Override + public void registerGuiHandlers(IGuiHandlerRegistration registration) { + registration.addGuiContainerHandler(ModularGuiContainer.class, new IGuiContainerHandler<>() { + @Override + public List getGuiExtraAreas(ModularGuiContainer screen) { + return FastStream.of(screen.getModularGui().getJeiExclusions()).map(e -> e.getRectangle().toRect2i()).toList(); + } + }); + Class> clazz = unsafeCast(ModularGuiContainer.class); + registration.addGhostIngredientHandler(clazz, new IngredientDropHandler()); + } + + private static class IngredientDropHandler implements IGhostIngredientHandler> { + + private ModularGui gui; + private boolean highlight = true; + + @Override + public List> getTargetsTyped(ModularGuiContainer screen, ITypedIngredient ingredient, boolean doStart) { + gui = screen.getModularGui(); + gui.setJeiHighlightTime(doStart ? 60 * 20 : 3 * 20); + highlight = !doStart; + if (!doStart) return Collections.emptyList(); + List> targets = new ArrayList<>(); + ingredient.getIngredient(VanillaTypes.ITEM_STACK).ifPresent(stack -> gui.getJeiDropTargets().forEach(e -> targets.add(new DropTarget<>(e)))); + return targets; + } + + @Override + public void onComplete() { + highlight = true; + gui.setJeiHighlightTime(0); + } + + @Override + public boolean shouldHighlightTargets() { + return highlight; + } + } + + private record DropTarget(GuiElement element) implements IGhostIngredientHandler.Target { + + @Override + public Rect2i getArea() { + return element.getRectangle().toRect2i(); + } + + @Override + public void accept(I ingredient) { + element.getJeiDropConsumer().accept((ItemStack) ingredient); + } + } +} diff --git a/src/main/java/codechicken/lib/internal/compat/package-info.java b/src/main/java/codechicken/lib/internal/compat/package-info.java new file mode 100644 index 00000000..6de2ee23 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/compat/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.compat; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java new file mode 100644 index 00000000..f614a5e7 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/CCLMixinPlugin.java @@ -0,0 +1,33 @@ +package codechicken.lib.internal.mixin; + +import org.jetbrains.annotations.Nullable; +import org.objectweb.asm.tree.ClassNode; +import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; + +import java.util.List; +import java.util.Set; + +/** + * Created by covers1624 on 13/11/23. + */ +public class CCLMixinPlugin implements IMixinConfigPlugin { + + private static final boolean USE_DEV_MIXINS = Boolean.getBoolean("ccl.dev.mixins"); + + @Override + public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { + // Don't load development mixins unless explicitly enabled. + // These mixins are usually quite hacky/aggressive and accomplish specific things for my dev environment. + return !mixinClassName.startsWith("codechicken.lib.internal.mixin.dev") || USE_DEV_MIXINS; + } + + // @formatter:off + @Override public void onLoad(String mixinPackage) { } + @Nullable @Override public String getRefMapperConfig() { return null; } + @Override public void acceptTargets(Set myTargets, Set otherTargets) { } + @Nullable @Override public List getMixins() { return null; } + @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } + // @formatter:on +} diff --git a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java deleted file mode 100644 index 223a1977..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/ItemRendererMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package codechicken.lib.internal.mixin; - -import codechicken.lib.render.item.IItemRenderer; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.client.ForgeHooksClient; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * {@link IItemRenderer} model extension mixin. - *

- * Created by covers1624 on 9/8/20. - */ -@Mixin (ItemRenderer.class) -public class ItemRendererMixin { - - @Inject ( - method = "render(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/client/renderer/block/model/ItemTransforms$TransformType;ZLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;IILnet/minecraft/client/resources/model/BakedModel;)V", - at = @At ("HEAD"), - cancellable = true - ) - public void onRenderItem(ItemStack stack, ItemTransforms.TransformType transformType, boolean leftHand, PoseStack mStack, MultiBufferSource buffers, int packedLight, int packedOverlay, BakedModel modelIn, CallbackInfo ci) { - if (modelIn instanceof IItemRenderer) { - ci.cancel(); - mStack.pushPose(); - //If anyone doesnt return an IItemRenderer from here, your doing it wrong. - IItemRenderer renderer = (IItemRenderer) ForgeHooksClient.handleCameraTransforms(mStack, modelIn, transformType, leftHand); - mStack.translate(-0.5D, -0.5D, -0.5D); - renderer.renderItem(stack, transformType, mStack, buffers, packedLight, packedOverlay); - mStack.popPose(); - } - } - -} diff --git a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java b/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java deleted file mode 100644 index 87578401..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/LevelRendererMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package codechicken.lib.internal.mixin; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; -import net.minecraft.client.Camera; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** - * Credit to jozufozu and Flywheel for this mixin <3 - *

- * Created by covers1624 on 1/1/22. - */ -@Mixin (LevelRenderer.class) -public abstract class LevelRendererMixin { - - @Inject ( - method = "renderLevel", - at = @At ( - value = "INVOKE", - ordinal = 1, - target = "Lnet/minecraft/client/renderer/PostChain;process(F)V" - ) - ) - private void disableTransparencyShaderDepth(PoseStack p1, float p2, long p3, boolean p4, Camera p5, GameRenderer p6, LightTexture p7, Matrix4f p8, CallbackInfo ci) { - GlStateManager._depthMask(false); - } -} diff --git a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java b/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java deleted file mode 100644 index 10976537..00000000 --- a/src/main/java/codechicken/lib/internal/mixin/ShaderInstanceMixin.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.internal.mixin; - -import codechicken.lib.render.shader.CCShaderInstance; -import com.mojang.blaze3d.shaders.Program; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceProvider; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.io.IOException; - -import static net.covers1624.quack.util.SneakyUtils.unsafeCast; - -/** - * Created by covers1624 on 9/4/22. - */ -@Mixin (ShaderInstance.class) -public abstract class ShaderInstanceMixin { - - private ShaderInstance self() { - return unsafeCast(this); - } - - @Redirect ( - method = "(Lnet/minecraft/server/packs/resources/ResourceProvider;Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/blaze3d/vertex/VertexFormat;)V", - at = @At ( - value = "INVOKE", - target = "Lnet/minecraft/client/renderer/ShaderInstance;getOrCreate(Lnet/minecraft/server/packs/resources/ResourceProvider;Lcom/mojang/blaze3d/shaders/Program$Type;Ljava/lang/String;)Lcom/mojang/blaze3d/shaders/Program;" - ) - ) - private Program onGetOrCreate(ResourceProvider provider, Program.Type type, String s) throws IOException { - if (self() instanceof CCShaderInstance instance) { - return instance.compileProgram(provider, type, new ResourceLocation(s)); - } - - return callGetOrCreate(provider, type, s); - } - - @Invoker - public abstract Program callGetOrCreate(ResourceProvider provider, Program.Type type, String s); -} diff --git a/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java new file mode 100644 index 00000000..440af603 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/dev/GameNarratorMixin.java @@ -0,0 +1,27 @@ +package codechicken.lib.internal.mixin.dev; + +import com.mojang.text2speech.Narrator; +import net.minecraft.client.GameNarrator; +import net.minecraft.client.Minecraft; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Redirect; + +/** + * Created by covers1624 on 13/11/23. + */ +@Mixin (GameNarrator.class) +abstract class GameNarratorMixin { + + @Redirect ( + method = "Lnet/minecraft/client/GameNarrator;(Lnet/minecraft/client/Minecraft;)V", + at = @At ( + value = "INVOKE", + target = "Lcom/mojang/text2speech/Narrator;getNarrator()Lcom/mojang/text2speech/Narrator;" + ) + ) + private Narrator redirectGetNarator(Minecraft mc) { + // GO AWAY NARRATOR ERRORS! + return Narrator.EMPTY; + } +} diff --git a/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java b/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java new file mode 100644 index 00000000..03aa8ecf --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/dev/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin.dev; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java b/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java new file mode 100644 index 00000000..5616cb9c --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/FriendlyByteBufMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.network; + +import codechicken.lib.packet.CCFriendlyByteBufExtension; +import net.minecraft.network.FriendlyByteBuf; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (FriendlyByteBuf.class) +public class FriendlyByteBufMixin implements CCFriendlyByteBufExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java b/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java new file mode 100644 index 00000000..7a688b80 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/RegistryFriendlyByteBufMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.network; + +import codechicken.lib.packet.CCRegistryFriendlyByteBufExtension; +import net.minecraft.network.RegistryFriendlyByteBuf; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (RegistryFriendlyByteBuf.class) +public class RegistryFriendlyByteBufMixin implements CCRegistryFriendlyByteBufExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/network/package-info.java b/src/main/java/codechicken/lib/internal/mixin/network/package-info.java new file mode 100644 index 00000000..94add508 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/network/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin.network; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/package-info.java b/src/main/java/codechicken/lib/internal/mixin/package-info.java new file mode 100644 index 00000000..69ca6a4f --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java b/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java new file mode 100644 index 00000000..81a0db72 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/render/GuiGraphicsMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.render; + +import codechicken.lib.gui.render.GuiGraphicsExtension; +import net.minecraft.client.gui.GuiGraphics; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 7/25/26. + */ +@Mixin (GuiGraphics.class) +public class GuiGraphicsMixin implements GuiGraphicsExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java b/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java new file mode 100644 index 00000000..0d6b460a --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/render/OrderedSubmitNodeCollectorMixin.java @@ -0,0 +1,12 @@ +package codechicken.lib.internal.mixin.render; + +import codechicken.lib.render.extension.CCOrderedSubmitNodeCollectorExtension; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import org.spongepowered.asm.mixin.Mixin; + +/** + * Created by covers1624 on 11/2/25. + */ +@Mixin (OrderedSubmitNodeCollector.class) +public interface OrderedSubmitNodeCollectorMixin extends CCOrderedSubmitNodeCollectorExtension { +} diff --git a/src/main/java/codechicken/lib/internal/mixin/render/package-info.java b/src/main/java/codechicken/lib/internal/mixin/render/package-info.java new file mode 100644 index 00000000..c220d793 --- /dev/null +++ b/src/main/java/codechicken/lib/internal/mixin/render/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.internal.mixin.render; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java b/src/main/java/codechicken/lib/internal/network/CCLNetwork.java deleted file mode 100644 index 99b73ea5..00000000 --- a/src/main/java/codechicken/lib/internal/network/CCLNetwork.java +++ /dev/null @@ -1,29 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.packet.PacketCustomChannelBuilder; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.network.event.EventNetworkChannel; - -/** - * Created by covers1624 on 28/10/19. - */ -public class CCLNetwork { - - public static final ResourceLocation NET_CHANNEL = new ResourceLocation("ccl:internal"); - public static EventNetworkChannel netChannel; - - //Client handled. - public static final int C_ADD_LANDING_EFFECTS = 1; - public static final int C_OPEN_CONTAINER = 10; - - //Login handled. - public static final int L_CONFIG_SYNC = 1; - - public static void init() { - netChannel = PacketCustomChannelBuilder.named(NET_CHANNEL)// - .assignClientHandler(() -> ClientPacketHandler::new)// - .assignLoginHandler(() -> LoginPacketHandler::new)// - .build(); - } - -} diff --git a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java b/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java deleted file mode 100644 index 8f7dd554..00000000 --- a/src/main/java/codechicken/lib/internal/network/ClientPacketHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.inventory.container.ICCLContainerType; -import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.render.particle.CustomParticleHandler; -import codechicken.lib.vec.Vector3; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.MenuScreens; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.MenuAccess; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.registries.ForgeRegistries; - -import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; -import static codechicken.lib.internal.network.CCLNetwork.C_OPEN_CONTAINER; - -/** - * Created by covers1624 on 14/07/2017. - */ -public class ClientPacketHandler implements IClientPacketHandler { - - @Override - public void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler) { - switch (packet.getType()) { - case C_ADD_LANDING_EFFECTS -> { - BlockPos pos = packet.readPos(); - Vector3 vec = packet.readVector(); - int numParticles = packet.readVarInt(); - BlockState state = mc.level.getBlockState(pos); - CustomParticleHandler.addLandingEffects(mc.level, pos, state, vec, numParticles); - } - case C_OPEN_CONTAINER -> handleOpenContainer(packet, mc); - } - } - - @SuppressWarnings ("unchecked") - private void handleOpenContainer(PacketCustom packet, Minecraft mc) { - MenuType rawType = packet.readRegistryIdDirect(ForgeRegistries.MENU_TYPES); - int windowId = packet.readVarInt(); - Component name = packet.readTextComponent(); - if (rawType instanceof ICCLContainerType type) { - MenuScreens.getScreenFactory(rawType, mc, windowId, name) - .map(e -> (MenuScreens.ScreenConstructor) e) - .ifPresent(screenFactory -> { - AbstractContainerMenu container = type.create(windowId, Minecraft.getInstance().player.getInventory(), packet); - Screen screen = screenFactory.create(container, mc.player.getInventory(), name); - mc.player.containerMenu = ((MenuAccess) screen).getMenu(); - mc.setScreen(screen); - }); - - } - } -} diff --git a/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java b/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java deleted file mode 100644 index 93092ac6..00000000 --- a/src/main/java/codechicken/lib/internal/network/LoginPacketHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -package codechicken.lib.internal.network; - -import codechicken.lib.config.ConfigSyncManager; -import codechicken.lib.packet.ICustomPacketHandler; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.client.Minecraft; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; -import net.minecraftforge.network.NetworkEvent; - -import java.util.function.BiConsumer; -import java.util.function.Supplier; - -import static codechicken.lib.internal.network.CCLNetwork.L_CONFIG_SYNC; - -/** - * Created by covers1624 on 5/3/20. - */ -public class LoginPacketHandler implements ICustomPacketHandler.ILoginPacketHandler { - - @Override - public void gatherLoginPackets(BiConsumer> consumer) { - ConfigSyncManager.handleLogin(consumer); - } - - @Override - public void handleLoginPacket(PacketCustom packet, Minecraft mc, ClientLoginPacketListener handler, NetworkEvent.Context context) { - switch (packet.getType()) { - case L_CONFIG_SYNC -> ConfigSyncManager.readSyncPacket(packet); - } - } -} diff --git a/src/main/java/codechicken/lib/internal/package-info.java b/src/main/java/codechicken/lib/internal/package-info.java index 5b874732..65183a0f 100644 --- a/src/main/java/codechicken/lib/internal/package-info.java +++ b/src/main/java/codechicken/lib/internal/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.internal; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/internal/proxy/Proxy.java b/src/main/java/codechicken/lib/internal/proxy/Proxy.java deleted file mode 100644 index 85fa05f7..00000000 --- a/src/main/java/codechicken/lib/internal/proxy/Proxy.java +++ /dev/null @@ -1,21 +0,0 @@ -package codechicken.lib.internal.proxy; - -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; -import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent; - -/** - * Created by covers1624 on 30/10/19. - */ -public class Proxy { - - public void commonSetup(FMLCommonSetupEvent event) { - } - - public void clientSetup(FMLClientSetupEvent event) { - } - - public void serverSetup(FMLDedicatedServerSetupEvent event) { - } - -} diff --git a/src/main/java/codechicken/lib/internal/proxy/ProxyClient.java b/src/main/java/codechicken/lib/internal/proxy/ProxyClient.java deleted file mode 100644 index ea0ab255..00000000 --- a/src/main/java/codechicken/lib/internal/proxy/ProxyClient.java +++ /dev/null @@ -1,63 +0,0 @@ -package codechicken.lib.internal.proxy; - -import codechicken.lib.CodeChickenLib; -import codechicken.lib.config.ConfigCategory; -import codechicken.lib.config.ConfigSyncManager; -import codechicken.lib.model.bakery.ModelBakery; -import codechicken.lib.render.CCRenderEventHandler; -import codechicken.lib.render.block.BlockRenderingRegistry; -import codechicken.lib.render.item.map.MapRenderRegistry; -import net.minecraftforge.client.event.ClientPlayerNetworkEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; - -/** - * Created by covers1624 on 30/10/19. - */ -public class ProxyClient extends Proxy { - - public static boolean catchBlockRenderExceptions; - public static boolean messagePlayerOnRenderExceptionCaught; - - @Override - public void clientSetup(FMLClientSetupEvent event) { - loadClientConfig(); - //OpenGLUtils.loadCaps(); - // CustomParticleHandler.init(); - BlockRenderingRegistry.init(); - ModelBakery.init(); - CCRenderEventHandler.init(); - - MinecraftForge.EVENT_BUS.register(new MapRenderRegistry()); - // ClientCommandHandler.instance.registerCommand(new CCLClientCommand()); - MinecraftForge.EVENT_BUS.addListener(this::onClientDisconnected); - } - - private void loadClientConfig() { - ConfigCategory clientTag = CodeChickenLib.config.getCategory("client"); - clientTag.delete("block_renderer_dispatcher_misc"); - clientTag.delete("catchItemRenderExceptions"); - clientTag.delete("attemptRecoveryOnItemRenderException"); - - catchBlockRenderExceptions = clientTag.getValue("catchBlockRenderExceptions") - .setComment( - "With this enabled, CCL will catch all exceptions thrown whilst rendering blocks.", - "If an exception is caught, the block will not be rendered." - ) - .setDefaultBoolean(true) - .getBoolean(); - messagePlayerOnRenderExceptionCaught = clientTag.getValue("messagePlayerOnRenderExceptionCaught") - .setComment( - "With this enabled, CCL will message the player upon an exception from rendering blocks or items.", - "Messages are Rate-Limited to one per 5 seconds in the event that the exception continues." - ) - .setDefaultBoolean(true) - .getBoolean(); - - clientTag.save(); - } - - private void onClientDisconnected(ClientPlayerNetworkEvent.LoggingOut event) { - ConfigSyncManager.onClientDisconnected(); - } -} diff --git a/src/main/java/codechicken/lib/inventory/InventoryCopy.java b/src/main/java/codechicken/lib/inventory/InventoryCopy.java index c0767233..bd377fb0 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryCopy.java +++ b/src/main/java/codechicken/lib/inventory/InventoryCopy.java @@ -5,7 +5,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.Objects; /** @@ -62,18 +61,15 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return items[slot]; } - @Nonnull public ItemStack removeItem(int slot, int amount) { return InventoryUtils.decrStackSize(this, slot, amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return InventoryUtils.removeStackFromSlot(this, slot); } @@ -89,11 +85,6 @@ public boolean stillValid(Player player) { return true; } - @Override - public int getMaxStackSize() { - return 64; - } - @Override public void setChanged() { } @@ -103,14 +94,6 @@ public boolean canPlaceItem(int i, ItemStack itemstack) { return inv.canPlaceItem(i, itemstack); } - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - @Override public void clearContent() { } diff --git a/src/main/java/codechicken/lib/inventory/InventoryNBT.java b/src/main/java/codechicken/lib/inventory/InventoryNBT.java deleted file mode 100644 index 6cc341e7..00000000 --- a/src/main/java/codechicken/lib/inventory/InventoryNBT.java +++ /dev/null @@ -1,105 +0,0 @@ -package codechicken.lib.inventory; - -import codechicken.lib.util.ArrayUtils; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.Container; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -import javax.annotation.Nonnull; -import java.util.Arrays; -import java.util.Objects; - -/** - * IInventory implementation which saves and loads from an NBT tag - */ -public class InventoryNBT implements Container { - - protected ItemStack[] items; - protected CompoundTag tag; - - public InventoryNBT(int size, CompoundTag tag) { - this.tag = tag; - items = new ItemStack[size]; - ArrayUtils.fillArray(items, ItemStack.EMPTY, (Objects::isNull)); - readNBT(); - } - - private void writeNBT() { - tag.put("items", InventoryUtils.writeItemStacksToTag(items, getMaxStackSize())); - } - - private void readNBT() { - if (tag.contains("items")) { - InventoryUtils.readItemStacksFromTag(items, tag.getList("items", 10)); - } - } - - @Override - public int getContainerSize() { - return items.length; - } - - @Override - public boolean isEmpty() { - return ArrayUtils.count(items, (stack -> !stack.isEmpty())) <= 0; - } - - @Override - @Nonnull - public ItemStack getItem(int slot) { - return items[slot]; - } - - @Override - @Nonnull - public ItemStack removeItem(int slot, int amount) { - return InventoryUtils.decrStackSize(this, slot, amount); - } - - @Override - @Nonnull - public ItemStack removeItemNoUpdate(int slot) { - return InventoryUtils.removeStackFromSlot(this, slot); - } - - @Override - public void setItem(int slot, ItemStack stack) { - items[slot] = stack; - setChanged(); - } - - @Override - public int getMaxStackSize() { - return 64; - } - - @Override - public void setChanged() { - writeNBT(); - } - - @Override - public void clearContent() { - Arrays.fill(items, ItemStack.EMPTY); - setChanged(); - } - - @Override - public boolean stillValid(Player player) { - return true; - } - - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - - @Override - public boolean canPlaceItem(int i, ItemStack itemstack) { - return true; - } -} diff --git a/src/main/java/codechicken/lib/inventory/InventoryRange.java b/src/main/java/codechicken/lib/inventory/InventoryRange.java index 57a24a8e..550857c4 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryRange.java +++ b/src/main/java/codechicken/lib/inventory/InventoryRange.java @@ -4,23 +4,18 @@ import net.minecraft.world.Container; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.item.ItemStack; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; /** * Inventory wrapper for unified ISided/IInventory access */ public class InventoryRange { - public Container inv; - public Direction face; - public WorldlyContainer sidedInv; - public int[] slots; - - @Deprecated// Use EnumFacing version. - public InventoryRange(Container inv, int side) { - this(inv, Direction.BY_3D_DATA[side]); - } + public final Container inv; + public @Nullable final Direction face; + public @Nullable WorldlyContainer sidedInv; + public final int[] slots; public InventoryRange(Container inv, Direction side) { this.inv = inv; @@ -42,6 +37,7 @@ public InventoryRange(Container inv) { public InventoryRange(Container inv, int fslot, int lslot) { this.inv = inv; + this.face = null; slots = new int[lslot - fslot]; for (int i = 0; i < slots.length; i++) { slots[i] = fslot + i; @@ -57,11 +53,11 @@ public InventoryRange(Container inv, InventoryRange access) { } } - public boolean canInsertItem(int slot, @Nonnull ItemStack item) { + public boolean canInsertItem(int slot, ItemStack item) { return sidedInv == null ? inv.canPlaceItem(slot, item) : sidedInv.canPlaceItemThroughFace(slot, item, face); } - public boolean canExtractItem(int slot, @Nonnull ItemStack item) { + public boolean canExtractItem(int slot, ItemStack item) { return sidedInv == null ? inv.canPlaceItem(slot, item) : sidedInv.canTakeItemThroughFace(slot, item, face); } diff --git a/src/main/java/codechicken/lib/inventory/InventorySimple.java b/src/main/java/codechicken/lib/inventory/InventorySimple.java index 7689e0a9..ac866d17 100644 --- a/src/main/java/codechicken/lib/inventory/InventorySimple.java +++ b/src/main/java/codechicken/lib/inventory/InventorySimple.java @@ -5,7 +5,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.Objects; @@ -64,19 +63,16 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return items[slot]; } @Override - @Nonnull public ItemStack removeItem(int slot, int amount) { return InventoryUtils.decrStackSize(this, slot, amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return InventoryUtils.removeStackFromSlot(this, slot); } @@ -97,23 +93,10 @@ public boolean stillValid(Player player) { return true; } - @Override - public boolean canPlaceItem(int i, ItemStack itemstack) { - return true; - } - @Override public void setChanged() { } - @Override - public void startOpen(Player player) { - } - - @Override - public void stopOpen(Player player) { - } - @Override public void clearContent() { Arrays.fill(items, ItemStack.EMPTY); diff --git a/src/main/java/codechicken/lib/inventory/InventoryUtils.java b/src/main/java/codechicken/lib/inventory/InventoryUtils.java index 9151f21e..33eba49d 100644 --- a/src/main/java/codechicken/lib/inventory/InventoryUtils.java +++ b/src/main/java/codechicken/lib/inventory/InventoryUtils.java @@ -1,25 +1,18 @@ package codechicken.lib.inventory; import codechicken.lib.util.ItemUtils; -import com.google.common.base.Objects; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NumericTag; -import net.minecraft.nbt.Tag; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraftforge.items.IItemHandler; - -import javax.annotation.Nonnull; +import net.minecraft.world.level.storage.ValueInput; +import net.minecraft.world.level.storage.ValueOutput; +import net.neoforged.neoforge.items.IItemHandler; public class InventoryUtils { /** * Static default implementation for IInventory method */ - @Nonnull public static ItemStack decrStackSize(Container inv, int slot, int size) { ItemStack item = inv.getItem(slot); @@ -54,7 +47,7 @@ public static ItemStack removeStackFromSlot(Container inv, int slot) { /** * @return The quantity of items from addition that can be added to base */ - public static int incrStackSize(@Nonnull ItemStack base, @Nonnull ItemStack addition) { + public static int incrStackSize(ItemStack base, ItemStack addition) { if (canStack(base, addition)) { return incrStackSize(base, addition.getCount()); } @@ -65,7 +58,7 @@ public static int incrStackSize(@Nonnull ItemStack base, @Nonnull ItemStack addi /** * @return The quantity of items from addition that can be added to base */ - public static int incrStackSize(@Nonnull ItemStack base, int addition) { + public static int incrStackSize(ItemStack base, int addition) { int totalSize = base.getCount() + addition; if (totalSize <= base.getMaxStackSize()) { @@ -80,42 +73,36 @@ public static int incrStackSize(@Nonnull ItemStack base, int addition) { /** * NBT item saving function */ - public static ListTag writeItemStacksToTag(ItemStack[] items) { - return writeItemStacksToTag(items, 64); + public static void writeItemStacksToOutput(ValueOutput output, ItemStack[] items) { + writeItemStacksToOutput(output, items, 64); } /** * NBT item saving function with support for stack sizes > 32K */ - public static ListTag writeItemStacksToTag(ItemStack[] items, int maxQuantity) { - ListTag tagList = new ListTag(); + public static void writeItemStacksToOutput(ValueOutput output, ItemStack[] items, int maxQuantity) { + var children = output.childrenList("Items"); for (int i = 0; i < items.length; i++) { - CompoundTag tag = new CompoundTag(); - tag.putShort("Slot", (short) i); - items[i].save(tag); - - if (maxQuantity > Short.MAX_VALUE) { - tag.putInt("Quantity", items[i].getCount()); - } else if (maxQuantity > Byte.MAX_VALUE) { - tag.putShort("Quantity", (short) items[i].getCount()); - } + var stack = items[i]; + if (stack.isEmpty()) continue; - tagList.add(tag); + var child = children.addChild(); + child.putInt("Slot", i); + child.store("Item", ItemStack.SINGLE_ITEM_CODEC, stack); + child.putInt("Quantity", Math.min(stack.getCount(), maxQuantity)); } - return tagList; } /** * NBT item loading function with support for stack sizes > 32K */ - public static void readItemStacksFromTag(ItemStack[] items, ListTag tagList) { - for (int i = 0; i < tagList.size(); i++) { - CompoundTag tag = tagList.getCompound(i); - int b = tag.getShort("Slot"); - items[b] = ItemStack.of(tag); - Tag quantTag = tag.get("Quantity"); - if (quantTag instanceof NumericTag quant) { - items[b].setCount(quant.getAsInt()); + public static void readItemStacksFromInput(ValueInput input, ItemStack[] items) { + var children = input.childrenListOrEmpty("Items"); + for (ValueInput child : children) { + var slot = child.getInt("Slot").orElseThrow(); + items[slot] = child.read("Item", ItemStack.SINGLE_ITEM_CODEC).orElse(ItemStack.EMPTY); + if (!items[slot].isEmpty()) { + items[slot].setCount(child.getInt("Quantity").orElseThrow()); } } } @@ -123,7 +110,7 @@ public static void readItemStacksFromTag(ItemStack[] items, ListTag tagList) { /** * Gets the maximum quantity of an item that can be inserted into inv */ - public static int getInsertibleQuantity(InventoryRange inv, @Nonnull ItemStack stack) { + public static int getInsertibleQuantity(InventoryRange inv, ItemStack stack) { int quantity = 0; stack = ItemUtils.copyStack(stack, Integer.MAX_VALUE); for (int slot : inv.slots) { @@ -133,7 +120,7 @@ public static int getInsertibleQuantity(InventoryRange inv, @Nonnull ItemStack s return quantity; } - public static int getInsertibleQuantity(Container inv, @Nonnull ItemStack stack) { + public static int getInsertibleQuantity(Container inv, ItemStack stack) { return getInsertibleQuantity(new InventoryRange(inv), stack); } @@ -147,7 +134,7 @@ public static int fitStackInSlot(InventoryRange inv, int slot, ItemStack stack) return Math.min(fit, stack.getCount()); } - public static int fitStackInSlot(Container inv, int slot, @Nonnull ItemStack stack) { + public static int fitStackInSlot(Container inv, int slot, ItemStack stack) { return fitStackInSlot(new InventoryRange(inv), slot, stack); } @@ -155,7 +142,7 @@ public static int fitStackInSlot(Container inv, int slot, @Nonnull ItemStack sta * @param simulate If set to true, no items will actually be inserted * @return The number of items unable to be inserted */ - public static int insertItem(InventoryRange inv, @Nonnull ItemStack stack, boolean simulate) { + public static int insertItem(InventoryRange inv, ItemStack stack, boolean simulate) { stack = stack.copy(); for (int pass = 0; pass < 2; pass++) { for (int slot : inv.slots) { @@ -188,7 +175,7 @@ public static int insertItem(InventoryRange inv, @Nonnull ItemStack stack, boole return stack.getCount(); } - public static int insertItem(Container inv, @Nonnull ItemStack stack, boolean simulate) { + public static int insertItem(Container inv, ItemStack stack, boolean simulate) { return insertItem(new InventoryRange(inv), stack, simulate); } @@ -208,16 +195,16 @@ public static ItemStack getExtractableStack(Container inv, int slot) { return getExtractableStack(new InventoryRange(inv), slot); } - public static boolean areStacksIdentical(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static boolean areStacksIdentical(ItemStack stack1, ItemStack stack2) { if (stack1.isEmpty() || stack2.isEmpty()) { return stack1 == stack2; } - return stack1.getItem() == stack2.getItem() && stack1.getDamageValue() == stack2.getDamageValue() && stack1.getCount() == stack2.getCount() && Objects.equal(stack1.getTag(), stack2.getTag()); + return stack1.getItem() == stack2.getItem() && stack1.getDamageValue() == stack2.getDamageValue() && stack1.getCount() == stack2.getCount() && ItemStack.isSameItemSameComponents(stack2, stack1); } - public static boolean canStack(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { - return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.tagMatches(stack2, stack1)) && stack1.isStackable(); + public static boolean canStack(ItemStack stack1, ItemStack stack2) { + return stack1.isEmpty() || stack2.isEmpty() || (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameComponents(stack2, stack1)) && stack1.isStackable(); } /** @@ -225,10 +212,9 @@ public static boolean canStack(@Nonnull ItemStack stack1, @Nonnull ItemStack sta */ public static void consumeItem(Container inv, int slot) { ItemStack stack = inv.getItem(slot); - Item item = stack.getItem(); - if (item.hasCraftingRemainingItem(stack)) { - ItemStack container = item.getCraftingRemainingItem(stack); - inv.setItem(slot, container); + ItemStack remaining = stack.getCraftingRemainder(); + if (!remaining.isEmpty()) { + inv.setItem(slot, remaining); } else { inv.removeItem(slot, 1); } diff --git a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java index dd59b6e7..398a360e 100644 --- a/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java +++ b/src/main/java/codechicken/lib/inventory/MappedInventoryAccess.java @@ -1,10 +1,10 @@ package codechicken.lib.inventory; import net.minecraft.world.Container; +import net.minecraft.world.entity.ContainerUser; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -53,19 +53,16 @@ public boolean isEmpty() { } @Override - @Nonnull public ItemStack getItem(int slot) { return inv.getItem(slotMap.get(slot)); } @Override - @Nonnull public ItemStack removeItem(int slot, int amount) { return inv.removeItem(slotMap.get(slot), amount); } @Override - @Nonnull public ItemStack removeItemNoUpdate(int slot) { return inv.removeItemNoUpdate(slotMap.get(slot)); } @@ -101,13 +98,18 @@ public boolean canPlaceItem(int slot, ItemStack stack) { } @Override - public void startOpen(Player player) { - inv.startOpen(player); + public void startOpen(ContainerUser user) { + inv.startOpen(user); } @Override - public void stopOpen(Player player) { - inv.stopOpen(player); + public void stopOpen(ContainerUser user) { + inv.stopOpen(user); + } + + @Override + public List getEntitiesWithContainerOpen() { + return inv.getEntitiesWithContainerOpen(); } @Override diff --git a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java index 05bb4697..0f24e696 100644 --- a/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java +++ b/src/main/java/codechicken/lib/inventory/container/ContainerExtended.java @@ -1,7 +1,6 @@ package codechicken.lib.inventory.container; -import codechicken.lib.packet.PacketCustom; -import net.minecraft.core.NonNullList; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; @@ -9,8 +8,7 @@ import net.minecraft.world.item.ItemStack; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import java.util.LinkedList; +import java.util.List; public abstract class ContainerExtended extends AbstractContainerMenu { @@ -28,7 +26,7 @@ protected ContainerExtended(MenuType type, int id, Inventory inv) { public void setSynchronizer(ContainerSynchronizer delegate) { super.setSynchronizer(new ContainerSynchronizer() { @Override - public void sendInitialData(AbstractContainerMenu container, NonNullList stacks, ItemStack carried, int[] data) { + public void sendInitialData(AbstractContainerMenu container, List stacks, ItemStack carried, int[] data) { delegate.sendInitialData(container, stacks, carried, data); if (player != null) { for (int i = 0; i < stacks.size(); i++) { @@ -43,8 +41,10 @@ public void sendInitialData(AbstractContainerMenu container, NonNullList Byte.MAX_VALUE) { - sendLargeStack(stack, slot, player); + if (player != null) { + if (stack.getCount() > Byte.MAX_VALUE) { + sendLargeStack(stack, slot, player); + } } } @@ -57,6 +57,11 @@ public void sendCarriedChange(AbstractContainerMenu container, ItemStack stack) public void sendDataChange(AbstractContainerMenu container, int slot, int data) { delegate.sendDataChange(container, slot, data); } + + @Override + public RemoteSlot createSlot() { + return delegate.createSlot(); + } }); } @@ -66,22 +71,20 @@ public void sendLargeStack(ItemStack stack, int slot, ServerPlayer player) { @Override public void clicked(int slot, int dragType, ClickType clickType, Player player) { if (slot >= 0 && slot < slots.size()) { - Slot actualSlot = getSlot(slot); - if (actualSlot instanceof SlotHandleClicks) { - ((SlotHandleClicks) actualSlot).slotClick(this, player, dragType, clickType); + if (getSlot(slot) instanceof SlotHandleClicks handleClicks) { + handleClicks.slotClick(this, player, dragType, clickType); return; } } super.clicked(slot, dragType, clickType, player); } - @Nonnull @Override - public ItemStack quickMoveStack(@Nonnull Player player, int slotIndex) { + public ItemStack quickMoveStack(Player player, int slotIndex) { ItemStack transferredStack = ItemStack.EMPTY; Slot slot = slots.get(slotIndex); - if (slot != null && slot.hasItem()) { + if (slot.hasItem()) { ItemStack stack = slot.getItem(); transferredStack = stack.copy(); @@ -100,7 +103,7 @@ public ItemStack quickMoveStack(@Nonnull Player player, int slotIndex) { } @Override - public boolean moveItemStackTo(@Nonnull ItemStack stack, int startIndex, int endIndex, boolean reverse) { + public boolean moveItemStackTo(ItemStack stack, int startIndex, int endIndex, boolean reverse) { boolean merged = false; int slotIndex = reverse ? endIndex - 1 : startIndex; @@ -113,7 +116,7 @@ public boolean moveItemStackTo(@Nonnull ItemStack stack, int startIndex, int end Slot slot = slots.get(slotIndex); ItemStack slotStack = slot.getItem(); - if (!slotStack.isEmpty() && ItemStack.isSameItemSameTags(stack, slotStack)) { + if (!slotStack.isEmpty() && ItemStack.isSameItemSameComponents(stack, slotStack)) { int totalStackSize = slotStack.getCount() + stack.getCount(); int maxStackSize = Math.min(stack.getMaxStackSize(), slot.getMaxStackSize()); if (totalStackSize <= maxStackSize) { @@ -176,7 +179,7 @@ protected void bindPlayerInventory(Inventory inventoryPlayer, int x, int y) { } @Override - public boolean stillValid(@Nonnull Player var1) { + public boolean stillValid(Player var1) { return true; } @@ -184,14 +187,14 @@ public boolean stillValid(@Nonnull Player var1) { * May be called from a client packet handler to handle additional info */ - public void handleOutputPacket(PacketCustom packet) { + public void handleOutputPacket(RegistryFriendlyByteBuf packet) { } /** * May be called from a server packet handler to handle additional info */ - public void handleInputPacket(PacketCustom packet) { + public void handleInputPacket(RegistryFriendlyByteBuf packet) { } /** diff --git a/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java b/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java deleted file mode 100644 index cb4aab03..00000000 --- a/src/main/java/codechicken/lib/inventory/container/ICCLContainerFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package codechicken.lib.inventory.container; - -import codechicken.lib.data.MCDataInput; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; - -/** - * Created by covers1624 on 28/10/19. - */ -public interface ICCLContainerFactory extends MenuType.MenuSupplier { - - T create(int windowId, Inventory inventory, MCDataInput packet); - - @Override - default T create(int windowId, Inventory inventory) { - return create(windowId, inventory, null); - } -} diff --git a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java b/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java deleted file mode 100644 index fb9fdc0a..00000000 --- a/src/main/java/codechicken/lib/inventory/container/ICCLContainerType.java +++ /dev/null @@ -1,33 +0,0 @@ -package codechicken.lib.inventory.container; - -import codechicken.lib.data.MCDataInput; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; - -/** - * Created by covers1624 on 28/10/19. - */ -public interface ICCLContainerType { - - static MenuType create(ICCLContainerFactory factory) { - return new CCLContainerType<>(factory); - } - - T create(int windowId, Inventory inventory, MCDataInput packet); - - class CCLContainerType extends MenuType implements ICCLContainerType { - - public CCLContainerType(MenuType.MenuSupplier factory) { - super(factory); - } - - @Override - public T create(int windowId, Inventory inventory, MCDataInput packet) { - if (constructor instanceof ICCLContainerFactory) { - return ((ICCLContainerFactory) constructor).create(windowId, inventory, packet); - } - return null; - } - } -} diff --git a/src/main/java/codechicken/lib/inventory/container/SlotDummy.java b/src/main/java/codechicken/lib/inventory/container/SlotDummy.java index 8a63e09f..7383c3dc 100644 --- a/src/main/java/codechicken/lib/inventory/container/SlotDummy.java +++ b/src/main/java/codechicken/lib/inventory/container/SlotDummy.java @@ -7,8 +7,6 @@ import net.minecraft.world.inventory.ClickType; import net.minecraft.world.item.ItemStack; -import javax.annotation.Nonnull; - public class SlotDummy extends SlotHandleClicks { public final int stackLimit; @@ -29,7 +27,7 @@ public void slotClick(ContainerExtended container, Player player, int button, Cl slotClick(held, button, shift); } - public void slotClick(@Nonnull ItemStack held, int button, boolean shift) { + public void slotClick(ItemStack held, int button, boolean shift) { ItemStack tstack = getItem(); if (!held.isEmpty() && (tstack.isEmpty() || !InventoryUtils.canStack(held, tstack))) { int quantity = Math.min(held.getCount(), stackLimit); @@ -63,7 +61,7 @@ public void slotClick(@Nonnull ItemStack held, int button, boolean shift) { } @Override - public void set(@Nonnull ItemStack stack) { + public void set(ItemStack stack) { if (!stack.isEmpty() && stack.getCount() > stackLimit) { stack = ItemUtils.copyStack(stack, stackLimit); } diff --git a/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java new file mode 100644 index 00000000..0c9cc133 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/AbstractDataStore.java @@ -0,0 +1,45 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +import java.util.Objects; + +/** + * The base class of a simple general purpose serializable data system. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public abstract class AbstractDataStore { + + protected T value; + + public AbstractDataStore(T defaultValue) { + this.value = defaultValue; + } + + public T get() { + return value; + } + + public void set(T value) { + this.value = value; + markDirty(); + } + + public void markDirty() { } + + public abstract void toBytes(RegistryFriendlyByteBuf buf); + + public abstract void fromBytes(RegistryFriendlyByteBuf buf); + + public abstract Tag toTag(HolderLookup.Provider holders); + + public abstract void fromTag(HolderLookup.Provider holders, Tag tag); + + public boolean isSameValue(T newValue) { + return Objects.equals(value, newValue); + } +} + diff --git a/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java new file mode 100644 index 00000000..528b6b12 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/BooleanData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class BooleanData extends AbstractDataStore { + + public BooleanData() { + super(false); + } + + public BooleanData(boolean defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeBoolean(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readBoolean(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return ByteTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).byteValue() != 0; + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/ByteData.java b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java new file mode 100644 index 00000000..e922ad12 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/ByteData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.ByteTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class ByteData extends AbstractDataStore { + + public ByteData() { + super((byte) 0); + } + + public ByteData(byte defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeByte(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readByte(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return ByteTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).byteValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java new file mode 100644 index 00000000..d95a07c4 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/DoubleData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.DoubleTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class DoubleData extends AbstractDataStore { + + public DoubleData() { + super(0D); + } + + public DoubleData(double defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeDouble(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readDouble(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return DoubleTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).doubleValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/FloatData.java b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java new file mode 100644 index 00000000..d4fd50ed --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/FloatData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.FloatTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class FloatData extends AbstractDataStore { + + public FloatData() { + super(0F); + } + + public FloatData(float defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeFloat(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readFloat(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return FloatTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).floatValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/FluidData.java b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java new file mode 100644 index 00000000..4f77f4ad --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/FluidData.java @@ -0,0 +1,60 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.fluids.FluidStack; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class FluidData extends AbstractDataStore { + + private static final Logger LOGGER = LoggerFactory.getLogger(FluidData.class); + + public FluidData() { + super(FluidStack.EMPTY); + } + + public FluidData(FluidStack defaultValue) { + super(defaultValue); + } + + @Override + public void set(FluidStack value) { + this.value = value.copy(); + markDirty(); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.cc$writeWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC, value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.cc$readWithRegistryCodec(FluidStack.OPTIONAL_STREAM_CODEC); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return FluidStack.OPTIONAL_CODEC + .encodeStart(holders.createSerializationContext(NbtOps.INSTANCE), value) + .getOrThrow(); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = FluidStack.OPTIONAL_CODEC + .parse(holders.createSerializationContext(NbtOps.INSTANCE), tag) + .getOrThrow(); + } + + @Override + public boolean isSameValue(FluidStack newValue) { + return value.equals(newValue); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/IntData.java b/src/main/java/codechicken/lib/inventory/container/data/IntData.java new file mode 100644 index 00000000..426b38d5 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/IntData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class IntData extends AbstractDataStore { + + public IntData() { + super(0); + } + + public IntData(int defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeVarInt(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readVarInt(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return IntTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).intValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/LongData.java b/src/main/java/codechicken/lib/inventory/container/data/LongData.java new file mode 100644 index 00000000..36e30d14 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/LongData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.LongTag; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class LongData extends AbstractDataStore { + + public LongData() { + super(0L); + } + + public LongData(long defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeVarLong(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readVarLong(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return LongTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).longValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/ShortData.java b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java new file mode 100644 index 00000000..8fe9ebf0 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/ShortData.java @@ -0,0 +1,41 @@ +package codechicken.lib.inventory.container.data; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.NumericTag; +import net.minecraft.nbt.ShortTag; +import net.minecraft.nbt.Tag; +import net.minecraft.network.RegistryFriendlyByteBuf; + +/** + * Created by brandon3055 on 09/09/2023 + */ +public class ShortData extends AbstractDataStore { + + public ShortData() { + super((short) 0); + } + + public ShortData(short defaultValue) { + super(defaultValue); + } + + @Override + public void toBytes(RegistryFriendlyByteBuf buf) { + buf.writeShort(value); + } + + @Override + public void fromBytes(RegistryFriendlyByteBuf buf) { + value = buf.readShort(); + } + + @Override + public Tag toTag(HolderLookup.Provider holders) { + return ShortTag.valueOf(value); + } + + @Override + public void fromTag(HolderLookup.Provider holders, Tag tag) { + value = ((NumericTag) tag).shortValue(); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/data/package-info.java b/src/main/java/codechicken/lib/inventory/container/data/package-info.java new file mode 100644 index 00000000..349edd07 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/data/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container.data; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java new file mode 100644 index 00000000..1c5bf69e --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularGuiContainerMenu.java @@ -0,0 +1,318 @@ +package codechicken.lib.inventory.container.modular; + +import codechicken.lib.gui.modular.elements.GuiSlots; +import codechicken.lib.gui.modular.lib.container.ContainerScreenAccess; +import codechicken.lib.gui.modular.lib.container.DataSync; +import codechicken.lib.gui.modular.lib.container.SlotGroup; +import codechicken.lib.gui.modular.lib.geometry.GuiParent; +import codechicken.lib.internal.CCLNetwork; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +/** + * The base abstract ContainerMenu for all modular gui containers. + *

+ * Created by brandon3055 on 08/09/2023 + */ +public abstract class ModularGuiContainerMenu extends AbstractContainerMenu { + + private static final Logger LOGGER = LogManager.getLogger(); + + public final Inventory inventory; + public final List slotGroups = new ArrayList<>(); + public final Map slotGroupMap = new HashMap<>(); + public final Map> zonedSlots = new HashMap<>(); + public final List> dataSyncs = new ArrayList<>(); + + protected ModularGuiContainerMenu(@Nullable MenuType menuType, int containerId, Inventory inventory) { + super(menuType, containerId); + this.inventory = inventory; + } + + /** + * Creates and returns a new slot group for this container. + * You can then add your inventory slots to this slot group, similar to how you would normally add slots to the container. + * With one big exception! You do not need to worry about setting slot positions! (Just use 0, 0) + *

+ * Make sure to save your slot groups to accessible fields in your container menu class. + * You will need to pass these to appropriate {@link GuiSlots} / {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} elements. + * The gui elements will handle positioning and rendering the slots. + *

+ * As far as splitting a containers slots into multiple groups, Typically the players main inventory and hot bar would be added as two separate groups. + * How you handle the containers slots is up to you, For something like a machine with several spread out slots, + * you can still add all the slots to a single group, then pass each individual slot from the group to a single {@link GuiSlots#singleSlot(GuiParent, ContainerScreenAccess, SlotGroup, int)} element. + * + * @param zoneId Used for quick-move (shift click) operations. Each group has a zone id, and you can specify which zones a group can quick-move to. + * Multiple groups can have the same zone id. Quick move work though the groups in a zone in the order the groups here added. + * @param quickMoveTo List of zones this group can quick-move to. + */ + protected SlotGroup createSlotGroup(int zoneId, int... quickMoveTo) { + SlotGroup group = new SlotGroup(this, zoneId, quickMoveTo); + slotGroups.add(group); + return group; + } + + /** + * Convenience method to create a slot group for player slots. + * Configured to quick-move to {@link #remoteSlotGroup()} groups. + * + * @see #createSlotGroup(int, int[]) + */ + protected SlotGroup playerSlotGroup() { + return createSlotGroup(0, 1); + } + + /** + * Convenience method to create a slot group for the 'other side' of the inventory + * So the Block/tile or whatever this inventory is attached to. + * Configured to quick-move to {@link #playerSlotGroup()} groups. + * + * @see #createSlotGroup(int, int[]) + */ + protected SlotGroup remoteSlotGroup() { + return createSlotGroup(1, 0); + } + + //=== Network ===// + + /** + * Send a packet to the client side container. + * + * @param packetId message id, Can be any value from 0 to 254, 255 is used by the {@link DataSync} system. + * @param packetWriter Use this callback to write your data to the packet. + */ + public void sendPacketToClient(int packetId, Consumer packetWriter) { + if (inventory.player instanceof ServerPlayer serverPlayer) { + var packet = CCLNetwork.GUI_SYNC.toClient(inventory.player); + packet.writeByte(containerId); + packet.writeByte((byte) packetId); + packetWriter.accept(packet); + packet.sendToPlayer(serverPlayer); + } + } + + /** + * Send a packet to the server side container. + * + * @param packetId message id, Can be any value from 0 to 255 + * @param packetWriter Use this callback to write your data to the packet. + */ + public void sendPacketToServer(int packetId, Consumer packetWriter) { + var packet = CCLNetwork.GUI_SYNC.toServer(); + packet.writeByte(containerId); + packet.writeByte((byte) packetId); + packetWriter.accept(packet); + packet.sendToServer(); + } + + public static void handlePacketFromClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + int containerId = packet.readByte(); + int packetId = packet.readByte() & 0xFF; + var player = ctx.player(); + if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { + menu.handlePacketFromClient(packet, ctx, packetId); + } + } + + /** + * Override this in your container menu implementation in order to receive packets sent via {@link #sendPacketToServer(int, Consumer)} + */ + public void handlePacketFromClient(RegistryFriendlyByteBuf packet, IPayloadContext ctx, int packetId) { + + } + + public static void handlePacketFromServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx) { + int containerId = packet.readByte(); + int packetId = packet.readByte() & 0xFF; + var player = ctx.player(); + if (player.containerMenu instanceof ModularGuiContainerMenu menu && menu.containerId == containerId) { + menu.handlePacketFromServer(packet, ctx, packetId); + } + } + + /** + * Override this in your container menu implementation in order to receive packets sent via {@link #sendPacketToServer(int, Consumer)} + *

+ * Don't forget to call super if you plan on using the {@link DataSync} system. + */ + public void handlePacketFromServer(RegistryFriendlyByteBuf packet, IPayloadContext ctx, int packetId) { + if (packetId == 255) { + int index = packet.readByte() & 0xFF; + if (dataSyncs.size() > index) { + dataSyncs.get(index).handleSyncPacket(packet); + } + } + } + + //=== Quick Move ===/// + + /** + * Determines if two @link {@link ItemStack} match and can be merged into a single slot + */ + public static boolean canStacksMerge(ItemStack stack1, ItemStack stack2) { + if (stack1.isEmpty() || stack2.isEmpty()) return false; + return ItemStack.matches(stack1, stack2); + } + + /** + * Transfers to the next zone in order, and will loop around to the lowest zone. + * TODO, Would be nice to have better control over quick-move + * Maybe just the ability to specify which zones each group quick-moves to... + */ + @Override + public ItemStack quickMoveStack(Player player, int slotIndex) { + Slot slot = getSlot(slotIndex); + if (!slot.hasItem()) { + return ItemStack.EMPTY; + } + + SlotGroup group = slotGroupMap.get(slot); + if (group == null) { + return ItemStack.EMPTY; + } + + ItemStack stack = slot.getItem(); + ItemStack result = stack.copy(); + + boolean movedAnything = false; + for (Integer zone : group.quickMoveTo) { + if (!zonedSlots.containsKey(zone)) { + LOGGER.warn("Attempted to quick move to zone id {} but there are no slots assigned to this zone! This is a bug!", zone); + continue; + } + if (moveItemStackTo(stack, zonedSlots.get(zone), false)) { + movedAnything = true; + break; + } + } + + if (!movedAnything) { + return ItemStack.EMPTY; + } + + if (stack.isEmpty()) { + slot.set(ItemStack.EMPTY); + } else { + slot.setChanged(); + } + + slot.onTake(player, stack); + return result; + } + + protected boolean moveItemStackTo(ItemStack stack, List targets, boolean reverse) { + int start = 0; + int end = targets.size(); + boolean moved = false; + int position = start; + if (reverse) { + position = end - 1; + } + + Slot slot; + ItemStack itemStack2; + if (stack.isStackable()) { + while (!stack.isEmpty()) { + if (reverse) { + if (position < start) { + break; + } + } else if (position >= end) { + break; + } + + slot = targets.get(position); + itemStack2 = slot.getItem(); + if (!itemStack2.isEmpty() && ItemStack.isSameItemSameComponents(stack, itemStack2)) { + int l = itemStack2.getCount() + stack.getCount(); + if (l <= Math.min(stack.getMaxStackSize(), slot.getMaxStackSize(stack))) { + stack.setCount(0); + itemStack2.setCount(l); + slot.setChanged(); + moved = true; + } else if (itemStack2.getCount() < Math.min(stack.getMaxStackSize(), slot.getMaxStackSize(stack))) { + stack.shrink(stack.getMaxStackSize() - itemStack2.getCount()); + itemStack2.setCount(stack.getMaxStackSize()); + slot.setChanged(); + moved = true; + } + } + + if (reverse) { + --position; + } else { + ++position; + } + } + } + + if (!stack.isEmpty()) { + if (reverse) { + position = end - 1; + } else { + position = start; + } + + while (true) { + if (reverse) { + if (position < start) { + break; + } + } else if (position >= end) { + break; + } + + slot = targets.get(position); + itemStack2 = slot.getItem(); + if (itemStack2.isEmpty() && slot.mayPlace(stack)) { + if (stack.getCount() > slot.getMaxStackSize(stack)) { + slot.set(stack.split(slot.getMaxStackSize(stack))); + } else { + slot.set(stack.split(stack.getCount())); + } + + slot.setChanged(); + moved = true; + break; + } + + if (reverse) { + --position; + } else { + ++position; + } + } + } + + return moved; + } + + //=== Internal Methods ===// + + public void mapSlot(Slot slot, SlotGroup slotGroup) { + slotGroupMap.put(slot, slotGroup); + zonedSlots.computeIfAbsent(slotGroup.zone, e -> new ArrayList<>()).add(slot); + } + + @Override + public void broadcastChanges() { + super.broadcastChanges(); + dataSyncs.forEach(DataSync::detectAndSend); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java new file mode 100644 index 00000000..cea22da4 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/ModularSlot.java @@ -0,0 +1,132 @@ +package codechicken.lib.inventory.container.modular; + +import net.minecraft.world.Container; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import net.neoforged.neoforge.items.IItemHandler; +import net.neoforged.neoforge.items.SlotItemHandler; +import net.neoforged.neoforge.items.wrapper.InvWrapper; + +import java.util.function.*; + +/** + * A fully configurable inventory slot. + * If there is anything this slot can not do... Let me know. + *

+ * Created by brandon3055 on 10/09/2023 + */ +public class ModularSlot extends SlotItemHandler { + + private boolean canPlace = true; + private boolean checkContainer = true; + private Supplier enabled = () -> true; + private Predicate validator = stack -> true; + private Function stackLimit = stack -> Integer.MAX_VALUE; + private BiPredicate canRemove = (player, stack) -> true; + private BiConsumer onSet = (oldStack, newStack) -> { }; + + public ModularSlot(Container container, int index) { + this(new InvWrapper(container), index, 0, 0); + } + + public ModularSlot(IItemHandler itemHandler, int index) { + this(itemHandler, index, 0, 0); + } + + public ModularSlot(Container container, int index, int xPos, int yPos) { + super(new InvWrapper(container), index, xPos, yPos); + } + + public ModularSlot(IItemHandler itemHandler, int index, int xPos, int yPos) { + super(itemHandler, index, xPos, yPos); + } + + /** + * Configure this slot as an output only slot. + * Items can not be placed in this slot by the player. + */ + public ModularSlot output() { + canPlace = false; + return this; + } + + /** + * Do not use the containers canPlaceItem when checking if an item can be placed. + */ + public ModularSlot noCheck() { + checkContainer = false; + return this; + } + + /** + * Allows you to attach a validator to control what items are allowed in this slot. + * You can also limit a slots allowed contents via the {@link Container#canPlaceItem(int, ItemStack)} method of the container. + * + * @param validator The validator predicate, If the predicate returns false for a stack, the stack will not be placed. + */ + public ModularSlot setValidator(Predicate validator) { + this.validator = validator; + return this; + } + + /** + * Allows you to get a callback when the slot contents are set. + * Parameters given are Old stack then New stack. + */ + public ModularSlot onSet(BiConsumer onSet) { + this.onSet = onSet; + return this; + } + + /** + * Allows you to apply a stack size limit that (if smaller) will override the container and the item stack limits. + */ + public ModularSlot setStackLimit(Function stackLimit) { + this.stackLimit = stackLimit; + return this; + } + + /** + * Allows you to attach a "can remove" predicate that can block removal of a stack from the slot by the player. + */ + public ModularSlot setCanRemove(BiPredicate canRemove) { + this.canRemove = canRemove; + return this; + } + + public ModularSlot setEnabled(Supplier enabled) { + this.enabled = enabled; + return this; + } + + public ModularSlot setEnabled(boolean enabled) { + this.enabled = () -> enabled; + return this; + } + + @Override + public boolean mayPlace(ItemStack itemStack) { + return canPlace && validator.test(itemStack) && (!checkContainer || getItemHandler().isItemValid(getContainerSlot(), itemStack)); + } + + @Override + public boolean mayPickup(Player player) { + return canRemove.test(player, getItem()); + } + + @Override + public void set(ItemStack itemStack) { + onSet.accept(getItem(), itemStack); + super.set(itemStack); + } + + @Override + public boolean isActive() { + return enabled.get(); + } + + @Override + public int getMaxStackSize(ItemStack itemStack) { + return Math.min(super.getMaxStackSize(itemStack), stackLimit.apply(itemStack)); + } +} diff --git a/src/main/java/codechicken/lib/inventory/container/modular/package-info.java b/src/main/java/codechicken/lib/inventory/container/modular/package-info.java new file mode 100644 index 00000000..2f3b2775 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/modular/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container.modular; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/container/package-info.java b/src/main/java/codechicken/lib/inventory/container/package-info.java new file mode 100644 index 00000000..494a5170 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/container/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory.container; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/inventory/package-info.java b/src/main/java/codechicken/lib/inventory/package-info.java new file mode 100644 index 00000000..6bf104e9 --- /dev/null +++ b/src/main/java/codechicken/lib/inventory/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.inventory; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java b/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java deleted file mode 100644 index 8305e01e..00000000 --- a/src/main/java/codechicken/lib/item/SimpleArmorMaterial.java +++ /dev/null @@ -1,156 +0,0 @@ -package codechicken.lib.item; - -import net.minecraft.sounds.SoundEvent; -import net.minecraft.util.LazyLoadedValue; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.ArmorMaterial; -import net.minecraft.world.item.ArmorMaterials; -import net.minecraft.world.item.crafting.Ingredient; - -import java.util.function.Supplier; - -/** - * Created by covers1624 on 14/12/20. - */ -public class SimpleArmorMaterial implements ArmorMaterial { - - private final int[] durability; - private final int[] damageReduction; - private final int enchantability; - private final SoundEvent soundEvent; - private final LazyLoadedValue repairMaterial; - private final String textureName; - private final float toughness; - private final float knockbackResistance; - - public SimpleArmorMaterial(int[] durability, int[] damageReduction, int enchantability, SoundEvent soundEvent, Supplier repairMaterial, String textureName, float toughness, float knockbackResistance) { - this.durability = durability; - this.damageReduction = damageReduction; - this.enchantability = enchantability; - this.soundEvent = soundEvent; - this.repairMaterial = new LazyLoadedValue<>(repairMaterial); - this.textureName = textureName; - this.toughness = toughness; - this.knockbackResistance = knockbackResistance; - } - - public static Builder builder() { - return new Builder(); - } - - @Override - public int getDurabilityForSlot(EquipmentSlot slot) { - return durability[slot.getIndex()]; - } - - @Override - public int getDefenseForSlot(EquipmentSlot slot) { - return damageReduction[slot.getIndex()]; - } - - @Override - public int getEnchantmentValue() { - return enchantability; - } - - @Override - public SoundEvent getEquipSound() { - return soundEvent; - } - - @Override - public Ingredient getRepairIngredient() { - return repairMaterial.get(); - } - - @Override - public String getName() { - return textureName; - } - - @Override - public float getToughness() { - return toughness; - } - - @Override - public float getKnockbackResistance() { - return knockbackResistance; - } - - public static class Builder { - - private final int[] durability = new int[4]; - private final int[] damageReduction = new int[4]; - private int enchantability; - private SoundEvent soundEvent; - private Supplier repairMaterial; - private String textureName; - private float toughness; - private float knockbackResistance; - - private Builder() { - } - - public Builder durability(EquipmentSlot slot, int value) { - durability[slot.getIndex()] = value; - return this; - } - - public Builder durabilityFactor(int factor) { - for (int i = 0; i < 4; i++) { - durability[i] = ArmorMaterials.HEALTH_PER_SLOT[i] * factor; - } - return this; - } - - public Builder durability(int[] durability) { - System.arraycopy(durability, 0, this.durability, 0, 4); - return this; - } - - public Builder damageReduction(EquipmentSlot slot, int value) { - damageReduction[slot.getIndex()] = value; - return this; - } - - public Builder damageReduction(int[] damageReduction) { - System.arraycopy(damageReduction, 0, this.damageReduction, 0, 4); - return this; - } - - public Builder enchantability(int enchantability) { - this.enchantability = enchantability; - return this; - } - - public Builder soundEvent(SoundEvent soundEvent) { - this.soundEvent = soundEvent; - return this; - } - - public Builder repairMaterial(Supplier repairMaterial) { - this.repairMaterial = repairMaterial; - return this; - } - - public Builder textureName(String textureName) { - this.textureName = textureName; - return this; - } - - public Builder toughness(float toughness) { - this.toughness = toughness; - return this; - } - - public Builder knockbackResistance(float knockbackResistance) { - this.knockbackResistance = knockbackResistance; - return this; - } - - public SimpleArmorMaterial build() { - return new SimpleArmorMaterial(durability, damageReduction, enchantability, soundEvent, repairMaterial, textureName, toughness, knockbackResistance); - } - } -} diff --git a/src/main/java/codechicken/lib/item/SimpleItemTier.java b/src/main/java/codechicken/lib/item/SimpleItemTier.java deleted file mode 100644 index 5fbd9ed9..00000000 --- a/src/main/java/codechicken/lib/item/SimpleItemTier.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.item; - -import net.minecraft.util.LazyLoadedValue; -import net.minecraft.world.item.Tier; -import net.minecraft.world.item.crafting.Ingredient; - -import java.util.function.Supplier; - -/** - * Created by covers1624 on 14/12/20. - */ -public class SimpleItemTier implements Tier { - - private final int maxUses; - private final float efficiency; - private final float attackDamage; - private final int harvestLevel; - private final int enchantability; - private final LazyLoadedValue repairMaterial; - - public SimpleItemTier(int maxUses, float efficiency, float attackDamage, int harvestLevel, int enchantability, Supplier repairMaterial) { - this.maxUses = maxUses; - this.efficiency = efficiency; - this.attackDamage = attackDamage; - this.harvestLevel = harvestLevel; - this.enchantability = enchantability; - this.repairMaterial = new LazyLoadedValue<>(repairMaterial); - } - - public static Builder builder() { - return new Builder(); - } - - public static Builder builder(Tier other) { - return builder().from(other); - } - - @Override - public int getUses() { - return maxUses; - } - - @Override - public float getSpeed() { - return efficiency; - } - - @Override - public float getAttackDamageBonus() { - return attackDamage; - } - - @Override - public int getLevel() { - return harvestLevel; - } - - @Override - public int getEnchantmentValue() { - return enchantability; - } - - @Override - public Ingredient getRepairIngredient() { - return repairMaterial.get(); - } - - public static class Builder { - - private int maxUses; - private float efficiency; - private float attackDamage; - private int harvestLevel; - private int enchantability; - private Supplier repairMaterial; - - private Builder() { - } - - public Builder from(Tier other) { - maxUses(other.getUses()); - efficiency(other.getSpeed()); - attackDamage(other.getAttackDamageBonus()); - harvestLevel(other.getLevel()); - enchantability(other.getEnchantmentValue()); - repairMaterial(other::getRepairIngredient); - return this; - } - - public Builder maxUses(int maxUses) { - this.maxUses = maxUses; - return this; - } - - public Builder efficiency(float efficiency) { - this.efficiency = efficiency; - return this; - } - - public Builder attackDamage(float attackDamage) { - this.attackDamage = attackDamage; - return this; - } - - public Builder harvestLevel(int harvestLevel) { - this.harvestLevel = harvestLevel; - return this; - } - - public Builder enchantability(int enchantability) { - this.enchantability = enchantability; - return this; - } - - public Builder repairMaterial(Supplier repairMaterial) { - this.repairMaterial = repairMaterial; - return this; - } - - public SimpleItemTier build() { - return new SimpleItemTier(maxUses, efficiency, attackDamage, harvestLevel, enchantability, repairMaterial); - } - } -} diff --git a/src/main/java/codechicken/lib/math/InterpHelper.java b/src/main/java/codechicken/lib/math/InterpHelper.java index 7c052166..4bdd06a6 100644 --- a/src/main/java/codechicken/lib/math/InterpHelper.java +++ b/src/main/java/codechicken/lib/math/InterpHelper.java @@ -18,21 +18,23 @@ package codechicken.lib.math; +import org.joml.Vector2d; + /** * @author covers1624 */ public class InterpHelper { - private float[][] posCache = new float[4][2]; - private float[] valCache = new float[4]; + private final Vector2d[] posCache = { new Vector2d(), new Vector2d(), new Vector2d(), new Vector2d() }; + private final double[] valCache = new double[4]; - private float x0; - private float x1; - private float y0; - private float y1; + private double x0; + private double x1; + private double y0; + private double y1; - private float rX; - private float rY; + private double rX; + private double rY; private int p00; private int p10; @@ -42,43 +44,27 @@ public class InterpHelper { /** * Resets the interp helper with the given quad. Does not care what order the vertices are in. */ - public void reset(float dx0, float dy0, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { - - float[] vec0 = this.posCache[0]; - float[] vec1 = this.posCache[1]; - float[] vec2 = this.posCache[2]; - float[] vec3 = this.posCache[3]; - - vec0[0] = dx0; - vec1[0] = dx1; - vec2[0] = dx2; - vec3[0] = dx3; - - vec0[1] = dy0; - vec1[1] = dy1; - vec2[1] = dy2; - vec3[1] = dy3; - } + public void reset(double dx0, double dy0, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { + posCache[0].set(dx0, dy0); + posCache[1].set(dx1, dy1); + posCache[2].set(dx2, dy2); + posCache[3].set(dx3, dy3); - /** - * Call when you are ready to use the InterpHelper. - */ - public void setup() { - this.p00 = 0;// Bottom Left is always first. - this.x0 = this.posCache[this.p00][0]; - this.y0 = this.posCache[this.p00][1]; + p00 = 0;// Bottom Left is always first. + x0 = posCache[p00].x; + y0 = posCache[p00].y; for (int i = 1; i < 4; i++) { - float x = this.posCache[i][0]; - float y = this.posCache[i][1]; - if (this.y0 == y) { - this.p10 = i;// Bottom right. - this.x1 = x; - } else if (this.x0 == x) { - this.p01 = i;// Top left. - this.y1 = y; + double x = posCache[i].x; + double y = posCache[i].y; + if (y0 == y) { + p10 = i;// Bottom right. + x1 = x; + } else if (x0 == x) { + p01 = i;// Top left. + y1 = y; } else { // Top right. - this.p11 = i; + p11 = i; } } } @@ -89,9 +75,29 @@ public void setup() { * @param x X interp location. * @param y Y interp location. */ - public void locate(float x, float y) { - this.rX = (x - this.x0) / (this.x1 - this.x0); - this.rY = (y - this.y0) / (this.y1 - this.y0); + public void locate(double x, double y) { + rX = (x - x0) / (x1 - x0); + rY = (y - y0) / (y1 - y0); + } + + /** + * Interpolates using the already computed coefficients. + * + * @param q0 Value at dx0 dy0 + * @param q1 Value at dx1 dy1 + * @param q2 Value at dx2 dy2 + * @param q3 Value at dx3 dy3 + * @return The result. + */ + public double interpolate(double q0, double q1, double q2, double q3) { + valCache[0] = q0; + valCache[1] = q1; + valCache[2] = q2; + valCache[3] = q3; + double f0 = (valCache[p00] * (1 - rX)) + (valCache[p10] * rX); + double f1 = (valCache[p01] * (1 - rX)) + (valCache[p11] * rX); + + return (f0 * (1 - rY)) + (f1 * rY); } /** @@ -104,13 +110,13 @@ public void locate(float x, float y) { * @return The result. */ public float interpolate(float q0, float q1, float q2, float q3) { - this.valCache[0] = q0; - this.valCache[1] = q1; - this.valCache[2] = q2; - this.valCache[3] = q3; - float f0 = (this.valCache[this.p00] * (1 - this.rX)) + (this.valCache[this.p10] * this.rX); - float f1 = (this.valCache[this.p01] * (1 - this.rX)) + (this.valCache[this.p11] * this.rX); + valCache[0] = q0; + valCache[1] = q1; + valCache[2] = q2; + valCache[3] = q3; + double f0 = (valCache[p00] * (1 - rX)) + (valCache[p10] * rX); + double f1 = (valCache[p01] * (1 - rX)) + (valCache[p11] * rX); - return (f0 * (1 - this.rY)) + (f1 * this.rY); + return (float) ((f0 * (1 - rY)) + (f1 * rY)); } } diff --git a/src/main/java/codechicken/lib/math/MathHelper.java b/src/main/java/codechicken/lib/math/MathHelper.java index 7cb2898f..14487d4e 100644 --- a/src/main/java/codechicken/lib/math/MathHelper.java +++ b/src/main/java/codechicken/lib/math/MathHelper.java @@ -3,6 +3,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; +import org.jetbrains.annotations.Nullable; public class MathHelper { @@ -220,7 +221,7 @@ public static float round(float number, float multiplier) { } /** - * @return min <= value <= max + * @return {@code min <= value <= max} */ public static boolean between(double min, double value, double max) { return min <= value && value <= max; @@ -297,29 +298,22 @@ public static int toSide(BlockPos pos) { return side == null ? -1 : side.get3DDataValue(); } - public static Direction getSide(BlockPos pos) { - if (!isAxial(pos)) { - return null; - } - if (pos.getY() < 0) { - return Direction.DOWN; - } - if (pos.getY() > 0) { - return Direction.UP; - } - if (pos.getZ() < 0) { - return Direction.NORTH; - } - if (pos.getZ() > 0) { - return Direction.SOUTH; - } - if (pos.getX() < 0) { - return Direction.WEST; - } - if (pos.getX() > 0) { - return Direction.EAST; - } - + public static @Nullable Direction getSide(BlockPos pos) { + if (!isAxial(pos)) return null; + if (pos.getY() < 0) return Direction.DOWN; + if (pos.getY() > 0) return Direction.UP; + if (pos.getZ() < 0) return Direction.NORTH; + if (pos.getZ() > 0) return Direction.SOUTH; + if (pos.getX() < 0) return Direction.WEST; + if (pos.getX() > 0) return Direction.EAST; return null; } + + public static boolean isInRect(double minX, double minY, double width, double height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } + + public static boolean isInRect(int minX, int minY, int width, int height, double testX, double testY) { + return ((testX >= minX && testX < minX + width) && (testY >= minY && testY < minY + height)); + } } diff --git a/src/main/java/codechicken/lib/math/package-info.java b/src/main/java/codechicken/lib/math/package-info.java new file mode 100644 index 00000000..9ced2de5 --- /dev/null +++ b/src/main/java/codechicken/lib/math/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.math; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/CachedFormat.java b/src/main/java/codechicken/lib/model/CachedFormat.java deleted file mode 100644 index ece442e3..00000000 --- a/src/main/java/codechicken/lib/model/CachedFormat.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model; - -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * A simple VertexFormat cache. - * This caches the existence of attributes and their indexes. - * - * @author covers1624 - */ -public class CachedFormat { - - private static final Map formatCache = new ConcurrentHashMap<>(); - public static final CachedFormat BLOCK = new CachedFormat(DefaultVertexFormat.BLOCK); - - /** - * Lookup or create the CachedFormat for a given VertexFormat. - * - * @param format The format to lookup. - * @return The CachedFormat. - */ - public static CachedFormat lookup(VertexFormat format) { - //Hotwire the common one. - if (format == DefaultVertexFormat.BLOCK) { - return BLOCK; - } - return formatCache.computeIfAbsent(format, CachedFormat::new); - } - - public final VertexFormat format; - - public final boolean hasPosition; - public final boolean hasNormal; - public final boolean hasColor; - public final boolean hasUV; - public final boolean hasOverlay; - public final boolean hasLightMap; - - public final int positionIndex; - public final int normalIndex; - public final int colorIndex; - public final int uvIndex; - public final int overlayIndex; - public final int lightMapIndex; - - public final int elementCount; - - /** - * Caches the vertex format element indexes for efficiency. - * - * @param format The format. - */ - private CachedFormat(VertexFormat format) { - this.format = format; - List elements = format.getElements(); - elementCount = elements.size(); - - boolean hasPosition = false; - boolean hasNormal = false; - boolean hasColor = false; - boolean hasUV = false; - boolean hasOverlay = false; - boolean hasLightMap = false; - - int positionIndex = -1; - int normalIndex = -1; - int colorIndex = -1; - int uvIndex = -1; - int overlayIndex = -1; - int lightMapIndex = -1; - - for (int i = 0; i < elementCount; i++) { - VertexFormatElement element = elements.get(i); - switch (element.getUsage()) { - case POSITION: - if (hasPosition) { - throw new IllegalStateException("Found 2 position elements.."); - } - hasPosition = true; - positionIndex = i; - break; - case NORMAL: - if (hasNormal) { - throw new IllegalStateException("Found 2 normal elements.."); - } - hasNormal = true; - normalIndex = i; - break; - case COLOR: - if (hasColor) { - throw new IllegalStateException("Found 2 color elements.."); - } - hasColor = true; - colorIndex = i; - break; - case UV: - switch (element.getIndex()) { - case 0 -> { - if (hasUV) { - throw new IllegalStateException("Found 2 UV elements.."); - } - hasUV = true; - uvIndex = i; - } - case 1 -> { - if (hasOverlay) { - throw new IllegalStateException("Found 2 Overlay elements.."); - } - hasOverlay = true; - overlayIndex = i; - } - case 2 -> { - if (hasLightMap) { - throw new IllegalStateException("Found 2 LightMap elements.."); - } - hasLightMap = true; - lightMapIndex = i; - } - } - break; - } - } - - this.hasPosition = hasPosition; - this.hasNormal = hasNormal; - this.hasColor = hasColor; - this.hasUV = hasUV; - this.hasOverlay = hasOverlay; - this.hasLightMap = hasLightMap; - - this.positionIndex = positionIndex; - this.normalIndex = normalIndex; - this.colorIndex = colorIndex; - this.uvIndex = uvIndex; - this.overlayIndex = overlayIndex; - this.lightMapIndex = lightMapIndex; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof CachedFormat other)) { - return false; - } - return other.elementCount == elementCount && - other.positionIndex == positionIndex && - other.normalIndex == normalIndex && - other.colorIndex == colorIndex && - other.uvIndex == uvIndex && - other.lightMapIndex == lightMapIndex; - } - - @Override - public int hashCode() { - int result = 1; - result = 31 * result + elementCount; - result = 31 * result + positionIndex; - result = 31 * result + normalIndex; - result = 31 * result + colorIndex; - result = 31 * result + uvIndex; - result = 31 * result + lightMapIndex; - return result; - } -} diff --git a/src/main/java/codechicken/lib/model/DummyBakedModel.java b/src/main/java/codechicken/lib/model/DummyBakedModel.java deleted file mode 100644 index 553cec52..00000000 --- a/src/main/java/codechicken/lib/model/DummyBakedModel.java +++ /dev/null @@ -1,56 +0,0 @@ -package codechicken.lib.model; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; - -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -/** - * Simple dummy model. - * Created by covers1624 on 7/25/2016. - */ -public class DummyBakedModel implements BakedModel { - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public boolean useAmbientOcclusion() { - return false; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return null; - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/DynamicModel.java b/src/main/java/codechicken/lib/model/DynamicModel.java new file mode 100644 index 00000000..f9ce528e --- /dev/null +++ b/src/main/java/codechicken/lib/model/DynamicModel.java @@ -0,0 +1,47 @@ +package codechicken.lib.model; + +import net.covers1624.quack.util.CrashLock; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.ResourceManagerReloadListener; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.neoforge.client.event.AddClientReloadListenersEvent; + +/** + * Created by covers1624 on 7/26/26. + */ +public abstract class DynamicModel { + + private final CrashLock LOCK = new CrashLock("Already Initialized."); + + protected Identifier identifier; + + public DynamicModel(Identifier identifier) { + this.identifier = identifier; + } + + public void register(IEventBus modBus) { + LOCK.lock(); + + modBus.addListener(AddClientReloadListenersEvent.class, event -> event.addListener(identifier, new ReloadListener())); + } + + /** + * Called to reload your model. + * + * @param resourceManager The resource manager. + */ + protected abstract void reload(ResourceManager resourceManager); + + protected void clear() { + } + + private class ReloadListener implements ResourceManagerReloadListener { + + @Override + public void onResourceManagerReload(ResourceManager resourceManager) { + clear(); + DynamicModel.this.reload(resourceManager); + } + } +} diff --git a/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java b/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java new file mode 100644 index 00000000..dc204a18 --- /dev/null +++ b/src/main/java/codechicken/lib/model/DynamicallyBakedModel.java @@ -0,0 +1,46 @@ +package codechicken.lib.model; + +import net.minecraft.client.renderer.block.model.BlockModelPart; +import net.minecraft.resources.Identifier; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * A simple cache around some dynamically loaded model. + *

+ * Created by covers1624 on 7/26/26. + */ +public abstract class DynamicallyBakedModel extends DynamicModel { + + private final Map> parts = new ConcurrentHashMap<>(); + + public DynamicallyBakedModel(Identifier identifier) { + super(identifier); + } + + /** + * Collect this models parts. + * + * @param state The model state. + * @param output The parts to add to. + */ + public final void collect(S state, List output) { + output.addAll(parts.computeIfAbsent(state, this::bake)); + } + + /** + * Called to bake your model into parts. + * + * @param state The state. + * @return The baked parts. + */ + protected abstract List bake(S state); + + @Override + protected void clear() { + super.clear(); + parts.clear(); + } +} diff --git a/src/main/java/codechicken/lib/model/IVertexConsumer.java b/src/main/java/codechicken/lib/model/IVertexConsumer.java deleted file mode 100644 index b53466b1..00000000 --- a/src/main/java/codechicken/lib/model/IVertexConsumer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model; - -import codechicken.lib.util.VertexUtils; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -public interface IVertexConsumer { - - VertexFormat getVertexFormat(); - - void setQuadTint(int tint); - - void setQuadOrientation(Direction orientation); - - void setApplyDiffuseLighting(boolean diffuse); - - void setTexture(TextureAtlasSprite texture); - - void put(int element, float... data); - - /** - * Assumes the data is already completely unpacked. - * You must always copy the data from the quad provided to an internal cache. - * basically: - * this.quad.put(quad); - * - * @param quad The quad to copy data from. - */ - void put(Quad quad); - - default void put(BakedQuad quad) { - VertexUtils.putQuad(this, quad); - } -} diff --git a/src/main/java/codechicken/lib/model/IVertexProducer.java b/src/main/java/codechicken/lib/model/IVertexProducer.java deleted file mode 100644 index 4a6917c9..00000000 --- a/src/main/java/codechicken/lib/model/IVertexProducer.java +++ /dev/null @@ -1,9 +0,0 @@ -package codechicken.lib.model; - -public interface IVertexProducer { - - /** - * @param consumer consumer to receive the vertex data this producer can provide - */ - void pipe(IVertexConsumer consumer); -} diff --git a/src/main/java/codechicken/lib/model/ItemQuadBakery.java b/src/main/java/codechicken/lib/model/ItemQuadBakery.java deleted file mode 100644 index f08628b4..00000000 --- a/src/main/java/codechicken/lib/model/ItemQuadBakery.java +++ /dev/null @@ -1,40 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.util.ArrayUtils; -import codechicken.lib.util.LambdaUtils; -import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.BlockElement; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.resources.ResourceLocation; -import net.minecraftforge.client.model.SimpleModelState; -import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper; - -import java.util.LinkedList; -import java.util.List; - -/** - * Created by covers1624 on 13/02/2017. - */ -public class ItemQuadBakery { - - public static final SimpleModelState IDENTITY = new SimpleModelState(Transformation.identity()); - - public static List bakeItem(TextureAtlasSprite... sprites) { - return bakeItem(IDENTITY, sprites); - } - - public static List bakeItem(ModelState state, TextureAtlasSprite... sprites) { - LambdaUtils.checkArgument(sprites, "Sprites must not be Null or empty!", ArrayUtils::isNullOrContainsNull); - - List quads = new LinkedList<>(); - for (int i = 0; i < sprites.length; i++) { - TextureAtlasSprite sprite = sprites[i]; - List unbaked = UnbakedGeometryHelper.createUnbakedItemElements(i, sprite); - quads.addAll(UnbakedGeometryHelper.bakeElements(unbaked, e -> sprite, state, new ResourceLocation("ccl:dynamic"))); - } - return quads; - } - -} diff --git a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java b/src/main/java/codechicken/lib/model/ModelRegistryHelper.java deleted file mode 100644 index 2f84aeeb..00000000 --- a/src/main/java/codechicken/lib/model/ModelRegistryHelper.java +++ /dev/null @@ -1,76 +0,0 @@ -package codechicken.lib.model; - -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.LinkedList; -import java.util.List; - -public class ModelRegistryHelper { - - private final List> registerModels = new LinkedList<>(); - private final List modelBakePreCallbacks = new LinkedList<>(); - private final List modelBakeCallbacks = new LinkedList<>(); - - public ModelRegistryHelper(IEventBus eventBus) { - eventBus.register(this); - } - - public ModelRegistryHelper() { - FMLJavaModLoadingContext.get().getModEventBus().register(this); - } - - public void registerPreBakeCallback(IModelBakeCallbackPre callback) { - modelBakePreCallbacks.add(callback); - } - - public void registerCallback(IModelBakeCallback callback) { - modelBakeCallbacks.add(callback); - } - - public void register(ModelResourceLocation location, BakedModel model) { - registerModels.add(new ImmutablePair<>(location, model)); - } - - @SubscribeEvent - public void onModelBake(ModelEvent.BakingCompleted event) { - for (IModelBakeCallbackPre callback : modelBakePreCallbacks) { - callback.onModelBakePre(event); - } - - for (Pair pair : registerModels) { - event.getModels().put(pair.getKey(), pair.getValue()); - } - - for (IModelBakeCallback callback : modelBakeCallbacks) { - callback.onModelBake(event); - } - } - - public interface IModelBakeCallbackPre { - - /** - * Called before CCL does anything to the ModelRegistry. - * Useful for wrapped models, Use this in the constructor of the wrapped model. - * - * @param event The Model event. - */ - void onModelBakePre(ModelEvent.BakingCompleted event); - } - - public interface IModelBakeCallback { - - /** - * A Simple callback for model baking. - * - * @param event The Model event. - */ - void onModelBake(ModelEvent.BakingCompleted event); - } -} diff --git a/src/main/java/codechicken/lib/model/PerspectiveModel.java b/src/main/java/codechicken/lib/model/PerspectiveModel.java deleted file mode 100644 index 44e7a6c7..00000000 --- a/src/main/java/codechicken/lib/model/PerspectiveModel.java +++ /dev/null @@ -1,52 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.util.TransformUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Transformation; -import com.mojang.math.Vector3f; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.resources.model.BakedModel; -import org.jetbrains.annotations.Nullable; - -/** - * A simple {@link BakedModel} implementation, with automatic handling of - * {@link PerspectiveModelState}s. - *

- * Created by covers1624 on 9/7/22. - * - * @see TransformUtils - */ -public interface PerspectiveModel extends BakedModel { - - /** - * The {@link PerspectiveModelState} for this model. - * - * @return The state or {@code null} for vanilla behaviour. - */ - @Nullable - PerspectiveModelState getModelState(); - - @Override - default BakedModel applyTransform(ItemTransforms.TransformType transformType, PoseStack pStack, boolean leftFlip) { - PerspectiveModelState modelState = getModelState(); - if (modelState != null) { - Transformation transform = getModelState().getTransform(transformType); - - Vector3f trans = transform.getTranslation(); - pStack.translate(trans.x(), trans.y(), trans.z()); - - pStack.mulPose(transform.getLeftRotation()); - - Vector3f scale = transform.getScale(); - pStack.scale(scale.x(), scale.y(), scale.z()); - - pStack.mulPose(transform.getRightRotation()); - - if (leftFlip) { - TransformUtils.applyLeftyFlip(pStack); - } - return this; - } - return BakedModel.super.applyTransform(transformType, pStack, leftFlip); - } -} diff --git a/src/main/java/codechicken/lib/model/PerspectiveModelState.java b/src/main/java/codechicken/lib/model/PerspectiveModelState.java deleted file mode 100644 index 130edd80..00000000 --- a/src/main/java/codechicken/lib/model/PerspectiveModelState.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.model; - -import codechicken.lib.util.TransformUtils; -import com.google.common.collect.ImmutableMap; -import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; -import net.minecraft.client.resources.model.ModelState; - -import java.util.Map; - -/** - * A simple {@link ModelState} implementation which - * is composed of multiple {@link Transformation}s. - *

- * Created by covers1624 on 9/7/22. - * @see TransformUtils - */ -public class PerspectiveModelState implements ModelState { - - public static final PerspectiveModelState IDENTITY = new PerspectiveModelState(ImmutableMap.of()); - - private final Map transforms; - private final boolean isUvLocked; - - public PerspectiveModelState(Map transforms) { - this(transforms, false); - } - - public PerspectiveModelState(Map transforms, boolean isUvLocked) { - this.transforms = ImmutableMap.copyOf(transforms); - this.isUvLocked = isUvLocked; - } - - public Transformation getTransform(TransformType type) { - return transforms.getOrDefault(type, Transformation.identity()); - } - - @Override - public boolean isUvLocked() { - return isUvLocked; - } -} diff --git a/src/main/java/codechicken/lib/model/Quad.java b/src/main/java/codechicken/lib/model/Quad.java index bd4428d0..0ddd8ad6 100644 --- a/src/main/java/codechicken/lib/model/Quad.java +++ b/src/main/java/codechicken/lib/model/Quad.java @@ -20,35 +20,41 @@ import codechicken.lib.math.InterpHelper; import codechicken.lib.math.MathHelper; -import codechicken.lib.util.VertexUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; +import codechicken.lib.vec.uv.UV; +import net.minecraft.client.model.geom.builders.UVPair; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; import net.minecraft.world.phys.AABB; +import net.neoforged.neoforge.client.model.quad.BakedColors; +import net.neoforged.neoforge.client.model.quad.BakedNormals; +import org.jetbrains.annotations.Nullable; +import org.joml.Vector3fc; + +import static java.util.Objects.requireNonNull; /** - * A simple easy to manipulate quad format. Can be reset and then used on a different format. + * A mutable {@link BakedQuad}. * * @author covers1624 */ -public class Quad implements IVertexProducer, IVertexConsumer { - - public CachedFormat format; - +public class Quad { + + public Vertex[] vertices = { + new Vertex(), + new Vertex(), + new Vertex(), + new Vertex() + }; public int tintIndex = -1; - public Direction orientation; - public boolean diffuseLighting = true; - public TextureAtlasSprite sprite; - - public Vertex[] vertices = new Vertex[4]; - public boolean full; - - // Not copied. - private int vertexIndex = 0; + public @Nullable Direction direction; + public @Nullable TextureAtlasSprite sprite; + public boolean shade = false; + public int lightEmission = 0; + public boolean ambientOcclusion = true; // Cache for normal computation. private final Vector3 v1 = new Vector3(); @@ -56,89 +62,15 @@ public class Quad implements IVertexProducer, IVertexConsumer { private final Vector3 t = new Vector3(); private final Cuboid6 c = new Cuboid6(); - /** - * Use this if you reset the quad each time you use it. - */ public Quad() { } - /** - * use this if you want to initialize the quad with a format. - * - * @param format The format. - */ - public Quad(CachedFormat format) { - this.format = format; - } - - @Override - public VertexFormat getVertexFormat() { - return format.format; - } - - @Override - public void setQuadTint(int tint) { - tintIndex = tint; - } - - @Override - public void setQuadOrientation(Direction orientation) { - this.orientation = orientation; - } - - @Override - public void setApplyDiffuseLighting(boolean diffuse) { - diffuseLighting = diffuse; - } - - @Override - public void setTexture(TextureAtlasSprite texture) { - sprite = texture; - } - - @Override - public void put(int element, float... data) { - if (full) { - throw new RuntimeException("Unable to add data when full."); - } - Vertex v = vertices[vertexIndex]; - if (v == null) { - v = new Vertex(format); - vertices[vertexIndex] = v; - } - System.arraycopy(data, 0, v.raw[element], 0, data.length); - if (element == (format.elementCount - 1)) { - vertexIndex++; - if (vertexIndex == 4) { - vertexIndex = 0; - full = true; - if (orientation == null) { - calculateOrientation(false); - } - } - } - } - - @Override - public void put(Quad quad) { + public Quad(Quad quad) { copyFrom(quad); } - @Override - public void pipe(IVertexConsumer consumer) { - if (consumer instanceof IVertexConsumer) { - ((IVertexConsumer) consumer).put(this); - } else { - consumer.setQuadTint(tintIndex); - consumer.setQuadOrientation(orientation); - consumer.setApplyDiffuseLighting(diffuseLighting); - consumer.setTexture(sprite); - for (Vertex v : vertices) { - for (int e = 0; e < format.elementCount; e++) { - consumer.put(e, v.raw[e]); - } - } - } + public Quad(BakedQuad quad) { + copyFrom(quad); } /** @@ -174,14 +106,92 @@ public void clamp(AABB bb) { */ public void clamp(Cuboid6 cuboid) { for (Vertex vertex : vertices) { - float[] vec = vertex.vec; - vec[0] = (float) MathHelper.clip(vec[0], cuboid.min.x, cuboid.max.x); - vec[1] = (float) MathHelper.clip(vec[1], cuboid.min.y, cuboid.max.y); - vec[2] = (float) MathHelper.clip(vec[2], cuboid.min.z, cuboid.max.z); + vertex.vec.x = MathHelper.clip(vertex.vec.x, cuboid.min.x, cuboid.max.x); + vertex.vec.y = MathHelper.clip(vertex.vec.y, cuboid.min.y, cuboid.max.y); + vertex.vec.z = MathHelper.clip(vertex.vec.z, cuboid.min.z, cuboid.max.z); } calculateOrientation(true); } + /** + * Reinterpolate this quad's UV's and Colors after some transformation. + *

+ * You will have needed to use {@link #resetInterp(InterpHelper, int)} prior + * to your transformations in order for reinterpolation to not output garbage. + * + * @param interp Your interpolation helper. + */ + public void reinterpolate(InterpHelper interp) { + requireNonNull(direction, "Quad must have a direction, side needed to compute dx/dy"); + reinterpolate(interp, direction.ordinal() >> 1); + } + + private void reinterpolate(InterpHelper interp, int side) { + reinterpolateUV(interp, side); + reinterpolateColor(interp, side); + } + + private void reinterpolateUV(InterpHelper interp, int side) { + double u0 = vertices[0].uv.u; + double v0 = vertices[0].uv.v; + + double u1 = vertices[1].uv.u; + double v1 = vertices[1].uv.v; + + double u2 = vertices[2].uv.u; + double v2 = vertices[2].uv.v; + + double u3 = vertices[3].uv.u; + double v3 = vertices[3].uv.v; + + for (int v = 0; v < 4; v++) { + interp.locate(vertices[v].dx(side), vertices[v].dy(side)); + var uv = vertices[v].uv; + uv.set( + interpUV(interp, uv.u, u0, u1, u2, u3), + interpUV(interp, uv.v, v0, v1, v2, v3) + ); + } + } + + private void reinterpolateColor(InterpHelper interp, int side) { + int c0 = vertices[0].color; + int c1 = vertices[1].color; + int c2 = vertices[2].color; + int c3 = vertices[3].color; + + for (int v = 0; v < 4; v++) { + interp.locate(vertices[v].dx(side), vertices[v].dy(side)); + var c = vertices[v].color; + vertices[v].color = ARGB.colorFromFloat( + interpColor(interp, ARGB.alphaFloat(c), + ARGB.alphaFloat(c0), + ARGB.alphaFloat(c1), + ARGB.alphaFloat(c2), + ARGB.alphaFloat(c3) + ), + interpColor(interp, ARGB.redFloat(c), + ARGB.redFloat(c0), + ARGB.redFloat(c1), + ARGB.redFloat(c2), + ARGB.redFloat(c3) + ), + interpColor(interp, ARGB.greenFloat(c), + ARGB.greenFloat(c0), + ARGB.greenFloat(c1), + ARGB.greenFloat(c2), + ARGB.greenFloat(c3) + ), + interpColor(interp, ARGB.blueFloat(c), + ARGB.blueFloat(c0), + ARGB.blueFloat(c1), + ARGB.blueFloat(c2), + ARGB.blueFloat(c3) + ) + ); + } + } + /** * Re-calculates the Orientation of this quad, * optionally the normal vector. @@ -194,143 +204,122 @@ public void calculateOrientation(boolean setNormal) { Vector3 normal = v2.crossProduct(v1).normalize(); - if (format.hasNormal && setNormal) { + if (setNormal) { for (Vertex vertex : vertices) { - vertex.normal[0] = (float) normal.x; - vertex.normal[1] = (float) normal.y; - vertex.normal[2] = (float) normal.z; - vertex.normal[3] = 0; + vertex.normal.set(normal); } } - orientation = Direction.getNearest(normal.x, normal.y, normal.z); + direction = Direction.getApproximateNearest(normal.x, normal.y, normal.z); } /** - * Used to create a new quad complete copy of this one. - * - * @return The new quad. + * @return A complete copy of this quad. */ public Quad copy() { - if (!full) { - throw new RuntimeException("Only copying full quads is supported."); - } - Quad quad = new Quad(format); - quad.tintIndex = tintIndex; - quad.orientation = orientation; - quad.diffuseLighting = diffuseLighting; - quad.sprite = sprite; - quad.full = true; - for (int i = 0; i < 4; i++) { - quad.vertices[i] = vertices[i].copy(); - } - return quad; + return new Quad(this); } /** - * Copies the data inside the given quad to this one. This ignores VertexFormat, please make sure your quads are in - * the same format. + * Copy the data from the given {@link BakedQuad} into this quad. * - * @param quad The Quad to copy from. + * @param quad The {@link BakedQuad} to copy from. * @return This quad. */ - public Quad copyFrom(Quad quad) { - tintIndex = quad.tintIndex; - orientation = quad.orientation; - diffuseLighting = quad.diffuseLighting; - sprite = quad.sprite; - full = quad.full; - for (int v = 0; v < 4; v++) { - for (int e = 0; e < format.elementCount; e++) { - System.arraycopy(quad.vertices[v].raw[e], 0, vertices[v].raw[e], 0, 4); - } + public Quad copyFrom(BakedQuad quad) { + var normals = quad.bakedNormals(); + var colors = quad.bakedColors(); + for (int i = 0; i < 4; i++) { + vertices[i].set( + quad.position(i), + quad.packedUV(i), + normals.normal(i), + colors.color(i) + ); } + tintIndex = quad.tintIndex(); + direction = quad.direction(); + sprite = quad.sprite(); + shade = quad.shade(); + lightEmission = quad.lightEmission(); + ambientOcclusion = quad.hasAmbientOcclusion(); return this; } /** - * Reset the quad to the new format. + * Copies the data from the given {@link Quad} into this quad. * - * @param format The new format. + * @param quad The {@link Quad} to copy from. + * @return This quad. */ - public void reset(CachedFormat format) { - this.format = format; - tintIndex = -1; - orientation = null; - diffuseLighting = true; - sprite = null; + public Quad copyFrom(Quad quad) { for (int i = 0; i < vertices.length; i++) { - Vertex v = vertices[i]; - if (v == null) { - vertices[i] = v = new Vertex(format); - } - v.reset(format); + vertices[i].copyFrom(quad.vertices[i]); } - vertexIndex = 0; - full = false; - } - - /** - * Rewind this Quad without completely resetting it. - */ - public void rewind() { - vertexIndex = 0; - full = false; + tintIndex = quad.tintIndex; + direction = quad.direction; + sprite = quad.sprite; + shade = quad.shade; + lightEmission = quad.lightEmission; + ambientOcclusion = quad.ambientOcclusion; + return this; } /** - * Bakes this Quad to a BakedQuad. + * Bakes this {@link Quad} to a {@link BakedQuad}. * - * @return The BakedQuad. + * @return The {@link BakedQuad}. */ public BakedQuad bake() { - int[] packedData = new int[format.format.getVertexSize()]; - for (int v = 0; v < 4; v++) { - for (int e = 0; e < format.elementCount; e++) { - VertexUtils.pack(vertices[v].raw[e], packedData, format.format, v, e); - } - } - - return makeQuad(packedData); + return new BakedQuad( + vertices[0].vec.vector3f(), + vertices[1].vec.vector3f(), + vertices[2].vec.vector3f(), + vertices[3].vec.vector3f(), + vertices[0].packUV(), + vertices[1].packUV(), + vertices[2].packUV(), + vertices[3].packUV(), + tintIndex, + requireNonNull(direction, "Direction not computed."), + requireNonNull(sprite, "Quad requires a sprite."), + shade, + lightEmission, + BakedNormals.of( + vertices[0].packNormal(), + vertices[1].packNormal(), + vertices[2].packNormal(), + vertices[3].packNormal() + ), + BakedColors.of( + vertices[0].color, + vertices[1].color, + vertices[2].color, + vertices[3].color + ), + ambientOcclusion + ); } - // Broken out as a stub for mixins to target easier. - private BakedQuad makeQuad(int[] packedData) { - if (format.format != DefaultVertexFormat.BLOCK) { - throw new IllegalStateException("Unable to bake this quad to the specified format. " + format.format); - } - return new BakedQuad(packedData, tintIndex, orientation, sprite, diffuseLighting); + private static float interpColor(InterpHelper interp, float orig, float a, float b, float c, float d) { + if (a == b && b == c && c == d) return orig; + + return interp.interpolate(a, b, c, d); } - /** - * A simple vertex format. - */ - public static class Vertex { + private static double interpUV(InterpHelper interp, double orig, double a, double b, double c, double d) { + if (a == b && b == c && c == d) return orig; - public CachedFormat format; + return interp.interpolate(a, b, c, d); + } - /** - * The raw data. - */ - public float[][] raw; + public static class Vertex { - // References to the arrays inside raw. - public float[] vec; - public float[] normal; - public float[] color; - public float[] uv; - public float[] overlay; - public float[] lightmap; + public Vector3 vec = new Vector3(); + public UV uv = new UV(); + public Vector3 normal = new Vector3(); + public int color = 0xFFFFFFFF; - /** - * Create a new Vertex. - * - * @param format The format for the vertex. - */ - public Vertex(CachedFormat format) { - this.format = format; - raw = new float[format.elementCount][4]; - preProcess(); - } + public Vertex() { } /** * Creates a new Vertex using the data inside the other. A copy! @@ -338,37 +327,7 @@ public Vertex(CachedFormat format) { * @param other The other. */ public Vertex(Vertex other) { - format = other.format; - raw = other.raw.clone(); - for (int v = 0; v < format.elementCount; v++) { - raw[v] = other.raw[v].clone(); - } - preProcess(); - } - - /** - * Pulls references to the individual element's arrays inside raw. Modifying the individual element arrays will - * update raw. - */ - public void preProcess() { - if (format.hasPosition) { - vec = raw[format.positionIndex]; - } - if (format.hasNormal) { - normal = raw[format.normalIndex]; - } - if (format.hasColor) { - color = raw[format.colorIndex]; - } - if (format.hasUV) { - uv = raw[format.uvIndex]; - } - if (format.hasOverlay) { - overlay = raw[format.overlayIndex]; - } - if (format.hasLightMap) { - lightmap = raw[format.lightMapIndex]; - } + copyFrom(other); } /** @@ -377,11 +336,11 @@ public void preProcess() { * @param s The axis. side >> 1 * @return The x coord. */ - public float dx(int s) { + public double dx(int s) { if (s <= 1) { - return vec[0]; + return vec.x; } else { - return vec[2]; + return vec.z; } } @@ -391,103 +350,69 @@ public float dx(int s) { * @param s The axis. side >> 1 * @return The y coord. */ - public float dy(int s) { + public double dy(int s) { if (s > 0) { - return vec[1]; + return vec.y; } else { - return vec[2]; + return vec.z; } } /** - * Interpolates the new color values for this Vertex using the others as a reference. + * Copies this Vertex to a new one. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @return The new Vertex. */ - public Vertex interpColorFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 4; e++) { - float p1 = others[0].color[e]; - float p2 = others[1].color[e]; - float p3 = others[2].color[e]; - float p4 = others[3].color[e]; - // Only interpolate if colors are different. - if (p1 != p2 || p2 != p3 || p3 != p4) { - color[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public Vertex copy() { + return new Vertex(this); } /** - * Interpolates the new UV values for this Vertex using the others as a reference. + * Copy the data in the given Vertex into this vertex. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @param other The other vertex. */ - public Vertex interpUVFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 2; e++) { - float p1 = others[0].uv[e]; - float p2 = others[1].uv[e]; - float p3 = others[2].uv[e]; - float p4 = others[3].uv[e]; - if (p1 != p2 || p2 != p3 || p3 != p4) { - uv[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public void copyFrom(Vertex other) { + vec.set(other.vec); + uv.set(other.uv); + normal.set(other.normal); + color = other.color; } /** - * Interpolates the new LightMap values for this Vertex using the others as a reference. + * Set the data in this Vertex from the provided packed data. * - * @param interpHelper The InterpHelper to use. - * @param others The other Vertices to use as a template. - * @return The same Vertex. + * @param vec The vector. + * @param packedUV The packed UV. + * @param packedNormal The packed normals. + * @param packedColor The packed color. */ - public Vertex interpLightMapFrom(InterpHelper interpHelper, Vertex[] others) { - for (int e = 0; e < 2; e++) { - float p1 = others[0].lightmap[e]; - float p2 = others[1].lightmap[e]; - float p3 = others[2].lightmap[e]; - float p4 = others[3].lightmap[e]; - if (p1 != p2 || p2 != p3 || p3 != p4) { - lightmap[e] = interpHelper.interpolate(p1, p2, p3, p4); - } - } - return this; + public void set(Vector3fc vec, long packedUV, int packedNormal, int packedColor) { + this.vec.set(vec); + uv.set( + UVPair.unpackU(packedUV), + UVPair.unpackV(packedUV) + ); + normal.set( + BakedNormals.unpackX(packedNormal), + BakedNormals.unpackY(packedNormal), + BakedNormals.unpackZ(packedNormal) + ); + color = packedColor; } /** - * Copies this Vertex to a new one. - * - * @return The new Vertex. + * @return The UV repacked into a long. */ - public Vertex copy() { - return new Vertex(this); + public long packUV() { + return UVPair.pack((float) uv.u, (float) uv.v); } /** - * Resets the Vertex to a new format. Expands the raw array if needed. - * - * @param format The format to reset to. + * @return The Normals repacked into an int. */ - public void reset(CachedFormat format) { - // If the format is different and our raw array is smaller, then expand it. - if (!this.format.equals(format) && format.elementCount > raw.length) { - raw = new float[format.elementCount][4]; - } - this.format = format; - - vec = null; - normal = null; - color = null; - uv = null; - lightmap = null; - - preProcess(); + public int packNormal() { + return BakedNormals.pack((float) normal.x, (float) normal.y, (float) normal.z); } } } diff --git a/src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java b/src/main/java/codechicken/lib/model/QuadAlphaOverride.java similarity index 61% rename from src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java rename to src/main/java/codechicken/lib/model/QuadAlphaOverride.java index b1ebb01f..58f95981 100644 --- a/src/main/java/codechicken/lib/model/pipeline/IPipelineElementFactory.java +++ b/src/main/java/codechicken/lib/model/QuadAlphaOverride.java @@ -16,13 +16,26 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline; +package codechicken.lib.model; + +import codechicken.lib.colour.Colour; +import codechicken.lib.model.Quad.Vertex; /** + * This transformer simply overrides the alpha of the quad. + * Only operates if the format has color. + * * @author covers1624 */ -@FunctionalInterface -public interface IPipelineElementFactory { +public class QuadAlphaOverride extends QuadTransformer { + + public float alphaOverride; - T create(); + @Override + public boolean transform(Quad quad) { + for (Vertex v : quad.vertices) { + v.color = Colour.replace(v.color, 3, alphaOverride); + } + return true; + } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java b/src/main/java/codechicken/lib/model/QuadClamper.java similarity index 60% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java rename to src/main/java/codechicken/lib/model/QuadClamper.java index 22742a3a..2aea9c5f 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadClamper.java +++ b/src/main/java/codechicken/lib/model/QuadClamper.java @@ -16,41 +16,22 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import codechicken.lib.vec.Cuboid6; import net.minecraft.world.phys.AABB; /** * This transformer simply clamps the vertices inside the provided box. - * You probably want to Re-Interpolate the UV's, Color, and Lmap, see {@link QuadReInterpolator} + * You probably want to Re-Interpolate the UV's, Color, etc, see {@link QuadReInterpolator} * * @author covers1624 */ public class QuadClamper extends QuadTransformer { - public static IPipelineElementFactory FACTORY = QuadClamper::new; - private final Cuboid6 clampBounds = new Cuboid6(); - QuadClamper() { - super(); - } - - public QuadClamper(IVertexConsumer parent, AABB bounds) { - super(parent); - clampBounds.set(bounds); - } - - public QuadClamper(IVertexConsumer parent, Cuboid6 bounds) { - super(parent); - clampBounds.set(bounds); - } - public void setClampBounds(AABB bounds) { clampBounds.set(bounds); } @@ -60,22 +41,23 @@ public void setClampBounds(Cuboid6 bounds) { } @Override - public boolean transform() { - int s = quad.orientation.ordinal() >> 1; + public boolean transform(Quad quad) { + assert quad.direction != null; + int s = quad.direction.ordinal() >> 1; quad.clamp(clampBounds); // Check if the quad would be invisible and cull it. Vertex[] vertices = quad.vertices; - float x1 = vertices[0].dx(s); - float x2 = vertices[1].dx(s); - float x3 = vertices[2].dx(s); - float x4 = vertices[3].dx(s); + double x1 = vertices[0].dx(s); + double x2 = vertices[1].dx(s); + double x3 = vertices[2].dx(s); + double x4 = vertices[3].dx(s); - float y1 = vertices[0].dy(s); - float y2 = vertices[1].dy(s); - float y3 = vertices[2].dy(s); - float y4 = vertices[3].dy(s); + double y1 = vertices[0].dy(s); + double y2 = vertices[1].dy(s); + double y3 = vertices[2].dy(s); + double y4 = vertices[3].dy(s); // These comparisons are safe as we are comparing clamped values. boolean flag1 = x1 == x2 && x2 == x3 && x3 == x4; diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java b/src/main/java/codechicken/lib/model/QuadCornerKicker.java similarity index 75% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java rename to src/main/java/codechicken/lib/model/QuadCornerKicker.java index 265866a0..879a9b3e 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadCornerKicker.java +++ b/src/main/java/codechicken/lib/model/QuadCornerKicker.java @@ -16,11 +16,9 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import net.minecraft.core.Direction; import net.minecraft.core.Direction.AxisDirection; import net.minecraft.core.Vec3i; @@ -43,9 +41,6 @@ */ public class QuadCornerKicker extends QuadTransformer { - // The factory for pipeline creation. - public static final IPipelineElementFactory FACTORY = QuadCornerKicker::new; - // Simple horizonal lookups. public static int[][] horizonals = new int[][] { // Around Y axis, NSWE. @@ -66,10 +61,6 @@ public class QuadCornerKicker extends QuadTransformer { private AABB box; private double thickness; - QuadCornerKicker() { - super(); - } - /** * Set's the side this Facade / Cover is attached to. * @@ -81,7 +72,7 @@ public void setSide(int side) { /** * Sets the bitmask of Facades / Covers in the blockspace. - * This is as simple as, mask = (1 << side) + * This is as simple as, {@code mask = (1 << side)} * * @param mask The mask. */ @@ -111,29 +102,27 @@ public void setThickness(double thickness) { } @Override - public boolean transform() { - int side = quad.orientation.ordinal(); - if (side != mySide && side != (mySide ^ 1)) { - for (int hoz : horizonals[mySide]) { - if (side != hoz && side != (hoz ^ 1)) { - if ((facadeMask & (1 << hoz)) != 0) { - Corner corner = Corner.fromSides(mySide ^ 1, side, hoz); - for (Vertex vertex : quad.vertices) { - float x = vertex.vec[0]; - float y = vertex.vec[1]; - float z = vertex.vec[2]; - if (epsComp(x, corner.pX(box)) && epsComp(y, corner.pY(box)) && epsComp(z, corner.pZ(box))) { - Vec3i vec = Direction.BY_3D_DATA[hoz].getNormal(); - x -= vec.getX() * thickness; - y -= vec.getY() * thickness; - z -= vec.getZ() * thickness; - vertex.vec[0] = x; - vertex.vec[1] = y; - vertex.vec[2] = z; - } - } - } - } + public boolean transform(Quad quad) { + assert quad.direction != null; + int side = quad.direction.ordinal(); + if (side == mySide || side == (mySide ^ 1)) return true; + + for (int hoz : horizonals[mySide]) { + if (side == hoz || side == (hoz ^ 1)) continue; + if ((facadeMask & (1 << hoz)) == 0) continue; + + Corner corner = Corner.fromSides(mySide ^ 1, side, hoz); + for (Vertex vertex : quad.vertices) { + double x = vertex.vec.x; + double y = vertex.vec.y; + double z = vertex.vec.z; + if (!epsComp(x, corner.pX(box)) || !epsComp(y, corner.pY(box)) || !epsComp(z, corner.pZ(box))) continue; + + Vec3i vec = Direction.BY_3D_DATA[hoz].getUnitVec3i(); + x -= vec.getX() * thickness; + y -= vec.getY() * thickness; + z -= vec.getZ() * thickness; + vertex.vec.set(x, y, z); } } diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java b/src/main/java/codechicken/lib/model/QuadFaceStripper.java similarity index 63% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java rename to src/main/java/codechicken/lib/model/QuadFaceStripper.java index c2f67693..dba208f7 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadFaceStripper.java +++ b/src/main/java/codechicken/lib/model/QuadFaceStripper.java @@ -16,12 +16,9 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; import codechicken.lib.vec.Cuboid6; import net.minecraft.core.Direction; import net.minecraft.world.phys.AABB; @@ -29,28 +26,16 @@ import static net.minecraft.core.Direction.AxisDirection.POSITIVE; /** - * This transformer strips quads that are on faces. + * This transformer strips quads that lie exactly on the faces of the provided bounds. * Simply set the bounds for the faces, and the strip mask. * * @author covers1624 */ public class QuadFaceStripper extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadFaceStripper::new; - private final Cuboid6 bounds = new Cuboid6(); private int mask; - QuadFaceStripper() { - super(); - } - - public QuadFaceStripper(IVertexConsumer parent, AABB bounds, int mask) { - super(parent); - this.bounds.set(bounds); - this.mask = mask; - } - /** * The bounds of the faces, * used as the .. bounds, if all vertices of a quad @@ -72,7 +57,7 @@ public void setBounds(AABB bounds) { /** * The mask to strip edges. * This is an opt-in system, - * the mask is simple 'mask = (1 << side)'. + * the mask is simple {@code mask = (1 << side)} * * @param mask The mask. */ @@ -81,37 +66,38 @@ public void setMask(int mask) { } @Override - public boolean transform() { - if (mask == 0) { - return true;// No mask, nothing changes. - } + public boolean transform(Quad quad) { + assert quad.direction != null; + // No mask, nothing changes. + if (mask == 0) return true; + // If the bit for this quad is set, then check if we should strip. - if ((mask & (1 << quad.orientation.ordinal())) != 0) { - Direction.AxisDirection dir = quad.orientation.getAxisDirection(); + if ((mask & (1 << quad.direction.ordinal())) != 0) { + Direction.AxisDirection dir = quad.direction.getAxisDirection(); Vertex[] vertices = quad.vertices; - switch (quad.orientation.getAxis()) { + switch (quad.direction.getAxis()) { case X -> { float bound = (float) (dir == POSITIVE ? bounds.max.x : bounds.min.x); - float x1 = vertices[0].vec[0]; - float x2 = vertices[1].vec[0]; - float x3 = vertices[2].vec[0]; - float x4 = vertices[3].vec[0]; + double x1 = vertices[0].vec.x; + double x2 = vertices[1].vec.x; + double x3 = vertices[2].vec.x; + double x4 = vertices[3].vec.x; return x1 != x2 || x2 != x3 || x3 != x4 || x4 != bound; } case Y -> { float bound = (float) (dir == POSITIVE ? bounds.max.y : bounds.min.y); - float y1 = vertices[0].vec[1]; - float y2 = vertices[1].vec[1]; - float y3 = vertices[2].vec[1]; - float y4 = vertices[3].vec[1]; + double y1 = vertices[0].vec.y; + double y2 = vertices[1].vec.y; + double y3 = vertices[2].vec.y; + double y4 = vertices[3].vec.y; return y1 != y2 || y2 != y3 || y3 != y4 || y4 != bound; } case Z -> { float bound = (float) (dir == POSITIVE ? bounds.max.z : bounds.min.z); - float z1 = vertices[0].vec[2]; - float z2 = vertices[1].vec[2]; - float z3 = vertices[2].vec[2]; - float z4 = vertices[3].vec[2]; + double z1 = vertices[0].vec.z; + double z2 = vertices[1].vec.z; + double z3 = vertices[2].vec.z; + double z4 = vertices[3].vec.z; return z1 != z2 || z2 != z3 || z3 != z4 || z4 != bound; } } diff --git a/src/main/java/codechicken/lib/model/QuadReInterpolator.java b/src/main/java/codechicken/lib/model/QuadReInterpolator.java new file mode 100644 index 00000000..67763216 --- /dev/null +++ b/src/main/java/codechicken/lib/model/QuadReInterpolator.java @@ -0,0 +1,43 @@ +/* + * This file is part of CodeChickenLib. + * Copyright (c) 2018, covers1624, All rights reserved. + * + * CodeChickenLib is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * CodeChickenLib is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with CodeChickenLib. If not, see . + */ + +package codechicken.lib.model; + +import codechicken.lib.math.InterpHelper; + +/** + * Reinterpolates quad properties after vertices have been transformed. + * + * @author covers1624 + */ +public class QuadReInterpolator extends QuadTransformer { + + private final InterpHelper interpHelper = new InterpHelper(); + + @Override + public void beforeTransform(Quad quad) { + assert quad.direction != null; + quad.resetInterp(interpHelper, quad.direction.ordinal() >> 1); + } + + @Override + public boolean transform(Quad quad) { + quad.reinterpolate(interpHelper); + return true; + } +} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java b/src/main/java/codechicken/lib/model/QuadTinter.java similarity index 59% rename from src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java rename to src/main/java/codechicken/lib/model/QuadTinter.java index b2750423..4cea728a 100644 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadTinter.java +++ b/src/main/java/codechicken/lib/model/QuadTinter.java @@ -16,53 +16,35 @@ * along with CodeChickenLib. If not, see . */ -package codechicken.lib.model.pipeline.transformers; +package codechicken.lib.model; -import codechicken.lib.model.IVertexConsumer; import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; +import net.minecraft.util.ARGB; /** * This transformer tints quads.. * Feed it the output of BlockColors.colorMultiplier. + * Colors are in ARGB, Alpha is completely ignored. * Color format: 0000 RRRR GGGG BBBB * * @author covers1624 */ public class QuadTinter extends QuadTransformer { - public static final IPipelineElementFactory FACTORY = QuadTinter::new; - private int tint; - QuadTinter() { - super(); - } - - public QuadTinter(IVertexConsumer consumer, int tint) { - super(consumer); - this.tint = tint; - } - public QuadTinter setTint(int tint) { this.tint = tint; return this; } @Override - public boolean transform() { - // Nuke tintIndex. + public boolean transform(Quad quad) { + if (tint == -1) return true; + quad.tintIndex = -1; - if (format.hasColor) { - float r = (tint >> 0x10 & 0xFF) / 255F; - float g = (tint >> 0x08 & 0xFF) / 255F; - float b = (tint & 0xFF) / 255F; - for (Vertex v : quad.vertices) { - v.color[0] *= r; - v.color[1] *= g; - v.color[2] *= b; - } + for (Vertex v : quad.vertices) { + v.color = ARGB.multiply(v.color, tint | 0xFF000000); } return true; } diff --git a/src/main/java/codechicken/lib/model/QuadTransformer.java b/src/main/java/codechicken/lib/model/QuadTransformer.java new file mode 100644 index 00000000..225223e1 --- /dev/null +++ b/src/main/java/codechicken/lib/model/QuadTransformer.java @@ -0,0 +1,82 @@ +/* + * This file is part of CodeChickenLib. + * Copyright (c) 2018, covers1624, All rights reserved. + * + * CodeChickenLib is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * CodeChickenLib is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with CodeChickenLib. If not, see . + */ + +package codechicken.lib.model; + +import java.util.Arrays; + +/** + * A {@link Quad} transformer. + * + * @author covers1624 + */ +public abstract class QuadTransformer { + + /** + * Transform the given quad. + * + * @param quad The quad to transform. + * @param transformers The transformers to apply. + * @return If the transforms completed. + * {@code false} if the quad should be discarded. + */ + public static boolean transform(Quad quad, QuadTransformer... transformers) { + return transform(quad, Arrays.asList(transformers)); + } + + /** + * Transform the given quad. + * + * @param quad The quad to transform. + * @param transformers The transformers to apply. + * @return If the transforms completed. + * {@code false} if the quad should be discarded. + */ + public static boolean transform(Quad quad, Iterable transformers) { + transformers.forEach(e -> e.beforeTransform(quad)); + + for (QuadTransformer transformer : transformers) { + if (!transformer.transform(quad)) { + return false; // Discarded + } + } + return true; + } + + /** + * Called before any transformation is performed on the quad. + * + * @param quad The quad. + */ + public void beforeTransform(Quad quad) { } + + /** + * Transform the quad. + * + * @return If transformation should continue. + * If {@code false}, the quad will be discarded. + */ + public abstract boolean transform(Quad quad); + + // Should be small enough. + private final static double EPSILON = 0.00001; + + public static boolean epsComp(double a, double b) { + return a == b || Math.abs(a - b) < EPSILON; + } +} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java b/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java deleted file mode 100644 index f0a4ee3c..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/AbstractBakedPropertiesModel.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.PerspectiveModel; -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.render.particle.IModelParticleProvider; -import codechicken.lib.util.VertexUtils; -import codechicken.lib.vec.Vector3; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.common.util.ConcatenatedListView; -import org.jetbrains.annotations.Nullable; - -import javax.annotation.Nonnull; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Created by covers1624 on 1/02/2017. - */ -public abstract class AbstractBakedPropertiesModel implements PerspectiveModel, IModelParticleProvider, BakedModel { - - protected final ModelProperties properties; - - public AbstractBakedPropertiesModel(ModelProperties properties) { - this.properties = properties; - } - - @Override - public boolean useAmbientOcclusion() { - return properties.isAmbientOcclusion(); - } - - @Override - public boolean isGui3d() { - return properties.isGui3d(); - } - - @Override - public boolean isCustomRenderer() { - return properties.isBuiltInRenderer(); - } - - @Override - public boolean usesBlockLight() { - return properties.usesBlockLight(); - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return properties.getParticleTexture(); - } - - protected List getAllQuads(BlockState state, ModelData modelData) { - List> quadsList = new LinkedList<>(); - for (RenderType layer : getRenderTypes(state, RandomSource.create(42), modelData)) { - quadsList.add(getQuads(state, null, RandomSource.create(0), modelData, layer)); - for (Direction face : Direction.BY_3D_DATA) { - quadsList.add(getQuads(state, face, RandomSource.create(0), modelData, layer)); - } - } - return ConcatenatedListView.of(quadsList); - } - - @Override - public Set getHitEffects(@Nonnull BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData) { - Vector3 vec = new Vector3(traceResult.getLocation()).subtract(traceResult.getBlockPos()); - return getAllQuads(state, modelData).stream() - .filter(quad -> quad.getDirection() == traceResult.getDirection()) - .filter(quad -> checkDepth(quad, vec, traceResult.getDirection())) - .map(BakedQuad::getSprite) - .collect(Collectors.toSet()); - } - - protected boolean checkDepth(BakedQuad quad, Vector3 hit, Direction hitFace) { - int[] quadData = quad.getVertices(); - CachedFormat format = CachedFormat.lookup(DefaultVertexFormat.BLOCK); - - Vector3 posVec = new Vector3(); - float[] pos = new float[4]; - for (int v = 0; v < 4; v++) { - VertexUtils.unpack(quadData, pos, format.format, v, format.positionIndex); - posVec.add(pos[0], pos[1], pos[2]); - } - posVec.divide(4); - - double diff = switch (hitFace.getAxis()) { - case X -> Math.abs(hit.x - posVec.x); - case Y -> Math.abs(hit.y - posVec.y); - case Z -> Math.abs(hit.z - posVec.z); - }; - return !(diff > 0.01); - } - - @Override - public Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - return getAllQuads(state, data).stream().map(BakedQuad::getSprite).collect(Collectors.toSet()); - } - - @Nullable - @Override - public PerspectiveModelState getModelState() { - return properties instanceof ModelProperties.PerspectiveProperties props ? props.getTransforms() : null; - } - - @Override - public BakedModel applyTransform(TransformType transformType, PoseStack pStack, boolean leftFlip) { - return PerspectiveModel.super.applyTransform(transformType, pStack, leftFlip); - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java b/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java deleted file mode 100644 index c35eb8df..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/ModelProperties.java +++ /dev/null @@ -1,237 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties.PerspectiveBuilder; -import codechicken.lib.texture.TextureUtils; -import codechicken.lib.util.Copyable; -import codechicken.lib.util.TransformUtils; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; - -import javax.annotation.Nullable; - -/** - * Created by covers1624 on 19/11/2016. - */ -public class ModelProperties implements Copyable { - - public static final ModelProperties DEFAULT_ITEM = ModelProperties.builder() - .withAO(true) - .build(); - public static final ModelProperties DEFAULT_BLOCK = ModelProperties.builder() - .withAO(true) - .withGui3D(true) - .withUsesBlockLight(true) - .build(); - - private final boolean isAO; - private final boolean isGui3D; - private final boolean isBuiltInRenderer; - private final boolean usesBlockLight; - - @Nullable - private TextureAtlasSprite particle; - - private ModelProperties(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, TextureAtlasSprite particle) { - this.isAO = isAO; - this.isGui3D = isGui3D; - this.isBuiltInRenderer = isBuiltInRenderer; - this.usesBlockLight = usesBlockLight; - this.particle = particle; - } - - private ModelProperties(ModelProperties other) { - this.isAO = other.isAO; - this.isGui3D = other.isGui3D; - this.isBuiltInRenderer = other.isBuiltInRenderer; - this.usesBlockLight = other.usesBlockLight; - this.particle = other.particle; - } - - public static ModelProperties fromModel(BakedModel model) { - return new ModelProperties(model.useAmbientOcclusion(), model.isGui3d(), model.usesBlockLight(), model.isCustomRenderer(), model.getParticleIcon()); - } - - public boolean isAmbientOcclusion() { - return isAO; - } - - public boolean isGui3d() { - return isGui3D; - } - - public boolean isBuiltInRenderer() { - return isBuiltInRenderer; - } - - public boolean usesBlockLight() { - return usesBlockLight; - } - - public TextureAtlasSprite getParticleTexture() { - //TODO, Move this to use a ResourceLocation. - if (particle == null) { - particle = TextureUtils.getMissingSprite(); - } - return particle; - } - - @Override - public ModelProperties copy() { - return new ModelProperties(this); - } - - public static Builder builder() { - return new Builder(); - } - - public Builder toBuilder() { - return new Builder(this); - } - - /** - * Created by covers1624 on 21/02/2017. - */ - public static class PerspectiveProperties extends ModelProperties { - - public static final PerspectiveProperties DEFAULT_ITEM = ModelProperties.builder() - .copyFrom(ModelProperties.DEFAULT_ITEM) - .withTransforms(TransformUtils.DEFAULT_ITEM) - .build(); - public static final PerspectiveProperties DEFAULT_BLOCK = ModelProperties.builder() - .copyFrom(ModelProperties.DEFAULT_BLOCK) - .withTransforms(TransformUtils.DEFAULT_BLOCK) - .build(); - - private final PerspectiveModelState transforms; - - private PerspectiveProperties(PerspectiveProperties properties) { - this(properties.getTransforms(), properties); - } - - private PerspectiveProperties(PerspectiveModelState transforms, ModelProperties properties) { - super(properties); - this.transforms = transforms; - } - - public PerspectiveModelState getTransforms() { - return transforms; - } - - @Override - public PerspectiveProperties copy() { - return new PerspectiveProperties(this); - } - - @Override - public PerspectiveBuilder toBuilder() { - return new PerspectiveBuilder(this); - } - - public static class PerspectiveBuilder extends Builder { - - private PerspectiveModelState transforms; - - protected PerspectiveBuilder(PerspectiveProperties properties) { - super(properties); - transforms = properties.transforms; - } - - protected PerspectiveBuilder(Builder builder) { - super(builder.isAO, builder.isAO, builder.usesBlockLight, builder.isBuiltInRenderer, builder.particle); - } - - @Override - public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { - this.transforms = transforms; - return this; - } - - @Override - public PerspectiveProperties build() { - return new PerspectiveProperties(transforms, super.build()); - } - } - } - - public static class Builder { - - private boolean isAO; - private boolean isGui3D; - private boolean isBuiltInRenderer; - private boolean usesBlockLight; - private TextureAtlasSprite particle; - - protected Builder() { - } - - protected Builder(ModelProperties properties) { - isAO = properties.isAO; - isGui3D = properties.isGui3D; - usesBlockLight = properties.usesBlockLight; - isBuiltInRenderer = properties.isBuiltInRenderer; - particle = properties.particle; - } - - protected Builder(boolean isAO, boolean isGui3D, boolean usesBlockLight, boolean isBuiltInRenderer, TextureAtlasSprite particle) { - this.isAO = isAO; - this.isGui3D = isGui3D; - this.usesBlockLight = usesBlockLight; - this.isBuiltInRenderer = isBuiltInRenderer; - this.particle = particle; - } - - public Builder copyFrom(BakedModel model) { - isAO = model.useAmbientOcclusion(); - isGui3D = model.isGui3d(); - usesBlockLight = model.usesBlockLight(); - isBuiltInRenderer = model.isCustomRenderer(); - particle = model.getParticleIcon(); - return this; - } - - public Builder copyFrom(ModelProperties properties) { - isAO = properties.isAO; - isGui3D = properties.isGui3D; - isBuiltInRenderer = properties.isBuiltInRenderer; - particle = properties.particle; - return this; - } - - public Builder withAO(boolean isAO) { - this.isAO = isAO; - return this; - } - - public Builder withGui3D(boolean isGui3D) { - this.isGui3D = isGui3D; - return this; - } - - public Builder withUsesBlockLight(boolean usesBlockLight) { - this.usesBlockLight = usesBlockLight; - return this; - } - - public Builder withBuiltInRenderer(boolean builtInRenderer) { - isBuiltInRenderer = builtInRenderer; - return this; - } - - public Builder withParticle(TextureAtlasSprite sprite) { - particle = sprite; - return this; - } - - public PerspectiveBuilder withTransforms(PerspectiveModelState transforms) { - PerspectiveBuilder builder = new PerspectiveBuilder(this); - builder.withTransforms(transforms); - return builder; - } - - public ModelProperties build() { - return new ModelProperties(isAO, isGui3D, usesBlockLight, isBuiltInRenderer, particle); - } - - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java b/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java deleted file mode 100644 index cb67cfa3..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/OverrideListModel.java +++ /dev/null @@ -1,61 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; - -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -/** - * Created by covers1624 on 29/06/2017. - */ -public class OverrideListModel implements BakedModel { - - private final ItemOverrides overrides; - - public OverrideListModel(ItemOverrides overrides) { - this.overrides = overrides; - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public boolean useAmbientOcclusion() { - return false; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return null; - } - - @Override - public ItemOverrides getOverrides() { - return overrides; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java deleted file mode 100644 index ac87a8b2..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareBakedModel.java +++ /dev/null @@ -1,66 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.List; -import java.util.Map; - -/** - * Created by covers1624 on 25/11/2016. - */ -public class PerspectiveAwareBakedModel extends AbstractBakedPropertiesModel { - - private final ImmutableMap> faceQuads; - private final ImmutableList generalQuads; - - public PerspectiveAwareBakedModel(Map> faceQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(faceQuads, ImmutableList.of(), transforms, properties); - } - - public PerspectiveAwareBakedModel(List generalQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(ImmutableMap.of(), generalQuads, transforms, properties); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, List generalQuads, PerspectiveModelState transforms, ModelProperties properties) { - this(faceQuads, generalQuads, properties.toBuilder().withTransforms(transforms).build()); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, PerspectiveProperties properties) { - this(faceQuads, ImmutableList.of(), properties); - } - - public PerspectiveAwareBakedModel(List generalQuads, PerspectiveProperties properties) { - this(ImmutableMap.of(), generalQuads, properties); - } - - public PerspectiveAwareBakedModel(Map> faceQuads, List generalQuads, PerspectiveProperties properties) { - super(properties); - this.faceQuads = ImmutableMap.copyOf(faceQuads); - this.generalQuads = ImmutableList.copyOf(generalQuads); - } - - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { - if (side == null) { - return generalQuads; - } else { - if (faceQuads.containsKey(side)) { - return faceQuads.get(side); - } - } - return ImmutableList.of(); - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java b/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java deleted file mode 100644 index 79ecec81..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/PerspectiveAwareLayeredModel.java +++ /dev/null @@ -1,70 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import com.google.common.collect.ImmutableMap; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -/** - * Created by covers1624 on 19/11/2016. - */ -public class PerspectiveAwareLayeredModel extends AbstractBakedPropertiesModel { - - private final ImmutableMap> unculledQuads; - private final ImmutableMap>> faceQuads; - private final RenderType generallayer; - private final ChunkRenderTypeSet chunkLayers; - - public PerspectiveAwareLayeredModel(Map>> faceQuads, PerspectiveProperties properties) { - this(faceQuads, ImmutableMap.of(), properties, RenderType.solid()); - } - - public PerspectiveAwareLayeredModel(Map>> faceQuads, Map> unculledQuads, PerspectiveProperties properties, RenderType generallayer) { - super(properties); - this.faceQuads = ImmutableMap.copyOf(faceQuads); - this.unculledQuads = ImmutableMap.copyOf(unculledQuads); - this.generallayer = generallayer; - chunkLayers = ChunkRenderTypeSet.union(ChunkRenderTypeSet.of(faceQuads.keySet()), ChunkRenderTypeSet.of(unculledQuads.keySet())); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand) { - return getQuads(state, side, rand, ModelData.EMPTY, null); - } - - @Override - public List getQuads(@Nullable BlockState state, @Nullable Direction side, RandomSource rand, ModelData data, @Nullable RenderType layer) { - if (layer == null) { - layer = generallayer; - } - if (side == null) { - return unculledQuads.getOrDefault(layer, List.of()); - } - Map> faceQuadMap = faceQuads.get(layer); - if (faceQuadMap != null) { - return faceQuadMap.getOrDefault(side, List.of()); - } - return List.of(); - } - - @Override - public ChunkRenderTypeSet getRenderTypes(@NotNull BlockState state, @NotNull RandomSource rand, @NotNull ModelData data) { - return chunkLayers; - } - - @Override - public ItemOverrides getOverrides() { - return ItemOverrides.EMPTY; - } -} diff --git a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java b/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java deleted file mode 100644 index 9c0172f4..00000000 --- a/src/main/java/codechicken/lib/model/bakedmodels/WrappedItemModel.java +++ /dev/null @@ -1,121 +0,0 @@ -package codechicken.lib.model.bakedmodels; - -import codechicken.lib.util.TransformUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.ItemBlockRenderTypes; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nullable; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.function.Function; - -/** - * A simple wrapper item model. - * Created by covers1624 on 5/07/2017. - */ -public abstract class WrappedItemModel implements BakedModel { - - protected final BakedModel wrapped; - protected final ModelState parentState; - @Nullable - protected LivingEntity entity; - @Nullable - protected ClientLevel world; - - private final ItemOverrides overrideList = new ItemOverrides() { - @Override - public BakedModel resolve(BakedModel originalModel, ItemStack stack, @Nullable ClientLevel world, @Nullable LivingEntity entity, int seed) { - WrappedItemModel.this.entity = entity; - WrappedItemModel.this.world = world == null ? entity == null ? null : (ClientLevel) entity.level : null; - return originalModel; - } - }; - - public WrappedItemModel(BakedModel wrapped) { - this.wrapped = wrapped; - parentState = TransformUtils.stateFromItemTransforms(wrapped.getTransforms()); - } - - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { - return Collections.emptyList(); - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return wrapped.getParticleIcon(); - } - - @Override - public TextureAtlasSprite getParticleIcon(@NotNull ModelData data) { - return wrapped.getParticleIcon(data); - } - - @Override - public ItemOverrides getOverrides() { - return overrideList; - } - - /** - * Render the wrapped model. - *

- * This does not take into account all the special edge cases hardcoded into - * {@link ItemRenderer#render(ItemStack, ItemTransforms.TransformType, boolean, PoseStack, MultiBufferSource, int, int, BakedModel)}. - * - * @param stack The stack. - * @param pStack The pose stack. - * @param buffers The {@link MultiBufferSource}. - * @param packedLight The packed light coords. See {@link LightTexture}. - * @param packedOverlay The packed Overlay coords. See {@link OverlayTexture}. - * @param fabulous If fabulous is required. (not sure on this desc, might be inaccurate as its value in vanilla - * is mixed with the aforementioned hardcoded edge cases.) - */ - protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSource buffers, int packedLight, int packedOverlay, boolean fabulous) { - renderWrapped(stack, pStack, buffers, packedLight, packedOverlay, fabulous, Function.identity()); - } - - /** - * Overload of {@link #renderWrapped(ItemStack, PoseStack, MultiBufferSource, int, int, boolean)}. - *

- * Except, with a callback to wrap the {@link VertexConsumer} used. - * - * @param stack The stack. - * @param pStack The pose stack. - * @param buffers The {@link MultiBufferSource}. - * @param packedLight The packed light coords. See {@link LightTexture}. - * @param packedOverlay The packed Overlay coords. See {@link OverlayTexture}. - * @param fabulous If fabulous is required. (not sure on this desc, might be inaccurate as its value in vanilla - * is mixed with the aforementioned hardcoded edge cases.) - */ - // TODO this needs to be redesigned so other IItemRenderers can be used as override models. - protected void renderWrapped(ItemStack stack, PoseStack pStack, MultiBufferSource buffers, int packedLight, int packedOverlay, boolean fabulous, Function consOverride) { - BakedModel model = wrapped.getOverrides().resolve(wrapped, stack, world, entity, 0); - - ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); - RenderType rType = ItemBlockRenderTypes.getRenderType(stack, fabulous); - VertexConsumer builder = ItemRenderer.getFoilBuffer(buffers, rType, true, stack.hasFoil()); - itemRenderer.renderModelLists(model, stack, packedLight, packedOverlay, pStack, consOverride.apply(builder)); - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java b/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java deleted file mode 100644 index 8f60b461..00000000 --- a/src/main/java/codechicken/lib/model/bakery/CCBakeryModel.java +++ /dev/null @@ -1,99 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.render.particle.IModelParticleProvider; -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; - -import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Created by covers1624 on 26/10/2016. - */ -public class CCBakeryModel implements BakedModel, IModelParticleProvider { - - public CCBakeryModel() { - } - - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand) { - return getQuads(state, side, rand, ModelData.EMPTY, null); - } - - @Nonnull - @Override - public List getQuads(BlockState state, Direction side, RandomSource rand, ModelData modelData, RenderType layer) { - return ModelBakery.getCachedModel(state, modelData).getQuads(state, side, rand, modelData, layer); - } - - @Override - public boolean useAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return false; - } - - @Override - public boolean usesBlockLight() { - return false; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - @Override - public Set getHitEffects(BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - BakedModel model = ModelBakery.getCachedModel(state, data); - if (model instanceof IModelParticleProvider) { - return ((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, data); - } - return Collections.emptySet(); - } - - @Override - public Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data) { - BakedModel model = ModelBakery.getCachedModel(state, data); - if (model instanceof IModelParticleProvider) { - return ((IModelParticleProvider) model).getDestroyEffects(state, world, pos, data); - } - return Collections.emptySet(); - } - - @Override - public ItemOverrides getOverrides() { - return new ItemOverrides() { - @Override - public BakedModel resolve(BakedModel originalModel, ItemStack stack, ClientLevel world, LivingEntity entity, int seed) { - BakedModel model = ModelBakery.getCachedItemModel(stack); - return Objects.requireNonNullElse(model, originalModel); - } - }; - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java b/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java deleted file mode 100644 index 33602f57..00000000 --- a/src/main/java/codechicken/lib/model/bakery/IBakeryProvider.java +++ /dev/null @@ -1,24 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.model.bakery.generation.IBakery; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; - -/** - * Created by covers1624 on 28/10/2016. - * For Blocks, implement this on your block class. - * For Items, implement this on your item class. - */ -public interface IBakeryProvider { - - /** - * Used to provide a bakery for the Item OR Block. - * This should basically always return either ILayeredBlockBakery or ISimpleBlockBakery for blocks or, - * IItemBakery for items. - * - * @return The Bakery! - */ - @OnlyIn (Dist.CLIENT) - IBakery getBakery(); - -} diff --git a/src/main/java/codechicken/lib/model/bakery/ModelBakery.java b/src/main/java/codechicken/lib/model/bakery/ModelBakery.java deleted file mode 100644 index bf5e43cb..00000000 --- a/src/main/java/codechicken/lib/model/bakery/ModelBakery.java +++ /dev/null @@ -1,229 +0,0 @@ -package codechicken.lib.model.bakery; - -import codechicken.lib.model.bakedmodels.ModelProperties; -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import codechicken.lib.model.bakedmodels.PerspectiveAwareBakedModel; -import codechicken.lib.model.bakedmodels.PerspectiveAwareLayeredModel; -import codechicken.lib.model.bakery.generation.IBlockBakery; -import codechicken.lib.model.bakery.generation.IItemBakery; -import codechicken.lib.model.bakery.key.IBlockStateKeyGenerator; -import codechicken.lib.model.bakery.key.IItemStackKeyGenerator; -import codechicken.lib.util.LogUtils; -import codechicken.lib.util.ResourceUtils; -import codechicken.lib.util.TransformUtils; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.event.ModelEvent; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.function.BiFunction; -import java.util.function.Function; - -/** - * Created by covers1624 on 25/10/2016. - */ -@OnlyIn (Dist.CLIENT) -public class ModelBakery { - - private static final Logger logger = LogManager.getLogger(); - - private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("ccl.debugBakeryLogging")); - private static final boolean FORCE_BLOCK_REBAKE = Boolean.parseBoolean(System.getProperty("ccl.debugForceBlockModelRebake")); - private static final boolean FORCE_ITEM_REBAKE = Boolean.parseBoolean(System.getProperty("ccl.debugForceItemModelRebake")); - - private static final Cache keyModelCache = CacheBuilder.newBuilder().expireAfterAccess(30, TimeUnit.MINUTES).build(); - - private static final ModelProperties DEFAULT = ModelProperties.builder() - .withAO(true) - .withGui3D(true) - .build(); - private static final PerspectiveProperties DEFAULT_PERSPECTIVE = DEFAULT.toBuilder() - .withTransforms(TransformUtils.DEFAULT_BLOCK) - .build(); - - private static final Map itemKeyGeneratorMap = Collections.synchronizedMap(new HashMap<>()); - private static final Map blockKeyGeneratorMap = Collections.synchronizedMap(new HashMap<>()); - private static BakedModel missingModel; - - public static final IBlockStateKeyGenerator defaultBlockKeyGenerator = (state, data) -> state.toString(); - - public static final IItemStackKeyGenerator defaultItemKeyGenerator = stack -> ForgeRegistries.ITEMS.getKey(stack.getItem()).toString() + "|" + stack.getDamageValue(); - - public static void init() { - ResourceUtils.registerReloadListener(e -> nukeModelCache()); - FMLJavaModLoadingContext.get().getModEventBus().addListener(ModelBakery::onModelBake); - } - - private static void onModelBake(ModelEvent.BakingCompleted event) { - missingModel = event.getModelManager().getMissingModel(); - } - - public static IBlockStateKeyGenerator getKeyGenerator(Block block) { - if (blockKeyGeneratorMap.containsKey(block)) { - return blockKeyGeneratorMap.get(block); - } - return defaultBlockKeyGenerator; - } - - public static IItemStackKeyGenerator getKeyGenerator(Item item) { - if (itemKeyGeneratorMap.containsKey(item)) { - return itemKeyGeneratorMap.get(item); - } - return defaultItemKeyGenerator; - } - - public static void registerBlockKeyGenerator(Block block, IBlockStateKeyGenerator generator) { - if (blockKeyGeneratorMap.containsKey(block)) { - throw new IllegalArgumentException("Unable to register IBlockStateKeyGenerator as one is already registered for block:" + ForgeRegistries.BLOCKS.getKey(block)); - } - blockKeyGeneratorMap.put(block, generator); - } - - public static void registerItemKeyGenerator(Item item, IItemStackKeyGenerator generator) { - if (itemKeyGeneratorMap.containsKey(item)) { - throw new IllegalArgumentException("Unable to register IItemStackKeyGenerator as one is already registered for item: " + ForgeRegistries.ITEMS.getKey(item)); - } - itemKeyGeneratorMap.put(item, generator); - } - - public static BakedModel getCachedItemModel(ItemStack stack) { - BakedModel model; - IItemStackKeyGenerator generator = getKeyGenerator(stack.getItem()); - String key = generator.generateKey(stack); - model = keyModelCache.getIfPresent(key); - if (model == null || FORCE_ITEM_REBAKE) { - try { - model = timeModelGeneration(ModelBakery::generateItemModel, stack, "ITEM: " + key); - } catch (Throwable t) { - LogUtils.errorOnce(logger, t, "ItemBaking", "Fatal exception thrown whilst baking item model for: " + stack); - return missingModel; - } - if (model != missingModel) { - keyModelCache.put(key, model); - } - } - return model; - - } - - public static BakedModel generateItemModel(ItemStack stack) { - Item item = stack.getItem(); - if (item instanceof IBakeryProvider bakeryProvider) { - - IItemBakery bakery = (IItemBakery) bakeryProvider.getBakery(); - - List unculledQuads = List.copyOf(bakery.bakeItemQuads(null, stack)); - - Map> faceQuads = new HashMap<>(); - for (Direction face : Direction.BY_3D_DATA) { - faceQuads.put(face, List.copyOf(bakery.bakeItemQuads(face, stack))); - } - - PerspectiveProperties properties = bakery.getModelProperties(stack); - return new PerspectiveAwareBakedModel(faceQuads, unculledQuads, properties); - } - return missingModel; - } - - public static BakedModel getCachedModel(BlockState state, ModelData data) { - if (state == null) { - return missingModel; - } - BakedModel model; - IBlockStateKeyGenerator keyGenerator = getKeyGenerator(state.getBlock()); - String key = keyGenerator.generateKey(state, data); - model = keyModelCache.getIfPresent(key); - if (model == null || FORCE_BLOCK_REBAKE) { - try { - model = timeModelGeneration(ModelBakery::generateModel, state, data, "BLOCK: " + key); - } catch (Throwable t) { - LogUtils.errorOnce(logger, t, "BlockBaking", "Fatal exception thrown whilst baking block model for: " + state); - return missingModel; - } - if (model != missingModel) { - keyModelCache.put(key, model); - } - } - return model; - } - - public static BakedModel generateModel(BlockState state, ModelData data) { - if (state.getBlock() instanceof IBakeryProvider bakeryProvider) { - IBlockBakery bakery = (IBlockBakery) bakeryProvider.getBakery(); - ChunkRenderTypeSet layers = bakery.getBlockRenderLayers(); - - Map> unculledQuads = new HashMap<>(); - Map>> culledQuads = new HashMap<>(); - for (RenderType layer : layers) { - unculledQuads.put(layer, List.copyOf(bakery.bakeFace(null, layer, state, data))); - - Map> faceQuadMap = new HashMap<>(); - for (Direction face : Direction.BY_3D_DATA) { - faceQuadMap.put(face, List.copyOf(bakery.bakeFace(face, layer, state, data))); - } - culledQuads.put(layer, faceQuadMap); - - } - return new PerspectiveAwareLayeredModel(culledQuads, unculledQuads, DEFAULT_PERSPECTIVE, RenderType.solid()); - } - return missingModel; - } - - private static R timeModelGeneration(Function func, T thing, String logPostfix) { - if (DEBUG) { - logger.info("Baking Model.. Key: {}", logPostfix); - } - long start = System.nanoTime(); - R ret = func.apply(thing); - long end = System.nanoTime(); - logGenTime(start, end); - return ret; - } - - private static R timeModelGeneration(BiFunction func, T thing, U thing2, String logPostfix) { - if (DEBUG) { - logger.info("Baking Model.. Key: {}", logPostfix); - } - long start = System.nanoTime(); - R ret = func.apply(thing, thing2); - long end = System.nanoTime(); - logGenTime(start, end); - return ret; - } - - private static void logGenTime(long start, long end) { - if (DEBUG) { - long delta = end - start; - long millis = TimeUnit.NANOSECONDS.toMillis(delta); - String s; - if (millis >= 5) { - s = millis + "ms"; - } else { - s = delta + "ns"; - } - - logger.info("Baking finished in {}.", s); - } - } - - public static void nukeModelCache() { - keyModelCache.invalidateAll(); - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java deleted file mode 100644 index c60ccd8d..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IBakery.java +++ /dev/null @@ -1,9 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -/** - * Created by covers1624 on 4/03/2017. - * Just a simple interface to mark things as a bakery. You should never need to implement this yourself. - */ -public interface IBakery { - -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java deleted file mode 100644 index 8107bc12..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IBlockBakery.java +++ /dev/null @@ -1,45 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.ChunkRenderTypeSet; -import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * Created by covers1624 on 28/10/2016. - */ -public interface IBlockBakery extends IItemBakery { - - ChunkRenderTypeSet SOLID = ChunkRenderTypeSet.of(RenderType.solid()); - ChunkRenderTypeSet CUTOUT_MIPPED = ChunkRenderTypeSet.of(RenderType.cutoutMipped()); - ChunkRenderTypeSet CUTOUT = ChunkRenderTypeSet.of(RenderType.cutout()); - ChunkRenderTypeSet TRANSLUCENT = ChunkRenderTypeSet.of(RenderType.translucent()); - - /** - * Gets the layers to generate quads for. - *

- * Please cache these, they are expensive to construct. - * - * @return The {@link ChunkRenderTypeSet}. - */ - ChunkRenderTypeSet getBlockRenderLayers(); - - /** - * Called to generate the quads for a given face, layer, state and model data. - * - * @param face The face quads are requested for, {@code null} for un-culled. - * @param layer The layer quads are requested for. - * @param state The {@link BlockState} of your block - * @param data Any {@link ModelData} your block may have returned. - * @return The quads for the layer or empty. - */ - @OnlyIn (Dist.CLIENT) - List bakeFace(@Nullable Direction face, RenderType layer, BlockState state, ModelData data); -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java b/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java deleted file mode 100644 index 434d586d..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/IItemBakery.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.model.bakery.generation; - -import codechicken.lib.model.bakedmodels.ModelProperties.PerspectiveProperties; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.core.Direction; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * A bakery capable of generating quads for an {@link ItemStack}. - *

- * This is used for regular items and {@link BlockItem}s. - *

- * Created by covers1624 on 12/02/2017. - */ -public interface IItemBakery extends IBakery { - - /** - * Used to generate quads for your {@link ItemStack}. - * - * @param face The face quads are requested for. - * @param stack The stack! - * @return The quads. - */ - @OnlyIn (Dist.CLIENT) - List bakeItemQuads(@Nullable Direction face, ItemStack stack); - - /** - * Return the {@link PerspectiveProperties} for the generated model. - * - * @return The {@link PerspectiveProperties} to use. - */ - @OnlyIn (Dist.CLIENT) - default PerspectiveProperties getModelProperties(ItemStack stack) { - return stack.getItem() instanceof BlockItem ? PerspectiveProperties.DEFAULT_BLOCK : PerspectiveProperties.DEFAULT_ITEM; - } -} diff --git a/src/main/java/codechicken/lib/model/bakery/generation/package-info.java b/src/main/java/codechicken/lib/model/bakery/generation/package-info.java deleted file mode 100644 index 111fca7b..00000000 --- a/src/main/java/codechicken/lib/model/bakery/generation/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -package codechicken.lib.model.bakery.generation; - -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java b/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java deleted file mode 100644 index 7299d235..00000000 --- a/src/main/java/codechicken/lib/model/bakery/key/IBlockStateKeyGenerator.java +++ /dev/null @@ -1,24 +0,0 @@ -package codechicken.lib.model.bakery.key; - -import net.minecraft.world.level.block.state.BlockState; -import net.minecraftforge.client.model.data.ModelData; - -/** - * Created by covers1624 on 26/11/2016. - */ -public interface IBlockStateKeyGenerator { - - /** - * Used to tell the bakery what BlockStates are the same. - * The bakery implementation is global, so make sure you prefix your blocks registry name and meta. - * E.g. "thermalexpansion:machine|6" - * Just remember, this key defines a model in the cache, if a model with the provided key is not found, your bakery will be called to generate one. - *

- * The stack is always as follows CCBakeryModel > Bakery > Gen Key > Hey does this key exist in cache ? ret model : Call block specific bakery to gen model > cache > ret. - * - * @param state - * @return - */ - String generateKey(BlockState state, ModelData modelData); - -} diff --git a/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java b/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java deleted file mode 100644 index 6ec1379c..00000000 --- a/src/main/java/codechicken/lib/model/bakery/key/IItemStackKeyGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -package codechicken.lib.model.bakery.key; - -import net.minecraft.world.item.ItemStack; - -/** - * Created by covers1624 on 2/11/2016. - * This is used so the bakery has some idea of the difference between generated models. - * This is used specifically as the cache key, and is called frequently, Make sure it's well optimized. - */ -public interface IItemStackKeyGenerator { - - /** - * Used to tell the bakery what ItemStacks are the same. - * The bakery implementation is global, so make sure you prefix your blocks registry name and meta. - * E.g. "thermalexpansion:machine|6" - * Just remember, this key defines a model in the cache, if a model with the provided key is not found, your bakery will be called to generate one. - *

- * The stack is always as follows ModelBakery > Bakery > Gen Key > Hey does this key exist in cache ? ret model : Call item specific bakery to gen model > cache > ret. - * - * @param stack The stack to generate a key for. - * @return The uniquely identifiable key for the given stack. - */ - String generateKey(ItemStack stack); - -} diff --git a/src/main/java/codechicken/lib/model/package-info.java b/src/main/java/codechicken/lib/model/package-info.java new file mode 100644 index 00000000..864653ce --- /dev/null +++ b/src/main/java/codechicken/lib/model/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.model; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java b/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java deleted file mode 100644 index bb6415bd..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/BakedPipeline.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.Map; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -/** - * The BakedPipeline! - * Basically this allows us to efficiently transform a BakedQuad, - * the Pipeline has Elements, each element has a name, state and a transformer, - * you can enable and disable elements easily, you can also grab the underlying - * transformer for the element if you need to set its state before rendering. - *

- * The BakedPipeline is final once created, you cannot add or remove elements, - * you should not need to add or remove them runtime, enable and disable exist. - *

- * You must use the Builder class to construct a BakedPipeline, see {@link #builder} - *

- * Transformers run on a mutable state inside each transformer, allowing for easy reuse. - * It is recommended to store your pipeline inside a ThreadLocal because 'minecraft'. - *

- * Each Transformer should be smart enough to expand itself for each newly sized VertexFormat it comes across, - * meaning that the internal states for the transformers can be safely shared across VertexFormats, this reduces - * array creations, and generally makes the system as efficient as it is. - *

- * To use the system: - * Grab any elements you need to set state data on first, using {@link #getElement(String, Class)} - * transformers should NOT clear their state on pipeline Reset's so set any global data on elements now. - * Assuming you are looping over a set of quads to transform, next you need to {@link #reset} the pipeline, - * Now you should disable / enable any optional elements that are needed, NOTE: Element states are reset when resetting - * the pipeline. - * Now you will need to call {@link #prepare(IVertexConsumer)} on the pipeline, here you will pass your collector, - * usually this is some form of {@link BakedQuadBuilder}, or {@link Quad} can also pack things. - * Now final step, simply pipe the quad you want to transform INTO the pipeline 'quad.pipe(pipeline)' - * And that's it! hell, Pipe a pipeline into each other for all i care, the system is efficient enough that there - * would be no performance penalty for doing so. - * - * @author covers1624 - */ -public class BakedPipeline implements IVertexConsumer { - - private final PipelineElement[] elements; - private final Map> nameLookup; - private IPipelineConsumer first; - - private final Quad unpacker = new Quad(); - - private BakedPipeline(PipelineElement[] elements) { - this.elements = elements; - nameLookup = Arrays.stream(elements).collect(Collectors.toMap(e -> e.name, e -> e)); - } - - /** - * Used to create a BakedPipeline. - * - * @return The builder. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset(VertexFormat format) { - reset(CachedFormat.lookup(format)); - } - - /** - * Used to reset the pipeline for the next quad. - * MUST be called between quads. - * - * @param format The format. - */ - public void reset(CachedFormat format) { - unpacker.reset(format); - for (PipelineElement element : elements) { - element.reset(format); - } - first = null; - } - - /** - * Get an element from the pipeline. - * - * @param name The name of the element. - * @param clazz The Class of the element, used to safe cast. - * @return The element. - */ - public T getElement(String name, Class clazz) { - PipelineElement element = nameLookup.get(name); - if (element != null) { - if (!clazz.isAssignableFrom(element.consumer.getClass())) { - throw new IllegalArgumentException("Element with name " + name + " is not assignable from reference class."); - } - return clazz.cast(element.consumer); - } - throw new IllegalArgumentException("Element with name " + name + " does not exist."); - } - - /** - * Used to enable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void enableElement(String name) { - setElementState(name, true); - } - - /** - * Used to disable an element on the pipeline with the specified name. - * - * @param name The elements name. - */ - public void disableElement(String name) { - setElementState(name, false); - } - - /** - * Used to set the state of an element on the pipeline. - * - * @param name The name of the element. - * @param enabled The state to set it to. - */ - public void setElementState(String name, boolean enabled) { - PipelineElement element = nameLookup.get(name); - if (element != null) { - element.isEnabled = enabled; - return; - } - throw new IllegalArgumentException("Element with name " + name + " does not exist."); - } - - /** - * Call when you are ready to use the pipeline. - * This builds the internal state of the Elements getting things ready to transform. - * - * @param collector The IVertexConsumer that should collect the transformed quad. - */ - public void prepare(IVertexConsumer collector) { - IPipelineConsumer next = null; - for (PipelineElement element : elements) { - if (element.isEnabled) { - if (first == null) { - first = element.consumer; - } else { - next.setParent(element.consumer); - } - next = element.consumer; - } - } - next.setParent(collector); - } - - @Override - public VertexFormat getVertexFormat() { - check(); - return first.getVertexFormat(); - } - - @Override - public void setQuadTint(int tint) { - check(); - unpacker.setQuadTint(tint); - } - - @Override - public void setQuadOrientation(Direction orientation) { - check(); - unpacker.setQuadOrientation(orientation); - } - - @Override - public void setApplyDiffuseLighting(boolean diffuse) { - check(); - unpacker.setApplyDiffuseLighting(diffuse); - } - - @Override - public void setTexture(TextureAtlasSprite texture) { - check(); - unpacker.setTexture(texture); - } - - @Override - public void put(int element, float... data) { - check(); - unpacker.put(element, data); - if (unpacker.full) { - onFull(); - } - } - - @Override - public void put(Quad quad) { - check(); - unpacker.put(quad); - } - - private void check() { - if (first == null) { - throw new IllegalStateException("Pipeline used before prepare was called."); - } - } - - private void onFull() { - first.setInputQuad(unpacker); - first.put(unpacker); - } - - /** - * Internal class, used to hold a PipelineElement's state. - */ - public static class PipelineElement { - - public String name; - public boolean defaultState; - public T consumer; - public boolean isEnabled; - - public void reset(CachedFormat format) { - isEnabled = defaultState; - consumer.setParent(null); - consumer.reset(format); - } - } - - /** - * The builder associated with the BakedPipeline. - * You must create a BakedPipeline with this, - * once created a pipeline cannot be modified, - * modifying should not be needed as you can enable - * and disable elements with ease. - */ - public static class Builder { - - private final LinkedList> elements = new LinkedList<>(); - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory) { - return addFirst(name, factory, true); - } - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState) { - return addFirst(name, factory, defaultState, e -> { - }); - } - - /** - * Inserts an element to the front of the list, Useful if you have a more complex system - * and each system need to be independent from each other, but this element must be first. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * @return The same builder. - */ - public Builder addFirst(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { - PipelineElement element = makeElement(name, factory, defaultState); - defaultsSetter.accept(element.consumer); - elements.addFirst(element); - return this; - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory) { - return addElement(name, factory, true); - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState) { - return addElement(name, factory, defaultState, e -> { - }); - } - - /** - * Adds an element at the end of the transform list, Suitable for 99% of cases. - * - * @param name The name to identify this element, used as an identifier when setting state, and retrieving the - * element. - * @param factory The factory used to create the Transformer. - * @param defaultState The default state for this element. - * @param defaultsSetter A callback used to set any defaults on the transformer. - * @return The same builder. - */ - public Builder addElement(String name, IPipelineElementFactory factory, boolean defaultState, Consumer defaultsSetter) { - PipelineElement element = makeElement(name, factory, defaultState); - defaultsSetter.accept(element.consumer); - elements.add(element); - return this; - } - - // Internal method, used to construct the PipelineElement class. - private PipelineElement makeElement(String name, IPipelineElementFactory factory, boolean defaultState) { - if (elements.stream().anyMatch(p -> p.name.equals(name))) { - throw new IllegalArgumentException("Unable to add element with duplicate name: " + name); - } - PipelineElement element = new PipelineElement<>(); - element.name = name; - element.consumer = factory.create(); - element.defaultState = defaultState; - return element; - } - - /** - * Call this once you are finished to build your BakedPipeline! - * - * @return The new Pipeline. - */ - public BakedPipeline build() { - return new BakedPipeline(elements.toArray(new PipelineElement[0])); - } - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java b/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java deleted file mode 100644 index edd5c8d8..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/IPipelineConsumer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import codechicken.lib.model.pipeline.transformers.QuadReInterpolator; - -/** - * Anything implementing this may be used in the BakedPipeline. - * - * @author covers1624 - */ -public interface IPipelineConsumer extends IVertexConsumer { - - /** - * The quad at the start of the transformation. - * This is useful for obtaining the vertex data before any transformations have been applied, - * such as interpolation, See {@link QuadReInterpolator}. - * When overriding this make sure you call setInputQuad on your parent consumer too. - * - * @param quad The quad. - */ - void setInputQuad(Quad quad); - - /** - * Resets the Consumer to the new format. - * This should resize any internal arrays if needed, ready for the new vertex data. - * - * @param format The format to reset to. - */ - void reset(CachedFormat format); - - /** - * Sets the parent consumer. - * This consumer may choose to not pipe any data, - * that's fine, but if it does, it MUST pipe the data to the one provided here. - * - * @param parent The parent. - */ - void setParent(IVertexConsumer parent); -} diff --git a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java b/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java deleted file mode 100644 index eb402930..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/QuadTransformer.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; - -import javax.annotation.OverridingMethodsMustInvokeSuper; - -/** - * Base class for a simple QuadTransformer. - * Operates on BakedQuads. - * QuadTransformers can be piped into each other at no performance penalty. - * - * @author covers1624 - */ -public abstract class QuadTransformer implements IVertexConsumer, IPipelineConsumer { - - protected final Quad quad; - protected CachedFormat format; - protected IVertexConsumer consumer; - - /** - * Used for the BakedPipeline. - */ - protected QuadTransformer() { - quad = new Quad(); - } - - public QuadTransformer(IVertexConsumer consumer) { - this(consumer.getVertexFormat(), consumer); - } - - public QuadTransformer(VertexFormat format, IVertexConsumer consumer) { - this(CachedFormat.lookup(format), consumer); - } - - public QuadTransformer(CachedFormat format, IVertexConsumer consumer) { - this.format = format; - this.consumer = consumer; - quad = new Quad(format); - } - - @Override - @OverridingMethodsMustInvokeSuper - public void reset(CachedFormat format) { - this.format = format; - quad.reset(format); - } - - @Override - public void setParent(IVertexConsumer parent) { - consumer = parent; - } - - @Override - @OverridingMethodsMustInvokeSuper - public void setInputQuad(Quad quad) { - if (consumer instanceof IPipelineConsumer) { - ((IPipelineConsumer) consumer).setInputQuad(quad); - } - } - - // @formatter:off - @Override public VertexFormat getVertexFormat() { return format.format; } - @Override public void setQuadTint( int tint ) { quad.setQuadTint( tint ); } - @Override public void setQuadOrientation( Direction orientation ) { quad.setQuadOrientation( orientation ); } - @Override public void setApplyDiffuseLighting( boolean diffuse ) { quad.setApplyDiffuseLighting( diffuse ); } - @Override public void setTexture( TextureAtlasSprite texture ) { quad.setTexture( texture ); } - // @formatter:on - - @Override - public void put(int element, float... data) { - quad.put(element, data); - if (quad.full) { - onFull(); - } - } - - @Override - public void put(Quad quad) { - this.quad.put(quad); - onFull(); - } - - /** - * Called to transform the vertices. - * - * @return If the transformer should pipe the quad. - */ - public abstract boolean transform(); - - public void onFull() { - if (transform()) { - quad.pipe(consumer); - } - } - - // Should be small enough. - private final static double EPSILON = 0.00001; - - public static boolean epsComp(float a, float b) { - if (a == b) { - return true; - } else { - return Math.abs(a - b) < EPSILON; - } - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java deleted file mode 100644 index 5a99b5f8..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadAlphaOverride.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline.transformers; - -import codechicken.lib.model.IVertexConsumer; -import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; - -/** - * This transformer simply overrides the alpha of the quad. - * Only operates if the format has color. - * - * @author covers1624 - */ -public class QuadAlphaOverride extends QuadTransformer { - - public static final IPipelineElementFactory FACTORY = QuadAlphaOverride::new; - - private float alphaOverride; - - QuadAlphaOverride() { - super(); - } - - public QuadAlphaOverride(IVertexConsumer consumer, float alphaOverride) { - super(consumer); - this.alphaOverride = alphaOverride; - } - - public QuadAlphaOverride setAlphaOverride(float alphaOverride) { - this.alphaOverride = alphaOverride; - return this; - } - - @Override - public boolean transform() { - if (format.hasColor) { - for (Vertex v : quad.vertices) { - v.color[3] = alphaOverride; - } - } - return true; - } -} diff --git a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java b/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java deleted file mode 100644 index 8bb27314..00000000 --- a/src/main/java/codechicken/lib/model/pipeline/transformers/QuadReInterpolator.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of CodeChickenLib. - * Copyright (c) 2018, covers1624, All rights reserved. - * - * CodeChickenLib is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 2.1 of the License, or - * (at your option) any later version. - * - * CodeChickenLib is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with CodeChickenLib. If not, see . - */ - -package codechicken.lib.model.pipeline.transformers; - -import codechicken.lib.math.InterpHelper; -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.Quad; -import codechicken.lib.model.Quad.Vertex; -import codechicken.lib.model.pipeline.IPipelineElementFactory; -import codechicken.lib.model.pipeline.QuadTransformer; - -/** - * This transformer Re-Interpolates the Color, UV's and LightMaps. - * Use this after all transformations that translate vertices in the pipeline. - *

- * This Transformation can only be used in the BakedPipeline. - * - * @author covers1624 - */ -public class QuadReInterpolator extends QuadTransformer { - - public static final IPipelineElementFactory FACTORY = QuadReInterpolator::new; - - private final Quad interpCache = new Quad(); - private final InterpHelper interpHelper = new InterpHelper(); - - QuadReInterpolator() { - super(); - } - - @Override - public void reset(CachedFormat format) { - super.reset(format); - interpCache.reset(format); - } - - @Override - public void setInputQuad(Quad quad) { - super.setInputQuad(quad); - quad.resetInterp(interpHelper, quad.orientation.ordinal() >> 1); - } - - @Override - public boolean transform() { - int s = quad.orientation.ordinal() >> 1; - if (format.hasColor || format.hasUV || format.hasLightMap) { - interpCache.copyFrom(quad); - interpHelper.setup(); - for (Vertex v : quad.vertices) { - interpHelper.locate(v.dx(s), v.dy(s)); - if (format.hasColor) { - v.interpColorFrom(interpHelper, interpCache.vertices); - } - if (format.hasUV) { - v.interpUVFrom(interpHelper, interpCache.vertices); - } - if (format.hasLightMap) { - v.interpLightMapFrom(interpHelper, interpCache.vertices); - } - } - } - return true; - } -} diff --git a/src/main/java/codechicken/lib/package-info.java b/src/main/java/codechicken/lib/package-info.java new file mode 100644 index 00000000..17d58fbd --- /dev/null +++ b/src/main/java/codechicken/lib/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java b/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java new file mode 100644 index 00000000..017b3f8c --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCFriendlyByteBufExtension.java @@ -0,0 +1,130 @@ +package codechicken.lib.packet; + +import codechicken.lib.vec.Cuboid6; +import codechicken.lib.vec.Vector3; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; + +/** + * An extension interface containing various helpers + * for reading and writing to {@link FriendlyByteBuf}. + *

+ * Created by covers1624 on 10/31/25. + * @see FriendlyByteBuf + * @see CCRegistryFriendlyByteBufExtension + */ +public interface CCFriendlyByteBufExtension { + + private FriendlyByteBuf self() { + return (FriendlyByteBuf) this; + } + + // region Signed var primitives. + + /** + * Writes a Signed Variable length int. + * Favourable for numbers {@code <= -1} + * + * @param i The int. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeSignedVarInt(int i) { + SignedVarInt.write(self(), i); + return self(); + } + + /** + * Reads a Variable length signed int. + * + * @return The int. + * @see CCFriendlyByteBufExtension#cc$writeSignedVarInt + */ + default int cc$readSignedVarInt() { + return SignedVarInt.read(self()); + } + + /** + * Writes a Signed Variable length long. + * Favourable for numbers {@code <= -1} + * + * @param i The long. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeSignedVarLong(long i) { + SignedVarLong.write(self(), i); + return self(); + } + + /** + * Reads a Variable length signed long. + * + * @return The long. + * @see CCFriendlyByteBufExtension#cc$writeSignedVarLong + */ + default long cc$readSignedVarLong() { + return SignedVarLong.read(self()); + } + // endregion + + /** + * Write to the stream with a {@link StreamEncoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @param thing The thing to write. + * @return The same stream. + */ + default FriendlyByteBuf cc$writeWithCodec(StreamEncoder codec, T thing) { + codec.encode(self(), thing); + return self(); + } + + /** + * Read from the stream with a {@link StreamDecoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @return The thing that was read. + */ + default T cc$readWithCodec(StreamDecoder codec) { + return codec.decode(self()); + } + + /** + * Write a {@link Vector3} to the stream. + * + * @param vec The vector. + * @return The same stream. + */ + default FriendlyByteBuf writeVector3(Vector3 vec) { + return cc$writeWithCodec(Vector3.STREAM_CODEC, vec); + } + + /** + * Read a {@link Vector3} from the stream. + * + * @return The vector. + */ + default Vector3 readVector3() { + return cc$readWithCodec(Vector3.STREAM_CODEC); + } + + /** + * Write a {@link Cuboid6} to the stream. + * + * @param cuboid The cuboid. + * @return The same stream. + */ + default FriendlyByteBuf writeCuboid6(Cuboid6 cuboid) { + return cc$writeWithCodec(Cuboid6.STREAM_CODEC, cuboid); + } + + /** + * Read a {@link Cuboid6} from the stream. + * + * @return The cuboid. + */ + default Cuboid6 readCuboid6() { + return cc$readWithCodec(Cuboid6.STREAM_CODEC); + } +} diff --git a/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java b/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java new file mode 100644 index 00000000..73aaa4e4 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCRegistryFriendlyByteBufExtension.java @@ -0,0 +1,44 @@ +package codechicken.lib.packet; + +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; + +/** + * An extension interface containing various helpers + * for reading and writing to {@link RegistryFriendlyByteBuf}. + *

+ * Created by covers1624 on 10/31/25. + * + * @see RegistryFriendlyByteBuf + * @see CCFriendlyByteBufExtension + */ +public interface CCRegistryFriendlyByteBufExtension extends CCFriendlyByteBufExtension { + + private RegistryFriendlyByteBuf self() { + return (RegistryFriendlyByteBuf) this; + } + + /** + * Write to the stream with a {@link StreamEncoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @param thing The thing to write. + * @return The same stream. + */ + default RegistryFriendlyByteBuf cc$writeWithRegistryCodec(StreamEncoder codec, T thing) { + codec.encode(self(), thing); + return self(); + } + + /** + * Read from the stream with a {@link StreamDecoder} / {@link StreamCodec}. + * + * @param codec The codec. + * @return The thing that was read. + */ + default T cc$readWithRegistryCodec(StreamDecoder codec) { + return codec.decode(self()); + } +} diff --git a/src/main/java/codechicken/lib/packet/CCStreamCodecs.java b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java new file mode 100644 index 00000000..3f477f9f --- /dev/null +++ b/src/main/java/codechicken/lib/packet/CCStreamCodecs.java @@ -0,0 +1,235 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.Utf8String; +import net.minecraft.network.VarInt; +import net.minecraft.network.VarLong; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class CCStreamCodecs { + + public static final StreamCodec BLOCK_STATE = ByteBufCodecs.idMapper(Block.BLOCK_STATE_REGISTRY); + + public static final StreamCodec BYTE_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + buf.writeBytes(arr); + }, + buf -> { + int len = VarInt.read(buf); + byte[] arr = new byte[len]; + buf.readBytes(arr); + return arr; + } + ); + + public static final StreamCodec CHAR_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (char v : arr) { + buf.writeChar(v); + } + }, + buf -> { + int len = VarInt.read(buf); + char[] arr = new char[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readChar(); + } + return arr; + } + ); + + public static final StreamCodec SHORT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (short v : arr) { + buf.writeShort(v); + } + }, + buf -> { + int len = VarInt.read(buf); + short[] arr = new short[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readShort(); + } + return arr; + } + ); + + public static final StreamCodec INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + buf.writeInt(v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readInt(); + } + return arr; + } + ); + + public static final StreamCodec VAR_INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + VarInt.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = VarInt.read(buf); + } + return arr; + } + ); + + public static final StreamCodec SIGNED_VAR_INT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (int v : arr) { + SignedVarInt.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + int[] arr = new int[len]; + for (int i = 0; i < len; i++) { + arr[i] = SignedVarInt.read(buf); + } + return arr; + } + ); + + public static final StreamCodec LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + buf.writeLong(v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readLong(); + } + return arr; + } + ); + + public static final StreamCodec VAR_LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + VarLong.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = VarLong.read(buf); + } + return arr; + } + ); + + public static final StreamCodec SIGNED_VAR_LONG_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (long v : arr) { + SignedVarLong.write(buf, v); + } + }, + buf -> { + int len = VarInt.read(buf); + long[] arr = new long[len]; + for (int i = 0; i < len; i++) { + arr[i] = SignedVarLong.read(buf); + } + return arr; + } + ); + + public static final StreamCodec FLOAT_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (float v : arr) { + buf.writeFloat(v); + } + }, + buf -> { + int len = VarInt.read(buf); + float[] arr = new float[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readFloat(); + } + return arr; + } + ); + + public static final StreamCodec DOUBLE_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (double v : arr) { + buf.writeDouble(v); + } + }, + buf -> { + int len = VarInt.read(buf); + double[] arr = new double[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readDouble(); + } + return arr; + } + ); + + public static final StreamCodec BOOLEAN_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (boolean v : arr) { + buf.writeBoolean(v); + } + }, + buf -> { + int len = VarInt.read(buf); + boolean[] arr = new boolean[len]; + for (int i = 0; i < len; i++) { + arr[i] = buf.readBoolean(); + } + return arr; + } + ); + + public static final StreamCodec STRING_ARRAY = StreamCodec.of( + (buf, arr) -> { + VarInt.write(buf, arr.length); + for (String v : arr) { + Utf8String.write(buf, v, Short.MAX_VALUE); + } + }, + buf -> { + int len = VarInt.read(buf); + String[] arr = new String[len]; + for (int i = 0; i < len; i++) { + arr[i] = Utf8String.read(buf, Short.MAX_VALUE); + } + return arr; + } + ); +} diff --git a/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java b/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java new file mode 100644 index 00000000..1e6845ce --- /dev/null +++ b/src/main/java/codechicken/lib/packet/ConfigurationStreamPacket.java @@ -0,0 +1,36 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; + +/** + * Created by covers1624 on 10/31/25. + */ +public class ConfigurationStreamPacket extends FriendlyByteBuf implements CustomPacketPayload { + + private final CustomPacketPayload.Type type; + + ConfigurationStreamPacket(CustomPacketPayload.Type type, ByteBuf source) { + super(source); + this.type = type; + } + + public static StreamCodec createCodec(Type type) { + return StreamCodec.of( + (buf, p) -> buf.writeBytes(p, 0, p.writerIndex()), + (buf) -> { + var packet = new ConfigurationStreamPacket(type, Unpooled.buffer(buf.readableBytes())); + buf.readBytes(packet); + return packet; + } + ); + } + + @Override + public Type type() { + return type; + } +} diff --git a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java index ebea637e..078e318f 100644 --- a/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/ICustomPacketHandler.java @@ -1,76 +1,64 @@ package codechicken.lib.packet; import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.network.NetworkEvent; +import net.minecraft.server.network.ConfigurationTask; +import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; +import org.jetbrains.annotations.ApiStatus; -import java.util.function.BiConsumer; -import java.util.function.Supplier; +import java.util.function.Consumer; /** * Created by covers1624 on 2/03/2017. */ +@Deprecated (forRemoval = true) public interface ICustomPacketHandler { + @Deprecated (forRemoval = true) interface IClientPacketHandler extends ICustomPacketHandler { /** * Called on the client to handle a packet sent from the server. * - * @param packet The packet. - * @param mc The Minecraft instance. - * @param handler The ClientPlayNetHandler. + * @param packet The packet. + * @param mc The Minecraft instance. */ - @OnlyIn (Dist.CLIENT) - void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler); + void handlePacket(PacketCustom packet, Minecraft mc); } + @Deprecated (forRemoval = true) interface IServerPacketHandler extends ICustomPacketHandler { /** * Called on the server to handle a packet sent from a client. * - * @param packet The Packet. - * @param sender The player who sent the packet. - * @param handler The ServerPlayNetHandler + * @param packet The Packet. + * @param sender The player who sent the packet. */ - void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler); + void handlePacket(PacketCustom packet, ServerPlayer sender); } - interface ILoginPacketHandler extends ICustomPacketHandler { + /** + * Used with {@link RegisterConfigurationTasksEvent} to send packets to the client during the configuration phase. + */ + @Deprecated (forRemoval = true) + interface IClientConfigurationPacketHandler extends ICustomPacketHandler { /** - * Called on the server to gather all login packets to be sent to the client. - * Unlike usual PacketCustom operation, Login packets are handled differently in FML, - * and require an acknowledgement response to be sent. Login packets must be sent using, - * this. + * Called on the client to handle a configuration phase packet. * - * @param consumer The consumer to accept any packets to be sent, - * The first generic parameter being a descriptive name for the packet used - * in FML logging, the second generic being a supplier used to generate the - * packet. Supplier is used for cleaner scope variable name hiding. + * @param packet The packet. + * @param mc The Minecraft instance. */ - void gatherLoginPackets(BiConsumer> consumer); + void handlePacket(PacketCustom packet, Minecraft mc); + } - /** - * Called on the client to handle a login packet provided through {@link #gatherLoginPackets}. - * This method unlike the other handlers, does not sync to the main thread for processing, instead - * it is fired on the network thread, this is to allow mods to choose if the packet is important - * in the handshake cycle and must be handled before anything else can continue. If the data isn't - * critical to the handshake process, feel free to use {@link NetworkEvent.Context#enqueueWork(Runnable)} - * to throw things on the main thread. - * - * @param packet The packet to handle. - * @param mc The Minecraft instance. - * @param handler Vanilla's NetHandler. - * @param context The network context. - */ - @OnlyIn (Dist.CLIENT) - void handleLoginPacket(PacketCustom packet, Minecraft mc, ClientLoginPacketListener handler, NetworkEvent.Context context); + // TODO this is tricky, as we don't have any context to identify the sending client and have a meaningful back/forth. + // Its likely not incredibly useful for our uses cases here. + @Deprecated (forRemoval = true) + @ApiStatus.Experimental + interface IServerConfigurationPacketHandler extends ICustomPacketHandler { + + void handlePacket(PacketCustom packet, ServerPlayer sender, Consumer onTaskCompleted); } } diff --git a/src/main/java/codechicken/lib/packet/PacketCustom.java b/src/main/java/codechicken/lib/packet/PacketCustom.java index 570aea2d..014e264a 100644 --- a/src/main/java/codechicken/lib/packet/PacketCustom.java +++ b/src/main/java/codechicken/lib/packet/PacketCustom.java @@ -1,180 +1,140 @@ package codechicken.lib.packet; import codechicken.lib.data.MCDataByteBuf; +import codechicken.lib.data.MCDataOutput; import codechicken.lib.math.MathHelper; -import codechicken.lib.util.ServerUtils; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; +import net.minecraft.core.*; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.chat.Component; +import net.minecraft.network.codec.StreamDecoder; +import net.minecraft.network.codec.StreamEncoder; import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.players.ServerOpList; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.network.NetworkDirection; -import net.minecraftforge.registries.IForgeRegistry; -import org.apache.commons.lang3.tuple.Pair; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.network.connection.ConnectionType; +import org.jetbrains.annotations.Nullable; import java.nio.*; import java.util.UUID; -//TODO, Evaluate explicit packet compression again. //Tasty Cheese! +@Deprecated (forRemoval = true) public final class PacketCustom extends MCDataByteBuf { - private final ResourceLocation channel; + private final Identifier channel; + private final boolean inbound; private final int type; + private final @Nullable RegistryAccess registryAccess; - public PacketCustom(ByteBuf payload) { - super(payload); - this.channel = null; - this.type = readUByte(); + PacketCustom(Pkt pkt) { + super(pkt.data, pkt.registryAccess); + channel = pkt.type().id(); + inbound = true; + type = readUByte(); + registryAccess = pkt.registryAccess(); } - public PacketCustom(ResourceLocation channel, int type) { - super(Unpooled.buffer()); + public PacketCustom(Identifier channel, int type, @Nullable RegistryAccess registryAccess) { + super(Unpooled.buffer(), registryAccess); if (!MathHelper.between(0, type, 255)) { throw new RuntimeException("Invalid packet type, Must be between 0 and 255. Got: " + type); } this.channel = channel; + inbound = false; this.type = type; + this.registryAccess = registryAccess; writeByte(type); } - public boolean incoming() { - return channel == null; + public boolean isInbound() { + return inbound; } public int getType() { return type; } - public ResourceLocation getChannel() { + public Identifier getChannel() { return channel; } - public Packet toPacket(NetworkDirection direction) { - return toPacket(direction, 0); - } - - public Packet toPacket(NetworkDirection direction, int index) { - if (incoming()) { - throw new IllegalStateException("Tried to write an incoming packet"); - } - return direction.buildPacket(Pair.of(toPacketBuffer(), index), channel).getThis(); - } - - //endregion - //region Server -> Client. - public void sendToPlayer(ServerPlayer player) { - sendToPlayer(toPacket(NetworkDirection.PLAY_TO_CLIENT), player); - } + public CustomPacketPayload toCustomPayload() { + if (isInbound()) throw new RuntimeException("Unable to send an inbound packet."); - public static void sendToPlayer(Packet packet, ServerPlayer player) { - if (player == null) { - sendToClients(packet); - } else { - player.connection.send(packet); - } + return new Pkt(new CustomPacketPayload.Type<>(channel), registryAccess, toFriendlyByteBuf()); } - public void sendToClients() { - sendToClients(toPacket(NetworkDirection.PLAY_TO_CLIENT)); + // region Server -> Client + public Packet toClientPacket() { + return PacketSender.toClientPacket(toCustomPayload()); } - public static void sendToClients(Packet packet) { - ServerUtils.getServer().getPlayerList().broadcastAll(packet); + public void sendToPlayer(@Nullable ServerPlayer player) { + PacketSender.sendToPlayer(toCustomPayload(), player); } - public void sendPacketToAllAround(BlockPos pos, double range, ResourceKey dim) { - sendPacketToAllAround(pos.getX(), pos.getY(), pos.getZ(), range, dim); + public void sendToAllPlayers() { + PacketSender.sendToAllPlayers(toCustomPayload()); } - public void sendPacketToAllAround(double x, double y, double z, double range, ResourceKey dim) { - sendToAllAround(toPacket(NetworkDirection.PLAY_TO_CLIENT), x, y, z, range, dim); + public void sendToAllAround(BlockPos pos, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toCustomPayload(), pos, range, dim); } - public static void sendToAllAround(Packet packet, double x, double y, double z, double range, ResourceKey dim) { - ServerUtils.getServer().getPlayerList().broadcast(null, x, y, z, range, dim, packet); + public void sendToAllAround(double x, double y, double z, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toCustomPayload(), x, y, z, range, dim); } public void sendToDimension(ResourceKey dim) { - sendToDimension(toPacket(NetworkDirection.PLAY_TO_CLIENT), dim); - } - - public static void sendToDimension(Packet packet, ResourceKey dim) { - ServerUtils.getServer().getPlayerList().broadcastAll(packet, dim); + PacketSender.sendToDimension(toCustomPayload(), dim); } public void sendToChunk(BlockEntity tile) { - sendToChunk(tile.getLevel(), tile.getBlockPos()); - } - - public void sendToChunk(Level world, BlockPos blockPos) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, blockPos); + PacketSender.sendToChunk(toCustomPayload(), tile); } - public void sendToChunk(Level world, int chunkX, int chunkZ) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, chunkX, chunkZ); + public void sendToChunk(ServerLevel level, BlockPos pos) { + PacketSender.sendToChunk(toCustomPayload(), level, pos); } - public void sendToChunk(Level world, ChunkPos pos) { - sendToChunk(toPacket(NetworkDirection.PLAY_TO_CLIENT), world, pos); + public void sendToChunk(ServerLevel level, int chunkX, int chunkZ) { + PacketSender.sendToChunk(toCustomPayload(), level, chunkX, chunkZ); } - public static void sendToChunk(Packet packet, Level world, BlockPos blockPos) { - sendToChunk(packet, world, blockPos.getX() >> 4, blockPos.getZ() >> 4); - } - - public static void sendToChunk(Packet packet, Level world, int chunkX, int chunkZ) { - sendToChunk(packet, world, new ChunkPos(chunkX, chunkZ)); - } - - public static void sendToChunk(Packet packet, Level world, ChunkPos pos) { - ServerLevel serverLevel = (ServerLevel) world; - serverLevel.getChunkSource().chunkMap.getPlayers(pos, false).forEach(e -> e.connection.send(packet)); + public void sendToChunk(ServerLevel level, ChunkPos pos) { + PacketSender.sendToChunk(toCustomPayload(), level, pos); } public void sendToOps() { - sendToOps(toPacket(NetworkDirection.PLAY_TO_CLIENT)); + PacketSender.sendToOps(toCustomPayload()); } + // endregion - public static void sendToOps(Packet packet) { - ServerOpList opList = ServerUtils.getServer().getPlayerList().getOps(); - for (ServerPlayer player : ServerUtils.getServer().getPlayerList().getPlayers()) { - if (opList.get(player.getGameProfile()) != null) { - sendToPlayer(packet, player); - } - } + // region Client -> Server + public Packet toServerPacket() { + return PacketSender.toServerPacket(toCustomPayload()); } - @OnlyIn (Dist.CLIENT) public void sendToServer() { - sendToServer(toPacket(NetworkDirection.PLAY_TO_SERVER)); + PacketSender.sendToServer(toCustomPayload()); } + // endregion - @OnlyIn (Dist.CLIENT) - public static void sendToServer(Packet packet) { - Minecraft.getInstance().getConnection().send(packet); - } - - //endregion //region Machine Generated overrides. //@formatter:off @Override public PacketCustom writeByte(int p0) { super.writeByte(p0); return this; } @@ -221,22 +181,25 @@ public static void sendToServer(Packet packet) { @Override public PacketCustom writeDoubleBuffer(DoubleBuffer buffer) { super.writeDoubleBuffer(buffer); return this; } @Override public PacketCustom writeVector(Vector3 vec) { super.writeVector(vec); return this; } @Override public PacketCustom writeCuboid(Cuboid6 cuboid) { super.writeCuboid(cuboid); return this; } - @Override public PacketCustom writeResourceLocation(ResourceLocation loc) { super.writeResourceLocation(loc); return this; } + @Override public PacketCustom writeResourceLocation(Identifier loc) { super.writeResourceLocation(loc); return this; } @Override public PacketCustom writeDirection(Direction dir) { super.writeDirection(dir); return this; } @Override public PacketCustom writePos(BlockPos pos) { super.writePos(pos); return this; } @Override public PacketCustom writeVec3i(Vec3i vec) { super.writeVec3i(vec); return this; } @Override public PacketCustom writeVec3d(Vec3 vec) { super.writeVec3d(vec); return this; } @Override public PacketCustom writeCompoundNBT(CompoundTag tag) { super.writeCompoundNBT(tag); return this; } + @Override public PacketCustom writeNullableCompoundNBT(@Nullable CompoundTag tag) { super.writeNullableCompoundNBT(tag); return this; } @Override public PacketCustom writeFluidStack(FluidStack stack) { super.writeFluidStack(stack); return this; } @Override public PacketCustom writeItemStack(ItemStack stack) { super.writeItemStack(stack); return this; } - @Override public PacketCustom writeItemStack(ItemStack stack, boolean limitedTag) { super.writeItemStack(stack, limitedTag); return this; } @Override public PacketCustom writeTextComponent(Component component) { super.writeTextComponent(component); return this; } - @Override public PacketCustom writeRegistryIdDirect(IForgeRegistry registry, T entry) { super.writeRegistryIdDirect(registry, entry); return this; } - @Override public PacketCustom writeRegistryIdDirect(IForgeRegistry registry, ResourceLocation entry) { super.writeRegistryIdDirect(registry, entry); return this; } - @Override public PacketCustom writeRegistryId(IForgeRegistry registry, T entry) { super.writeRegistryId(registry, entry); return this; } - @Override public PacketCustom writeRegistryId(IForgeRegistry registry, ResourceLocation entry) { super.writeRegistryId(registry, entry); return this; } + @Override public PacketCustom writeRegistryIdDirect(Registry registry, T entry) { super.writeRegistryIdDirect(registry, entry); return this; } + @Override public PacketCustom writeRegistryIdDirect(Registry registry, Identifier entry) { super.writeRegistryIdDirect(registry, entry); return this; } + @Override public PacketCustom writeRegistryId(Registry registry, T entry) { super.writeRegistryId(registry, entry); return this; } + @Override public PacketCustom writeRegistryId(Registry registry, Identifier entry) { super.writeRegistryId(registry, entry); return this; } @Override public PacketCustom writeByteBuf(ByteBuf buf) { super.writeByteBuf(buf); return this; } @Override public PacketCustom append(ByteBuf buf) { super.append(buf); return this; } - //@formatter:off + //@formatter:on //endregion + + record Pkt(Type type, @Nullable RegistryAccess registryAccess, ByteBuf data) implements CustomPacketPayload { + } } diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannel.java b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java new file mode 100644 index 00000000..c89a6ff8 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/PacketCustomChannel.java @@ -0,0 +1,157 @@ +package codechicken.lib.packet; + +import codechicken.lib.packet.ICustomPacketHandler.IClientConfigurationPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IServerConfigurationPacketHandler; +import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.client.network.event.RegisterClientPayloadHandlersEvent; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import net.neoforged.neoforge.network.registration.HandlerThread; +import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.function.Supplier; + +/** + * Created by covers1624 on 3/7/24. + */ +@Deprecated (forRemoval = true) +public class PacketCustomChannel { + + private static final Logger LOGGER = LoggerFactory.getLogger(PacketCustomChannel.class); + + public final Identifier channel; + + private @Nullable String version; + private boolean optional; + private @Nullable IClientConfigurationPacketHandler clientConfiguration; + private @Nullable IServerConfigurationPacketHandler serverConfiguration; + + private @Nullable IClientPacketHandler client; + private @Nullable IServerPacketHandler server; + + public PacketCustomChannel(Identifier channel) { + this.channel = channel; + } + + public PacketCustomChannel versioned(String version) { + this.version = version; + return this; + } + + public PacketCustomChannel optional() { + optional = true; + return this; + } + + public PacketCustomChannel clientConfiguration(Supplier> supplier) { + if (FMLEnvironment.getDist().isClient()) { + clientConfiguration = supplier.get().get(); + } + return this; + } + + // TODO +// public PacketCustomChannel serverConfiguration(Supplier> supplier) { +// serverConfiguration = supplier.get().get(); +// return this; +// } + + public PacketCustomChannel client(Supplier> supplier) { + if (FMLEnvironment.getDist().isClient()) { + client = supplier.get().get(); + } + return this; + } + + public PacketCustomChannel server(Supplier> supplier) { + server = supplier.get().get(); + return this; + } + + public void init(IEventBus modBus) { + modBus.addListener(this::onRegisterPayloadHandlerEvent); + if (FMLEnvironment.getDist().isClient()) { + modBus.addListener(this::onRegisterClientPayloads); + } + } + + private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event) { + PayloadRegistrar registrar = event.registrar(channel.getNamespace()); + + if (optional) registrar = registrar.optional(); + if (version != null) registrar = registrar.versioned(version); + registrar = registrar.executesOn(HandlerThread.NETWORK); + + CustomPacketPayload.Type type = new CustomPacketPayload.Type<>(channel); + StreamCodec codec = StreamCodec.of( + (buf, p) -> buf.writeBytes(p.data(), 0, p.data().writerIndex()), + buf -> { + RegistryAccess access = buf instanceof RegistryFriendlyByteBuf b ? b.registryAccess() : null; + return new PacketCustom.Pkt(type, access, buf.readBytes(buf.readableBytes())); + } + ); + registrar.playBidirectional( + type, + codec, + (payload, context) -> { + if (server != null) { + enqueue(context, payload, () -> { + server.handlePacket(new PacketCustom(payload), (ServerPlayer) context.player()); + }); + } + } + ); + registrar.configurationToClient( + new CustomPacketPayload.Type<>(channel.withPrefix("configuration/")), + codec, + (payload, context) -> { + if (clientConfiguration != null) { + enqueue(context, payload, () -> { + clientConfiguration.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + } + ); + } + + private void onRegisterClientPayloads(RegisterClientPayloadHandlersEvent event) { + event.register( + new CustomPacketPayload.Type(channel), + HandlerThread.NETWORK, + (payload, context) -> { + if (client != null) { + enqueue(context, payload, () -> { + client.handlePacket(new PacketCustom(payload), Minecraft.getInstance()); + }); + } + } + ); + } + + private static void enqueue(IPayloadContext context, PacketCustom.Pkt payload, Runnable runnable) { + context.enqueueWork(() -> { + try { + runnable.run(); + } finally { + payload.data().release(); + } + }).exceptionally(ex -> { + LOGGER.error("Error processing packet on channel {}", payload.type().id(), ex); + return null; + }); + } +} diff --git a/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java b/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java deleted file mode 100644 index db032ec4..00000000 --- a/src/main/java/codechicken/lib/packet/PacketCustomChannelBuilder.java +++ /dev/null @@ -1,282 +0,0 @@ -package codechicken.lib.packet; - -import codechicken.lib.packet.ICustomPacketHandler.IClientPacketHandler; -import codechicken.lib.packet.ICustomPacketHandler.ILoginPacketHandler; -import codechicken.lib.packet.ICustomPacketHandler.IServerPacketHandler; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.PacketListener; -import net.minecraft.network.protocol.login.ClientLoginPacketListener; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.network.NetworkEvent; -import net.minecraftforge.network.NetworkRegistry; -import net.minecraftforge.network.event.EventNetworkChannel; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.function.Predicate; -import java.util.function.Supplier; - -import static net.covers1624.quack.util.SneakyUtils.trueP; - -/** - * Used to build a network channel for use with {@link PacketCustom}. - * Similar in design to {@link NetworkRegistry.ChannelBuilder}. - *

- * Created by covers1624 on 28/10/19. - */ -public class PacketCustomChannelBuilder { - - private static final Logger LOGGER = LogManager.getLogger(); - - private static final Supplier CONST_1 = () -> "1"; - - private final NetworkRegistry.ChannelBuilder parent; - private final ResourceLocation channelName; - - private Supplier networkProtocolVersion = CONST_1; - private Predicate clientAcceptedVersions = trueP(); - private Predicate serverAcceptedVersions = trueP(); - - private IClientPacketHandler clientHandler; - private IServerPacketHandler serverHandler; - private ILoginPacketHandler loginHandler; - - private PacketCustomChannelBuilder(ResourceLocation channelName) { - this.channelName = channelName; - parent = NetworkRegistry.ChannelBuilder.named(channelName); - } - - /** - * Create a new {@link PacketCustomChannelBuilder} with the given channel name. - * Channel names are global and must be unique per mod. Just use this format: - * "mod_id:network_name". For example: 'codechickenlib:internal' - * - * @param channelName The Channel name. - * @return The builder. - */ - public static PacketCustomChannelBuilder named(ResourceLocation channelName) { - return new PacketCustomChannelBuilder(channelName); - } - - /** - * Register a Supplier that provides the protocol version associated with this channel. - * You are able to compare this value each side of the connection against its local version, - * if you wish to talk across protocol versions. The default is to provide '1' as the version. - * - * @param networkProtocolVersion The version Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder networkProtocolVersion(Supplier networkProtocolVersion) { - this.networkProtocolVersion = networkProtocolVersion; - return this; - } - - /** - * Register a Predicate to check the Server side protocol version on the Client. The - * default will accept any remote versions. - * - * @param clientAcceptedVersions The Predicate. - * @return The same builder. - */ - public PacketCustomChannelBuilder clientAcceptedVersions(Predicate clientAcceptedVersions) { - this.clientAcceptedVersions = clientAcceptedVersions; - return this; - } - - /** - * Register a Predicate to check the Client side protocol version on the Server. The - * default will accept any remote versions. - * - * @param serverAcceptedVersions The Predicate. - * @return The same builder. - */ - public PacketCustomChannelBuilder serverAcceptedVersions(Predicate serverAcceptedVersions) { - this.serverAcceptedVersions = serverAcceptedVersions; - return this; - } - - /** - * Register a double Supplier, to construct the {@link IClientPacketHandler} for the client side. - * The double Supplier is used to avoid class loading issues on the server side, you do NOT - * need any external sided checks if you call using the following example: - *
- * builder.assignClientHandler(() -> ClientPacketHandler::new); - *

- * - * @param clientHandler The Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder assignClientHandler(Supplier> clientHandler) { - if (FMLEnvironment.dist == Dist.CLIENT) { - this.clientHandler = clientHandler.get().get(); - } - return this; - } - - /** - * Register a double Supplier, to construct the {@link IServerPacketHandler} for the client side. - * The double Supplier is used to avoid confusion with {@link #assignClientHandler}. - * Example usage: builder.assignClientHandler(() -> ServerPacketHandler::new); - * - * @param serverHandler The Supplier. - * @return The same builder. - */ - - public PacketCustomChannelBuilder assignServerHandler(Supplier> serverHandler) { - this.serverHandler = serverHandler.get().get(); - return this; - } - - /** - * Register a double Supplier, to construct the {@link ILoginPacketHandler} for sending packets - * to the client during handshake. See {@link ILoginPacketHandler} for more information. - * Example usage: builder.assignClientHandler(() -> ServerPacketHandler::new); - * - * @param loginHandler The Supplier. - * @return The same builder. - */ - public PacketCustomChannelBuilder assignLoginHandler(Supplier> loginHandler) { - this.loginHandler = loginHandler.get().get(); - return this; - } - - /** - * Actually build and register the channel with Forge. - * - * @return The underlying {@link EventNetworkChannel} - */ - public synchronized EventNetworkChannel build() { - EventNetworkChannel channel = parent - .networkProtocolVersion(networkProtocolVersion) - .clientAcceptedVersions(clientAcceptedVersions) - .serverAcceptedVersions(serverAcceptedVersions) - .eventNetworkChannel(); - - if (clientHandler != null) { - channel.registerObject(new ClientHandler(clientHandler)); - } - - if (serverHandler != null) { - channel.registerObject(new ServerHandler(serverHandler)); - } - if (loginHandler != null) { - channel.registerObject(new LoginHandler(loginHandler)); - } - return channel; - } - - /** - * Handler for Client received packets. - */ - private class ClientHandler { - - private final IClientPacketHandler packetHandler; - - public ClientHandler(IClientPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onClientPayload(NetworkEvent.ServerCustomPayloadEvent event) { - if (event instanceof NetworkEvent.ServerCustomPayloadLoginEvent) { - return; - } - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ClientPacketListener nh) { - ctx.enqueueWork(() -> { - try { - packetHandler.handlePacket(packet, Minecraft.getInstance(), nh); - } catch (Throwable ex) { - LOGGER.error("Error handling packet on channel {}.", channelName, ex); - } finally { - payload.release(); - } - }); - } - } - } - - /** - * Handler for Server received packets. - */ - private class ServerHandler { - - private final IServerPacketHandler packetHandler; - - public ServerHandler(IServerPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onServerPayload(NetworkEvent.ClientCustomPayloadEvent event) { - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ServerGamePacketListenerImpl nh) { - ctx.enqueueWork(() -> { - try { - packetHandler.handlePacket(packet, nh.player, nh); - } catch (Throwable ex) { - LOGGER.error("Error handling packet on channel {}.", channelName, ex); - } finally { - payload.release(); - } - }); - } - } - } - - /** - * Handler for Login packets. - */ - private class LoginHandler { - - private final ILoginPacketHandler packetHandler; - - public LoginHandler(ILoginPacketHandler packetHandler) { - this.packetHandler = packetHandler; - } - - @SubscribeEvent - public void onGatherLoginPayloads(NetworkEvent.GatherLoginPayloadsEvent event) { - packetHandler.gatherLoginPackets((ctx, packetSupplier) -> { - PacketCustom packet = packetSupplier.get(); - event.add(packet.toPacketBuffer(), packet.getChannel(), ctx); - }); - } - - @SubscribeEvent - public void onClientPayload(NetworkEvent.LoginPayloadEvent event) { - ByteBuf payload = event.getPayload().copy(); - PacketCustom packet = new PacketCustom(payload); - NetworkEvent.Context ctx = event.getSource().get(); - PacketListener netHandler = ctx.getNetworkManager().getPacketListener(); - ctx.setPacketHandled(true); - if (netHandler instanceof ClientLoginPacketListener nh) { - try { - packetHandler.handleLoginPacket(packet, Minecraft.getInstance(), nh, ctx); - } catch (Throwable ex) { - LOGGER.error("Error handling login packet on channel {}.", channelName, ex); - } finally { - payload.release(); - //For _some_ reason sending this response packet in FML is private. So just spoof the packet :D - ctx.getPacketDispatcher().sendPacket(new ResourceLocation("fml:handshake"), new FriendlyByteBuf(Unpooled.buffer().writeByte(99))); - } - } - } - } -} diff --git a/src/main/java/codechicken/lib/packet/PacketSender.java b/src/main/java/codechicken/lib/packet/PacketSender.java new file mode 100644 index 00000000..d6134b57 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/PacketSender.java @@ -0,0 +1,277 @@ +package codechicken.lib.packet; + +import net.minecraft.client.Minecraft; +import net.minecraft.core.BlockPos; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.ClientboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.ServerboundCustomPayloadPacket; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.players.PlayerList; +import net.minecraft.server.players.ServerOpList; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; +import static net.neoforged.neoforge.server.ServerLifecycleHooks.getCurrentServer; + +/** + * Created by covers1624 on 17/9/24. + */ +public class PacketSender { + + // region Server -> Client + + /** + * Create a client bound packet for the given custom payload. + * + * @param payload The payload. + * @return The packet. + */ + public static Packet toClientPacket(CustomPacketPayload payload) { + return payload.toVanillaClientbound(); + } + + /** + * Overload of {@link #sendToPlayer(Packet, ServerPlayer)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToPlayer(CustomPacketPayload payload, @Nullable ServerPlayer player) { + sendToPlayer(toClientPacket(payload), player); + } + + /** + * Send the given packet to the specified player. If the specified player is {@code null}, + * sends the packet to all connected clients. + * + * @param packet The packet to send. + * @param player The receiver. {@code null} for all players. + */ + public static void sendToPlayer(Packet packet, @Nullable ServerPlayer player) { + if (player == null) { + sendToAllPlayers(packet); + } else { + player.connection.send(packet); + } + } + + /** + * Overload of {@link #sendToAllPlayers(Packet)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllPlayers(CustomPacketPayload payload) { + sendToAllPlayers(toClientPacket(payload)); + } + + /** + * Sends the given packet to all connected clients. + * + * @param packet The packet to send. + */ + public static void sendToAllPlayers(Packet packet) { + getCurrentServer().getPlayerList().broadcastAll(packet); + } + + /** + * Overload of {@link #sendToAllAround(Packet, BlockPos, double, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllAround(CustomPacketPayload payload, BlockPos pos, double range, ResourceKey dim) { + sendToAllAround(toClientPacket(payload), pos, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param packet The packet to send. + * @param pos The origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public static void sendToAllAround(Packet packet, BlockPos pos, double range, ResourceKey dim) { + sendToAllAround(packet, pos.getX(), pos.getY(), pos.getZ(), range, dim); + } + + /** + * Overload of {@link #sendToAllAround(Packet, double, double, double, double, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToAllAround(CustomPacketPayload payload, double x, double y, double z, double range, ResourceKey dim) { + sendToAllAround(toClientPacket(payload), x, y, z, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param packet The packet to send. + * @param x The X origin point to send around. + * @param y The Y origin point to send around. + * @param z The Z origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public static void sendToAllAround(Packet packet, double x, double y, double z, double range, ResourceKey dim) { + getCurrentServer().getPlayerList().broadcast(null, x, y, z, range, dim, packet); + } + + /** + * Overload of {@link #sendToDimension(Packet, ResourceKey)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToDimension(CustomPacketPayload payload, ResourceKey dim) { + sendToDimension(toClientPacket(payload), dim); + } + + /** + * Send the given packet to all players within the given dimension. + * + * @param packet The packet to send. + * @param dim The dimension to send to. + */ + public static void sendToDimension(Packet packet, ResourceKey dim) { + getCurrentServer().getPlayerList().broadcastAll(packet, dim); + } + + /** + * Overload of {@link #sendToChunk(Packet, BlockEntity)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, BlockEntity tile) { + sendToChunk(toClientPacket(payload), tile); + } + + /** + * Send the given packet to all players watching the chunk, that the given {@link BlockEntity} + * is within. + * + * @param packet The packet to send. + * @param tile The {@link BlockEntity} of the watched chunk to send to. + */ + public static void sendToChunk(Packet packet, BlockEntity tile) { + sendToChunk(packet, (ServerLevel) requireNonNull(tile.getLevel()), tile.getBlockPos()); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, BlockPos)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, BlockPos pos) { + sendToChunk(toClientPacket(payload), level, pos); + } + + /** + * Send the given packet to all players watching the chunk specified by the + * given {@link BlockPos} in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param pos The {@link BlockPos} specifying the chunk to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, BlockPos pos) { + sendToChunk(packet, level, pos.getX() >> 4, pos.getZ() >> 4); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, int, int)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, int chunkX, int chunkZ) { + sendToChunk(toClientPacket(payload), level, chunkX, chunkZ); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param chunkX The chunk X coordinate to send to. + * @param chunkZ The chunk Z coordinate to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, int chunkX, int chunkZ) { + sendToChunk(packet, level, new ChunkPos(chunkX, chunkZ)); + } + + /** + * Overload of {@link #sendToChunk(Packet, ServerLevel, ChunkPos)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToChunk(CustomPacketPayload payload, ServerLevel level, ChunkPos pos) { + sendToChunk(toClientPacket(payload), level, pos); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param packet The packet to send. + * @param level The level containing the chunk to send to. + * @param pos The {@link ChunkPos} to send to. + */ + public static void sendToChunk(Packet packet, ServerLevel level, ChunkPos pos) { + level.getChunkSource().chunkMap.getPlayers(pos, false).forEach(e -> sendToPlayer(packet, e)); + } + + /** + * Overload of {@link #sendToOps(Packet)} first wrapping {@code payload} to + * a client bound packet. + */ + public static void sendToOps(CustomPacketPayload payload) { + sendToOps(toClientPacket(payload)); + } + + /** + * Send the given packet to all server operators. + * + * @param packet The packet to send. + */ + public static void sendToOps(Packet packet) { + PlayerList playerList = getCurrentServer().getPlayerList(); + ServerOpList opList = playerList.getOps(); + for (ServerPlayer player : playerList.getPlayers()) { + if (opList.get(player.nameAndId()) != null) { + sendToPlayer(packet, player); + } + } + } + // endregion + + // region Client -> Server + + /** + * Create a server bound packet for the given custom payload. + * + * @param payload The payload. + * @return The packet. + */ + public static Packet toServerPacket(CustomPacketPayload payload) { + return payload.toVanillaServerbound(); + } + + /** + * Overload of {@link #sendToServer(Packet)} first wrapping {@code payload} to + * a server bound packet. + */ + public static void sendToServer(CustomPacketPayload payload) { + sendToServer(toServerPacket(payload)); + } + + /** + * Send the given packet to the server. + * + * @param packet The packet to send. + */ + public static void sendToServer(Packet packet) { + requireNonNull(Minecraft.getInstance().getConnection()).send(packet); + } + + // endregion +} diff --git a/src/main/java/codechicken/lib/packet/SignedVarInt.java b/src/main/java/codechicken/lib/packet/SignedVarInt.java new file mode 100644 index 00000000..1534f7f6 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/SignedVarInt.java @@ -0,0 +1,19 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.VarInt; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class SignedVarInt { + + public static ByteBuf write(ByteBuf buf, int i) { + return VarInt.write(buf, i >= 0 ? 2 * i : -2 * (i + 1) + 1); + } + + public static int read(ByteBuf buf) { + int i = VarInt.read(buf); + return (i & 1) == 0 ? i >>> 1 : -(i >>> 1) - 1; + } +} diff --git a/src/main/java/codechicken/lib/packet/SignedVarLong.java b/src/main/java/codechicken/lib/packet/SignedVarLong.java new file mode 100644 index 00000000..f7b2b3eb --- /dev/null +++ b/src/main/java/codechicken/lib/packet/SignedVarLong.java @@ -0,0 +1,20 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import net.minecraft.network.VarInt; +import net.minecraft.network.VarLong; + +/** + * Created by covers1624 on 10/31/25. + */ +public final class SignedVarLong { + + public static ByteBuf write(ByteBuf buf, long i) { + return VarLong.write(buf, i >= 0 ? 2 * i : -2 * (i + 1) + 1); + } + + public static long read(ByteBuf buf) { + long i = VarLong.read(buf); + return (i & 1) == 0 ? i >>> 1 : -(i >>> 1) - 1; + } +} diff --git a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java index 8e9510f9..5a6eb87a 100644 --- a/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleClientPacketHandler.java @@ -12,6 +12,7 @@ /** * Created by covers1624 on 21/5/20. */ +@Deprecated (forRemoval = true) public class SimpleClientPacketHandler implements IClientPacketHandler { private static final Logger LOGGER = LogManager.getLogger(); @@ -26,10 +27,10 @@ protected void addHandler(int id, IClientPacketHandler handler) { } @Override - public void handlePacket(PacketCustom packet, Minecraft mc, ClientPacketListener handler) { + public void handlePacket(PacketCustom packet, Minecraft mc) { IClientPacketHandler h = handlers.get(packet.getType()); if (h != null) { - h.handlePacket(packet, mc, handler); + h.handlePacket(packet, mc); } else { LOGGER.warn("Received unknown packet on channel '{}' with descriptor '{}'.", packet.getChannel(), packet.getType()); } diff --git a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java index 18831e58..619fbe43 100644 --- a/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java +++ b/src/main/java/codechicken/lib/packet/SimpleServerPacketHandler.java @@ -12,6 +12,7 @@ /** * Created by covers1624 on 21/5/20. */ +@Deprecated (forRemoval = true) public class SimpleServerPacketHandler implements IServerPacketHandler { private static final Logger LOGGER = LogManager.getLogger(); @@ -26,10 +27,10 @@ protected void addHandler(int id, IServerPacketHandler handler) { } @Override - public void handlePacket(PacketCustom packet, ServerPlayer sender, ServerGamePacketListenerImpl handler) { + public void handlePacket(PacketCustom packet, ServerPlayer sender) { IServerPacketHandler h = handlers.get(packet.getType()); if (h != null) { - h.handlePacket(packet, sender, handler); + h.handlePacket(packet, sender); } else { LOGGER.warn("Received unknown packet on channel '{}' with descriptor '{}'.", packet.getChannel(), packet.getType()); } diff --git a/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java new file mode 100644 index 00000000..dc87533d --- /dev/null +++ b/src/main/java/codechicken/lib/packet/StreamNetworkChannel.java @@ -0,0 +1,466 @@ +package codechicken.lib.packet; + +import codechicken.lib.internal.CCLNetwork; +import io.netty.buffer.Unpooled; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.client.Minecraft; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.network.protocol.configuration.ServerConfigurationPacketListener; +import net.minecraft.resources.Identifier; +import net.minecraft.server.network.ConfigurationTask; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.loading.FMLEnvironment; +import net.neoforged.neoforge.network.configuration.ICustomConfigurationTask; +import net.neoforged.neoforge.network.connection.ConnectionType; +import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent; +import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; +import net.neoforged.neoforge.network.handling.IPayloadContext; +import net.neoforged.neoforge.network.handling.IPayloadHandler; +import net.neoforged.neoforge.network.handling.MainThreadPayloadHandler; +import net.neoforged.neoforge.network.registration.HandlerThread;import net.neoforged.neoforge.network.registration.PayloadRegistrar; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; + +import static java.util.Objects.requireNonNull; + +/** + * A simple Stream based network channel, very similar to the NeoForge api, however + * provides raw, stream-based packets. + *

+ * You would construct one of these and store it statically, see {@link CCLNetwork} for inspiration. + *

+ * Created by covers1624 on 10/26/25. + */ +public final class StreamNetworkChannel { + + private final CrashLock LOCK = new CrashLock("Already initialized."); + + private final String namespace; + private boolean optional; + + private final Map> packets = new HashMap<>(); + + /** + * Create a new network channel. + * + * @param namespace The namespace, usually your mod id. + */ + public StreamNetworkChannel(String namespace) { + this.namespace = namespace; + } + + /** + * Called with your mod event bus and mod container. + * + * @param bus Your mod event bus. + * @param container Your mod container. + */ + public void init(IEventBus bus, ModContainer container) { + LOCK.lock(); + bus.addListener(RegisterPayloadHandlersEvent.class, e -> onRegisterPayloadHandlerEvent(e, container)); + bus.addListener(this::onGameConfigurationEvent); + } + + /** + * Mark this network channel as optional, not required on the client/server. + * + * @return The same channel. + */ + public StreamNetworkChannel optional() { + this.optional = true; + return this; + } + + /** + * Register a packet to be set to the client during gameplay. + *

+ * The packet handle must be assigned via {@link #assignClientHandler} on the client-side only. + * + * @param name The name of the packet. + * @return A handle to construct packets. + * @see #assignClientHandler(ClientPacketHandle, PlayHandler) + */ + public ClientPacketHandle playToClient(String name) { + return createType("play", name, PacketKind.CLIENT_HANDLED, PlayPacketType::new); + } + + /** + * Register a packet to be set to the server during gameplay. + * + * @param name The name of the packet. + * @param handler The handler for the packet. + * @return A handle to construct packets. + */ + public ServerPacketHandle playToServer(String name, PlayHandler handler) { + var type = createType("play", name, PacketKind.SERVER_HANDLED, PlayPacketType::new); + type.serverHandler = handler; + return type; + } + + /** + * Register a packet to be set to either the client or the server during gameplay. + *

+ * The packet's client handle must be assigned via {@link #assignClientHandler} on the client-side only. + * + * @param name The name of the packet. + * @param serverHandler The handler for the packet server-side. + * @return A handle to construct packets. + * @see #assignClientHandler(ClientPacketHandle, PlayHandler) + */ + public BidirectionalPacketHandle playBidirectional(String name, PlayHandler serverHandler) { + var type = createType("play", name, PacketKind.BI_DIRECTIONAL, PlayPacketType::new); + type.serverHandler = serverHandler; + return type; + } + + /** + * Assign the client-side handler for a packet. + * + * @param handle The packet handle to attach to. + * @param handler The handler. + */ + public void assignClientHandler(ClientPacketHandle handle, PlayHandler handler) { + // ClientPacketHandle is sealed. + var packet = ((PlayPacketType) handle); + // Technically possible with whacky casts. + if (packet.kind != PacketKind.CLIENT_HANDLED && packet.kind != PacketKind.BI_DIRECTIONAL) { + throw new IllegalStateException("Server packets can't have client handlers."); + } + if (packet.clientHandler != null) { + throw new IllegalArgumentException("Client handler already assigned for packet. " + packet.type.id()); + } + + packet.clientHandler = requireNonNull(handler); + } + + /** + * Register a packet to configure a connecting client. + * + * @param name The name of the packet. + * @param factory The factory to construct a {@link ICustomConfigurationTask}. + * @return The packet handle. + */ + public ConfigurationPacketHandle configurationToClient(String name, ConfigurationTaskFactory factory) { + return createType("configuration", name, PacketKind.CLIENT_HANDLED, (id, kind) -> new ConfigurationPacketType(id, kind, factory)); + } + + /** + * Assign the client-side handler for a configuration task packet. + * + * @param handle The packet handle to attach to. + * @param handler The handler. + */ + public void assignClientHandler(ConfigurationPacketHandle handle, ConfigurationHandler handler) { + var packet = ((ConfigurationPacketType) handle); + if (packet.kind != PacketKind.CLIENT_HANDLED && packet.kind != PacketKind.BI_DIRECTIONAL) { + throw new IllegalStateException("Server packets can't have client handlers."); + } + + if (packet.handler != null) { + throw new IllegalArgumentException("Handler already assigned for packet. " + packet.type.id()); + } + packet.handler = requireNonNull(handler); + } + + // region Events + private void onRegisterPayloadHandlerEvent(RegisterPayloadHandlersEvent event, ModContainer container) { + var registrar = event.registrar(container.getModInfo().getVersion().toString()); + if (optional) registrar = registrar.optional(); + + for (PacketType type : packets.values()) { + type.register(registrar); + } + } + + private void onGameConfigurationEvent(RegisterConfigurationTasksEvent event) { + for (PacketType type : packets.values()) { + if (type instanceof ConfigurationPacketType cType) { + event.register(cType.getTask(event.getListener())); + } + } + } + // endregion + + private > T createType(String phase, String name, PacketKind kind, BiFunction func) { + var id = makeId(phase, name); + if (packets.containsKey(id)) throw new IllegalArgumentException("Packet with name " + name + " for the " + phase + " phase is already registered."); + + var type = func.apply(id, kind); + packets.put(id, type); + return type; + } + + private Identifier makeId(String prefix, String name) { + return Identifier.fromNamespaceAndPath(namespace, prefix + "/" + name); + } + + // region Registration internal + private static abstract sealed class PacketType permits PlayPacketType, ConfigurationPacketType { + + protected final CustomPacketPayload.Type type; + + private PacketType(Identifier id) { + type = new CustomPacketPayload.Type<>(id); + } + + public abstract void register(PayloadRegistrar registrar); + } + + private static final class PlayPacketType extends PacketType implements BidirectionalPacketHandle { + + private final PacketKind kind; + private @Nullable PlayHandler clientHandler; + private @Nullable PlayHandler serverHandler; + + private PlayPacketType(Identifier id, PacketKind kind) { + super(id); + this.kind = kind; + } + + private IPayloadHandler clientHandler() { + if (clientHandler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a client handler assigned."); + } + + return clientHandler::accept; + } + + private IPayloadHandler serverHandler() { + // Should not be possible.. + if (serverHandler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a server handler assigned."); + } + + return serverHandler::accept; + } + + @Override + public void register(PayloadRegistrar registrar) { + var codec = StreamPacket.createCodec(type); + + switch (kind) { + case CLIENT_HANDLED -> { + if (FMLEnvironment.getDist().isClient()) { + registrar.playToClient(type, codec, clientHandler()); + } else { + registrar.playToClient(type, codec); + } + } + case SERVER_HANDLED -> registrar.playToServer(type, codec, serverHandler()); + case BI_DIRECTIONAL -> { + if (FMLEnvironment.getDist().isClient()) { + if (FMLEnvironment.getDist().isClient()) { + registrar.playBidirectional(type, codec, serverHandler(), clientHandler()); + } else { + registrar.playBidirectional(type, codec, serverHandler()); + } + } + } + } + } + + @Override + public StreamPacket.ToClient toClient(RegistryAccess registryAccess) { + return new StreamPacket.ToClient( + type, + Unpooled.buffer(), + registryAccess, + ConnectionType.NEOFORGE + ); + } + + @Override + public StreamPacket.ToServer toServer() { + return new StreamPacket.ToServer( + type, + Unpooled.buffer(), + Minecraft.getInstance().getConnection().registryAccess(), + ConnectionType.NEOFORGE + ); + } + } + + private static final class ConfigurationPacketType extends PacketType implements ConfigurationPacketHandle { + + private final PacketKind kind; + public final ConfigurationTask.Type configurationType; + private final ConfigurationTaskFactory factory; + private @Nullable ConfigurationHandler handler; + + private ConfigurationPacketType(Identifier id, PacketKind kind, ConfigurationTaskFactory factory) { + super(id); + this.kind = kind; + this.factory = factory; + configurationType = new ConfigurationTask.Type(type.id()); + } + + private IPayloadHandler handler() { + if (handler == null) { + throw new IllegalStateException("Packet " + type.id() + " does not have a handler assigned."); + } + + return handler::accept; + } + + @Override + public void register(PayloadRegistrar registrar) { + var codec = ConfigurationStreamPacket.createCodec(type); + + if (FMLEnvironment.getDist().isClient()) { + registrar.configurationToClient(type, codec, handler()); + } else { + registrar.configurationToClient(type, codec); + } + } + + public ConfigurationTask getTask(ServerConfigurationPacketListener listener) { + var context = new ConfigurationContext() { + + @Override + public ConfigurationStreamPacket newPacket() { + return new ConfigurationStreamPacket(type, Unpooled.buffer()); + } + + @Override + public ServerConfigurationPacketListener packetListener() { + return listener; + } + }; + return factory.apply(configurationType, context); + } + } + // endregion + + /** + * A helpful interface for the gameplay packet handler type. + */ + public interface PlayHandler extends BiConsumer { + + @Override + void accept(RegistryFriendlyByteBuf packet, IPayloadContext ctx); + } + + /** + * A helpful interface for the configuration phase packet handler type. + */ + public interface ConfigurationHandler extends BiConsumer { + + @Override + void accept(FriendlyByteBuf packet, IPayloadContext ctx); + } + + /** + * The context available when executing a configuration task. + */ + public interface ConfigurationContext { + + /** + * Create a new packet to be sent on the configuration channel. + * + * @return The packet. + */ + ConfigurationStreamPacket newPacket(); + + /** + * @return The active configuration packet listener. + */ + ServerConfigurationPacketListener packetListener(); + } + + /** + * A factory for constructing {@link ICustomConfigurationTask} instances. Usually a record, storing both the type and context. + */ + public interface ConfigurationTaskFactory extends BiFunction { } + + public sealed interface ConfigurationPacketHandle { } + + /** + * A handle for constructing client-bound packets. + */ + public sealed interface ClientPacketHandle { + + /** + * Construct a packet bound for a client. + * + * @param registryAccess The {@link RegistryAccess} instance. + * @return The packet. + */ + StreamPacket.ToClient toClient(RegistryAccess registryAccess); + + /** + * Construct a packet bound for a client. + * + * @param level A level to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Level level) { + return toClient(level.registryAccess()); + } + + /** + * Construct a packet bound for a client. + * + * @param player A player to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Player player) { + return toClient(player.registryAccess()); + } + + /** + * Construct a packet bound for a client. + * + * @param tile A BlockEntity to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(BlockEntity tile) { + return toClient(tile.getLevel()); + } + + /** + * Construct a packet bound for a client. + * + * @param entity An entity to grab the {@link RegistryAccess} from. + * @return The packet. + */ + default StreamPacket.ToClient toClient(Entity entity) { + return toClient(entity.level()); + } + } + + /** + * A handle for constructing server-bound packets. + */ + public sealed interface ServerPacketHandle { + + /** + * Construct a packet bound for the server. + * + * @return The packet. + */ + StreamPacket.ToServer toServer(); + } + + /** + * A handle for constructing a packet bound for a client or the server. + */ + public sealed interface BidirectionalPacketHandle extends ClientPacketHandle, ServerPacketHandle { } + + private enum PacketKind { + CLIENT_HANDLED, + SERVER_HANDLED, + BI_DIRECTIONAL + } +} diff --git a/src/main/java/codechicken/lib/packet/StreamPacket.java b/src/main/java/codechicken/lib/packet/StreamPacket.java new file mode 100644 index 00000000..920ad4a1 --- /dev/null +++ b/src/main/java/codechicken/lib/packet/StreamPacket.java @@ -0,0 +1,204 @@ +package codechicken.lib.packet; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import net.minecraft.core.BlockPos; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.neoforged.neoforge.network.connection.ConnectionType; +import org.jetbrains.annotations.Nullable; + +/** + * An outbound packet for a specific {@link StreamNetworkChannel} packet. + *

+ * You will generally only ever see one of the subclasses, {@link ToClient} or {@link ToServer}. + *

+ * Created by covers1624 on 10/30/25. + */ +//Tasty Cheese! +public sealed class StreamPacket extends RegistryFriendlyByteBuf implements CustomPacketPayload permits StreamPacket.ToClient, StreamPacket.ToServer { + + private final Type type; + + StreamPacket(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(source, registryAccess, connectionType); + this.type = type; + } + + @Override + public Type type() { + return type; + } + + static StreamCodec createCodec(Type type) { + return StreamCodec.of( + (buf, p) -> buf.writeBytes(p, 0, p.writerIndex()), + (buf) -> { + var packet = new StreamPacket(type, Unpooled.buffer(buf.readableBytes()), buf.registryAccess(), ConnectionType.NEOFORGE); + buf.readBytes(packet); + return packet; + } + ); + } + + /** + * A client-bound packet, write your data, then use one of the various send methods, + * or {@link #toVanilla()} to send it out a vanilla path. + */ + public static final class ToClient extends StreamPacket { + + ToClient(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(type, source, registryAccess, connectionType); + } + + /** + * Wrap this packet into a vanilla {@link Packet}. + * + * @return The vanilla packet. + */ + public Packet toVanilla() { + return PacketSender.toClientPacket(this); + } + + /** + * Send the given packet to the specified player. If the specified player is {@code null}, + * sends the packet to all connected clients. + * + * @param player The receiver. {@code null} for all players. + */ + public void sendToPlayer(@Nullable ServerPlayer player) { + PacketSender.sendToPlayer(toVanilla(), player); + } + + /** + * Sends the given packet to all connected clients. + */ + public void sendToAllPlayers() { + PacketSender.sendToAllPlayers(toVanilla()); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param pos The origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public void sendToAllAround(BlockPos pos, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toVanilla(), pos, range, dim); + } + + /** + * Sends the given packet to all players in the specified dimension, within the specified radius, around + * the specified origin. + *

+ * For blocks, it is advised to instead use one of the {@link #sendToChunk} methods. + * + * @param x The X origin point to send around. + * @param y The Y origin point to send around. + * @param z The Z origin point to send around. + * @param range The range in which to send. + * @param dim The dimension to send to. + */ + public void sendToAllAround(double x, double y, double z, double range, ResourceKey dim) { + PacketSender.sendToAllAround(toVanilla(), x, y, z, range, dim); + } + + /** + * Send the given packet to all players within the given dimension. + * + * @param dim The dimension to send to. + */ + public void sendToDimension(ResourceKey dim) { + PacketSender.sendToDimension(toVanilla(), dim); + } + + /** + * Send the given packet to all players watching the chunk, that the given {@link BlockEntity} + * is within. + * + * @param tile The {@link BlockEntity} of the watched chunk to send to. + */ + public void sendToChunk(BlockEntity tile) { + PacketSender.sendToChunk(toVanilla(), tile); + } + + /** + * Send the given packet to all players watching the chunk specified by the + * given {@link BlockPos} in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param pos The {@link BlockPos} specifying the chunk to send to. + */ + public void sendToChunk(ServerLevel level, BlockPos pos) { + PacketSender.sendToChunk(toVanilla(), level, pos); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param chunkX The chunk X coordinate to send to. + * @param chunkZ The chunk Z coordinate to send to. + */ + public void sendToChunk(ServerLevel level, int chunkX, int chunkZ) { + PacketSender.sendToChunk(toVanilla(), level, chunkX, chunkZ); + } + + /** + * Send the given packet to all players watching the specified chunk in the specified dimension. + * + * @param level The level containing the chunk to send to. + * @param pos The {@link ChunkPos} to send to. + */ + public void sendToChunk(ServerLevel level, ChunkPos pos) { + PacketSender.sendToChunk(toVanilla(), level, pos); + } + + /** + * Send the given packet to all server operators. + */ + public void sendToOps() { + PacketSender.sendToOps(toVanilla()); + } + } + + /** + * A server-bound packet, write your data, then use one of the various send methods, + * or {@link #toVanilla()} to send it out a vanilla path. + */ + public static final class ToServer extends StreamPacket { + + ToServer(Type type, ByteBuf source, RegistryAccess registryAccess, ConnectionType connectionType) { + super(type, source, registryAccess, connectionType); + } + + /** + * Wrap this packet into a vanilla {@link Packet}. + * + * @return The vanilla packet. + */ + public Packet toVanilla() { + return PacketSender.toServerPacket(this); + } + + /** + * Send this packet to the server. + */ + public void sendToServer() { + PacketSender.sendToServer(toVanilla()); + } + } +} diff --git a/src/main/java/codechicken/lib/packet/package-info.java b/src/main/java/codechicken/lib/packet/package-info.java new file mode 100644 index 00000000..f675488c --- /dev/null +++ b/src/main/java/codechicken/lib/packet/package-info.java @@ -0,0 +1,7 @@ +/** + * Created by covers1624 on 3/7/24. + */ +@NonNullApi +package codechicken.lib.packet; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java index e459d887..b64a06d4 100644 --- a/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java +++ b/src/main/java/codechicken/lib/raytracer/IndexedVoxelShape.java @@ -6,13 +6,12 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; - -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; /** * A VoxelShape implementation, produces a {@link VoxelShapeBlockHitResult} when ray traced. - * {@link IndexedVoxelShape#data} will be passed through to {@link RayTraceResult#hitInfo} and - * to {@link RayTraceResult#subHit} if its an integer. + * {@link IndexedVoxelShape#data} will be passed through to {@link VoxelShapeBlockHitResult#hitInfo} and + * to {@link VoxelShapeBlockHitResult#subHit} if it's an integer. *

* Created by covers1624 on 5/12/20. */ diff --git a/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java b/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java deleted file mode 100644 index 74506a86..00000000 --- a/src/main/java/codechicken/lib/raytracer/MergedVoxelShapeHolder.java +++ /dev/null @@ -1,55 +0,0 @@ -package codechicken.lib.raytracer; - -import net.minecraft.world.phys.shapes.Shapes; -import net.minecraft.world.phys.shapes.VoxelShape; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.function.Function; - -/** - * Created by covers1624 on 3/10/20. - */ -public class MergedVoxelShapeHolder { - - private final Set shapeParts = new HashSet<>(); - private final Set partCache = new HashSet<>(); - - private VoxelShape mergedShape; - private Function extractor; - private Function postProcess; - - public MergedVoxelShapeHolder setExtractor(Function extractor) { - this.extractor = extractor; - return this; - } - - public MergedVoxelShapeHolder setPostProcessHook(Function postProcess) { - this.postProcess = postProcess; - return this; - } - - public void clear() { - shapeParts.clear(); - partCache.clear(); - mergedShape = null; - } - - public VoxelShape update(Collection things) { - partCache.clear(); - for (T thing : things) { - partCache.add(extractor.apply(thing)); - } - if (!partCache.equals(shapeParts) || mergedShape == null) { - shapeParts.clear(); - shapeParts.addAll(partCache); - //Same as VoxelShapes.or(VoxelShapes.empty(), shapeParts.toArray()); Except we skip useless array creation. - VoxelShape merged = shapeParts.stream().reduce(Shapes.empty(), Shapes::or); - mergedShape = postProcess.apply(merged); - } - - return mergedShape; - } - -} diff --git a/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java b/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java index 817e2f55..f9ebff45 100644 --- a/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java +++ b/src/main/java/codechicken/lib/raytracer/MultiIndexedVoxelShape.java @@ -6,8 +6,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; - -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; import static net.covers1624.quack.util.SneakyUtils.unsafeCast; diff --git a/src/main/java/codechicken/lib/raytracer/RayTracer.java b/src/main/java/codechicken/lib/raytracer/RayTracer.java index 193a6e3d..b725fad5 100644 --- a/src/main/java/codechicken/lib/raytracer/RayTracer.java +++ b/src/main/java/codechicken/lib/raytracer/RayTracer.java @@ -1,39 +1,34 @@ package codechicken.lib.raytracer; import codechicken.lib.vec.Vector3; -import net.covers1624.quack.annotation.ReplaceWith; -import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.ClipContext; -import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.common.ForgeMod; +import org.jetbrains.annotations.Nullable; public class RayTracer { - - @Deprecated (forRemoval = true, since = "1.18.2") // Unnecessarily specific level type. - public static BlockHitResult retraceBlock(LevelReader level, Player player, BlockPos pos) { - return retraceBlock((BlockGetter) level, player, pos); + @Nullable + public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos) { + return retraceBlock(level, player, pos, ClipContext.Block.OUTLINE); } - public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos) { + @Nullable + public static BlockHitResult retraceBlock(BlockGetter level, Player player, BlockPos pos, ClipContext.Block context) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player); + BlockState state = level.getBlockState(pos); - VoxelShape baseShape = state.getShape(level, pos); + VoxelShape baseShape = context.get(state, level, pos, CollisionContext.of(player)); BlockHitResult baseTraceResult = baseShape.clip(startVec, endVec, pos); if (baseTraceResult != null) { - BlockHitResult raytraceTraceShape = state.getVisualShape(level, pos, CollisionContext.of(player)).clip(startVec, endVec, pos); + BlockHitResult raytraceTraceShape = state.getInteractionShape(level, pos).clip(startVec, endVec, pos); if (raytraceTraceShape != null) { return raytraceTraceShape; } @@ -41,25 +36,16 @@ public static BlockHitResult retraceBlock(BlockGetter level, Player player, Bloc return baseTraceResult; } - private static double getBlockReachDistance_server(ServerPlayer player) { - return player.getAttribute(ForgeMod.REACH_DISTANCE.get()).getValue(); - } - - @OnlyIn (Dist.CLIENT) - private static double getBlockReachDistance_client() { - return Minecraft.getInstance().gameMode.getPickRange(); - } - public static BlockHitResult retrace(Player player) { return retrace(player, ClipContext.Block.OUTLINE); } public static BlockHitResult retrace(Player player, ClipContext.Block blockMode) { - return retrace(player, getBlockReachDistance(player), blockMode, ClipContext.Fluid.NONE); + return retrace(player, player.blockInteractionRange(), blockMode, ClipContext.Fluid.NONE); } public static BlockHitResult retrace(Player player, ClipContext.Block blockMode, ClipContext.Fluid fluidMode) { - return retrace(player, getBlockReachDistance(player), blockMode, fluidMode); + return retrace(player, player.blockInteractionRange(), blockMode, fluidMode); } public static BlockHitResult retrace(Player player, double reach, ClipContext.Block blockMode) { @@ -69,7 +55,7 @@ public static BlockHitResult retrace(Player player, double reach, ClipContext.Bl public static BlockHitResult retrace(Player player, double reach, ClipContext.Block blockMode, ClipContext.Fluid fluidMode) { Vec3 startVec = getStartVec(player); Vec3 endVec = getEndVec(player, reach); - return player.level.clip(new ClipContext(startVec, endVec, blockMode, fluidMode, player)); + return player.level().clip(new ClipContext(startVec, endVec, blockMode, fluidMode, player)); } public static Vec3 getCorrectedHeadVec(Player player) { @@ -81,15 +67,10 @@ public static Vec3 getStartVec(Player player) { return getCorrectedHeadVec(player); } - @Deprecated // Use attribute directly? avoid all this nonsense. - public static double getBlockReachDistance(Player player) { - return player.level.isClientSide ? getBlockReachDistance_client() : player instanceof ServerPlayer ? getBlockReachDistance_server((ServerPlayer) player) : 5D; - } - public static Vec3 getEndVec(Player player) { Vec3 headVec = getCorrectedHeadVec(player); Vec3 lookVec = player.getViewVector(1.0F); - double reach = getBlockReachDistance(player); + double reach = player.blockInteractionRange(); return headVec.add(lookVec.x * reach, lookVec.y * reach, lookVec.z * reach); } diff --git a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java index 26d7c195..743c3e2c 100644 --- a/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java +++ b/src/main/java/codechicken/lib/raytracer/SubHitBlockHitResult.java @@ -5,6 +5,7 @@ import net.minecraft.core.Direction; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import org.jetbrains.annotations.Nullable; public class SubHitBlockHitResult extends BlockHitResult implements Comparable { @@ -12,19 +13,19 @@ public class SubHitBlockHitResult extends BlockHitResult implements Comparable instances = ThreadLocal.withInitial(BakedVertexSource::new); - - private final Quad unpacker = new Quad(CachedFormat.lookup(DefaultVertexFormat.BLOCK)); - - private int vertexIndex = 0; - private Vertex5[] vertices = new Vertex5[0]; - private Object[] attributes = new Object[0]; - private TextureAtlasSprite[] sprites = new TextureAtlasSprite[0]; - - @VisibleForTesting - BakedVertexSource() { - ensureAttr(AttributeKeyRegistry.numAttributes() - 1); - ensureSpace(24); //Ensure enough space for a full standard block model. - } - - public static BakedVertexSource instance() { - return instances.get(); - } - - @Override - public Vertex5[] getVertices() { - return vertices; - } - - @Override - public int getVertexCount() { - return vertexIndex; - } - - @Override - public T getAttribute(AttributeKey attr) { - ensureAttr(attr.attributeKeyIndex); - return unsafeCast(attributes[attr.attributeKeyIndex]); - } - - @Override - public boolean hasAttribute(AttributeKey attr) { - return attr == NormalAttribute.attributeKey || attr == ColourAttribute.attributeKey || attr == LightCoordAttribute.attributeKey; - } - - @Override - public void prepareVertex(CCRenderState ccrs) { - ccrs.sprite = sprites[ccrs.vertexIndex]; - } - - public void reset() { - reset(CachedFormat.lookup(DefaultVertexFormat.BLOCK)); - } - - public void reset(CachedFormat format) { - vertexIndex = 0; - unpacker.reset(format); - } - - // Use getVertexCount() - @Deprecated(forRemoval = true, since = "1.18.2") - public int availableVertices() { - return vertexIndex; - } - - private void onFull() { - ensureSpace(getVertexCount() + 4); - for (int i = 0; i < 4; i++) { - int v = vertexIndex++; - Quad.Vertex vertex = unpacker.vertices[i]; - Vertex5 vertex5 = vertices[v]; - vertex5.vec.set(vertex.vec); - vertex5.uv.set(vertex.uv); - - Vector3 normal = getAttr(NormalAttribute.attributeKey)[v]; - normal.set(vertex.normal); - getAttr(LightCoordAttribute.attributeKey)[v].compute(vertex5.vec, normal); - - getAttr(ColourAttribute.attributeKey)[v] = Colour.packRGBA(vertex.color); - - sprites[v] = unpacker.sprite; - } - unpacker.rewind(); - } - - private void ensureAttr(int aIdx) { - if (attributes.length <= aIdx) { - attributes = Arrays.copyOf(attributes, aIdx + 1); - } - } - - //Expands array storage. - @VisibleForTesting - void ensureSpace(int numVertices) { - //If we don't have enough, or are full, expand. - if (vertices.length < numVertices) { - int prevLen = vertices.length; - int fillStart = vertexIndex; - vertices = Arrays.copyOf(vertices, numVertices); - fill(vertices, fillStart, numVertices, Vertex5::new); - for (int aIdx = 0; aIdx < attributes.length; aIdx++) { - Object attr = attributes[aIdx]; - AttributeKey key = AttributeKeyRegistry.getAttributeKey(aIdx); - if (attr == null) { - attr = key.createDefault(numVertices); - } else { - Object newAttr = key.createDefault(numVertices); - //noinspection SuspiciousSystemArraycopy - System.arraycopy(attr, 0, newAttr, 0, prevLen); - attr = newAttr; - } - attributes[aIdx] = attr; - //Fill non primitive vertex attributes with new things. - if (key == NormalAttribute.attributeKey) { - fill((Object[]) attr, fillStart, numVertices, Vector3::new); - } else if (key == LightCoordAttribute.attributeKey) { - fill((Object[]) attr, fillStart, numVertices, LC::new); - } - } - sprites = Arrays.copyOf(sprites, numVertices); - } - } - - private T getAttr(AttributeKey key) { - return unsafeCast(attributes[key.attributeKeyIndex]); - } - - @Override - public void put(Quad quad) { - unpacker.put(quad); - onFull(); - } - - @Override - public void put(int element, float... data) { - unpacker.put(element, data); - if (unpacker.full) { - onFull(); - } - } - - //@formatter:off - @Override public VertexFormat getVertexFormat() { return DefaultVertexFormat.BLOCK; } - @Override public void setQuadTint(int tint) { unpacker.setQuadTint(tint); } - @Override public void setQuadOrientation(Direction orientation) { unpacker.setQuadOrientation(orientation); } - @Override public void setApplyDiffuseLighting(boolean diffuse) { unpacker.setApplyDiffuseLighting(diffuse); } - @Override public void setTexture(TextureAtlasSprite texture) { unpacker.setTexture(texture); } - //@formatter:on - - private static void fill(Object[] arr, int start, int end, Supplier supplier) { - for (int i = start; i < end; i++) { - arr[i] = supplier.get(); - } - } -} diff --git a/src/main/java/codechicken/lib/render/CCModel.java b/src/main/java/codechicken/lib/render/CCModel.java index 568144a4..a9ff032a 100644 --- a/src/main/java/codechicken/lib/render/CCModel.java +++ b/src/main/java/codechicken/lib/render/CCModel.java @@ -28,16 +28,17 @@ public class CCModel implements IVertexSource, Copyable { public Vertex5[] verts; public ArrayList attributes = new ArrayList<>(); - protected CCModel(VertexFormat.Mode vertexMode) { + protected CCModel(VertexFormat.Mode vertexMode, int numVerts) { if (vertexMode != VertexFormat.Mode.QUADS && vertexMode != VertexFormat.Mode.TRIANGLES) { throw new IllegalArgumentException("Models must be QUADS or TRIANGLES"); } this.vertexMode = vertexMode; vp = vertexMode == VertexFormat.Mode.QUADS ? 4 : 3; + verts = new Vertex5[numVerts]; } - public Vector3[] normals() { + public Vector3 @Nullable [] normals() { return getAttribute(NormalAttribute.attributeKey); } @@ -347,6 +348,8 @@ public CCModel computeNormals(int start, int length) { */ public CCModel computeLighting(LightModel light) { Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + int[] colours = getAttribute(LightingAttribute.attributeKey); if (colours == null) { colours = getOrAllocate(LightingAttribute.attributeKey); @@ -364,14 +367,23 @@ public CCModel setColour(int c) { return this; } + public CCModel setTex(int tex) { + for (Vertex5 vert : verts) { + vert.uv.tex = tex; + } + return this; + } + /** * Computes the minecraft lighting coordinates for use with a LightMatrix * * @return The model */ public CCModel computeLightCoords() { - LC[] lcs = getOrAllocate(LightCoordAttribute.attributeKey); Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + + LC[] lcs = getOrAllocate(LightCoordAttribute.attributeKey); for (int i = 0; i < verts.length; i++) { lcs[i] = new LC().compute(verts[i].vec, normals[i]); } @@ -384,8 +396,10 @@ public CCModel computeLightCoords() { * @return The model */ public CCModel smoothNormals() { - ArrayList map = new ArrayList<>(); Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + + ArrayList map = new ArrayList<>(); nextvert: for (int k = 0; k < verts.length; k++) { Vector3 vec = verts[k].vec; @@ -489,14 +503,12 @@ public static CCModel triModel(int numVerts) { return newModel(VertexFormat.Mode.TRIANGLES, numVerts); } - public static CCModel newModel(VertexFormat.Mode vertexMode, int numVerts) { - CCModel model = newModel(vertexMode); - model.verts = new Vertex5[numVerts]; - return model; + public static CCModel newModel(VertexFormat.Mode vertexMode) { + return newModel(vertexMode, 0); } - public static CCModel newModel(VertexFormat.Mode vertexMode) { - return new CCModel(vertexMode); + public static CCModel newModel(VertexFormat.Mode vertexMode, int numVerts) { + return new CCModel(vertexMode, numVerts); } public static CCModel createModel(List verts, List uvs, List normals, VertexFormat.Mode vertexMode, List polys) { @@ -507,9 +519,7 @@ public static CCModel createModel(List verts, List uvs, List 0; CCModel model = CCModel.newModel(vertexMode, polys.size()); - if (hasNormals) { - model.getOrAllocate(NormalAttribute.attributeKey); - } + Vector3[] mNormals = hasNormals ? model.getOrAllocate(NormalAttribute.attributeKey) : null; for (int i = 0; i < polys.size(); i++) { int[] ai = polys.get(i); @@ -521,7 +531,7 @@ public static CCModel createModel(List verts, List uvs, List models) { - if (models.isEmpty()) { - return null; - } + if (models.isEmpty()) throw new IllegalArgumentException("Can't combine an empty collection of models."); int numVerts = 0; VertexFormat.Mode vertexMode = null; @@ -800,10 +809,12 @@ public Vector3 collapse() { } public CCModel zOffset(Cuboid6 offsets) { + Vector3[] normals = normals(); + if (normals == null) throw new IllegalStateException("Normals not computed."); + for (int k = 0; k < verts.length; k++) { Vertex5 vert = verts[k]; - Vector3 normal = normals()[k]; - switch (VectorUtils.findSide(normal)) { + switch (VectorUtils.findSide(normals[k])) { case 0 -> vert.vec.y += offsets.min.y; case 1 -> vert.vec.y += offsets.max.y; case 2 -> vert.vec.z += offsets.min.z; diff --git a/src/main/java/codechicken/lib/render/CCModelLibrary.java b/src/main/java/codechicken/lib/render/CCModelLibrary.java index 91f095c0..fd7bd768 100644 --- a/src/main/java/codechicken/lib/render/CCModelLibrary.java +++ b/src/main/java/codechicken/lib/render/CCModelLibrary.java @@ -3,26 +3,23 @@ import codechicken.lib.vec.Quat; import codechicken.lib.vec.Vector3; import codechicken.lib.vec.Vertex5; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.client.renderer.rendertype.RenderSetup; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.resources.Identifier; +import static codechicken.lib.CodeChickenLib.MOD_ID; import static codechicken.lib.math.MathHelper.phi; public class CCModelLibrary { - public static CCModel icosahedron4; - public static CCModel icosahedron7; + public static final CCModel icosahedron4; + public static final CCModel icosahedron7; private static int i; static { - generateIcosahedron(); - } - - private static void generateIcosahedron() { Vector3[] verts = new Vector3[12]; verts[0] = new Vector3(-1, phi, 0); @@ -85,21 +82,23 @@ private static void addIcosahedronTriangle(Vector3 vec1, double u1, double v1, V i++; } - public static RenderType getIcos4RenderType(ResourceLocation texture) { - return RenderType.create("icosahedron4", DefaultVertexFormat.BLOCK, VertexFormat.Mode.TRIANGLES, 256, makeIcosState(texture)); + public static RenderType getIcos4RenderType(Identifier texture) { + return RenderType.create( + MOD_ID + ":icosahedron4", + RenderSetup.builder(CCRenderPipelines.SOLID_TRIANGLES) + .withTexture("Sampler0", texture) + .useLightmap() + .createRenderSetup() + ); } - public static RenderType getIcos7RenderType(ResourceLocation texture) { - return RenderType.create("icosahedron7", DefaultVertexFormat.BLOCK, VertexFormat.Mode.QUADS, 256, makeIcosState(texture)); + public static RenderType getIcos7RenderType(Identifier texture) { + return RenderType.create( + MOD_ID + ":icosahedron7", + RenderSetup.builder(RenderPipelines.SOLID_BLOCK) + .withTexture("Sampler0", texture) + .useLightmap() + .createRenderSetup() + ); } - - public static RenderType.CompositeState makeIcosState(ResourceLocation texture) { - return RenderType.CompositeState.builder() - .setShaderState(RenderStateShard.BLOCK_SHADER) - .setTextureState(new RenderStateShard.TextureStateShard(texture, false, false)) - .setTransparencyState(RenderStateShard.NO_TRANSPARENCY) - .setLightmapState(RenderStateShard.LIGHTMAP) - .createCompositeState(false); - } - } diff --git a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java index 7bd13335..d582a942 100644 --- a/src/main/java/codechicken/lib/render/CCRenderEventHandler.java +++ b/src/main/java/codechicken/lib/render/CCRenderEventHandler.java @@ -2,53 +2,51 @@ import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Matrix4; +import net.covers1624.quack.util.CrashLock; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.state.BlockOutlineRenderState; import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.event.RenderHighlightEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.event.TickEvent; -import net.minecraftforge.eventbus.api.EventPriority; -import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.event.ClientTickEvent; +import net.neoforged.neoforge.client.event.ExtractBlockOutlineRenderStateEvent; +import net.neoforged.neoforge.client.event.RenderFrameEvent; +import net.neoforged.neoforge.common.NeoForge; + +import java.util.List; public class CCRenderEventHandler { + private static final CrashLock LOCK = new CrashLock("Already Initialized"); + public static int renderTime; public static float renderFrame; - private static boolean hasInit = false; - public static void init() { - if (!hasInit) { - MinecraftForge.EVENT_BUS.register(new CCRenderEventHandler()); - hasInit = true; - } + LOCK.lock(); + NeoForge.EVENT_BUS.addListener(CCRenderEventHandler::clientTick); + NeoForge.EVENT_BUS.addListener(CCRenderEventHandler::renderTick); + NeoForge.EVENT_BUS.addListener(EventPriority.LOW, CCRenderEventHandler::onBlockHighlight); } - @SubscribeEvent - public void clientTick(TickEvent.ClientTickEvent event) { - if (event.phase == TickEvent.Phase.END) { - renderTime++; - } + private static void clientTick(ClientTickEvent.Post event) { + renderTime++; } - @SubscribeEvent - public void renderTick(TickEvent.RenderTickEvent event) { - if (event.phase == TickEvent.Phase.START) { - renderFrame = event.renderTickTime; - } + private static void renderTick(RenderFrameEvent.Pre event) { + renderFrame = event.getPartialTick().getGameTimeDeltaPartialTick(true); } - @OnlyIn (Dist.CLIENT) - @SubscribeEvent (priority = EventPriority.LOW) - public void onBlockHighlight(RenderHighlightEvent.Block event) { - //We have found a CuboidRayTraceResult, Lets render it properly.. - BlockHitResult hit = event.getTarget(); - if (hit instanceof VoxelShapeBlockHitResult voxelHit) { + private static void onBlockHighlight(ExtractBlockOutlineRenderStateEvent event) { + if (event.getHitResult() instanceof VoxelShapeBlockHitResult hit) { event.setCanceled(true); - Matrix4 mat = new Matrix4(event.getPoseStack()); - mat.translate(voxelHit.getBlockPos()); - RenderUtils.bufferShapeHitBox(mat, event.getMultiBufferSource(), event.getCamera(), voxelHit.shape); + event.getLevelRenderState().blockOutlineRenderState = new BlockOutlineRenderState( + event.getBlockPos(), + event.isInTranslucentPass(), + event.isHighContrast(), + hit.shape, + List.of() + ); } } } diff --git a/src/main/java/codechicken/lib/render/CCRenderPipelines.java b/src/main/java/codechicken/lib/render/CCRenderPipelines.java new file mode 100644 index 00000000..9e982093 --- /dev/null +++ b/src/main/java/codechicken/lib/render/CCRenderPipelines.java @@ -0,0 +1,32 @@ +package codechicken.lib.render; + +import com.mojang.blaze3d.pipeline.RenderPipeline; +import com.mojang.blaze3d.vertex.DefaultVertexFormat; +import com.mojang.blaze3d.vertex.VertexFormat; +import net.minecraft.client.renderer.RenderPipelines; +import net.minecraft.resources.Identifier; + +import static codechicken.lib.CodeChickenLib.MOD_ID; + +/** + * Created by covers1624 on 7/6/26. + */ +public class CCRenderPipelines { + + public static final RenderPipeline SOLID_TRIANGLES = RenderPipelines.SOLID_BLOCK.toBuilder() + .withVertexFormat(DefaultVertexFormat.BLOCK, VertexFormat.Mode.TRIANGLES) + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/solid_triangles")) + .build(); + + public static final RenderPipeline POSITION_COLOR = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthWrite(true) // Overwritten from DEBUG_FILLED_SNIPPET as we very much want depth here. + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/position_color")) + .build(); + + public static final RenderPipeline POSITION_COLOR_NO_DEPTH = RenderPipeline.builder(RenderPipelines.DEBUG_FILLED_SNIPPET) + .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.QUADS) + .withDepthWrite(false) + .withLocation(Identifier.fromNamespaceAndPath(MOD_ID, "pipeline/position_color_no_depth")) + .build(); +} diff --git a/src/main/java/codechicken/lib/render/CCRenderState.java b/src/main/java/codechicken/lib/render/CCRenderState.java index 7415fd27..ed59f77a 100644 --- a/src/main/java/codechicken/lib/render/CCRenderState.java +++ b/src/main/java/codechicken/lib/render/CCRenderState.java @@ -2,7 +2,7 @@ import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.model.CachedFormat; +import codechicken.lib.render.buffer.BakedQuadVertexBuilder; import codechicken.lib.render.buffer.ISpriteAwareVertexConsumer; import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.render.lighting.LC; @@ -16,24 +16,30 @@ import codechicken.lib.vec.Matrix4; import codechicken.lib.vec.Vector3; import codechicken.lib.vec.Vertex5; -import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.vertex.*; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.rendertype.RenderType; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +import static java.util.Objects.requireNonNull; /** * The core of the CodeChickenLib render system. * Where possible assign a local var of CCRenderState to avoid millions of calls to instance(); * Uses a ThreadLocal system to assign each thread their own CCRenderState so we can use it in Multithreaded chunk batching. - * TODO, proper piping of BakedQuads and CCBakedQuads. + *

+ * Piping Vanilla {@link BakedQuad} instances through here possible via {@link BakedVertexSource}. */ public class CCRenderState { @@ -47,14 +53,13 @@ public class CCRenderState { public final VertexAttribute lightCoordAttrib = new LightCoordAttribute(); //pipeline state - public IVertexSource model; + public @Nullable IVertexSource model; public int firstVertexIndex; public int lastVertexIndex; public int vertexIndex; public CCRenderPipeline pipeline; - public VertexConsumer r; - public VertexFormat fmt; - public CachedFormat cFmt; + public @Nullable VertexConsumer r; + public @Nullable VertexFormat fmt; //context /** @@ -84,7 +89,7 @@ public class CCRenderState { //attribute storage public int side; public LC lc = new LC(); - public TextureAtlasSprite sprite; + public @Nullable TextureAtlasSprite sprite; private CCRenderState() { pipeline = new CCRenderPipeline(this); @@ -95,33 +100,22 @@ public static CCRenderState instance() { } /** - * Bind this {@link CCRenderState} instance to the {@link Tesselator} buffer - * and prepare to start drawing vertices for the given mode and {@link VertexFormat}. - * - * @param mode The Draw Mode. - * @param format The {@link VertexFormat}. - * @return The {@link BufferBuilder} instance from {@link Tesselator}. + * Bind this {@link CCRenderState} instance to a new {@link BakedQuadVertexBuilder}. */ - public BufferBuilder startDrawing(VertexFormat.Mode mode, VertexFormat format) { - BufferBuilder r = Tesselator.getInstance().getBuilder(); - r.begin(mode, format); - bind(r); + public BakedQuadVertexBuilder bindBaking() { + var r = new BakedQuadVertexBuilder(); + bind(r, DefaultVertexFormat.BLOCK); return r; } /** - * Bind this {@link CCRenderState} instance to the given {@link BufferBuilder} - * and prepare to start drawing vertices for the given mode and {@link VertexFormat}. + * Bind this {@link CCRenderState} instance to the given {@link BakedQuadVertexBuilder}. * - * @param mode The Draw Mode. - * @param format The {@link VertexFormat}. - * @param buffer The {@link BufferBuilder} to bind to. - * @return The same {@link BufferBuilder} that was passed in. + * @param r The {@link BakedQuadVertexBuilder}. */ - public BufferBuilder startDrawing(VertexFormat.Mode mode, VertexFormat format, BufferBuilder buffer) { - buffer.begin(mode, format); - bind(buffer); - return buffer; + public BakedQuadVertexBuilder bind(BakedQuadVertexBuilder r) { + bind(r, DefaultVertexFormat.BLOCK); + return r; } /** @@ -142,7 +136,16 @@ public void bind(BufferBuilder r) { public void bind(VertexConsumer consumer, VertexFormat format) { r = consumer; fmt = format; - cFmt = CachedFormat.lookup(format); + } + + /** + * Bind this {@link CCRenderState} to the given {@link VertexConsumer} and {@link RenderType}. + * + * @param consumer The {@link VertexConsumer} to bind to. + * @param renderType The {@link RenderType} of the {@link VertexConsumer}. + */ + public void bind(VertexConsumer consumer, RenderType renderType) { + bind(consumer, renderType.format()); } /** @@ -232,6 +235,10 @@ public void render(IVertexOperation... ops) { } public void render() { + if (r == null) throw new IllegalStateException("VertexConsumer is not bound."); + if (fmt == null) throw new IllegalStateException("VertexFormat is not bound?"); // this should be handled by the VertexConsumer assertion. + if (model == null) throw new IllegalStateException("Model is not set."); + Vertex5[] verts = model.getVertices(); for (vertexIndex = firstVertexIndex; vertexIndex < lastVertexIndex; vertexIndex++) { model.prepareVertex(this); @@ -246,46 +253,32 @@ public void runPipeline() { } public void writeVert() { - if (r instanceof ISpriteAwareVertexConsumer) { - ((ISpriteAwareVertexConsumer) r).sprite(sprite); + assert r != null; + assert fmt != null; + if (sprite != null && r instanceof ISpriteAwareVertexConsumer cons) { + cons.sprite(sprite); } - ImmutableList elements = fmt.getElements(); - for (int e = 0; e < elements.size(); e++) { - VertexFormatElement fmte = elements.get(e); - switch (fmte.getUsage()) { - case POSITION: - r.vertex(vert.vec.x, vert.vec.y, vert.vec.z); - break; - case UV: - int idx = fmte.getIndex(); - switch (idx) { - case 0 -> r.uv((float) vert.uv.u, (float) vert.uv.v); - case 1 -> r.overlayCoords(overlay); - case 2 -> r.uv2(brightness); - } - break; - case COLOR: - if (r instanceof BufferBuilder && ((BufferBuilder) r).defaultColorSet) { - //-_- Fucking mojang.. - ((BufferBuilder) r).nextElement(); - } else { - r.color(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); + List elements = fmt.getElements(); + for (VertexFormatElement fmte : elements) { + switch (fmte.usage()) { + case POSITION -> r.addVertex((float) vert.vec.x, (float) vert.vec.y, (float) vert.vec.z); + case UV -> { + switch (fmte.index()) { + case 0 -> r.setUv((float) vert.uv.u, (float) vert.uv.v); + case 1 -> r.setOverlay(overlay); + case 2 -> r.setLight(brightness); + default -> throw new UnsupportedOperationException("Unknown UV index. " + fmte.index()); } - break; - case NORMAL: - r.normal((float) normal.x, (float) normal.y, (float) normal.z); - break; - case PADDING: - break; - default: - throw new UnsupportedOperationException("Generic vertex format element"); + } + case COLOR -> r.setColor(colour >>> 24, colour >> 16 & 0xFF, colour >> 8 & 0xFF, alphaOverride >= 0 ? alphaOverride : colour & 0xFF); + case NORMAL -> r.setNormal((float) normal.x, (float) normal.y, (float) normal.z); + default -> throw new UnsupportedOperationException("Generic vertex format element"); } } - r.endVertex(); } public void setBrightness(BlockAndTintGetter world, BlockPos pos) { - brightness = LevelRenderer.getLightColor(world, world.getBlockState(pos), pos); + brightness = LevelRenderer.getLightColor(world, pos); } public void setBrightness(Entity entity, float frameDelta) { @@ -309,14 +302,10 @@ public ColourRGBA getColour() { } public VertexConsumer getConsumer() { - return r; + return requireNonNull(r, "VertexConsumer is not bound."); } public VertexFormat getVertexFormat() { - return fmt; - } - - public void draw() { - Tesselator.getInstance().end(); + return requireNonNull(fmt, "VertexFormat is not bound."); } } diff --git a/src/main/java/codechicken/lib/render/CachedModel.java b/src/main/java/codechicken/lib/render/CachedModel.java new file mode 100644 index 00000000..8e9908c4 --- /dev/null +++ b/src/main/java/codechicken/lib/render/CachedModel.java @@ -0,0 +1,200 @@ +//package codechicken.lib.render; +// +//import com.mojang.blaze3d.buffers.GpuBuffer; +//import com.mojang.blaze3d.systems.RenderPass; +//import com.mojang.blaze3d.systems.RenderSystem; +//import com.mojang.blaze3d.vertex.*; +//import net.minecraft.client.renderer.rendertype.RenderType; +//import net.minecraft.util.Mth; +//import org.jetbrains.annotations.Nullable; +//import org.joml.Vector3f; +//import org.joml.Vector4f; +//import org.lwjgl.system.MemoryUtil; +// +//import java.util.OptionalDouble; +//import java.util.OptionalInt; +//import java.util.function.BiConsumer; +//import java.util.function.Consumer; +//import java.util.function.IntConsumer; +// +///** +// * Created by covers1624 on 11/3/25. +// */ +//public class CachedModel { +// +// private final String label; +// private final RenderType.CompositeRenderType renderType; +// private final BiConsumer factory; +// +// private final ByteBufferBuilder builder; +// +// private boolean dirty = true; +// private @Nullable GpuBuffer vertexBuffer; +// +// private @Nullable IndexBuffer indexBuffer; +// +// public CachedModel(String label, RenderType renderType, BiConsumer factory) { +// this.label = label; +// this.renderType = (RenderType.CompositeRenderType) renderType; +// this.factory = factory; +// +// builder = new ByteBufferBuilder(renderType.bufferSize()); +// } +// +// public void setDirty() { +// dirty = true; +// } +// +// public void render(Consumer cons) { +// renderType.setupRenderState(); +// if (dirty) { +// // Re-build the mesh data if we are marked dirty, we cache the underlying native byte buffer used, +// // we may wish to consider a cleanup heuristic, after 5 mins or smth. +// builder.discard(); +// BufferBuilder buffer = new BufferBuilder(builder, renderType.mode(), renderType.format()); +// factory.accept(renderType.format(), buffer); +// uploadMesh(buffer.buildOrThrow()); +// builder.discard(); +// dirty = false; +// } +// // These should be impossible, uploadMesh always sets both. +// assert vertexBuffer != null; +// assert indexBuffer != null; +// +// // Mirrors all the logic in RenderType.CompositeRenderType#render +// // However, uses our cached gpu buffers, and fires a callback to modify the RenderPass before draw. +// var target = renderType.state.outputState.getRenderTarget(); +// var colourTexture = RenderSystem.outputColorTextureOverride != null ? RenderSystem.outputColorTextureOverride : target.getColorTextureView(); +// var depthTexture = target.useDepth ? (RenderSystem.outputDepthTextureOverride != null ? RenderSystem.outputDepthTextureOverride : target.getDepthTextureView()) : null; +// +// var dynamicTransforms = RenderSystem.getDynamicUniforms() +// .writeTransform( +// RenderSystem.getModelViewMatrix(), +// new Vector4f(1.0F, 1.0F, 1.0F, 1.0F), +// new Vector3f(), +// RenderSystem.getTextureMatrix(), +// RenderSystem.getShaderLineWidth() +// ); +// +// try (var pass = RenderSystem.getDevice() +// .createCommandEncoder() +// .createRenderPass(() -> "CachedModel draw: " + label, colourTexture, OptionalInt.empty(), depthTexture, OptionalDouble.empty())) { +// pass.setPipeline(renderType.pipeline()); +// var scissorState = RenderSystem.getScissorStateForRenderTypeDraws(); +// if (scissorState.enabled()) { +// pass.enableScissor(scissorState.x(), scissorState.y(), scissorState.width(), scissorState.height()); +// } +// +// RenderSystem.bindDefaultUniforms(pass); +// pass.setUniform("DynamicTransforms", dynamicTransforms); +// cons.accept(pass); +// +// pass.setVertexBuffer(0, vertexBuffer); +// +// for (int i = 0; i < 12; i++) { +// var texture = RenderSystem.getShaderTexture(i); +// if (texture != null) { +// pass.bindSampler("Sampler" + i, texture); +// } +// } +// +// pass.setIndexBuffer(indexBuffer.buffer, indexBuffer.type); +// pass.drawIndexed(0, 0, indexBuffer.indexCount(), 1); +// } +// renderType.clearRenderState(); +// } +// +// private void uploadMesh(MeshData mesh) { +// try (mesh) { +// vertexBuffer = VertexFormat.uploadToBuffer( +// vertexBuffer, +// mesh.vertexBuffer(), +// GpuBuffer.USAGE_VERTEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Vertex Buffer for CachedModel: " + label +// ); +// +// if (mesh.indexBuffer() == null) { +// indexBuffer = buildIndexBuffer( +// indexBuffer != null ? indexBuffer.buffer : null, +// mesh.drawState().mode(), +// mesh.drawState().indexCount() +// ); +// } else { +// indexBuffer = new IndexBuffer( +// VertexFormat.uploadToBuffer( +// indexBuffer != null ? indexBuffer.buffer : null, +// mesh.vertexBuffer(), +// GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Index Buffer for CachedModel: " + label +// ), +// mesh.drawState().indexType(), +// mesh.drawState().indexCount() +// ); +// } +// } +// } +// +// // Mostly mirrors RenderSystem.AutoStorageIndexBuffer, however, does not over-provision the buffer. +// private IndexBuffer buildIndexBuffer(@Nullable GpuBuffer indexBuffer, VertexFormat.Mode mode, int indexCount) { +// var gen = getGenForMode(mode); +// +// var type = VertexFormat.IndexType.least(indexCount); +// var buffer = MemoryUtil.memAlloc(Mth.roundToward(indexCount * type.bytes, 4)); +// IntConsumer inserter = switch (type) { +// case SHORT -> e -> buffer.putShort((short) e); +// case INT -> buffer::putInt; +// }; +// +// try { +// for (int i = 0; i < indexCount; i += gen.indexStride) { +// gen.func.buildIndex(inserter, i * gen.vertexStride / gen.indexStride); +// } +// +// buffer.flip(); +// +// return new IndexBuffer( +// VertexFormat.uploadToBuffer( +// indexBuffer, +// buffer, +// GpuBuffer.USAGE_INDEX | GpuBuffer.USAGE_COPY_DST, +// () -> "Index Buffer for CachedModel: " + label +// ), +// type, +// indexCount +// ); +// } finally { +// MemoryUtil.memFree(buffer); +// } +// } +// +// private static IndexGen getGenForMode(VertexFormat.Mode mode) { +// return switch (mode) { +// case QUADS -> new IndexGen(4, 6, (cons, i) -> { +// cons.accept(i); +// cons.accept(i + 1); +// cons.accept(i + 2); +// cons.accept(i + 2); +// cons.accept(i + 3); +// cons.accept(i); +// }); +// case LINES -> new IndexGen(4, 6, (cons, i) -> { +// cons.accept(i); +// cons.accept(i + 1); +// cons.accept(i + 2); +// cons.accept(i + 3); +// cons.accept(i + 2); +// cons.accept(i + 1); +// }); +// default -> new IndexGen(1, 1, IntConsumer::accept); +// }; +// } +// +// private record IndexGen(int vertexStride, int indexStride, GenFunc func) { +// } +// +// private interface GenFunc { +// void buildIndex(IntConsumer cons, int i); +// } +// +// private record IndexBuffer(GpuBuffer buffer, VertexFormat.IndexType type, int indexCount) { } +//} diff --git a/src/main/java/codechicken/lib/render/ExtentsContainer.java b/src/main/java/codechicken/lib/render/ExtentsContainer.java new file mode 100644 index 00000000..6d5f1695 --- /dev/null +++ b/src/main/java/codechicken/lib/render/ExtentsContainer.java @@ -0,0 +1,36 @@ +package codechicken.lib.render; + +import codechicken.lib.render.buffer.ExtentsConsumer; +import codechicken.lib.vec.Cuboid6; +import com.mojang.blaze3d.vertex.VertexConsumer; +import org.joml.Vector3fc; +import org.jspecify.annotations.Nullable; + +import java.util.function.Consumer; + +/** + * Created by covers1624 on 7/26/26. + */ +public final class ExtentsContainer { + + private @Nullable Cuboid6 extents; + + public void visitExtents(Consumer extents, Consumer cons) { + var box = get(cons); + extents.accept(box.min.vector3f()); + extents.accept(box.max.vector3f()); + } + + public Cuboid6 get(Consumer extentsBuilder) { + if (extents == null) { + Cuboid6 box = new Cuboid6(); + extentsBuilder.accept(new ExtentsConsumer(box::enclose)); + extents = box; + } + return extents; + } + + public void reset() { + extents = null; + } +} diff --git a/src/main/java/codechicken/lib/render/ModelHelper.java b/src/main/java/codechicken/lib/render/ModelHelper.java deleted file mode 100644 index d127a629..00000000 --- a/src/main/java/codechicken/lib/render/ModelHelper.java +++ /dev/null @@ -1,187 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.vec.Vector3; -import codechicken.lib.vec.Vertex5; -import com.mojang.blaze3d.vertex.VertexFormat; - -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -/** - * Various helpers for CCModels - *

- * Created by covers1624 on 21/06/2017. - */ -public class ModelHelper { - - /** - * Quadulates a CCModel. - * Only Position and UV data is copied. - * - * @param inModel The in model. - * @return The new model. - */ - public static CCModel quadulate(CCModel inModel) { - if (inModel.vertexMode == VertexFormat.Mode.QUADS) { - throw new IllegalArgumentException("Cannot quadulate a quad model. Check if the model is triangles before calling this"); - } - List verts = new LinkedList<>(); - Iterator iter = verts.iterator(); - while (iter.hasNext()) { - verts.add(iter.next()); - verts.add(iter.next()); - Vertex5 copy = iter.next(); - verts.add(copy); - verts.add(copy.copy()); - } - CCModel outModel = CCModel.quadModel(verts.size()); - outModel.verts = verts.toArray(outModel.verts); - return outModel; - } - - /** - * Attempts to combine square faces. - * A NEW model is returned with combined faces. - * You WILL need to copy / compute normals yourself. - * - * @param model Input. - * @return New model with combined faces. - */ - public static CCModel simplifyModel(CCModel model) { - List verts = new LinkedList<>(); - Collections.addAll(verts, model.getVertices()); - List combinedVerts = simplifyModel(verts); - CCModel outModel = CCModel.quadModel(combinedVerts.size()); - outModel.verts = combinedVerts.toArray(outModel.verts); - return outModel; - } - - /** - * Attempts to combine square faces. - * - * @param in Quads in. - * @return Quads out. - * @author RwTema - */ - public static LinkedList simplifyModel(List in) { - - LinkedList faces = new LinkedList<>(); - Iterator iter = in.iterator(); - while (iter.hasNext()) { - Face f = Face.loadFromIterator(iter); - - faces.removeIf(f::attemptToCombine); - faces.add(f); - } - - LinkedList out = new LinkedList<>(); - for (Face f : faces) { - Collections.addAll(out, f.verts); - } - - return out; - } - - private static class Face { - - public static Face loadFromIterator(Iterator iter) { - - Face f = new Face(new Vertex5[4]); - for (int i = 0; i < 4; i++) { - f.verts[i] = iter.next(); - } - - return f; - } - - public Vertex5[] verts; - - public Vertex5 vec(int s) { - - return verts[s & 3]; - } - - public void setVec(int s, Vertex5 newVec) { - - verts[s & 3] = newVec; - } - - public Face(Vertex5... v) { - - assert v.length == 4; - this.verts = v; - } - - public boolean isPolygon() { - - for (int i = 0; i < 4; i++) { - if (vec(i).vec.equalsT(vec(i + 1).vec)) { - return true; - } - } - return false; - } - - public Face reverse() { - - verts = new Vertex5[] { verts[3], verts[2], verts[1], verts[0] }; - return this; - } - - public boolean attemptToCombine(Face other) { - - if (isPolygon() || other.isPolygon()) { - return false; - } - - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - other.reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - if (attemptToCombineUnflipped(other)) { - return true; - } - reverse(); - other.reverse(); - return false; - } - - public boolean equalVert(Vertex5 a, Vertex5 b) { - - return a.vec.equalsT(b.vec) && a.uv.equals(b.uv); - } - - public boolean attemptToCombineUnflipped(Face other) { - - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - if (equalVert(vec(i), vec(j)) && equalVert(vec(i + 1), vec(j - 1))) { - Vector3 l1 = (vec(i - 1).vec.copy().subtract(vec(i).vec)).normalize(); - Vector3 l2 = (vec(i + 2).vec.copy().subtract(vec(i + 1).vec)).normalize(); - - Vector3 l3 = (other.vec(j).vec.copy().subtract(other.vec(j + 1).vec)).normalize(); - Vector3 l4 = (other.vec(j - 1).vec.copy().subtract(other.vec(j - 2).vec)).normalize(); - - if (l1.equalsT(l3) && l2.equalsT(l4)) { - setVec(i, other.vec(j + 1)); - setVec(i + 1, other.vec(j - 2)); - return true; - } - } - } - } - return false; - } - } -} diff --git a/src/main/java/codechicken/lib/render/RenderUtils.java b/src/main/java/codechicken/lib/render/RenderUtils.java index bd20ff3b..6b26ad8c 100644 --- a/src/main/java/codechicken/lib/render/RenderUtils.java +++ b/src/main/java/codechicken/lib/render/RenderUtils.java @@ -2,21 +2,21 @@ import codechicken.lib.render.buffer.TransformingVertexConsumer; import codechicken.lib.vec.*; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Camera; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.rendertype.RenderType; +import net.minecraft.client.renderer.rendertype.RenderTypes; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.Material; import net.minecraft.core.BlockPos; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; -import net.minecraftforge.client.ForgeHooksClient; -import net.minecraftforge.client.extensions.common.IClientFluidTypeExtensions; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidType; +import net.neoforged.neoforge.client.ClientHooks; +import net.neoforged.neoforge.client.extensions.common.IClientFluidTypeExtensions; +import net.neoforged.neoforge.fluids.FluidStack; +import net.neoforged.neoforge.fluids.FluidType; import java.util.ArrayList; import java.util.List; @@ -32,17 +32,7 @@ public class RenderUtils { } } - public static RenderType getFluidRenderType() { - return RenderType.create("ccl:fluid_render", DefaultVertexFormat.POSITION_COLOR_TEX_LIGHTMAP, VertexFormat.Mode.QUADS, 256, RenderType.CompositeState.builder() - .setShaderState(RenderType.POSITION_COLOR_TEX_LIGHTMAP_SHADER) - .setTextureState(RenderType.BLOCK_SHEET) - .setTransparencyState(RenderType.TRANSLUCENT_TRANSPARENCY) - .setLightmapState(RenderType.LIGHTMAP) - .createCompositeState(false) - ); - } - - public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, RenderType renderType, MultiBufferSource source, FluidStack stack, Cuboid6 bound, double capacity, double res) { + public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, FluidStack stack, Cuboid6 bound, double capacity, double res) { if (stack.isEmpty()) { return; } @@ -54,10 +44,9 @@ public static void renderFluidCuboid(CCRenderState ccrs, Matrix4 mat, RenderType bound.max.y = bound.min.y + (bound.max.y - bound.min.y) * capacity; } IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(type); - Material material = ForgeHooksClient.getBlockMaterial(props.getStillTexture(stack)); - ccrs.bind(renderType, source); + TextureAtlasSprite sprite = Minecraft.getInstance().getAtlasManager().get(ClientHooks.getBlockMaterial(props.getStillTexture(stack))); ccrs.baseColour = props.getTintColor(stack) << 8 | alpha; - makeFluidModel(bound, material.sprite(), res).render(ccrs, mat); + makeFluidModel(bound, sprite, res).render(ccrs, mat); } public static CCModel makeFluidModel(Cuboid6 bound, TextureAtlasSprite tex, double res) { @@ -65,6 +54,7 @@ public static CCModel makeFluidModel(Cuboid6 bound, TextureAtlasSprite tex, doub List verts = new ArrayList<>(); makeFluidCuboid(verts, bound, tex, res); model.verts = verts.toArray(new Vertex5[0]); + model.computeNormals(); return model; } @@ -139,47 +129,50 @@ public static void makeFluidQuadVertices(List vertices, Vector3 base, V * @param a Alpha channel. */ public static void bufferCuboidSolid(VertexConsumer builder, Cuboid6 c, float r, float g, float b, float a) { - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.min.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.min.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.min.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); - builder.vertex(c.max.x, c.min.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.min.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.max.y, c.max.z).color(r, g, b, a).endVertex(); - builder.vertex(c.max.x, c.min.y, c.max.z).color(r, g, b, a).endVertex(); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.min.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.max.y, (float) c.max.z).setColor(r, g, b, a); + builder.addVertex((float) c.max.x, (float) c.min.y, (float) c.max.z).setColor(r, g, b, a); } + @Deprecated public static void bufferHitbox(Matrix4 mat, MultiBufferSource getter, Camera renderInfo, Cuboid6 cuboid) { - Vec3 projectedView = renderInfo.getPosition(); + Vec3 projectedView = renderInfo.position(); bufferHitBox(mat.copy().translate(-projectedView.x, -projectedView.y, -projectedView.z), getter, cuboid); } + @Deprecated public static void bufferHitBox(Matrix4 mat, MultiBufferSource getter, Cuboid6 cuboid) { - VertexConsumer builder = new TransformingVertexConsumer(getter.getBuffer(RenderType.lines()), mat); + VertexConsumer builder = new TransformingVertexConsumer(getter.getBuffer(RenderTypes.lines()), mat); bufferCuboidOutline(builder, cuboid.copy().expand(0.0020000000949949026D), 0.0F, 0.0F, 0.0F, 0.4F); } + @Deprecated public static void bufferCuboidOutline(VertexConsumer builder, Cuboid6 c, float r, float g, float b, float a) { bufferLinePair(builder, c.min.x, c.min.y, c.min.z, c.max.x, c.min.y, c.min.z, r, g, b, a); bufferLinePair(builder, c.max.x, c.min.y, c.min.z, c.max.x, c.min.y, c.max.z, r, g, b, a); @@ -195,28 +188,32 @@ public static void bufferCuboidOutline(VertexConsumer builder, Cuboid6 c, float bufferLinePair(builder, c.min.x, c.min.y, c.max.z, c.min.x, c.max.y, c.max.z, r, g, b, a); } + @Deprecated public static void bufferShapeHitBox(Matrix4 mat, MultiBufferSource buffers, Camera renderInfo, VoxelShape shape) { - Vec3 projectedView = renderInfo.getPosition(); + Vec3 projectedView = renderInfo.position(); bufferShapeHitBox(mat.copy().translate(-projectedView.x, -projectedView.y, -projectedView.z), buffers, shape); } + @Deprecated public static void bufferShapeHitBox(Matrix4 mat, MultiBufferSource buffers, VoxelShape shape) { - VertexConsumer builder = new TransformingVertexConsumer(buffers.getBuffer(RenderType.lines()), mat); + VertexConsumer builder = new TransformingVertexConsumer(buffers.getBuffer(RenderTypes.lines()), mat); bufferShapeOutline(builder, shape, 0.0F, 0.0F, 0.0F, 0.4F); } + @Deprecated public static void bufferShapeOutline(VertexConsumer builder, VoxelShape shape, float r, float g, float b, float a) { shape.forAllEdges((x1, y1, z1, x2, y2, z2) -> { bufferLinePair(builder, x1, y1, z1, x2, y2, z2, r, g, b, a); }); } + @Deprecated private static void bufferLinePair(VertexConsumer builder, double x1, double y1, double z1, double x2, double y2, double z2, float r, float g, float b, float a) { Vector3 v1 = vectors[0].set(x1, y1, z1).subtract(x2, y2, z2); double d = v1.mag(); v1.divide(d); - builder.vertex(x1, y1, z1).color(r, g, b, a).normal((float) v1.x, (float) v1.y, (float) v1.z).endVertex(); - builder.vertex(x2, y2, z2).color(r, g, b, a).normal((float) v1.x, (float) v1.y, (float) v1.z).endVertex(); + builder.addVertex((float) x1, (float) y1, (float) z1).setColor(r, g, b, a).setNormal((float) v1.x, (float) v1.y, (float) v1.z); + builder.addVertex((float) x2, (float) y2, (float) z2).setColor(r, g, b, a).setNormal((float) v1.x, (float) v1.y, (float) v1.z); } public static Matrix4 getMatrix(Matrix4 in, Vector3 translation, Rotation rotation, double scale) { diff --git a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java b/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java deleted file mode 100644 index 220f71d0..00000000 --- a/src/main/java/codechicken/lib/render/block/BlockRenderingRegistry.java +++ /dev/null @@ -1,119 +0,0 @@ -package codechicken.lib.render.block; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.core.Holder; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.material.Fluid; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.registries.ForgeRegistries; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - -/** - * Registry for {@link ICCBlockRenderer} instances. - *

- * Created by covers1624 on 8/09/2016. - * - * @see ICCBlockRenderer - */ -public class BlockRenderingRegistry { - - private static boolean initialized = false; - - private static final Map, ICCBlockRenderer> blockRenderers = new HashMap<>(); - private static final Map, ICCBlockRenderer> fluidRenderers = new HashMap<>(); - private static final List globalRenderers = new ArrayList<>(); - - @OnlyIn (Dist.CLIENT) - public static void init() { - if (!initialized) { - Minecraft mc = Minecraft.getInstance(); - BlockRenderDispatcher parentDispatcher = mc.getBlockRenderer(); - mc.blockRenderer = new CCBlockRendererDispatcher(parentDispatcher, mc.getBlockColors()); - initialized = true; - } - } - - /** - * Register an {@link ICCBlockRenderer} for the given block. - *

- * Unlike {@link #registerGlobalRenderer}, registering your {@link ICCBlockRenderer} via this method - * is guaranteed to only be tested against the block provided. - * - * @param block The block to register to. - * @param renderer The {@link ICCBlockRenderer}. - * @throws IllegalArgumentException If the same Block is registered twice. - */ - public static synchronized void registerRenderer(Block block, ICCBlockRenderer renderer) { - Holder delegate = ForgeRegistries.BLOCKS.getDelegateOrThrow(block); - ICCBlockRenderer prev = blockRenderers.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); - if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for block. " + ForgeRegistries.BLOCKS.getKey(block)); - } - blockRenderers.put(delegate, renderer); - } - - /** - * Register an {@link ICCBlockRenderer} for the given fluid. - *

- * Unlike {@link #registerGlobalRenderer}, registering your {@link ICCBlockRenderer} via this method - * is guaranteed to only be tested against the fluid provided. - * - * @param fluid The fluid to register to. - * @param renderer The {@link ICCBlockRenderer}. - * @throws IllegalArgumentException If the same Fluid is registered twice. - */ - public static synchronized void registerRenderer(Fluid fluid, ICCBlockRenderer renderer) { - Holder delegate = ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid); - ICCBlockRenderer prev = blockRenderers.get(delegate); - if (prev != null) { - throw new IllegalArgumentException("Renderer already registered for fluid. " + ForgeRegistries.FLUIDS.getKey(fluid)); - } - fluidRenderers.put(delegate, renderer); - } - - /** - * Register a global {@link ICCBlockRenderer}, capable of overriding the - * rendering of any block in world. - * - * @param renderer The {@link ICCBlockRenderer}. - */ - public static synchronized void registerGlobalRenderer(ICCBlockRenderer renderer) { - globalRenderers.add(renderer); - } - - @Nullable - static ICCBlockRenderer findFor(Block block, Predicate pred) { - for (ICCBlockRenderer renderer : globalRenderers) { - if (pred.test(renderer)) { - return renderer; - } - } - - ICCBlockRenderer found = blockRenderers.get(ForgeRegistries.BLOCKS.getDelegateOrThrow(block)); - if (found != null && pred.test(found)) return found; - - return null; - } - - @Nullable - static ICCBlockRenderer findFor(Fluid fluid, Predicate pred) { - for (ICCBlockRenderer renderer : globalRenderers) { - if (pred.test(renderer)) { - return renderer; - } - } - - ICCBlockRenderer found = fluidRenderers.get(ForgeRegistries.FLUIDS.getDelegateOrThrow(fluid)); - if (found != null && pred.test(found)) return found; - - return null; - } -} diff --git a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java b/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java deleted file mode 100644 index f5ede1a4..00000000 --- a/src/main/java/codechicken/lib/render/block/CCBlockRendererDispatcher.java +++ /dev/null @@ -1,147 +0,0 @@ -package codechicken.lib.render.block; - -import codechicken.lib.internal.ExceptionMessageEventHandler; -import codechicken.lib.internal.proxy.ProxyClient; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.CrashReport; -import net.minecraft.CrashReportCategory; -import net.minecraft.ReportedException; -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.block.BlockRenderDispatcher; -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.client.model.data.ModelData; -import net.minecraftforge.registries.ForgeRegistries; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.util.concurrent.TimeUnit; - -import static codechicken.lib.util.LambdaUtils.tryOrNull; - -/** - * Created by covers1624 on 8/09/2016. - */ -public class CCBlockRendererDispatcher extends BlockRenderDispatcher { - - private static final Logger logger = LogManager.getLogger(); - - public final BlockRenderDispatcher parentDispatcher; - private static long lastTime; - - public CCBlockRendererDispatcher(BlockRenderDispatcher parent, BlockColors blockColours) { - super(parent.getBlockModelShaper(), parent.blockEntityRenderer, blockColours); - parentDispatcher = parent; - this.modelRenderer = parent.modelRenderer; - this.liquidBlockRenderer = parent.liquidBlockRenderer; - } - - //In world. - @Override - public void renderBatched(BlockState state, BlockPos pos, BlockAndTintGetter level, PoseStack stack, VertexConsumer builder, boolean checkSides, RandomSource rand, ModelData modelData, RenderType renderType, boolean queryModelSpecificData) { - try { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(state.getBlock(), e -> e.canHandleBlock(level, pos, state, renderType)); - if (renderer != null) { - renderer.renderBlock(state, pos, level, stack, builder, rand, modelData, renderType); - return; - } - } catch (Throwable t) { - if (ProxyClient.catchBlockRenderExceptions) { - handleCaughtException(t, state, pos, level); - return; - } - CrashReport crashreport = CrashReport.forThrowable(t, "Tessellating CCL block in world"); - CrashReportCategory crashreportcategory = crashreport.addCategory("Block being tessellated"); - CrashReportCategory.populateBlockDetails(crashreportcategory, level, pos, state); - throw new ReportedException(crashreport); - } - try { - parentDispatcher.renderBatched(state, pos, level, stack, builder, checkSides, rand, modelData, renderType, queryModelSpecificData); - } catch (Throwable t) { - if (ProxyClient.catchBlockRenderExceptions) { - handleCaughtException(t, state, pos, level); - return; - } - throw t; - } - } - - //Block Damage - @Override - public void renderBreakingTexture(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack matrixStackIn, VertexConsumer vertexBuilderIn, ModelData data) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(state.getBlock(), e -> e.canHandleBlock(world, pos, state, null)); - if (renderer != null) { - renderer.renderBreaking(state, pos, world, matrixStackIn, vertexBuilderIn, data); - } else { - parentDispatcher.renderBreakingTexture(state, pos, world, matrixStackIn, vertexBuilderIn, data); - } - } - - //Fluids - @Override - public void renderLiquid(BlockPos pos, BlockAndTintGetter world, VertexConsumer builder, BlockState blockState, FluidState fluidState) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(fluidState.getType(), e -> e.canHandleFluid(world, pos, blockState, fluidState)); - if (renderer != null) { - renderer.renderFluid(pos, world, builder, blockState, fluidState); - return; - } - parentDispatcher.renderLiquid(pos, world, builder, blockState, fluidState); - } - - //From an entity - @Override - public void renderSingleBlock(BlockState blockStateIn, PoseStack matrixStackIn, MultiBufferSource bufferTypeIn, int combinedLightIn, int combinedOverlayIn, ModelData modelData, RenderType renderType) { - ICCBlockRenderer renderer = BlockRenderingRegistry.findFor(blockStateIn.getBlock(), e -> e.canHandleEntity(blockStateIn)); - if (renderer != null) { - renderer.renderEntity(blockStateIn, matrixStackIn, bufferTypeIn, combinedLightIn, combinedOverlayIn, modelData, renderType); - } else { - parentDispatcher.renderSingleBlock(blockStateIn, matrixStackIn, bufferTypeIn, combinedLightIn, combinedOverlayIn, modelData, renderType); - } - } - - @SuppressWarnings ("Convert2MethodRef")//Suppress these, the lambdas need to be synthetic functions instead of a method reference. - private static void handleCaughtException(Throwable t, BlockState inState, BlockPos pos, BlockAndTintGetter world) { - Block inBlock = inState.getBlock(); - BlockEntity tile = world.getBlockEntity(pos); - - StringBuilder builder = new StringBuilder("\n CCL has caught an exception whilst rendering a block\n"); - builder.append(" BlockPos: ").append(String.format("x:%s, y:%s, z:%s", pos.getX(), pos.getY(), pos.getZ())).append("\n"); - builder.append(" Block Class: ").append(tryOrNull(() -> inBlock.getClass())).append("\n"); - builder.append(" Registry Name: ").append(tryOrNull(() -> ForgeRegistries.BLOCKS.getKey(inBlock))).append("\n"); - builder.append(" State: ").append(inState).append("\n"); - builder.append(" Tile at position\n"); - builder.append(" Tile Class: ").append(tryOrNull(() -> tile.getClass())).append("\n"); - builder.append(" Tile Id: ").append(tryOrNull(() -> ForgeRegistries.BLOCK_ENTITY_TYPES.getKey(tile.getType()))).append("\n"); - builder.append(" Tile NBT: ").append(tryOrNull(() -> tile.saveWithFullMetadata())).append("\n"); - builder.append("This functionality can be disabled in the CCL config file.\n"); - if (ProxyClient.messagePlayerOnRenderExceptionCaught) { - builder.append("You can also turn off player messages in the CCL config file.\n"); - } - String logMessage = builder.toString(); - String key = ExceptionUtils.getStackTrace(t) + logMessage; - if (ExceptionMessageEventHandler.exceptionMessageCache.add(key)) { - logger.error(logMessage, t); - } - Player player = Minecraft.getInstance().player; - if (ProxyClient.messagePlayerOnRenderExceptionCaught && player != null) { - long time = System.nanoTime(); - if (TimeUnit.NANOSECONDS.toSeconds(time - lastTime) > 5) { - lastTime = time; - player.sendSystemMessage(Component.literal("CCL Caught an exception rendering a block. See the log for info.")); - } - } - } - -} diff --git a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java b/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java deleted file mode 100644 index 21a73861..00000000 --- a/src/main/java/codechicken/lib/render/block/ICCBlockRenderer.java +++ /dev/null @@ -1,136 +0,0 @@ -package codechicken.lib.render.block; - -import codechicken.lib.render.CCRenderState; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.renderer.LevelRenderer; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.FluidState; -import net.minecraftforge.client.model.data.ModelData; -import org.jetbrains.annotations.Nullable; - -/** - * Capable of rendering Blocks and Fluids directly to the chunk buffer. - *

- * Created by covers1624 on 8/09/2016. - * - * @see BlockRenderingRegistry - */ -public interface ICCBlockRenderer { - - //region Block - - /** - * Called to evaluate weather this ICCBlockRenderer will be called for the specified BlockState. - * - * @param world The world. - * @param pos The pos. - * @param blockState The BlockState. - * @param renderType The {@link RenderType}, {@code null} for breaking. - * @return If you wish to render the BlockState. - */ - boolean canHandleBlock(BlockAndTintGetter world, BlockPos pos, BlockState blockState, @Nullable RenderType renderType); - - /** - * Called to render your block in world. - * You MUST use the provided {@link VertexConsumer}. - * THE BUFFER IS ALREADY DRAWING! - * YOU MAY BE FIRED ON THE CHUNK BATCHING THREAD! - * - * @param state Your state. - * @param pos Position. - * @param world World. - * @param mStack The {@link PoseStack}. - * @param builder The {@link VertexConsumer} to add quads to. - * @param random Position seeded Random for this block position. - * @param data Any ModelData. - * @param renderType The {@link RenderType}, {@code null} for breaking. - */ - void renderBlock(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, RandomSource random, ModelData data, @Nullable RenderType renderType); - - /** - * Called when vanilla is rendering breaking texture over your block. - * Usually just render out your normal quads. - * - * @param state Your state. - * @param pos Position. - * @param world World. - * @param mStack The {@link PoseStack}. - * @param builder The {@link VertexConsumer} to add quads to. - * @param data Any ModelData. - */ - default void renderBreaking(BlockState state, BlockPos pos, BlockAndTintGetter world, PoseStack mStack, VertexConsumer builder, ModelData data) { - CCRenderState ccrs = CCRenderState.instance(); - ccrs.overlay = OverlayTexture.NO_OVERLAY; - ccrs.brightness = LevelRenderer.getLightColor(world, state, pos); - mStack.pushPose(); - renderBlock(state, pos, world, mStack, builder, RandomSource.create(), data, null); - mStack.popPose(); - } - //endregion - - //region Rendering from an entity, Minecarts, enderman, etc. - - /** - * Called to evaluate weather this ICCBlockRenderer will be called to handle - * {@link #renderEntity} for the given BlockState. - * - * @param state The state. - * @return If you wish to render this block. - */ - default boolean canHandleEntity(BlockState state) { - return false; - } - - /** - * Called for misc entities holding or have blocks as part of their model. - * IronGolems, Enderman, Mooshroom, Minecarts, TNT. - * - * @param state The BlockState to render. - * @param nStack The {@link PoseStack}. - * @param builder The {@link MultiBufferSource} - * @param packedLight The {@link LightTexture} packed coords. - * @param packedOverlay The {@link OverlayTexture} packed coords. - * @param data Any ModelData. - * @param renderType The {@link RenderType} may be {@code null}. - */ - default void renderEntity(BlockState state, PoseStack nStack, MultiBufferSource builder, int packedLight, int packedOverlay, ModelData data, @Nullable RenderType renderType) { } - //endregion - - //region Fluids - - /** - * Called to evaluate weather this ICCBlockRenderer will be called for the specified IFluidState. - * - * @param world The world. - * @param pos The pos. - * @param blockState The {@link BlockState} - * @param fluidState The {@link FluidState}. - * @return If you wish to render the {@link FluidState}. - */ - default boolean canHandleFluid(BlockAndTintGetter world, BlockPos pos, BlockState blockState, FluidState fluidState) { - return false; - } - - /** - * Called to render your fluid in world. - * You MUST use the provided {@link VertexConsumer}. - * THE BUFFER IS ALREADY DRAWING! - * YOU MAY BE FIRED ON THE CHUNK BATCHING THREAD! - * - * @param pos Position. - * @param world World. - * @param builder The {@link VertexConsumer}. - * @param blockState The {@link BlockState} - * @param fluidState The {@link FluidState} - */ - default void renderFluid(BlockPos pos, BlockAndTintGetter world, VertexConsumer builder, BlockState blockState, FluidState fluidState) { } - //endregion -} diff --git a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java index cc2b9f95..e07a6b64 100644 --- a/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/AlphaOverrideVertexConsumer.java @@ -19,7 +19,12 @@ public AlphaOverrideVertexConsumer(VertexConsumer delegate, int alpha) { } @Override - public VertexConsumer color(int r, int g, int b, int a) { - return super.color(r, g, b, alpha); + public VertexConsumer setColor(int r, int g, int b, int a) { + return super.setColor(r, g, b, alpha); + } + + @Override + public VertexConsumer setColor(int color) { + return super.setColor((color & 0xFFFFFF) | alpha & 0xFF); } } diff --git a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java index b72a3f1d..c7a62fa9 100644 --- a/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java +++ b/src/main/java/codechicken/lib/render/buffer/BakedQuadVertexBuilder.java @@ -1,17 +1,16 @@ package codechicken.lib.render.buffer; -import codechicken.lib.colour.Colour; -import codechicken.lib.colour.ColourRGBA; -import codechicken.lib.model.CachedFormat; import codechicken.lib.model.Quad; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.QuadCollection; +import net.minecraft.core.Direction; +import net.minecraft.util.ARGB; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; /** * A {@link VertexConsumer} implementation to build {@link BakedQuad}s. @@ -20,175 +19,143 @@ */ public class BakedQuadVertexBuilder implements VertexConsumer, ISpriteAwareVertexConsumer { - private final List quadList = new ArrayList<>(); + private final List quadList = new ArrayList<>(); private final VertexFormat.Mode mode; - private final int vSize; - private CachedFormat format; - private Colour defaultColour; - private Quad current; - private int vertex; + private boolean shade = false; + private boolean ambientOcclusion = true; + + private final Quad current = new Quad(); + private int vertex = -1; public BakedQuadVertexBuilder() { this(VertexFormat.Mode.QUADS); } - public BakedQuadVertexBuilder(VertexFormat format) { - this(format, VertexFormat.Mode.QUADS); - } - - public BakedQuadVertexBuilder(CachedFormat format) { - this(format, VertexFormat.Mode.QUADS); - } - public BakedQuadVertexBuilder(VertexFormat.Mode mode) { - this(CachedFormat.BLOCK, mode); - } - - public BakedQuadVertexBuilder(VertexFormat format, VertexFormat.Mode mode) { - this(CachedFormat.lookup(format), mode); - } - - public BakedQuadVertexBuilder(CachedFormat format, VertexFormat.Mode mode) { if (mode != VertexFormat.Mode.QUADS && mode != VertexFormat.Mode.TRIANGLES) { throw new IllegalArgumentException("Only QUADS or TRIANGLES supported. Got: " + mode); } this.mode = mode; - this.format = format; - vSize = mode.primitiveLength; } - // Provided for interop with other mods that may provide different quad formats. - public void setFormat(VertexFormat format) { - setFormat(CachedFormat.lookup(format)); + public void reset() { + quadList.clear(); + shade = false; + ambientOcclusion = true; + vertex = -1; } - // Provided for interop with other mods that may provide different quad formats. - public void setFormat(CachedFormat format) { - this.format = format; + public void setShade(boolean shade) { + this.shade = shade; } - public void reset() { - quadList.clear(); - current = null; - vertex = 0; + public void setAmbientOcclusion(boolean ambientOcclusion) { + this.ambientOcclusion = ambientOcclusion; } @Override public void sprite(TextureAtlasSprite sprite) { - checkNewQuad(); - current.setTexture(sprite); + current.sprite = sprite; } @Override - public VertexConsumer vertex(double x, double y, double z) { - if (!format.hasPosition) return this; - - checkNewQuad(); - current.vertices[vertex].vec[0] = (float) x; - current.vertices[vertex].vec[1] = (float) y; - current.vertices[vertex].vec[2] = (float) z; + public VertexConsumer addVertex(float x, float y, float z) { + endPrevVertex(); + current.vertices[vertex].vec.set(x, y, z); return this; } @Override - public VertexConsumer color(int red, int green, int blue, int alpha) { - if (!format.hasColor) return this; - - checkNewQuad(); - current.vertices[vertex].color[0] = red / 255F; - current.vertices[vertex].color[1] = green / 255F; - current.vertices[vertex].color[2] = blue / 255F; - current.vertices[vertex].color[3] = alpha / 255F; + public VertexConsumer setColor(int color) { + current.vertices[vertex].color = color; return this; } @Override - public VertexConsumer uv(float u, float v) { - if (!format.hasUV) return this; - - checkNewQuad(); - current.vertices[vertex].uv[0] = u; - current.vertices[vertex].uv[1] = v; + public VertexConsumer setColor(int red, int green, int blue, int alpha) { + setColor(ARGB.color(alpha, red, green, blue)); return this; } @Override - public VertexConsumer overlayCoords(int u, int v) { - if (!format.hasOverlay) return this; - - checkNewQuad(); - current.vertices[vertex].overlay[0] = u / (float) 0xF0; - current.vertices[vertex].overlay[1] = v / (float) 0xF0; + public VertexConsumer setUv(float u, float v) { + current.vertices[vertex].uv.set(u, v); return this; } @Override - public VertexConsumer uv2(int u, int v) { - if (!format.hasLightMap) return this; - - checkNewQuad(); - current.vertices[vertex].lightmap[0] = u / (float) 0xF0; - current.vertices[vertex].lightmap[1] = v / (float) 0xF0; + public VertexConsumer setNormal(float x, float y, float z) { + current.vertices[vertex].normal.set(x, y, z); return this; } @Override - public VertexConsumer normal(float x, float y, float z) { - if (!format.hasNormal) return this; + public VertexConsumer setUv1(int u, int v) { + // Baked quads dont support overlay. + return this; + } - checkNewQuad(); - current.vertices[vertex].normal[0] = x; - current.vertices[vertex].normal[1] = y; - current.vertices[vertex].normal[2] = z; + @Override + public VertexConsumer setUv2(int u, int v) { + // Baked quads dont support arbitrary lightmap. return this; } @Override - public void endVertex() { + public VertexConsumer setLineWidth(float lineWidth) { + // Baked quads dont support line width. + return this; + } + + private void endPrevVertex() { vertex++; - if (vertex == vSize) { + if (vertex == mode.primitiveLength) { if (mode == VertexFormat.Mode.TRIANGLES) { - //Quadulate. - for (int e = 0; e < current.format.elementCount; e++) { - System.arraycopy(current.vertices[2].raw[e], 0, current.vertices[3].raw[e], 0, 4); - } + // Quadulate. + current.vertices[3].copyFrom(current.vertices[2]); } if (current.sprite == null) { throw new IllegalStateException("Sprite not set."); } - if (defaultColour != null) { - float[] colour = defaultColour.getRGBA(); - for (Quad.Vertex v : current.vertices) { - System.arraycopy(colour, 0, v.color, 0, 4); - } - } - quadList.add(current); - current = null; + current.calculateOrientation(false); + current.shade = shade; + current.ambientOcclusion = ambientOcclusion; + quadList.add(current.bake()); vertex = 0; } } - @Override - public void defaultColor(int r, int g, int b, int a) { - defaultColour = new ColourRGBA(r, g, b, a); + private List finish() { + endPrevVertex(); + vertex = -1; + return quadList; } - @Override - public void unsetDefaultColor() { - defaultColour = null; + public List getQuads() { + return new ArrayList<>(finish()); } - public List bake() { - if (current != null) { - throw new IllegalStateException("Not finished building."); - } - return quadList.stream().map(Quad::bake).collect(Collectors.toList()); + /** + * Add all quads as culled on the specified face. + */ + public void getAsCulled(QuadCollection.Builder builder, Direction face) { + finish().forEach(e -> builder.addCulledFace(face, e)); } - private void checkNewQuad() { - if (current == null) { - current = new Quad(format); - } + /** + * Add all quads as culled, based on the orientation of the quad. + *

+ * Does not check if the quad lies on its face. + */ + public void getAsCulled(QuadCollection.Builder builder) { + finish().forEach(e -> builder.addCulledFace(e.direction(), e)); + } + + /** + * Add all the quads to the builder as unculled. + */ + public void getAsUnculled(QuadCollection.Builder builder) { + finish().forEach(builder::addUnculledFace); } } diff --git a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java b/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java deleted file mode 100644 index 52956eeb..00000000 --- a/src/main/java/codechicken/lib/render/buffer/DelegateRenderType.java +++ /dev/null @@ -1,37 +0,0 @@ -package codechicken.lib.render.buffer; - -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderType; - -/** - * Created by covers1624 on 25/5/20. - */ -public class DelegateRenderType extends RenderType { - - protected RenderType parent; - - public DelegateRenderType(RenderType parent) { - this(parent, parent.format()); - } - - public DelegateRenderType(RenderType parent, VertexFormat format) { - super(parent.name, format, parent.mode(), parent.bufferSize(), parent.affectsCrumbling(), parent.sortOnUpload, null, null); - this.parent = parent; - } - - @Override - public void end(BufferBuilder p_228631_1_, int p_228631_2_, int p_228631_3_, int p_228631_4_) { - parent.end(p_228631_1_, p_228631_2_, p_228631_3_, p_228631_4_); - } - - @Override - public void setupRenderState() { - parent.setupRenderState(); - } - - @Override - public void clearRenderState() { - parent.clearRenderState(); - } -} diff --git a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java index b2b28ab6..a56766fb 100644 --- a/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/DelegatingVertexConsumer.java @@ -24,53 +24,50 @@ public void sprite(TextureAtlasSprite sprite) { } @Override - public VertexConsumer vertex(double x, double y, double z) { - delegate.vertex(x, y, z); + public VertexConsumer addVertex(float x, float y, float z) { + delegate.addVertex(x, y, z); return this; } @Override - public VertexConsumer color(int r, int g, int b, int a) { - delegate.color(r, g, b, a); + public VertexConsumer setColor(int r, int g, int b, int a) { + delegate.setColor(r, g, b, a); return this; } @Override - public VertexConsumer uv(float u, float v) { - delegate.uv(u, v); + public VertexConsumer setColor(int color) { + delegate.setColor(color); return this; } @Override - public VertexConsumer overlayCoords(int u, int v) { - delegate.overlayCoords(u, v); + public VertexConsumer setUv(float u, float v) { + delegate.setUv(u, v); return this; } @Override - public VertexConsumer uv2(int u, int v) { - delegate.uv2(u, v); + public VertexConsumer setUv1(int u, int v) { + delegate.setUv1(u, v); return this; } @Override - public VertexConsumer normal(float x, float y, float z) { - delegate.normal(x, y, z); + public VertexConsumer setUv2(int u, int v) { + delegate.setUv2(u, v); return this; } @Override - public void endVertex() { - delegate.endVertex(); - } - - @Override - public void defaultColor(int r, int g, int b, int a) { - delegate.defaultColor(r, g, b, a); + public VertexConsumer setNormal(float x, float y, float z) { + delegate.setNormal(x, y, z); + return this; } @Override - public void unsetDefaultColor() { - delegate.unsetDefaultColor(); + public VertexConsumer setLineWidth(float lineWidth) { + delegate.setLineWidth(lineWidth); + return this; } } diff --git a/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java b/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java new file mode 100644 index 00000000..1c08c080 --- /dev/null +++ b/src/main/java/codechicken/lib/render/buffer/ExtentsConsumer.java @@ -0,0 +1,65 @@ +package codechicken.lib.render.buffer; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import org.joml.Vector3f; +import org.joml.Vector3fc; + +import java.util.function.Consumer; + +/** + * Created by covers1624 on 11/2/25. + */ +public class ExtentsConsumer implements ISpriteAwareVertexConsumer { + + private final Consumer cons; + + public ExtentsConsumer(Consumer cons) { + this.cons = cons; + } + + @Override + public VertexConsumer addVertex(float x, float y, float z) { + cons.accept(new Vector3f(x, y, z)); + return this; + } + + @Override + public VertexConsumer setColor(int red, int green, int blue, int alpha) { + return this; + } + + @Override + public VertexConsumer setColor(int color) { + return this; + } + + @Override + public VertexConsumer setUv(float u, float v) { + return this; + } + + @Override + public VertexConsumer setUv1(int u, int v) { + return this; + } + + @Override + public VertexConsumer setUv2(int u, int v) { + return this; + } + + @Override + public VertexConsumer setNormal(float normalX, float normalY, float normalZ) { + return this; + } + + @Override + public VertexConsumer setLineWidth(float lineWidth) { + return this; + } + + @Override + public void sprite(TextureAtlasSprite sprite) { + } +} diff --git a/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java b/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java index 145535b0..e536f99f 100644 --- a/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java +++ b/src/main/java/codechicken/lib/render/buffer/TransformingVertexConsumer.java @@ -24,16 +24,16 @@ public TransformingVertexConsumer(VertexConsumer delegate, Transformation transf } @Override - public VertexConsumer vertex(double x, double y, double z) { + public VertexConsumer addVertex(float x, float y, float z) { storage.set(x, y, z); transform.apply(storage); - return super.vertex(storage.x, storage.y, storage.z); + return super.addVertex((float) storage.x, (float) storage.y, (float) storage.z); } @Override - public VertexConsumer normal(float x, float y, float z) { + public VertexConsumer setNormal(float x, float y, float z) { storage.set(x, y, z); transform.applyN(storage); - return delegate.normal((float) storage.x, (float) storage.y, (float) storage.z); + return delegate.setNormal((float) storage.x, (float) storage.y, (float) storage.z); } } diff --git a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java b/src/main/java/codechicken/lib/render/buffer/VBORenderType.java deleted file mode 100644 index 80d817b7..00000000 --- a/src/main/java/codechicken/lib/render/buffer/VBORenderType.java +++ /dev/null @@ -1,157 +0,0 @@ -package codechicken.lib.render.buffer; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.VertexBuffer; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.client.renderer.RenderStateShard; -import net.minecraft.client.renderer.RenderType; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.BiConsumer; - -import static net.covers1624.quack.util.SneakyUtils.none; - -/** - * A RenderType that is backed by a VertexBufferObject used for Instanced rendering. - *

- * Created by covers1624 on 25/5/20. - */ -public class VBORenderType extends DelegateRenderType implements AutoCloseable { - - private final BiConsumer factory; - private final VertexBuffer vertexBuffer = new VertexBuffer(); - private final BufferBuilder builder; - private boolean dirty = true; - - /** - * Create a new VBORenderType, delegates render state setup - * to the provided parent, also uses the parents VertexFormat. - * - * @param parent The parent, for state setup and buffer VertexFormat. - * @param factory The Factory used to fill the BufferBuilder with data. - */ - public VBORenderType(RenderType parent, BiConsumer factory) { - super(parent, parent.format()); - this.factory = factory; - builder = new BufferBuilder(bufferSize()); - } - - /** - * Marks this {@link VBORenderType} as needing to be re-built. - */ - public void setDirty() { - dirty = true; - } - - /** - * An extra {@link Runnable} to be applied before draw calls. - * - * @param action The action. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withCallback(Runnable action) { - return new WithCallbacks().withAction(action); - } - - /** - * An extra {@link RenderStateShard} to be applied. - * - * @param shard The {@link RenderStateShard}. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withState(RenderStateShard shard) { - return new WithCallbacks().withState(shard); - } - - private void render() { - rebuild(); - this.vertexBuffer.drawWithShader(RenderSystem.getModelViewMatrix(), RenderSystem.getProjectionMatrix(), RenderSystem.getShader()); - } - - private void rebuild() { - if (!dirty) return; - builder.begin(mode(), format()); - factory.accept(format(), builder); - vertexBuffer.upload(builder.end()); - builder.clear(); - dirty = false; - } - - @Override - public void end(BufferBuilder buffer, int cameraX, int cameraY, int cameraZ) { - // End buffer and discard state, we don't operate like this. - buffer.endOrDiscardIfEmpty(); - - setupRenderState(); - render(); - clearRenderState(); - } - - @Override - public void close() throws Exception { - vertexBuffer.close(); - } - - public class WithCallbacks extends DelegateRenderType { - - private final List shards = new LinkedList<>(); - - public WithCallbacks() { - super(VBORenderType.this); - } - - /** - * An extra {@link Runnable} to be applied before draw calls. - * - * @param action The action. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withAction(Runnable action) { - return withState(new RenderStateShard("none", none(), none()) { - @Override - public void setupRenderState() { - action.run(); - } - }); - } - - /** - * An extra {@link RenderStateShard} to be applied. - * - * @param shard The {@link RenderStateShard}. - * @return The same {@link WithCallbacks}. - */ - public WithCallbacks withState(RenderStateShard shard) { - shards.add(shard); - return this; - } - - @Override - public void setupRenderState() { - super.setupRenderState(); - for (RenderStateShard state : shards) { - state.setupRenderState(); - } - } - - @Override - public void end(BufferBuilder buffer, int cameraX, int cameraY, int cameraZ) { - // End buffer and discard state, we don't operate like this. - buffer.endOrDiscardIfEmpty(); - - setupRenderState(); - render(); - clearRenderState(); - } - - @Override - public void clearRenderState() { - for (RenderStateShard state : shards) { - state.clearRenderState(); - } - super.clearRenderState(); - } - } -} diff --git a/src/main/java/codechicken/lib/render/buffer/package-info.java b/src/main/java/codechicken/lib/render/buffer/package-info.java new file mode 100644 index 00000000..af5aa421 --- /dev/null +++ b/src/main/java/codechicken/lib/render/buffer/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.buffer; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java b/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java new file mode 100644 index 00000000..5d8ac283 --- /dev/null +++ b/src/main/java/codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension.java @@ -0,0 +1,109 @@ +package codechicken.lib.render.extension; + +import codechicken.lib.render.CCRenderState; +import codechicken.lib.vec.Matrix4; +import com.mojang.blaze3d.vertex.PoseStack; +import com.mojang.blaze3d.vertex.VertexConsumer; +import net.minecraft.client.renderer.OrderedSubmitNodeCollector; +import net.minecraft.client.renderer.SubmitNodeCollector; +import net.minecraft.client.renderer.rendertype.RenderType; + +/** + * Created by covers1624 on 11/2/25. + */ +public interface CCOrderedSubmitNodeCollectorExtension { + + private OrderedSubmitNodeCollector self() { + return (OrderedSubmitNodeCollector) this; + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however using a {@link Matrix4}. + *

+ * The matrix is copied for your invocation and provided to your callback. + * + * @param mat The matrix. + * @param renderType The render type. + * @param renderer Your renderer callback. + */ + default void cc$submitCustomGeometry(Matrix4 mat, RenderType renderType, Mat4CustomGeometryRenderer renderer) { + var matCopy = mat.copy(); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> renderer.render(matCopy, renderType, consumer)); + } + + /** + * Similar to {@link SubmitNodeCollector.CustomGeometryRenderer} except + * carries a {@link Matrix4} instead of a {@link PoseStack.Pose}. + */ + interface Mat4CustomGeometryRenderer { + + void render(Matrix4 mat, RenderType renderType, VertexConsumer cons); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} except, additionally + * provides you the {@link RenderType} you requested as a callback parameter. + * + * @param pStack The pose stack. + * @param renderType The render type. + * @param renderer Your renderer callback. + */ + default void cc$submitCustomGeometry(PoseStack pStack, RenderType renderType, CustomGeometryRendererExtended renderer) { + self().submitCustomGeometry(pStack, renderType, (pose, consumer) -> renderer.render(pose, renderType, consumer)); + } + + /** + * Similar to {@link SubmitNodeCollector.CustomGeometryRenderer} except + * additionally carries the {@link RenderType} for convenience. + */ + interface CustomGeometryRendererExtended { + + void render(PoseStack.Pose pose, RenderType renderType, VertexConsumer cons); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however, provides + * you a {@link CCRenderState} instance already reset and bound. + * + * @param mat The matrix to capture. + * @param renderType The render type. + * @param renderer Your render callback. + */ + default void cc$submitCCRS(Matrix4 mat, RenderType renderType, CustomGeometryRendererCCRS renderer) { + var matCopy = mat.copy(); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> { + var ccrs = CCRenderState.instance(); + ccrs.reset(); + ccrs.bind(consumer, renderType.format()); + renderer.render(matCopy, ccrs); + }); + } + + /** + * The same as {@link OrderedSubmitNodeCollector#submitCustomGeometry} however, provides + * you a {@link CCRenderState} instance already reset and bound. + * + * @param pose The pose to capture. + * @param renderType The render type. + * @param renderer Your render callback. + */ + default void cc$submitCCRS(PoseStack pose, RenderType renderType, CustomGeometryRendererCCRS renderer) { + var matCopy = new Matrix4(pose); + self().submitCustomGeometry(Internal.EMPTY, renderType, (p, consumer) -> { + var ccrs = CCRenderState.instance(); + ccrs.reset(); + ccrs.bind(consumer, renderType.format()); + renderer.render(matCopy, ccrs); + }); + } + + interface CustomGeometryRendererCCRS { + + void render(Matrix4 mat, CCRenderState ccrs); + } + + class Internal { + + private static final PoseStack EMPTY = new PoseStack(); + } +} diff --git a/src/main/java/codechicken/lib/render/extension/package-info.java b/src/main/java/codechicken/lib/render/extension/package-info.java new file mode 100644 index 00000000..558c32d0 --- /dev/null +++ b/src/main/java/codechicken/lib/render/extension/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.extension; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/item/IItemRenderer.java b/src/main/java/codechicken/lib/render/item/IItemRenderer.java deleted file mode 100644 index e9b7d23a..00000000 --- a/src/main/java/codechicken/lib/render/item/IItemRenderer.java +++ /dev/null @@ -1,42 +0,0 @@ -package codechicken.lib.render.item; - -import codechicken.lib.model.PerspectiveModel; -import codechicken.lib.texture.TextureUtils; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.LightTexture; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.Collections; -import java.util.List; - -public interface IItemRenderer extends PerspectiveModel { - - /** - * Called to render your item with complete control. Bypasses all vanilla rendering of your model. - * - * @param stack The {@link ItemStack} being rendered. - * @param transformType The {@link TransformType} of where we are rendering. - * @param mStack The {@link PoseStack} to get / add transformations to. - * @param source The {@link MultiBufferSource} to retrieve buffers from. - * @param packedLight The {@link LightTexture} packed coords. - * @param packedOverlay The {@link OverlayTexture} packed coords. - */ - void renderItem(ItemStack stack, TransformType transformType, PoseStack mStack, MultiBufferSource source, int packedLight, int packedOverlay); - - //Useless methods for IItemRenderer. - //@formatter:off - @Override default List getQuads(BlockState state, Direction side, RandomSource rand) { return Collections.emptyList(); } - @Override default boolean isCustomRenderer() { return true; } - @Override default TextureAtlasSprite getParticleIcon() { return TextureUtils.getMissingSprite(); } - @Override default ItemOverrides getOverrides() { return ItemOverrides.EMPTY; } - //@formatter:on -} diff --git a/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java b/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java deleted file mode 100644 index 79706dec..00000000 --- a/src/main/java/codechicken/lib/render/item/map/IMapRenderer.java +++ /dev/null @@ -1,30 +0,0 @@ -package codechicken.lib.render.item.map; - -import net.minecraft.world.item.ItemStack; - -/** - * Used to handle rendering FirstPerson items the same as a map. - *

- * Created by covers1624 on 15/02/2017. - */ -public interface IMapRenderer { - - /** - * If the IMapRenderer should handle rendering the data from this map. - * - * @param stack The ItemStack to render map data from. - * @param inFrame If the ItemStack is inside an ItemFrame. - * @return Should this IMapRenderer handle with this context. - */ - boolean shouldHandle(ItemStack stack, boolean inFrame); - - /** - * If this is called you are expected to do something. - * This is ONLY called if shouldHandle returns true. - * - * @param stack The ItemStack to render the map data from. - * @param inFrame If the ItemStack is inside an ItemFrame. - */ - void renderMap(ItemStack stack, boolean inFrame); - -} diff --git a/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java b/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java deleted file mode 100644 index 95df7a33..00000000 --- a/src/main/java/codechicken/lib/render/item/map/MapRenderRegistry.java +++ /dev/null @@ -1,103 +0,0 @@ -package codechicken.lib.render.item.map; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import java.util.IdentityHashMap; - -/** - * Created by covers1624 on 15/02/2017. - */ -public class MapRenderRegistry { - - private static IdentityHashMap mapRenderers = new IdentityHashMap<>(); - - public static boolean shouldHandle(ItemStack stack, boolean inFrame) { - IMapRenderer mapRenderer = mapRenderers.get(stack.getItem()); - if (mapRenderer != null) { - return mapRenderer.shouldHandle(stack, inFrame); - } - return false; - } - - public static void handleRender(ItemStack stack, boolean inFrame) { - IMapRenderer mapRenderer = mapRenderers.get(stack.getItem()); - if (mapRenderer != null) { - mapRenderer.renderMap(stack, inFrame); - } - } - - public static void registerMapRenderer(Item item, IMapRenderer mapRenderer) { - mapRenderers.put(item, mapRenderer); - } - - // @SubscribeEvent - // public void onItemFrameRender(RenderItemInFrameEvent event) { - // if (shouldHandle(event.getItem(), true)) { - // event.setCanceled(true); - // handleRender(event.getItem(), true); - // } - // } - // - // @SubscribeEvent - // public void renderFirstPersonHand(RenderSpecificHandEvent event) { - // ItemStack stack = event.getItemStack(); - // if (!shouldHandle(stack, false)) { - // return; - // } - // event.setCanceled(true); - // Minecraft minecraft = Minecraft.getInstance(); - // FirstPersonRenderer firstPersonRenderer = minecraft.getFirstPersonRenderer(); - // ClientPlayerEntity player = minecraft.player; - // Hand hand = event.getHand(); - // float partialTicks = event.getPartialTicks(); - // float interpPitch = event.getInterpolatedPitch(); - // float swingProgress = event.getSwingProgress(); - // float equipProgress = event.getEquipProgress(); - // - // //Begin reimplementation of vanilla -_- - // boolean flag = hand == Hand.MAIN_HAND; - // HandSide handSide = flag ? player.getPrimaryHand() : player.getPrimaryHand().opposite(); - // - // GlStateManager.pushMatrix(); - // if (flag && firstPersonRenderer.itemStackOffHand.isEmpty()) { - // float f = MathHelper.sqrt(swingProgress); - // float f1 = -0.2F * MathHelper.sin(swingProgress * (float) Math.PI); - // float f2 = -0.4F * MathHelper.sin(f * (float) Math.PI); - // GlStateManager.translatef(0.0F, -f1 / 2.0F, f2); - // float f3 = firstPersonRenderer.getMapAngleFromPitch(interpPitch); - // GlStateManager.translatef(0.0F, 0.04F + equipProgress * -1.2F + f3 * -0.5F, -0.72F); - // GlStateManager.rotatef(f3 * -85.0F, 1.0F, 0.0F, 0.0F); - // firstPersonRenderer.renderArms(); - // float f4 = MathHelper.sin(f * (float) Math.PI); - // GlStateManager.rotatef(f4 * 20.0F, 1.0F, 0.0F, 0.0F); - // GlStateManager.scalef(2.0F, 2.0F, 2.0F); - // handleRender(stack, false); - // } else { - // float f = handSide == HandSide.RIGHT ? 1.0F : -1.0F; - // GlStateManager.translatef(f * 0.125F, -0.125F, 0.0F); - // - // if (!player.isInvisible()) { - // GlStateManager.pushMatrix(); - // GlStateManager.rotatef(f * 10.0F, 0.0F, 0.0F, 1.0F); - // firstPersonRenderer.renderArmFirstPerson(equipProgress, swingProgress, handSide); - // GlStateManager.popMatrix(); - // } - // - // GlStateManager.pushMatrix(); - // GlStateManager.translatef(f * 0.51F, -0.08F + equipProgress * -1.2F, -0.75F); - // float f1 = MathHelper.sqrt(swingProgress); - // float f2 = MathHelper.sin(f1 * (float) Math.PI); - // float f3 = -0.5F * f2; - // float f4 = 0.4F * MathHelper.sin(f1 * ((float) Math.PI * 2F)); - // float f5 = -0.3F * MathHelper.sin(swingProgress * (float) Math.PI); - // GlStateManager.translatef(f * f3, f4 - 0.3F * f2, f5); - // GlStateManager.rotatef(f2 * -45.0F, 1.0F, 0.0F, 0.0F); - // GlStateManager.rotatef(f * f2 * -30.0F, 0.0F, 1.0F, 0.0F); - // handleRender(stack, false); - // GlStateManager.popMatrix(); - // } - // GlStateManager.popMatrix(); - // } - -} diff --git a/src/main/java/codechicken/lib/render/lighting/LC.java b/src/main/java/codechicken/lib/render/lighting/LC.java index af7d9ef2..2f13b870 100644 --- a/src/main/java/codechicken/lib/render/lighting/LC.java +++ b/src/main/java/codechicken/lib/render/lighting/LC.java @@ -47,27 +47,15 @@ public LC compute(Vector3 vec, Vector3 normal) { } public LC compute(Vector3 vec, int side) { - boolean offset = false; - switch (side) { - case 0: - offset = vec.y <= 0; - break; - case 1: - offset = vec.y >= 1; - break; - case 2: - offset = vec.z <= 0; - break; - case 3: - offset = vec.z >= 1; - break; - case 4: - offset = vec.x <= 0; - break; - case 5: - offset = vec.x >= 1; - break; - } + boolean offset = switch (side) { + case 0 -> vec.y <= 0; + case 1 -> vec.y >= 1; + case 2 -> vec.z <= 0; + case 3 -> vec.z >= 1; + case 4 -> vec.x <= 0; + case 5 -> vec.x >= 1; + default -> false; + }; if (!offset) { side += 6; } diff --git a/src/main/java/codechicken/lib/render/lighting/LightMatrix.java b/src/main/java/codechicken/lib/render/lighting/LightMatrix.java index 4746f99d..7fb58a21 100644 --- a/src/main/java/codechicken/lib/render/lighting/LightMatrix.java +++ b/src/main/java/codechicken/lib/render/lighting/LightMatrix.java @@ -8,6 +8,9 @@ import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.block.state.BlockState; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * Note that when using the class as a vertex transformer, the vertices are assumed to be within the BB (x, y, z) -> (x+1, y+1, z+1) @@ -20,7 +23,7 @@ public class LightMatrix implements IVertexOperation { public float[][] ao = new float[13][4]; public int[][] brightness = new int[13][4]; - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; @@ -89,6 +92,7 @@ public void locate(BlockAndTintGetter a, BlockPos bPos) { } public void sample(int i) { + requireNonNull(access, "LightMatrix must be located first."); if ((sampled & 1 << i) == 0) { BlockPos bp = new BlockPos(pos.getX() + (i % 3) - 1, pos.getY() + (i / 9) - 1, pos.getZ() + (i / 3 % 3) - 1); BlockState b = access.getBlockState(bp); diff --git a/src/main/java/codechicken/lib/render/lighting/LightModel.java b/src/main/java/codechicken/lib/render/lighting/LightModel.java index fc2c4e85..2db5be22 100644 --- a/src/main/java/codechicken/lib/render/lighting/LightModel.java +++ b/src/main/java/codechicken/lib/render/lighting/LightModel.java @@ -9,27 +9,6 @@ public class LightModel implements IVertexOperation { public static final int operationIndex = IVertexOperation.registerOperation(); - public static class Light { - - public Vector3 ambient = new Vector3(); - public Vector3 diffuse = new Vector3(); - public Vector3 position; - - public Light(Vector3 pos) { - position = pos.copy().normalize(); - } - - public Light setDiffuse(Vector3 vec) { - diffuse.set(vec); - return this; - } - - public Light setAmbient(Vector3 vec) { - ambient.set(vec); - return this; - } - } - public static LightModel standardLightModel; static { @@ -43,8 +22,8 @@ public Light setAmbient(Vector3 vec) { //@formatter:on } - private Vector3 ambient = new Vector3(); - private Light[] lights = new Light[8]; + private final Vector3 ambient = new Vector3(); + private final Light[] lights = new Light[8]; private int lightCount; public LightModel addLight(Light light) { @@ -115,4 +94,25 @@ public PlanarLightModel reducePlanar() { } return new PlanarLightModel(colours); } + + public static class Light { + + public Vector3 ambient = new Vector3(); + public Vector3 diffuse = new Vector3(); + public Vector3 position; + + public Light(Vector3 pos) { + position = pos.copy().normalize(); + } + + public Light setDiffuse(Vector3 vec) { + diffuse.set(vec); + return this; + } + + public Light setAmbient(Vector3 vec) { + ambient.set(vec); + return this; + } + } } diff --git a/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java b/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java index 028670ab..384478a8 100644 --- a/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java +++ b/src/main/java/codechicken/lib/render/lighting/PlanarLightMatrix.java @@ -5,13 +5,16 @@ import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.BlockAndTintGetter; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; public class PlanarLightMatrix extends PlanarLightModel { public static final int operationIndex = IVertexOperation.registerOperation(); public static PlanarLightMatrix instance = new PlanarLightMatrix(); - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; @@ -29,6 +32,7 @@ public PlanarLightMatrix locate(BlockAndTintGetter a, BlockPos bPos) { } public int brightness(int side) { + requireNonNull(access, "PlanarLightMatrix must be located first."); if ((sampled & 1 << side) == 0) { brightness[side] = LevelRenderer.getLightColor(access, pos); sampled |= 1 << side; diff --git a/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java b/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java index 28cc4bab..af98ff73 100644 --- a/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java +++ b/src/main/java/codechicken/lib/render/lighting/SimpleBrightnessModel.java @@ -6,6 +6,9 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockAndTintGetter; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; /** * Simple brightness model that only works for axis planar sides @@ -15,12 +18,11 @@ public class SimpleBrightnessModel implements IVertexOperation { public static final int operationIndex = IVertexOperation.registerOperation(); public static SimpleBrightnessModel instance = new SimpleBrightnessModel(); - public BlockAndTintGetter access; + public @Nullable BlockAndTintGetter access; public BlockPos pos = BlockPos.ZERO; private int sampled = 0; - private int[] samples = new int[6]; - private BlockPos c = BlockPos.ZERO; + private final int[] samples = new int[6]; public void locate(BlockAndTintGetter a, BlockPos bPos) { access = a; @@ -29,9 +31,9 @@ public void locate(BlockAndTintGetter a, BlockPos bPos) { } public int sample(int side) { + requireNonNull(access, "SimpleBrightnessModel must be located first."); if ((sampled & 1 << side) == 0) { - c = pos.relative(Direction.BY_3D_DATA[side]); - samples[side] = LevelRenderer.getLightColor(access, c); + samples[side] = LevelRenderer.getLightColor(access, pos.relative(Direction.BY_3D_DATA[side])); sampled |= 1 << side; } return samples[side]; diff --git a/src/main/java/codechicken/lib/render/lighting/package-info.java b/src/main/java/codechicken/lib/render/lighting/package-info.java new file mode 100644 index 00000000..9479687b --- /dev/null +++ b/src/main/java/codechicken/lib/render/lighting/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.lighting; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/model/MatLib.java b/src/main/java/codechicken/lib/render/model/MatLib.java index 5f11baba..65de8e6d 100644 --- a/src/main/java/codechicken/lib/render/model/MatLib.java +++ b/src/main/java/codechicken/lib/render/model/MatLib.java @@ -1,7 +1,7 @@ package codechicken.lib.render.model; import codechicken.lib.util.ResourceUtils; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.ResourceProvider; import org.jetbrains.annotations.Nullable; @@ -17,7 +17,7 @@ public class MatLib { public final Map materials = new HashMap<>(); - public static MatLib parse(ResourceProvider resourceProvider, ResourceLocation loc) { + public static MatLib parse(ResourceProvider resourceProvider, Identifier loc) { MatLib matLib = new MatLib(); ModelMaterial curr = null; for (String line : ResourceUtils.loadResource(resourceProvider, loc)) { diff --git a/src/main/java/codechicken/lib/render/model/OBJParser.java b/src/main/java/codechicken/lib/render/model/OBJParser.java index a20e2b1a..6d36269c 100644 --- a/src/main/java/codechicken/lib/render/model/OBJParser.java +++ b/src/main/java/codechicken/lib/render/model/OBJParser.java @@ -7,7 +7,7 @@ import codechicken.lib.vec.Vector3; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.ResourceProvider; import org.jetbrains.annotations.Nullable; @@ -18,32 +18,28 @@ */ public class OBJParser { - private final ResourceLocation location; - @Nullable - private ResourceProvider provider; + private final Identifier location; + private final ResourceProvider provider; private VertexFormat.Mode vertexMode = VertexFormat.Mode.TRIANGLES; @Nullable private Transformation coordSystem; private boolean ignoreMtl; /** - * Create a new instance of an OBJParser for a nice builder-like structure. - * - * @param location The {@link ResourceLocation} of the OBJ. + * @param location The {@link Identifier} of the OBJ. */ - public OBJParser(ResourceLocation location) { - this.location = location; + // TODO should we deprecate this and stop promoting blindly reading obj models statically? + public OBJParser(Identifier location) { + this(Minecraft.getInstance().getResourceManager(), location); } /** - * Set the {@link ResourceProvider} used to locate assets. - * - * @param provider The {@link ResourceProvider}. - * @return The same parser. + * @param provider The {@link ResourceProvider} to load from. + * @param location The {@link Identifier} of the OBJ. */ - public OBJParser provider(ResourceProvider provider) { + public OBJParser(ResourceProvider provider, Identifier location) { + this.location = location; this.provider = provider; - return this; } /** @@ -106,9 +102,6 @@ public OBJParser ignoreMtl() { * @return The parsed models. */ public Map parse() { - if (provider == null) { - provider = Minecraft.getInstance().getResourceManager(); - } return parse(provider, location, vertexMode, coordSystem, ignoreMtl); } @@ -116,13 +109,13 @@ public Map parse() { * Parse an OBJ model into a named map of {@link CCModel}s. * * @param provider The {@link ResourceProvider} to locate assets. - * @param loc The {@link ResourceLocation} of the OBJ model. + * @param loc The {@link Identifier} of the OBJ model. * @param vertexMode The {@link VertexFormat.Mode} to parse the model into. * @param coordSystem The coordinate system transformation to apply during parsing. * @param ignoreMtl If MTL files should be ignored. * @return The parsed models. */ - public static Map parse(ResourceProvider provider, ResourceLocation loc, VertexFormat.Mode vertexMode, @Nullable Transformation coordSystem, boolean ignoreMtl) { + public static Map parse(ResourceProvider provider, Identifier loc, VertexFormat.Mode vertexMode, @Nullable Transformation coordSystem, boolean ignoreMtl) { if (vertexMode != VertexFormat.Mode.QUADS && vertexMode != VertexFormat.Mode.TRIANGLES) throw new IllegalStateException("Only Quads and Triangles are supported."); Map builtModels = new HashMap<>(); @@ -296,9 +289,9 @@ private static double[] parseDoubles(String s, String token) { return values; } - private static ResourceLocation maybeRelative(ResourceLocation other, String resource) { + private static Identifier maybeRelative(Identifier other, String resource) { if (resource.contains(":")) { - return new ResourceLocation(resource); + return Identifier.parse(resource); } String path = other.getPath(); int lastSlash = path.lastIndexOf("/"); @@ -307,6 +300,6 @@ private static ResourceLocation maybeRelative(ResourceLocation other, String res } else { path = ""; } - return new ResourceLocation(other.getNamespace(), path + "/" + resource); + return Identifier.fromNamespaceAndPath(other.getNamespace(), path + "/" + resource); } } diff --git a/src/main/java/codechicken/lib/render/model/OBJWriter.java b/src/main/java/codechicken/lib/render/model/OBJWriter.java index ce78f776..2cbd7b18 100644 --- a/src/main/java/codechicken/lib/render/model/OBJWriter.java +++ b/src/main/java/codechicken/lib/render/model/OBJWriter.java @@ -34,15 +34,16 @@ public static void exportObj(Map models, PrintWriter p) { int vStart = verts.size(); int uStart = uvs.size(); int nStart = normals.size(); - boolean hasNormals = m.normals() != null; polys.clear(); + Vector3[] mNormals = m.normals(); + boolean hasNormals = mNormals != null; for (int i = 0; i < m.verts.length; i++) { int[] ia = new int[hasNormals ? 3 : 2]; ia[0] = addIndex(verts, m.verts[i].vec); ia[1] = addIndex(uvs, m.verts[i].uv); if (hasNormals) { - ia[2] = addIndex(normals, m.normals()[i]); + ia[2] = addIndex(normals, mNormals[i]); } polys.add(ia); } diff --git a/src/main/java/codechicken/lib/render/model/package-info.java b/src/main/java/codechicken/lib/render/model/package-info.java index 9d91f4db..0c42dc1d 100644 --- a/src/main/java/codechicken/lib/render/model/package-info.java +++ b/src/main/java/codechicken/lib/render/model/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.render.model; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/package-info.java b/src/main/java/codechicken/lib/render/package-info.java new file mode 100644 index 00000000..2be7d43e --- /dev/null +++ b/src/main/java/codechicken/lib/render/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java index ee50397b..95d13f39 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java +++ b/src/main/java/codechicken/lib/render/particle/CustomBreakingParticle.java @@ -1,23 +1,21 @@ package codechicken.lib.render.particle; import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.particle.ParticleRenderType; -import net.minecraft.client.particle.TextureSheetParticle; +import net.minecraft.client.particle.SingleQuadParticle; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -public class CustomBreakingParticle extends TextureSheetParticle { +public class CustomBreakingParticle extends SingleQuadParticle { private final float uo; private final float vo; public CustomBreakingParticle(ClientLevel world, double x, double y, double z, double dx, double dy, double dz, TextureAtlasSprite icon) { - super(world, x, y, z, dx, dy, dz); - setSprite(icon); + super(world, x, y, z, dx, dy, dz, icon); gravity = 1; rCol = gCol = bCol = 0.6F; quadSize /= 2.0F; - this.uo = this.random.nextFloat() * 3.0F; - this.vo = this.random.nextFloat() * 3.0F; + uo = random.nextFloat() * 3.0F; + vo = random.nextFloat() * 3.0F; } public static CustomBreakingParticle newLandingParticle(ClientLevel world, double x, double y, double z, double dx, double dy, double dz, TextureAtlasSprite icon) { @@ -28,24 +26,25 @@ public static CustomBreakingParticle newLandingParticle(ClientLevel world, doubl return particle; } - public ParticleRenderType getRenderType() { - return ParticleRenderType.TERRAIN_SHEET; + @Override + protected Layer getLayer() { + return Layer.TERRAIN; } protected float getU0() { - return this.sprite.getU((double) ((this.uo + 1.0F) / 4.0F * 16.0F)); + return sprite.getU((uo + 1.0F) / 4.0F); } protected float getU1() { - return this.sprite.getU((double) (this.uo / 4.0F * 16.0F)); + return sprite.getU(uo / 4.0F); } protected float getV0() { - return this.sprite.getV((double) (this.vo / 4.0F * 16.0F)); + return sprite.getV(vo / 4.0F); } protected float getV1() { - return this.sprite.getV((double) ((this.vo + 1.0F) / 4.0F * 16.0F)); + return sprite.getV((vo + 1.0F) / 4.0F); } public void setScale(float scale) { diff --git a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java index ff630200..1ae1dd3b 100644 --- a/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java +++ b/src/main/java/codechicken/lib/render/particle/CustomParticleHandler.java @@ -1,166 +1,22 @@ package codechicken.lib.render.particle; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.packet.PacketCustom; -import codechicken.lib.raytracer.VoxelShapeBlockHitResult; import codechicken.lib.vec.Cuboid6; import codechicken.lib.vec.Vector3; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.particle.ParticleEngine; -import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraft.world.phys.HitResult; -import net.minecraft.world.phys.Vec3; -import net.minecraftforge.api.distmarker.Dist; -import net.minecraftforge.api.distmarker.OnlyIn; -import net.minecraftforge.client.model.data.ModelData; -import java.util.ArrayList; import java.util.List; -import java.util.Random; -import java.util.Set; - -import static codechicken.lib.internal.network.CCLNetwork.C_ADD_LANDING_EFFECTS; /** * Created by covers1624 on 21/11/2016. */ public class CustomParticleHandler { - /** - * Call from {@link Block#addLandingEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * - * @param world The world. - * @param pos The position of the block. - * @param entity The entity. - * @param numParticles The number of particles to spawn. - * @return Always true for this, basically just return the result of this method inside {@link Block#addLandingEffects} - */ - public static boolean handleLandingEffects(ServerLevel world, BlockPos pos, LivingEntity entity, int numParticles) { - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_ADD_LANDING_EFFECTS); - packet.writePos(pos); - packet.writeVector(Vector3.fromEntity(entity)); - packet.writeVarInt(numParticles); - packet.sendToPlayer((ServerPlayer) entity); - return true; - } - - @OnlyIn (Dist.CLIENT) - public static boolean handleRunningEffects(Level world, BlockPos pos, BlockState state, Entity entity) { - //Spoof a raytrace from the feet. - BlockHitResult traceResult = new BlockHitResult(entity.position().add(0, 1, 0), Direction.UP, pos, false); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); - ParticleEngine particleManager = Minecraft.getInstance().particleEngine; - List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); - TextureAtlasSprite rolledSprite = sprites.get(world.random.nextInt(sprites.size())); - double x = entity.getX() + (world.random.nextFloat() - 0.5D) * entity.getBbWidth(); - double y = entity.getBoundingBox().minY + 0.1D; - double z = entity.getZ() + (world.random.nextFloat() - 0.5D) * entity.getBbWidth(); - particleManager.add(new CustomBreakingParticle((ClientLevel) world, x, y, z, -entity.getDeltaMovement().x * 4.0D, 1.5D, -entity.getDeltaMovement().z * 4.0D, rolledSprite)); - return true; - } - - return false; - } - - /** - * Call from {@link Block#addLandingEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * Use the default PerspectiveModel implementations in CCL, Hit effects will be polled from your model based on your bounding box hit. - * - * @param state The state. - * @param world The world. - * @param traceResult The trace result. - * @param manager The ParticleManager. - * @return True if particles were added, basically just return the result of this method inside {@link Block#addLandingEffects} - */ - @OnlyIn (Dist.CLIENT) - public static boolean handleHitEffects(BlockState state, Level world, HitResult traceResult, ParticleEngine manager) { - if (traceResult instanceof BlockHitResult hit) { - BlockPos pos = hit.getBlockPos(); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); - Cuboid6 bounds = new Cuboid6(); - if (hit instanceof VoxelShapeBlockHitResult) { - bounds.set(((VoxelShapeBlockHitResult) hit).shape.bounds()); - } else { - bounds.set(state.getShape(world, pos).bounds()); - } - bounds = bounds.copy().add(pos); - Set hitSprites = ((IModelParticleProvider) model).getHitEffects(hit, state, world, pos, modelData); - List sprites = new ArrayList<>(hitSprites); - addBlockHitEffects(world, bounds, hit.getDirection(), sprites.get(world.random.nextInt(sprites.size())), manager); - return true; - } - } - return false; - } - - /** - * {@link Block#addHitEffects} - * Provided the model bound is an instance of IModelParticleProvider, you will have landing particles just handled for you. - * Use the default PerspectiveModel implementations inside CCL, Destroy effects will just be handled for you. - * - * @param world The world. - * @param pos The position of the block. - * @param manager The ParticleManager. - * @return True if particles were added, basically just return the result of this method inside {@link Block#addHitEffects} - */ - @OnlyIn (Dist.CLIENT) - public static boolean handleDestroyEffects(Level world, BlockPos pos, BlockState state, ParticleEngine manager) { - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); - Cuboid6 bounds = new Cuboid6(state.getShape(world, pos).bounds()); - addBlockDestroyEffects(world, bounds.add(pos), new ArrayList<>(((IModelParticleProvider) model).getDestroyEffects(state, world, pos, modelData)), manager); - return true; - } - return false; - } - - @OnlyIn (Dist.CLIENT) - public static void addLandingEffects(Level world, BlockPos pos, BlockState state, Vector3 entityPos, int numParticles) { - //Spoof a raytrace from the feet. - BlockHitResult traceResult = new BlockHitResult(new Vec3(entityPos.x, pos.getY() + 1, entityPos.z), Direction.UP, pos, false); - ParticleEngine manager = Minecraft.getInstance().particleEngine; - Random randy = new Random(); - BlockModelShaper modelShapes = Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(); - BakedModel model = modelShapes.getBlockModel(state); - if (model instanceof IModelParticleProvider) { - ModelData modelData = world.getModelDataManager().getAt(pos); - List sprites = new ArrayList<>(((IModelParticleProvider) model).getHitEffects(traceResult, state, world, pos, modelData)); - - double speed = 0.15000000596046448D; - if (numParticles != 0) { - for (int i = 0; i < numParticles; i++) { - double mX = randy.nextGaussian() * speed; - double mY = randy.nextGaussian() * speed; - double mZ = randy.nextGaussian() * speed; - manager.add(CustomBreakingParticle.newLandingParticle((ClientLevel) world, entityPos.x, entityPos.y, entityPos.z, mX, mY, mZ, sprites.get(randy.nextInt(sprites.size())))); - } - } - } - } - - @OnlyIn (Dist.CLIENT) public static void addBlockHitEffects(Level world, Cuboid6 bounds, Direction side, TextureAtlasSprite icon, ParticleEngine particleManager) { float border = 0.1F; Vector3 diff = bounds.max.copy().subtract(bounds.min).add(-2 * border); @@ -191,7 +47,6 @@ public static void addBlockHitEffects(Level world, Cuboid6 bounds, Direction sid particleManager.add(new CustomBreakingParticle((ClientLevel) world, pos.x, pos.y, pos.z, 0, 0, 0, icon).setPower(0.2F).scale(0.6F)); } - @OnlyIn (Dist.CLIENT) public static void addBlockDestroyEffects(Level world, Cuboid6 bounds, List icons, ParticleEngine particleManager) { Vector3 diff = bounds.max.copy().subtract(bounds.min); Vector3 center = bounds.min.copy().add(bounds.max).multiply(0.5); @@ -208,4 +63,29 @@ public static void addBlockDestroyEffects(Level world, Cuboid6 bounds, List - * Created by covers1624 on 31/10/19. - */ -public interface ICustomParticleBlock extends IForgeBlock { - - @Override - default boolean addLandingEffects(BlockState state1, ServerLevel worldserver, BlockPos pos, BlockState state2, LivingEntity entity, int numberOfParticles) { - CustomParticleHandler.handleLandingEffects(worldserver, pos, entity, numberOfParticles); - return true; - } - - @Override - default boolean addRunningEffects(BlockState state, Level world, BlockPos pos, Entity entity) { - return world.isClientSide && CustomParticleHandler.handleRunningEffects(world, pos, state, entity); - } - - // TODO IBlockRenderProperties -// @Override -// @OnlyIn (Dist.CLIENT) -// default boolean addHitEffects(BlockState state, World worldObj, RayTraceResult target, ParticleManager manager) { -// return CustomParticleHandler.handleHitEffects(state, worldObj, target, manager); -// } -// -// @Override -// @OnlyIn (Dist.CLIENT) -// default boolean addDestroyEffects(BlockState state, World world, BlockPos pos, ParticleManager manager) { -// return CustomParticleHandler.handleDestroyEffects(world, pos, state, manager); -// } -} diff --git a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java b/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java deleted file mode 100644 index e6f3af71..00000000 --- a/src/main/java/codechicken/lib/render/particle/IModelParticleProvider.java +++ /dev/null @@ -1,46 +0,0 @@ -package codechicken.lib.render.particle; - -import codechicken.lib.texture.TextureUtils; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockAndTintGetter; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; -import net.minecraftforge.client.model.data.ModelData; - -import javax.annotation.Nonnull; -import java.util.Set; - -/** - * Created by covers1624 on 12/07/2017. - */ -public interface IModelParticleProvider extends BakedModel { - - @Override - default TextureAtlasSprite getParticleIcon() { - return TextureUtils.getMissingSprite(); - } - - /** - * Used to retrieve the particles to randomly choose from for hit particles. - * - * @param traceResult The trace result. - * @param state The state, getActualState and getExtendedState has been called. - * @param world The world. - * @param pos The pos. - * @return A Set of Textures to use. - */ - Set getHitEffects(@Nonnull BlockHitResult traceResult, BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData modelData); - - /** - * Used to retrieve the destroy particles for the block. - * - * @param state The state, getActualState and getExtendedState has been called. - * @param world The world. - * @param pos The pos. - * @return A Set of Textures to use. - */ - Set getDestroyEffects(BlockState state, BlockAndTintGetter world, BlockPos pos, ModelData data); - -} diff --git a/src/main/java/codechicken/lib/render/particle/package-info.java b/src/main/java/codechicken/lib/render/particle/package-info.java new file mode 100644 index 00000000..ceb3beea --- /dev/null +++ b/src/main/java/codechicken/lib/render/particle/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.particle; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java index dd0bf217..43497135 100644 --- a/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java +++ b/src/main/java/codechicken/lib/render/pipeline/CCRenderPipeline.java @@ -1,6 +1,8 @@ package codechicken.lib.render.pipeline; import codechicken.lib.render.CCRenderState; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -10,21 +12,15 @@ public class CCRenderPipeline { private final CCRenderState renderState; - @Deprecated - private final PipelineBuilder builder; - - @Deprecated//Hack removed. - public boolean forceFormatAttributes = true; private final List> attribs = new ArrayList<>(); private final List ops = new ArrayList<>(); private final List nodes = new ArrayList<>(); private final List sorted = new ArrayList<>(); - private PipelineNode loading; + private @Nullable PipelineNode loading; public CCRenderPipeline(CCRenderState renderState) { this.renderState = renderState; - builder = new PipelineBuilder(renderState); } public void setPipeline(IVertexOperation... ops) { @@ -52,10 +48,10 @@ public void rebuild() { unbuild(); - if (renderState.cFmt.hasNormal) { + if (renderState.fmt.contains(VertexFormatElement.NORMAL)) { addAttribute(renderState.normalAttrib); } - if (renderState.cFmt.hasColor) { + if (renderState.fmt.contains(VertexFormatElement.COLOR)) { addAttribute(renderState.colourAttrib); } if (renderState.computeLighting) { @@ -76,6 +72,7 @@ public void rebuild() { for (int i = 0; i < ops.size(); i++) { IVertexOperation op = ops.get(i); loading = nodes.get(op.operationID()); + assert loading != null; boolean loaded = op.load(renderState); if (loaded) { loading.op = op; @@ -97,10 +94,12 @@ public void rebuild() { } public void addRequirement(int opRef) { + assert loading != null; loading.deps.add(nodes.get(opRef)); } public void addDependency(VertexAttribute attrib) { + assert loading != null; loading.deps.add(nodes.get(attrib.operationID())); addAttribute(attrib); } @@ -119,45 +118,10 @@ public void operate() { } } - @Deprecated - public PipelineBuilder builder() { - ops.clear(); - return builder; - } - - @Deprecated - public class PipelineBuilder { - - private final CCRenderState renderState; - - public PipelineBuilder(CCRenderState renderState) { - this.renderState = renderState; - } - - public PipelineBuilder add(IVertexOperation op) { - ops.add(op); - return this; - } - - public PipelineBuilder add(IVertexOperation... ops) { - Collections.addAll(CCRenderPipeline.this.ops, ops); - return this; - } - - public void build() { - rebuild(); - } - - public void render() { - rebuild(); - renderState.render(); - } - } - private class PipelineNode { public ArrayList deps = new ArrayList<>(); - public IVertexOperation op; + public @Nullable IVertexOperation op; public void add() { if (op == null) { diff --git a/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java b/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java index a8a4c247..00b74a87 100644 --- a/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java +++ b/src/main/java/codechicken/lib/render/pipeline/IVertexOperation.java @@ -8,7 +8,7 @@ public interface IVertexOperation { static int registerOperation() { - return VertexOperationRegistry.nextOperationIndex++; + return VertexOperationRegistry.nextOperationIndex(); } static int operationCount() { @@ -35,5 +35,9 @@ static int operationCount() { class VertexOperationRegistry { static int nextOperationIndex; + + private static synchronized int nextOperationIndex() { + return VertexOperationRegistry.nextOperationIndex++; + } } } diff --git a/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java b/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java index 59acee13..60252a90 100644 --- a/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java +++ b/src/main/java/codechicken/lib/render/pipeline/IVertexSource.java @@ -19,7 +19,7 @@ public interface IVertexSource { /** * The number of vertices available in the model. - * + *

* By default, this method just returns the * length of the @link #getVertices()} array. * @@ -36,7 +36,8 @@ default int getVertexCount() { * @return The {@code T} for the given {@link AttributeKey} * or {@code null} of the Attribute does not exist. */ - @Nullable T getAttribute(AttributeKey attr); + @Nullable + T getAttribute(AttributeKey attr); /** * Returns {@code true} if the specified attribute is provided by this {@link IVertexSource}. diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java index 6c35d681..f54b73f3 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/AttributeKey.java @@ -6,6 +6,7 @@ import codechicken.lib.util.ArrayUtils; import codechicken.lib.util.Copyable; +import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -44,7 +45,7 @@ public T createDefault(int length) { @Override public T copy(T src, int length) { T dst = createDefault(length); - ArrayUtils.arrayCopy(src, 0, dst, 0, ((Object[]) src).length); + ArrayUtils.arrayCopy(src, 0, dst, 0, Array.getLength(src)); return dst; } @@ -93,7 +94,7 @@ public static class AttributeKeyRegistry { private static final Map> nameMap = new HashMap<>(); private static final List> attributeKeys = new ArrayList<>(); - private static int registerAttributeKey(AttributeKey attr) { + private static synchronized int registerAttributeKey(AttributeKey attr) { if (nameMap.containsKey(attr.name)) { throw new IllegalArgumentException("Duplicate registration of attribute with name: " + attr.name); } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java index 8508f4ca..db7b650f 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/ColourAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; +import org.jetbrains.annotations.Nullable; /** * Sets colour in CCRS to the specified colour in the model. @@ -11,7 +12,7 @@ public class ColourAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("colour", int[]::new); - private int[] colourRef; + private int @Nullable [] colourRef; public ColourAttribute() { super(attributeKey); @@ -19,6 +20,8 @@ public ColourAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + colourRef = ccrs.model.getAttribute(attributeKey); return colourRef != null || !ccrs.model.hasAttribute(attributeKey); } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java index d8135cda..5aff5974 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightCoordAttribute.java @@ -5,6 +5,7 @@ import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.vec.Transformation; import codechicken.lib.vec.Vector3; +import org.jetbrains.annotations.Nullable; /** * Uses the position of the lightmatrix to compute LC if not provided @@ -13,10 +14,9 @@ public class LightCoordAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("light_coord", LC[]::new); - private final Vector3 vec = new Vector3();//for computation - private final Vector3 pos = new Vector3(); + private final Vector3 vec = new Vector3(); // for computation - private LC[] lcRef; + private LC @Nullable [] lcRef; public LightCoordAttribute() { super(attributeKey); @@ -24,12 +24,13 @@ public LightCoordAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + lcRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return lcRef != null; } - pos.set(ccrs.lightMatrix.pos); ccrs.pipeline.addDependency(ccrs.sideAttrib); ccrs.pipeline.addRequirement(Transformation.operationIndex); return true; @@ -40,7 +41,7 @@ public void operate(CCRenderState ccrs) { if (lcRef != null) { ccrs.lc.set(lcRef[ccrs.vertexIndex]); } else { - ccrs.lc.compute(vec.set(ccrs.vert.vec).subtract(pos), ccrs.side); + ccrs.lc.compute(vec.set(ccrs.vert.vec), ccrs.side); } } } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java index 4bc25c90..dbaf6b9b 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/LightingAttribute.java @@ -3,6 +3,8 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; +import com.mojang.blaze3d.vertex.VertexFormatElement; +import org.jetbrains.annotations.Nullable; /** * Created by covers1624 on 10/10/2016. @@ -11,7 +13,7 @@ public class LightingAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("lighting", int[]::new); - private int[] colourRef; + private int @Nullable [] colourRef; public LightingAttribute() { super(attributeKey); @@ -19,7 +21,10 @@ public LightingAttribute() { @Override public boolean load(CCRenderState ccrs) { - if (!ccrs.computeLighting || !ccrs.cFmt.hasColor || !ccrs.model.hasAttribute(attributeKey)) { + assert ccrs.fmt != null; + assert ccrs.model != null; + + if (!ccrs.computeLighting || !ccrs.fmt.contains(VertexFormatElement.COLOR) || !ccrs.model.hasAttribute(attributeKey)) { return false; } @@ -33,6 +38,7 @@ public boolean load(CCRenderState ccrs) { @Override public void operate(CCRenderState ccrs) { + assert colourRef != null; ccrs.colour = ColourRGBA.multiply(ccrs.colour, colourRef[ccrs.vertexIndex]); } } diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java index 236b8963..01796d2d 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/NormalAttribute.java @@ -4,6 +4,7 @@ import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.vec.Rotation; import codechicken.lib.vec.Vector3; +import org.jetbrains.annotations.Nullable; /** * Apples normals to the render operation. If the model is a planar model it uses known normals. @@ -12,7 +13,7 @@ public class NormalAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("normal", Vector3[]::new); - private Vector3[] normalRef; + private Vector3 @Nullable [] normalRef; public NormalAttribute() { super(attributeKey); @@ -20,6 +21,8 @@ public NormalAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + normalRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return normalRef != null; diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java b/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java index 12643206..9bc69b46 100644 --- a/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/SideAttribute.java @@ -3,6 +3,7 @@ import codechicken.lib.render.CCRenderState; import codechicken.lib.render.pipeline.VertexAttribute; import codechicken.lib.util.VectorUtils; +import org.jetbrains.annotations.Nullable; /** * Sets the side state in CCRS based on the provided model. If the model does not have side data it requires normals. @@ -11,7 +12,7 @@ public class SideAttribute extends VertexAttribute { public static final AttributeKey attributeKey = AttributeKey.create("side", int[]::new); - private int[] sideRef; + private int @Nullable [] sideRef; public SideAttribute() { super(attributeKey); @@ -19,6 +20,8 @@ public SideAttribute() { @Override public boolean load(CCRenderState ccrs) { + assert ccrs.model != null; + sideRef = ccrs.model.getAttribute(attributeKey); if (ccrs.model.hasAttribute(attributeKey)) { return sideRef != null; diff --git a/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java b/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java new file mode 100644 index 00000000..10e76952 --- /dev/null +++ b/src/main/java/codechicken/lib/render/pipeline/attribute/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.pipeline.attribute; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/pipeline/package-info.java b/src/main/java/codechicken/lib/render/pipeline/package-info.java new file mode 100644 index 00000000..61587d81 --- /dev/null +++ b/src/main/java/codechicken/lib/render/pipeline/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.render.pipeline; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java b/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java deleted file mode 100644 index 7f9d3dee..00000000 --- a/src/main/java/codechicken/lib/render/shader/AbstractShaderObject.java +++ /dev/null @@ -1,54 +0,0 @@ -package codechicken.lib.render.shader; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.util.Collection; - -/** - * Created by covers1624 on 24/5/20. - */ -public abstract class AbstractShaderObject extends NamedShaderObject { - - protected int shaderId = -1; - protected boolean dirty; - - protected AbstractShaderObject(String name, ShaderType type, Collection uniforms) { - super(name, type, uniforms); - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void alloc() { - if (dirty || shaderId == -1) { - if (shaderId == -1) { - shaderId = GL20.glCreateShader(getShaderType().getGLCode()); - if (shaderId == 0) { - throw new RuntimeException("Allocation of ShaderObject failed."); - } - } - GL20.glShaderSource(shaderId, getSource()); - GL20.glCompileShader(shaderId); - if (GL20.glGetShaderi(shaderId, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetShaderInfoLog(shaderId)); - } - dirty = false; - } - } - - @Override - public int getShaderID() { - return shaderId; - } - - @Override - public void onLink(int programId) { - - } - - protected abstract String getSource(); -} diff --git a/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java b/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java deleted file mode 100644 index ca524460..00000000 --- a/src/main/java/codechicken/lib/render/shader/AssetShaderObject.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.render.shader; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Objects; - -/** - * Created by covers1624 on 24/5/20. - */ -public class AssetShaderObject extends AbstractShaderObject implements ResourceManagerReloadListener { - - private static final Logger LOGGER = LogManager.getLogger(); - - private final ResourceLocation asset; - @Nullable - private String source; - - public AssetShaderObject(String name, ShaderType type, Collection uniforms, ResourceLocation asset) { - super(name, type, uniforms); - this.asset = Objects.requireNonNull(asset); - } - - @Override - protected String getSource() { - if (source == null) { - source = new GlslProcessor(asset).process().processedSource(); - } - - return source; - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - source = null; - dirty = true; - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java b/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java deleted file mode 100644 index 390866ea..00000000 --- a/src/main/java/codechicken/lib/render/shader/BinaryShaderObject.java +++ /dev/null @@ -1,111 +0,0 @@ -package codechicken.lib.render.shader; - -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL46; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Collection; -import java.util.function.Consumer; - -/** - * Allows using pre-compiled shader binaries with {@link ShaderProgram}. - *

- * Created by KitsuneAlex on 18/11/21. - */ -public class BinaryShaderObject extends NamedShaderObject implements ResourceManagerReloadListener { - - private static final Logger LOGGER = LogManager.getLogger(); - - private final ResourceLocation asset; - private final BinaryType binaryType; - private final String entryPoint; - private final ShaderConstantCache constantCache = new ShaderConstantCache(); - private final Consumer specializationCallback; - private boolean dirty = false; - private int shaderId = -1; - - public BinaryShaderObject(String name, ResourceLocation asset, ShaderType type, BinaryType binaryType, String entryPoint, Collection uniforms, Consumer specializationCallback) { - super(name, type, uniforms); - this.asset = asset; - this.binaryType = binaryType; - this.entryPoint = entryPoint; - this.specializationCallback = specializationCallback; - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void alloc() { - if (dirty || shaderId == -1) { - if (shaderId == -1) { - shaderId = GL20.glCreateShader(getShaderType().getGLCode()); - if (shaderId == 0) { - throw new IllegalStateException("Allocation of ShaderObject failed."); - } - } - - byte[] source = getRawSource(); - ByteBuffer sourceBuffer = BufferUtils.createByteBuffer(source.length).order(ByteOrder.nativeOrder()); - sourceBuffer.put(source); - sourceBuffer.flip(); - GL46.glShaderBinary(new int[] { shaderId }, binaryType.getGLCode(), sourceBuffer); - - specializationCallback.accept(constantCache); - GL46.glSpecializeShader(shaderId, entryPoint, constantCache.getIndices(), constantCache.getValues()); - - if (GL20.glGetShaderi(shaderId, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetShaderInfoLog(shaderId)); - } - - dirty = false; - } - } - - @Override - public int getShaderID() { - return shaderId; - } - - @Override - public void onLink(int programId) { - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - dirty = true; - } - - private byte[] getRawSource() { - try { - Resource resource = Minecraft.getInstance().getResourceManager().getResourceOrThrow(asset); - try (InputStream istream = resource.open()) { - ByteArrayOutputStream ostream = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int read; - while ((read = istream.read(buffer)) != -1) { - ostream.write(buffer, 0, read); - } - return ostream.toByteArray(); - } - } catch (Throwable t) { - LOGGER.error("Failed to read shader asset.", t); - return new byte[0]; - } - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/BinaryType.java b/src/main/java/codechicken/lib/render/shader/BinaryType.java deleted file mode 100644 index 86ccb071..00000000 --- a/src/main/java/codechicken/lib/render/shader/BinaryType.java +++ /dev/null @@ -1,22 +0,0 @@ -package codechicken.lib.render.shader; - -import org.lwjgl.opengl.GL46; - -/** - * All currently supported shader binary types. - *

- * Created by KitsuneAlex on 19/11/21. - */ -public enum BinaryType { - SPIR_V(GL46.GL_SHADER_BINARY_FORMAT_SPIR_V); - - private final int glCode; - - BinaryType(int glCode) { - this.glCode = glCode; - } - - public int getGLCode() { - return glCode; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java b/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java deleted file mode 100644 index 2c5c621e..00000000 --- a/src/main/java/codechicken/lib/render/shader/CCShaderInstance.java +++ /dev/null @@ -1,200 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.GlslProcessor.ProcessedShader; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.mojang.blaze3d.shaders.Program; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.Util; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ChainedJsonException; -import net.minecraft.server.packs.resources.ResourceProvider; -import net.minecraft.util.GsonHelper; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.io.IOException; -import java.util.*; - -/** - * A Slightly extended ShaderInstance supporting: - * - Better Uniform caching. - * - All OpenGL Uniform types. - * - Global Uniform callbacks. - * - Better import/includes in shaders. - *

- * Created by covers1624 on 8/4/22. - */ -public class CCShaderInstance extends ShaderInstance { - - private final List applyCallbacks = new LinkedList<>(); - - protected CCShaderInstance(ResourceProvider resourceProvider, ResourceLocation loc, VertexFormat format) throws IOException { - super(resourceProvider, loc, format); - } - - public static CCShaderInstance create(ResourceProvider resourceProvider, ResourceLocation loc, VertexFormat format) { - try { - return new CCShaderInstance(resourceProvider, loc, format); - } catch (IOException ex) { - throw new RuntimeException("Failed to initialize shader.", ex); - } - } - - /** - * Add a callback for when this {@link CCShaderInstance} is applied. - *

- * Use this for global uniforms, or whatever else. - * - * @param callback The callback. - */ - public void onApply(Runnable callback) { - applyCallbacks.add(callback); - } - - @Override - public void apply() { - for (Runnable callback : applyCallbacks) { - callback.run(); - } - super.apply(); - } - - @Nullable - @Override - public CCUniform getUniform(String name) { - return (CCUniform) super.getUniform(name); - } - - @Override - protected void parseUniformNode(JsonElement json) throws ChainedJsonException { - JsonObject obj = GsonHelper.convertToJsonObject(json, "uniform"); - String name = GsonHelper.getAsString(obj, "name"); - String typeStr = GsonHelper.getAsString(obj, "type"); - UniformType type = UniformType.parse(typeStr); - if (type == null) { - throw new ChainedJsonException("Invalid type '%s'. See UniformType enum. All vanilla types supported.".formatted(typeStr)); - } - - int count = GsonHelper.getAsInt(obj, "count"); - // Hack for vanilla compat. Vanilla specifies 'float, count 4' for vec4, we need ot to be a vec4 - switch (type) { - case FLOAT -> { - switch(count) { - case 2 -> type = UniformType.VEC2; - case 3 -> type = UniformType.VEC3; - case 4 -> type = UniformType.VEC4; - } - } - case INT -> { - switch(count) { - case 2 -> type = UniformType.I_VEC2; - case 3 -> type = UniformType.I_VEC3; - case 4 -> type = UniformType.I_VEC4; - } - } - case U_INT -> { - switch(count) { - case 2 -> type = UniformType.U_VEC2; - case 3 -> type = UniformType.U_VEC3; - case 4 -> type = UniformType.U_VEC4; - } - } - } - CCUniform uniform = CCUniform.makeUniform(name, type, count, this); - - JsonArray jsonValues = GsonHelper.getAsJsonArray(obj, "values"); - if (jsonValues.size() != count && jsonValues.size() > 1) { - throw new ChainedJsonException("Invalid amount of values specified (expected " + count + ", found " + jsonValues.size() + ")"); - } - switch (type.getCarrier()) { - case INT, U_INT -> uniform.glUniformI(parseInts(count, jsonValues)); - case FLOAT, MATRIX -> uniform.glUniformF(false, parseFloats(count, jsonValues)); - case DOUBLE, D_MATRIX -> uniform.glUniformD(false, parseDoubles(count, jsonValues)); - } - uniforms.add(uniform); - } - - public Program compileProgram(ResourceProvider resourceProvider, Program.Type programType, ResourceLocation loc) throws IOException { - ResourceLocation adjustedLoc = new ResourceLocation(loc.getNamespace(), "shaders/core/" + loc.getPath() + programType.getExtension()); - String cacheString = "ccl__" + adjustedLoc; - Program program = programType.getPrograms().get(cacheString); - if (program != null) return program; - - ProcessedShader processedShader = new GlslProcessor(resourceProvider, adjustedLoc).process(); - - int id = GL20.glCreateShader(programType.getGlType()); - GL20.glShaderSource(id, processedShader.processedSource()); - GL20.glCompileShader(id); - if (GL20.glGetShaderi(id, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) { - String s1 = GL20.glGetShaderInfoLog(id); - throw new IOException("Couldn't compile " + programType.getName() + " program (" + processedShader.sourceName() + ", " + adjustedLoc + ") : " + s1); - } - program = new Program(programType, id, cacheString); - programType.getPrograms().put(cacheString, program); - return program; - } - - private static float[] parseFloats(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - float[] values = new float[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToFloat(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } - - private static int[] parseInts(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - int[] values = new int[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToInt(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } - - private static double[] parseDoubles(int count, JsonArray jsonValues) throws ChainedJsonException { - int i = 0; - double[] values = new double[Math.max(count, 16)]; - for (JsonElement jsonValue : jsonValues) { - try { - values[i++] = GsonHelper.convertToDouble(jsonValue, "value"); - } catch (Exception ex) { - ChainedJsonException chainedjsonexception = ChainedJsonException.forException(ex); - chainedjsonexception.prependJsonKey("values[" + i + "]"); - throw chainedjsonexception; - } - } - - // If only one value is specified, copy to all in array. - if (count > 1 && jsonValues.size() == 1) { - Arrays.fill(values, 1, values.length, values[0]); - } - return Arrays.copyOfRange(values, 0, count); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/CCUniform.java b/src/main/java/codechicken/lib/render/shader/CCUniform.java deleted file mode 100644 index 42a2c6cc..00000000 --- a/src/main/java/codechicken/lib/render/shader/CCUniform.java +++ /dev/null @@ -1,287 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.UniformType.Carrier; -import com.mojang.blaze3d.shaders.Shader; -import com.mojang.blaze3d.shaders.Uniform; -import com.mojang.math.Matrix3f; -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; -import org.apache.commons.lang3.NotImplementedException; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL21; -import org.lwjgl.opengl.GL30; -import org.lwjgl.opengl.GL40; -import org.lwjgl.system.MemoryUtil; - -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.util.Arrays; - -/** - * Created by covers1624 on 8/4/22. - */ -public abstract class CCUniform extends Uniform implements ICCUniform { - - protected final UniformType type; - - @SuppressWarnings ("ConstantConditions") - protected CCUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type.getVanillaType(), count, parent); - this.type = type; - if (intValues != null) { - MemoryUtil.memFree(intValues); - intValues = null; - } - if (floatValues != null) { - MemoryUtil.memFree(floatValues); - floatValues = null; - } - } - - static CCUniform makeUniform(String name, UniformType type, int count, @Nullable Shader parent) { - if (count % type.getSize() != 0) throw new IllegalArgumentException("Expected count to be a multiple of the uniform type size: " + type.getSize()); - return switch (type.getCarrier()) { - case INT, U_INT -> new IntUniform(name, type, count, parent); - case FLOAT, MATRIX -> new FloatUniform(name, type, count, parent); - case DOUBLE, D_MATRIX -> new DoubleUniform(name, type, count, parent); - }; - } - - @Override - public IntBuffer getIntBuffer() { - throw new NotImplementedException("TODO"); - } - - @Override - public FloatBuffer getFloatBuffer() { - throw new NotImplementedException("TODO"); - } - - private static abstract class UniformEntry extends CCUniform { - - @Nullable - protected T cache; - protected boolean transpose; - - public UniformEntry(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - } - - // @formatter:off - @Override public void set(float f0) { glUniformF(false, f0); } - @Override public void set(float f0, float f1) { glUniformF(false, f0, f1); } - @Override public void set(int i, float f) { throw new UnsupportedOperationException("Unable to set specific index."); } - @Override public void set(float f0, float f1, float f2) { glUniformF(false, f0, f1, f2); } - @Override public void set(Vector3f vec) { glUniformF(false, vec.x(), vec.y(), vec.z()); } - @Override public void set(float f0, float f1, float f2, float f3) { glUniformF(false, f0, f1, f2, f3); } - @Override public void set(Vector4f vec) { glUniformF(false, vec.x(), vec.y(), vec.z(), vec.w()); } - @Override public void set(int i0) { glUniformI(i0); } - @Override public void set(int i0, int i1) { glUniformI(i0, i1); } - @Override public void set(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - @Override public void set(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - @Override public void set(float[] p_85632_) { glUniformF(false, p_85632_); } - @Override public void setMat2x2(float m00, float m01, float m10, float m11) { glUniformF(true, m00, m01, m10, m11); } - @Override public void setMat2x3(float m00, float m01, float m02, float m10, float m11, float m12) { glUniformF(true, m00, m01, m02, m10, m11, m12); } - @Override public void setMat2x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13); } - @Override public void setMat3x2(float m00, float m01, float m10, float m11, float m20, float m21) { glUniformF(true, m00, m01, m10, m11, m20, m21); } - @Override public void setMat3x3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { glUniformF(true, m00, m01, m02, m10, m11, m12, m20, m21, m22); } - @Override public void setMat3x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23); } - @Override public void setMat4x2(float m00, float m01, float m10, float m11, float m20, float m21, float m30, float m31) { glUniformF(true, m00, m01, m10, m11, m20, m21, m30, m31); } - @Override public void setMat4x3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m23, float m30, float m31, float m32) { glUniformF(true, m00, m01, m02, m10, m11, m12, m20, m21, m23, m30, m31, m32); } - @Override public void setMat4x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { glUniformF(true, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); } - @Override public void set(Matrix4f mat) { glUniformMatrix4f(mat); } - @Override public void set(Matrix3f mat) { glUniformMatrix3f(mat); } - // @formatter:on - - @Override - public void setSafe(float f0, float f1, float f2, float f3) { - assert type.getCarrier() == Carrier.FLOAT; - switch (type.getSize()) { - case 1 -> glUniform1f(f0); - case 2 -> glUniform2f(f0, f1); - case 3 -> glUniform3f(f0, f1, f2); - case 4 -> glUniform4f(f0, f1, f2, f3); - } - throw new IllegalStateException("Unexpected type size: " + type); - } - - @Override - public void setSafe(int i0, int i1, int i2, int i3) { - assert type.getCarrier() == Carrier.INT || type.getCarrier() == Carrier.U_INT; - switch (type.getSize()) { - case 1 -> glUniform1i(i0); - case 2 -> glUniform2i(i0, i1); - case 3 -> glUniform3i(i0, i1, i2); - case 4 -> glUniform4i(i0, i1, i2, i3); - } - throw new IllegalStateException("Unexpected type size: " + type); - } - - @Override - public void glUniformI(int... values) { - if (type.getCarrier() != Carrier.INT && type.getCarrier() != Carrier.U_INT) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of INT or U_INT, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, false); - } - - @Override - public void glUniformF(boolean transpose, float... values) { - if (type.getCarrier() != Carrier.FLOAT && type.getCarrier() != Carrier.MATRIX) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of FLOAT or MATRIX, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, transpose); - } - - @Override - public void glUniformD(boolean transpose, double... values) { - if (type.getCarrier() != Carrier.DOUBLE && type.getCarrier() != Carrier.D_MATRIX) { - throw new IllegalArgumentException("Uniform '%s' isn't registered with the carrier of DOUBLE or D_MATRIX, Got type '%s' with carrier '%s'.".formatted(getName(), type, type.getCarrier())); - } - set((T) values, transpose); - } - - public void set(T values, boolean transpose) { - assert !transpose || type.getCarrier() == Carrier.MATRIX || type.getCarrier() == Carrier.D_MATRIX; - - if (len(values) != getCount()) { - throw new IllegalArgumentException("Invalid size for uniform '%s', Expected: '%s', Got: '%s'.".formatted(getName(), getCount(), len(values))); - } - - if (!equals(cache, values) || this.transpose != transpose) { - cache = values; - this.transpose = transpose; - dirty = true; - } - } - - @Override - public void upload() { - if (!dirty) return; - - flush(); - dirty = false; - } - - public abstract void flush(); - - public abstract T make(int len); - - public abstract int len(T arr); - - public abstract boolean equals(@Nullable T a, T b); - } - - private static class IntUniform extends UniformEntry { - - public IntUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.INT || type.getCarrier() == Carrier.U_INT; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case INT -> GL20.glUniform1iv(getLocation(), cache); - case U_INT -> GL30.glUniform1uiv(getLocation(), cache); - case I_VEC2, B_VEC2 -> GL20.glUniform2iv(getLocation(), cache); - case U_VEC2 -> GL30.glUniform2uiv(getLocation(), cache); - case I_VEC3, B_VEC3 -> GL20.glUniform3iv(getLocation(), cache); - case U_VEC3 -> GL30.glUniform3uiv(getLocation(), cache); - case I_VEC4, B_VEC4 -> GL20.glUniform4iv(getLocation(), cache); - case U_VEC4 -> GL30.glUniform4uiv(getLocation(), cache); - default -> throw new IllegalStateException("Unhandled uniform type for IntUniform: " + type); - } - } - - //@formatter:off - @Override public int[] make(int len) { return new int[len]; } - @Override public int len(int[] cache) { return cache.length; } - @Override public boolean equals(int @Nullable [] a, int[] b) { return Arrays.equals(a, b); } - //@formatter:on - } - - private static class FloatUniform extends UniformEntry { - - public FloatUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.FLOAT || type.getCarrier() == Carrier.MATRIX; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case FLOAT -> GL20.glUniform1fv(getLocation(), cache); - case VEC2 -> GL20.glUniform2fv(getLocation(), cache); - case VEC3 -> GL20.glUniform3fv(getLocation(), cache); - case VEC4 -> GL20.glUniform4fv(getLocation(), cache); - - case MAT2 -> GL20.glUniformMatrix2fv (getLocation(), transpose, cache); - case MAT2x3 -> GL21.glUniformMatrix2x3fv(getLocation(), transpose, cache); - case MAT2x4 -> GL21.glUniformMatrix2x4fv(getLocation(), transpose, cache); - - case MAT3 -> GL20.glUniformMatrix3fv (getLocation(), transpose, cache); - case MAT3x2 -> GL21.glUniformMatrix3x2fv(getLocation(), transpose, cache); - case MAT3x4 -> GL21.glUniformMatrix3x4fv(getLocation(), transpose, cache); - - case MAT4 -> GL20.glUniformMatrix4fv (getLocation(), transpose, cache); - case MAT4x2 -> GL21.glUniformMatrix4x2fv(getLocation(), transpose, cache); - case MAT4x3 -> GL21.glUniformMatrix4x3fv(getLocation(), transpose, cache); - - default -> throw new IllegalStateException("Unhandled uniform type for FloatUniform: " + type); - } - } - - //@formatter:off - @Override public float[] make(int len) { return new float[len]; } - @Override public int len(float[] cache) { return cache.length; } - @Override public boolean equals(float @Nullable [] a, float[] b) { return Arrays.equals(a, b); } - //@formatter:on - } - - private static class DoubleUniform extends UniformEntry { - - public DoubleUniform(String name, UniformType type, int count, @Nullable Shader parent) { - super(name, type, count, parent); - assert type.getCarrier() == Carrier.DOUBLE || type.getCarrier() == Carrier.D_MATRIX; - } - - @Override - public void flush() { - assert cache != null; - - switch (type) { - case DOUBLE -> GL40.glUniform1dv(getLocation(), cache); - case D_VEC2 -> GL40.glUniform2dv(getLocation(), cache); - case D_VEC3 -> GL40.glUniform3dv(getLocation(), cache); - case D_VEC4 -> GL40.glUniform4dv(getLocation(), cache); - - case D_MAT2 -> GL40.glUniformMatrix2dv (getLocation(), transpose, cache); - case D_MAT2x3 -> GL40.glUniformMatrix2x3dv(getLocation(), transpose, cache); - case D_MAT2x4 -> GL40.glUniformMatrix2x4dv(getLocation(), transpose, cache); - - case D_MAT3 -> GL40.glUniformMatrix3dv (getLocation(), transpose, cache); - case D_MAT3x2 -> GL40.glUniformMatrix3x2dv(getLocation(), transpose, cache); - case D_MAT3x4 -> GL40.glUniformMatrix3x4dv(getLocation(), transpose, cache); - - case D_MAT4 -> GL40.glUniformMatrix4dv (getLocation(), transpose, cache); - case D_MAT4x2 -> GL40.glUniformMatrix4x2dv(getLocation(), transpose, cache); - case D_MAT4x3 -> GL40.glUniformMatrix4x3dv(getLocation(), transpose, cache); - - default -> throw new IllegalStateException("Unhandled uniform type for DoubleUniform: " + type); - } - } - - //@formatter:off - @Override public double[] make(int len) { return new double[len]; } - @Override public int len(double[] cache) { return cache.length; } - @Override public boolean equals(double @Nullable [] a, double[] b) { return Arrays.equals(a, b); } - //@formatter:on - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ConstantCache.java b/src/main/java/codechicken/lib/render/shader/ConstantCache.java deleted file mode 100644 index c78a104d..00000000 --- a/src/main/java/codechicken/lib/render/shader/ConstantCache.java +++ /dev/null @@ -1,17 +0,0 @@ -package codechicken.lib.render.shader; - -/** - * Provides methods to mutate specilization constants - * before the shader is specialized. - *

- * Created by KitsuneAlex on 19/11/21. - */ -public interface ConstantCache { - - void constant1i(int id, int value); - - void constant1f(int id, float value); - - void constant1b(int id, boolean value); - -} diff --git a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java b/src/main/java/codechicken/lib/render/shader/GlslProcessor.java deleted file mode 100644 index b9c7deb4..00000000 --- a/src/main/java/codechicken/lib/render/shader/GlslProcessor.java +++ /dev/null @@ -1,197 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.graph.GraphBuilder; -import com.google.common.graph.MutableGraph; -import com.mojang.blaze3d.preprocessor.GlslPreprocessor; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.ints.IntSet; -import net.covers1624.quack.io.IOUtils; -import net.covers1624.quack.sort.TopologicalSort; -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceProvider; -import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -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.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Similar to Mojang's own {@link GlslPreprocessor}. - * However, more suited to a modded environment. - *

- * Created by covers1624 on 22/3/22. - */ -@SuppressWarnings ("ALL") -public class GlslProcessor { - - private static Logger LOGGER = LogManager.getLogger(); - - private static final boolean DEBUG = Boolean.getBoolean("ccl.glsl_processor.debug"); - - private static final Pattern VERSION_PATTERN = Pattern.compile("^#version (.*)$"); - // Matches #moj_import with <> or "" - private static final Pattern IMPORT_PATTERN = Pattern.compile("^#moj_import (?>(?><(.*)>)|(?>\"(.*)\"))$"); - - private final ResourceProvider resourceProvider; - private final ResourceLocation shader; - - private final Map processorLookup = new HashMap<>(); - private final LinkedList newProcessors = new LinkedList<>(); - - public GlslProcessor(ResourceLocation shader) { - this(Minecraft.getInstance().getResourceManager(), shader); - } - - public GlslProcessor(ResourceProvider resourceProvider, ResourceLocation shader) { - this.resourceProvider = resourceProvider; - this.shader = shader; - newProcessors.add(processorLookup.computeIfAbsent(shader, ProcessorEntry::new)); - } - - public ProcessedShader process() { - ProcessorEntry mainEntry = newProcessors.peek(); - String mainVersion = Objects.requireNonNull(mainEntry.version, "Main Shader '" + shader + "' in chain requires #version."); - - if (mainEntry.includes.isEmpty()) { - return new ProcessedShader( - shader, - mainEntry.sourceName, - List.of(shader), - String.join("\n", mainEntry.lines) - ); - } - - MutableGraph graph = GraphBuilder.directed().build(); - while (!newProcessors.isEmpty()) { - ProcessorEntry entry = newProcessors.pop(); - if (entry.version != null && !entry.version.equals(mainVersion)) { - LOGGER.warn("Shader chain {} -> {} version discrepency. Main Shader: {}, Included Shader: {}. This shader may not compile.", shader, entry.shader, mainVersion, entry.version); - } - for (ResourceLocation include : entry.includes) { - graph.putEdge(include, entry.shader); - if (!processorLookup.containsKey(include)) { - newProcessors.add(processorLookup.computeIfAbsent(include, ProcessorEntry::new)); - } - } - } - - List order = TopologicalSort.topologicalSort(graph, null); - List outputLines = new LinkedList<>(); - outputLines.add("#version " + mainVersion); - for (ResourceLocation resourceLocation : order) { - outputLines.add(""); - outputLines.add("/*" + resourceLocation + "*/"); - ProcessorEntry entry = processorLookup.get(resourceLocation); - for (int i = 0; i < entry.lines.size(); i++) { - String line = entry.lines.get(i); - if (entry.linesToComment.contains(i)) { - outputLines.add("/*" + line + "*/"); - } else { - outputLines.add(line); - } - } - } - - if (DEBUG) { - Path out = Paths.get("glsl") - .resolve("assets") - .resolve(shader.getNamespace()) - .resolve(shader.getPath()); - try { - Files.write(IOUtils.makeParents(out), outputLines, StandardCharsets.UTF_8); - } catch (IOException ex) { - LOGGER.error("Failed to write debug glsl output to {}", out); - } - } - - return new ProcessedShader( - shader, - mainEntry.sourceName, - List.copyOf(order), - String.join("\n", outputLines) - ); - } - - public static record ProcessedShader( - ResourceLocation shader, - String sourceName, - List order, - String processedSource) { - } - - private class ProcessorEntry { - - private final ResourceLocation shader; - private final String sourceName; - private final List lines; - private final List includes; - @Nullable - private final String version; - private final IntSet linesToComment; - - private ProcessorEntry(ResourceLocation shader) { - this.shader = shader; - try { - Resource resource = resourceProvider.getResourceOrThrow(shader); - sourceName = resource.sourcePackId(); - try (BufferedReader reader = resource.openAsReader()) { - lines = reader.lines().toList(); - } - } catch (IOException ex) { - throw new RuntimeException("Unable to read asset '" + shader + "'.", ex); - } - linesToComment = new IntOpenHashSet(); - includes = extractIncludes(lines, linesToComment); - version = extractVersion(lines, linesToComment); - } - - private static List extractIncludes(List lines, IntSet linesToComment) { - List imports = new LinkedList<>(); - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - Matcher matcher = IMPORT_PATTERN.matcher(line); - if (matcher.find()) { - linesToComment.add(i); - String match = matcher.group(1); - boolean includeFolder = match != null; - if (!includeFolder) { - match = matcher.group(2); - } - ResourceLocation loc = new ResourceLocation(match); - if (includeFolder) { - loc = new ResourceLocation(loc.getNamespace(), FilenameUtils.normalize("shaders/include/" + loc.getPath(), true)); - } - imports.add(loc); - } - } - - return List.copyOf(imports); - } - - @Nullable - private static String extractVersion(List lines, IntSet linesToComment) { - for (int i = 0; i < lines.size(); i++) { - String line = lines.get(i); - Matcher matcher = VERSION_PATTERN.matcher(line); - if (matcher.find()) { - linesToComment.add(i); - return matcher.group(1); - } - } - return null; - } - } - -} diff --git a/src/main/java/codechicken/lib/render/shader/ICCUniform.java b/src/main/java/codechicken/lib/render/shader/ICCUniform.java deleted file mode 100644 index 5fb38430..00000000 --- a/src/main/java/codechicken/lib/render/shader/ICCUniform.java +++ /dev/null @@ -1,247 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.vec.Matrix4; -import com.mojang.math.Matrix3f; -import com.mojang.math.Matrix4f; - -/** - * Created by covers1624 on 8/4/22. - */ -public interface ICCUniform { - - // region Int - default void glUniform1i(int i0) { glUniformI(i0); } - - default void glUniform2i(int i0, int i1) { glUniformI(i0, i1); } - - default void glUniform3i(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - - default void glUniform4i(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - // endregion - - // region Unsigned Int - default void glUniform1ui(int i0) { glUniformI(i0); } - - default void glUniform2ui(int i0, int i1) { glUniformI(i0, i1); } - - default void glUniform3ui(int i0, int i1, int i2) { glUniformI(i0, i1, i2); } - - default void glUniform4ui(int i0, int i1, int i2, int i3) { glUniformI(i0, i1, i2, i3); } - // endregion - - // region Float - default void glUniform1f(float f0) { glUniformF(false, f0); } - - default void glUniform2f(float f0, float f1) { glUniformF(false, f0, f1); } - - default void glUniform3f(float f0, float f1, float f2) { glUniformF(false, f0, f1, f2); } - - default void glUniform4f(float f0, float f1, float f2, float f3) { glUniformF(false, f0, f1, f2, f3); } - // endregion - - // region Double - default void glUniform1d(float d0) { glUniformD(false, d0); } - - default void glUniform2d(float d0, float d1) { glUniformD(false, d0, d1); } - - default void glUniform3d(float d0, float d1, float d2) { glUniformD(false, d0, d1, d2); } - - default void glUniform4d(float d0, float d1, float d2, float d3) { glUniformD(false, d0, d1, d2, d3); } - // endregion - - // region Boolean - default void glUniform1b(boolean b0) { glUniformI(b0 ? 1 : 0); } - - default void glUniform2b(boolean b0, boolean b1) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0); } - - default void glUniform3b(boolean b0, boolean b1, boolean b2) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0, b2 ? 1 : 0); } - - default void glUniform4b(boolean b0, boolean b1, boolean b2, boolean b3) { glUniformI(b0 ? 1 : 0, b1 ? 1 : 0, b2 ? 1 : 0, b3 ? 1 : 0); } - // endregion - - // region 2x Float Matrix - default void glUniformMatrix2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix2x3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2x3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix2x4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix2x4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 3x Float Matrix - default void glUniformMatrix3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix3f(Matrix3f matrix) { glUniformF(false, toArrayF(matrix)); } - - default void glUniformMatrix3f(boolean transpose, Matrix3f matrix) { glUniformF(transpose, toArrayF(matrix)); } - - default void glUniformMatrix3x2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3x2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix3x4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix3x4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 4x Float Matrix - default void glUniformMatrix4f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix4f(Matrix4 matrix) { glUniformF(false, matrix.toArrayF()); } - - default void glUniformMatrix4f(boolean transpose, Matrix4 matrix) { glUniformF(transpose, matrix.toArrayF()); } - - default void glUniformMatrix4f(Matrix4f matrix) { glUniformF(false, toArrayF(matrix)); } - - default void glUniformMatrix4f(boolean transpose, Matrix4f matrix) { glUniformF(transpose, toArrayF(matrix)); } - - default void glUniformMatrix4x2f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4x2f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - - default void glUniformMatrix4x3f(float[] matrix) { glUniformF(false, matrix); } - - default void glUniformMatrix4x3f(boolean transpose, float[] matrix) { glUniformF(transpose, matrix); } - // endregion - - // region 2x Double matrix - default void glUniformMatrix2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix2x3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2x3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix2x4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix2x4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region 3x Double Matrix - default void glUniformMatrix3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix3d(Matrix3f matrix) { glUniformD(false, toArrayD(matrix)); } - - default void glUniformMatrix3d(boolean transpose, Matrix3f matrix) { glUniformD(transpose, toArrayD(matrix)); } - - default void glUniformMatrix3x2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3x2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix3x4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix3x4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region 4x Double Matrix - default void glUniformMatrix4d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix4d(Matrix4 matrix) { glUniformD(false, matrix.toArrayD()); } - - default void glUniformMatrix4d(boolean transpose, Matrix4 matrix) { glUniformD(transpose, matrix.toArrayD()); } - - default void glUniformMatrix4d(Matrix4f matrix) { glUniformD(false, toArrayD(matrix)); } - - default void glUniformMatrix4d(boolean transpose, Matrix4f matrix) { glUniformD(transpose, toArrayD(matrix)); } - - default void glUniformMatrix4x2d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4x2d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - - default void glUniformMatrix4x3d(double[] matrix) { glUniformD(false, matrix); } - - default void glUniformMatrix4x3d(boolean transpose, double[] matrix) { glUniformD(transpose, matrix); } - // endregion - - // region Raw - void glUniformI(int... values); - - void glUniformF(boolean transpose, float... values); - - void glUniformD(boolean transpose, double... values); - // endregion - - private static float[] toArrayF(Matrix3f matrix) { - return new float[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m02, - matrix.m12, - matrix.m22, - }; - } - - private static float[] toArrayF(Matrix4f matrix) { - return new float[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m30, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m31, - matrix.m02, - matrix.m12, - matrix.m22, - matrix.m32, - matrix.m03, - matrix.m13, - matrix.m23, - matrix.m33, - }; - } - - private static double[] toArrayD(Matrix3f matrix) { - return new double[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m02, - matrix.m12, - matrix.m22, - }; - } - - private static double[] toArrayD(Matrix4f matrix) { - return new double[] { - matrix.m00, - matrix.m10, - matrix.m20, - matrix.m30, - matrix.m01, - matrix.m11, - matrix.m21, - matrix.m31, - matrix.m02, - matrix.m12, - matrix.m22, - matrix.m32, - matrix.m03, - matrix.m13, - matrix.m23, - matrix.m33, - }; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java b/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java deleted file mode 100644 index bc409573..00000000 --- a/src/main/java/codechicken/lib/render/shader/NamedShaderObject.java +++ /dev/null @@ -1,37 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; - -import java.util.Collection; -import java.util.Objects; - -/** - * Created by covers1624 on 9/3/22. - */ -public abstract class NamedShaderObject implements ShaderObject { - - private final String name; - private final ShaderType type; - private final ImmutableList uniforms; - - protected NamedShaderObject(String name, ShaderType type, Collection uniforms) { - this.name = Objects.requireNonNull(name); - this.type = Objects.requireNonNull(type); - this.uniforms = ImmutableList.copyOf(uniforms); - } - - @Override - public String getName() { - return name; - } - - @Override - public ShaderType getShaderType() { - return type; - } - - @Override - public ImmutableList getUniforms() { - return uniforms; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java b/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java deleted file mode 100644 index 122b4741..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderConstantCache.java +++ /dev/null @@ -1,49 +0,0 @@ -package codechicken.lib.render.shader; - -import it.unimi.dsi.fastutil.ints.Int2IntArrayMap; - -/** - * Created by KitsuneAlex on 19/11/21. - */ -public class ShaderConstantCache implements ConstantCache { - - private final Int2IntArrayMap values = new Int2IntArrayMap(); - - @Override - public void constant1i(int id, int value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - int oldValue = values.get(id); - if (oldValue == value) return; - - values.put(id, value); - } - - @Override - public void constant1f(int id, float value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - float oldValue = Float.intBitsToFloat(values.get(id)); - if (oldValue == value) return; - - values.put(id, Float.floatToIntBits(value)); - } - - @Override - public void constant1b(int id, boolean value) { - if (id < 0) throw new IllegalArgumentException("Constant location ID must be >= 0"); - - boolean oldValue = values.get(id) == 1; - if (oldValue == value) return; - - values.put(id, value ? 1 : 0); - } - - public int[] getIndices() { - return values.keySet().toIntArray(); - } - - public int[] getValues() { - return values.values().toIntArray(); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderObject.java b/src/main/java/codechicken/lib/render/shader/ShaderObject.java deleted file mode 100644 index 0291ee53..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderObject.java +++ /dev/null @@ -1,104 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; -import org.lwjgl.opengl.GL20; -import org.lwjgl.opengl.GL32; -import org.lwjgl.opengl.GL40; -import org.lwjgl.opengl.GL43; - -/** - * Created by covers1624 on 24/5/20. - */ -public interface ShaderObject { - - /** - * A simple identifier for this {@link ShaderObject}, - * used for logging. - * - * @return The name. - */ - String getName(); - - /** - * Gets the {@link ShaderType} for this shader. - * - * @return The {@link ShaderType}. - */ - ShaderType getShaderType(); - - /** - * Gets all {@link UniformPair}s this shader exposes. - * It is expected that a {@link ShaderObject} will not - * dynamically change the uniforms it exposes over its - * lifetime. Doing so is not enforced, but will break - * the Uniform pipeline. - * - * @return The {@link UniformPair}s. - */ - ImmutableList getUniforms(); - - /** - * Checks if this shader is dirty and requires re-compiling. - * - * @return If this shader is dirty. - */ - boolean isDirty(); - - /** - * Allocates and compiles this {@link ShaderObject}. - * Does nothing if the shader is already compiled. - */ - void alloc(); - - /** - * Gets the GL id for this {@link ShaderObject}. - * - * @return The id, -1 of not allocated. - */ - int getShaderID(); - - /** - * Called when this {@link ShaderObject} is linked to a {@link ShaderProgram}. - * - * @param programId The GL id of the program. - */ - void onLink(int programId); - - /** - * Represents a Shader Type. - */ - interface ShaderType { - - /** - * The GL code used in {@link GL20#glCreateShader}. - * - * @return The code. - */ - int getGLCode(); - } - - /** - * Standard ShaderTypes. - */ - enum StandardShaderType implements ShaderType { - //@formatter:off - VERTEX (GL20.GL_VERTEX_SHADER ), - FRAGMENT (GL20.GL_FRAGMENT_SHADER ), - GEOMETRY (GL32.GL_GEOMETRY_SHADER ), - TESS_CONTROL(GL40.GL_TESS_CONTROL_SHADER ), - TESS_EVAL (GL40.GL_TESS_EVALUATION_SHADER), - COMPUTE (GL43.GL_COMPUTE_SHADER ); - //@formatter:on - - private final int glCode; - - StandardShaderType(int glCode) { - this.glCode = glCode; - } - - @Override - public int getGLCode() { - return glCode; - } - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java b/src/main/java/codechicken/lib/render/shader/ShaderProgram.java deleted file mode 100644 index e4dcb223..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderProgram.java +++ /dev/null @@ -1,155 +0,0 @@ -package codechicken.lib.render.shader; - -import com.google.common.collect.ImmutableList; -import net.covers1624.quack.collection.StreamableIterable; -import net.minecraft.client.renderer.ShaderInstance; -import net.minecraft.server.packs.resources.ReloadableResourceManager; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import org.jetbrains.annotations.Nullable; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL20; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -/** - * A ShaderProgram. - *

- * As of 1.18.2, you will probably want to use {@link CCShaderInstance} instead as an extension - * to Vanilla's {@link ShaderInstance}. - *

- * You probably want {@link ShaderProgramBuilder} to construct a ShaderProgram. - * it should be noted, that a ShaderProgram is a {@link ResourceManagerReloadListener}, - * its recommended that you ensure this is registered to {@link ReloadableResourceManager} - * to ensure {@link ShaderObject}s are re loaded properly when Resources are reloaded. - *

- * Created by covers1624 on 24/5/20. - */ -public class ShaderProgram implements ResourceManagerReloadListener { - - private final List shaders; - private final Map uniforms; - @Nullable - private final Runnable applyCallback; - private int programId = -1; - private boolean bound; - - ShaderProgram(Collection shaders, Collection uniforms, @Nullable Runnable applyCallback) { - this.shaders = ImmutableList.copyOf(shaders); - this.uniforms = StreamableIterable.of(uniforms) - .toImmutableMap(UniformPair::name, e -> CCUniform.makeUniform(e.name(), e.type(), e.type().getSize(), null)); // TODO dont specify count of 1 here. - this.applyCallback = applyCallback; - } - - /** - * Gets all {@link ShaderObject}s that make up this {@link ShaderProgram}. - * - * @return The {@link ShaderObject}s. - */ - public List getShaders() { - return shaders; - } - - /** - * Get all {@link UniformPair}s exposed by this shader. - * - * @return The uniforms. - */ - public Map getUniforms() { - return uniforms; - } - - /** - * Get a {@link CCUniform} from this {@link ShaderProgram}. - * - * @param name The name of the Uniform. - * @return the {@link CCUniform}. - */ - @Nullable - public CCUniform getUniform(String name) { - return uniforms.get(name); - } - - /** - * Gets the GL {@link ShaderProgram} id for this shader. - * Might not be initialized until {@link #use()} is called once. - * - * @return The id, -1 if not initialized. - */ - public int getProgramId() { - return programId; - } - - /** - * Binds this shader for use, Lazily allocates, links - * and compiles all {@link ShaderObject}s. - */ - public void use() { - if (bound) { - throw new IllegalStateException("Already bound."); - } - compile(); - GL20.glUseProgram(programId); - if (applyCallback != null) { - applyCallback.run(); - } - bound = true; - } - - /** - * Forces the ShaderProgram to compile and link. - *

- * This will happen automatically when calling {@link #use()}, however, - * it may be required to call this ahead of time in some cases. - *

- * Be sure to only call this when you have GL context. - */ - public void compile() { - if (programId != -1 && shaders.stream().noneMatch(ShaderObject::isDirty)) return; - - for (ShaderObject shaderObject : shaders) { - shaderObject.alloc(); - } - - if (programId == -1) { - programId = GL20.glCreateProgram(); - if (programId == 0) { - throw new IllegalStateException("Allocation of ShaderProgram has failed."); - } - shaders.forEach(shader -> GL20.glAttachShader(programId, shader.getShaderID())); - } - GL20.glLinkProgram(programId); - if (GL20.glGetProgrami(programId, GL20.GL_LINK_STATUS) == GL11.GL_FALSE) { - throw new RuntimeException("ShaderProgram linkage failure. \n" + GL20.glGetProgramInfoLog(programId)); - } - for (ShaderObject shader : shaders) { - shader.onLink(programId); - } - for (CCUniform value : uniforms.values()) { - value.setLocation(GL20.glGetUniformLocation(programId, value.getName())); - } - } - - /** - * Releases this shader. - */ - public void release() { - if (!bound) { - throw new IllegalStateException("Not bound"); - } - bound = false; - GL20.glUseProgram(0); - } - - @Override - public void onResourceManagerReload(ResourceManager resourceManager) { - for (ShaderObject shader : shaders) { - if (shader instanceof ResourceManagerReloadListener) { - ((ResourceManagerReloadListener) shader).onResourceManagerReload(resourceManager); - } - } - compile(); - } -} diff --git a/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java b/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java deleted file mode 100644 index a07593ea..00000000 --- a/src/main/java/codechicken/lib/render/shader/ShaderProgramBuilder.java +++ /dev/null @@ -1,186 +0,0 @@ -package codechicken.lib.render.shader; - -import codechicken.lib.render.shader.ShaderObject.ShaderType; -import net.covers1624.quack.util.SneakyUtils; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Consumer; - -import static net.covers1624.quack.util.SneakyUtils.nullCons; - -/** - * Created by covers1624 on 24/5/20. - */ -public class ShaderProgramBuilder { - - private final Map shaders = new HashMap<>(); - private final Map allUniforms = new HashMap<>(); - @Nullable - private Runnable applyCallback; - - private ShaderProgramBuilder() { - } - - public static ShaderProgramBuilder builder() { - return new ShaderProgramBuilder(); - } - - public ShaderProgramBuilder addBinaryShader(String name, Consumer func) { - BinaryShaderObjectBuilder builder = new BinaryShaderObjectBuilder(name); - func.accept(builder); - return addShader(builder.build()); - } - - public ShaderProgramBuilder addShader(String name, Consumer func) { - ShaderObjectBuilder builder = new ShaderObjectBuilder(name); - func.accept(builder); - return addShader(builder.build()); - } - - public ShaderProgramBuilder addShader(ShaderObject shader) { - if (shaders.containsKey(shader.getName())) { - throw new IllegalArgumentException("Duplicate shader with name: " + shader.getName()); - } - shaders.put(shader.getName(), shader); - return this; - } - - public ShaderProgramBuilder whenUsed(Runnable callback) { - if (applyCallback == null) { - applyCallback = callback; - } else { - applyCallback = SneakyUtils.concat(applyCallback, callback); - } - return this; - } - - public ShaderProgram build() { - return new ShaderProgram(shaders.values(), allUniforms.values(), applyCallback); - } - - /** - * Created by covers1624 on 24/5/20. - * Edited by KitsuneAlex on 18/11/21. - */ - public class ShaderObjectBuilder { - - protected final String name; - protected final Map uniforms = new HashMap<>(); - @Nullable - protected ShaderType type; - @Nullable - protected String simpleSource; - @Nullable - protected ResourceLocation assetSource; - - private ShaderObjectBuilder(String name) { - this.name = Objects.requireNonNull(name); - } - - public ShaderObjectBuilder type(ShaderType type) { - if (this.type != null) throw new IllegalArgumentException("Type already set."); - - this.type = Objects.requireNonNull(type); - return this; - } - - public ShaderObjectBuilder source(String source) { - if (simpleSource != null || assetSource != null) throw new IllegalArgumentException("Source already set."); - - simpleSource = Objects.requireNonNull(source); - return this; - } - - public ShaderObjectBuilder source(ResourceLocation asset) { - if (assetSource != null || simpleSource != null) throw new IllegalArgumentException("Source already set."); - - assetSource = Objects.requireNonNull(asset); - return this; - } - - public ShaderObjectBuilder uniform(String name, UniformType type) { - UniformPair uniform = allUniforms.get(name); - if (uniform != null && uniform.type() != type) throw new IllegalArgumentException("Uniform with name '" + name + "' already exists with a different type: " + uniform.type()); - - if (uniform == null) { - uniform = new UniformPair(name, type); - allUniforms.put(name, uniform); - } - uniforms.put(name, uniform); - return this; - } - - protected ShaderObject build() { - if (type == null) throw new IllegalStateException("Type not set."); - if (simpleSource == null && assetSource == null) throw new IllegalStateException("SimpleSource or AssetSource not set."); - if (simpleSource != null) return new SimpleShaderObject(name, type, uniforms.values(), simpleSource); - - return new AssetShaderObject(name, type, uniforms.values(), assetSource); - } - } - - /** - * Created by KitsuneAlex on 18/11/21. - */ - public class BinaryShaderObjectBuilder extends ShaderObjectBuilder { - - @Nullable - private BinaryType binaryType; - @Nullable - private String entryPoint; - private Consumer specializationCallback = nullCons(); - - private BinaryShaderObjectBuilder(String name) { - super(name); - } - - @Override - public BinaryShaderObjectBuilder source(String source) { - throw new IllegalStateException("Binary shaders don't have string source."); - } - - @Override - public BinaryShaderObjectBuilder source(ResourceLocation asset) { - return (BinaryShaderObjectBuilder) super.source(asset); - } - - @Override - public BinaryShaderObjectBuilder uniform(String name, UniformType type) { - return (BinaryShaderObjectBuilder) super.uniform(name, type); - } - - public BinaryShaderObjectBuilder binaryType(BinaryType binaryType) { - if (this.binaryType != null) throw new IllegalStateException("Binary type already set."); - - this.binaryType = binaryType; - return this; - } - - public BinaryShaderObjectBuilder entryPoint(String entryPoint) { - if (this.entryPoint != null) throw new IllegalStateException("Entry point already set."); - - this.entryPoint = entryPoint; - return this; - } - - public BinaryShaderObjectBuilder whenSpecialized(Consumer specializationCallback) { - this.specializationCallback = specializationCallback; - return this; - } - - @Override - protected ShaderObject build() { - if (type == null) throw new IllegalStateException("Type not set."); - if (assetSource == null) throw new IllegalStateException("AssetSource not set."); - if (binaryType == null) throw new IllegalStateException("Binary type not set"); - if (entryPoint == null || entryPoint.isEmpty()) throw new IllegalStateException("Entry point not set."); - - return new BinaryShaderObject(name, assetSource, type, binaryType, entryPoint, allUniforms.values(), specializationCallback); - } - - } -} diff --git a/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java b/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java deleted file mode 100644 index fe2cef0e..00000000 --- a/src/main/java/codechicken/lib/render/shader/SimpleShaderObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package codechicken.lib.render.shader; - -import java.util.Collection; - -/** - * Created by covers1624 on 24/5/20. - */ -public class SimpleShaderObject extends AbstractShaderObject { - - private final String source; - - protected SimpleShaderObject(String name, ShaderType type, Collection uniforms, String source) { - super(name, type, uniforms); - this.source = source; - } - - @Override - protected String getSource() { - return source; - } -} diff --git a/src/main/java/codechicken/lib/render/shader/UniformPair.java b/src/main/java/codechicken/lib/render/shader/UniformPair.java deleted file mode 100644 index 8b1c1e5f..00000000 --- a/src/main/java/codechicken/lib/render/shader/UniformPair.java +++ /dev/null @@ -1,7 +0,0 @@ -package codechicken.lib.render.shader; - -/** - * Created by covers1624 on 24/5/20. - */ -public record UniformPair(String name, UniformType type) { -} diff --git a/src/main/java/codechicken/lib/render/shader/UniformType.java b/src/main/java/codechicken/lib/render/shader/UniformType.java deleted file mode 100644 index ef5bf0bb..00000000 --- a/src/main/java/codechicken/lib/render/shader/UniformType.java +++ /dev/null @@ -1,124 +0,0 @@ -package codechicken.lib.render.shader; - -import com.mojang.blaze3d.shaders.Uniform; -import org.jetbrains.annotations.Nullable; - -import java.util.Locale; - -/** - * Created by covers1624 on 24/5/20. - */ -public enum UniformType { - //@formatter:off - INT (Carrier.INT, 1), - U_INT (Carrier.U_INT, 1), - FLOAT (Carrier.FLOAT, 1), - - VEC2 (Carrier.FLOAT, 2), - I_VEC2 (Carrier.INT, 2), - U_VEC2 (Carrier.U_INT, 2), - B_VEC2 (Carrier.INT, 2), - - VEC3 (Carrier.FLOAT, 3), - I_VEC3 (Carrier.INT, 3), - U_VEC3 (Carrier.U_INT, 3), - B_VEC3 (Carrier.INT, 3), - - VEC4 (Carrier.FLOAT, 4), - I_VEC4 (Carrier.INT, 4), - U_VEC4 (Carrier.U_INT, 4), - B_VEC4 (Carrier.INT, 4), - - MAT2 (Carrier.MATRIX, 2 * 2), - MAT2x3 (Carrier.MATRIX, 2 * 3), - MAT2x4 (Carrier.MATRIX, 2 * 4), - - MAT3 (Carrier.MATRIX, 3 * 3), - MAT3x2 (Carrier.MATRIX, 3 * 2), - MAT3x4 (Carrier.MATRIX, 3 * 4), - - MAT4 (Carrier.MATRIX, 4 * 4), - MAT4x2 (Carrier.MATRIX, 4 * 2), - MAT4x3 (Carrier.MATRIX, 4 * 3), - - DOUBLE (Carrier.DOUBLE, 1), - D_VEC2 (Carrier.DOUBLE, 2), - D_VEC3 (Carrier.DOUBLE, 3), - D_VEC4 (Carrier.DOUBLE, 4), - - D_MAT2 (Carrier.D_MATRIX, 2 * 2), - D_MAT2x3(Carrier.D_MATRIX, 2 * 3), - D_MAT2x4(Carrier.D_MATRIX, 2 * 4), - - D_MAT3 (Carrier.D_MATRIX, 3 * 3), - D_MAT3x2(Carrier.D_MATRIX, 3 * 2), - D_MAT3x4(Carrier.D_MATRIX, 3 * 4), - - D_MAT4 (Carrier.D_MATRIX, 4 * 4), - D_MAT4x2(Carrier.D_MATRIX, 4 * 2), - D_MAT4x3(Carrier.D_MATRIX, 4 * 3); - //@formatter:on - - public static final UniformType[] VALUES = values(); - - private final Carrier carrier; - private final int size; - - UniformType(Carrier carrier, int size) { - this.carrier = carrier; - this.size = size; - } - - public Carrier getCarrier() { - return carrier; - } - - public int getSize() { - return size; - } - - public int getVanillaType() { - return switch (this) { - case INT, U_INT -> Uniform.UT_INT1; - case FLOAT -> Uniform.UT_FLOAT1; - case VEC2 -> Uniform.UT_FLOAT2; - case I_VEC2, U_VEC2, B_VEC2 -> Uniform.UT_INT2; - case VEC3 -> Uniform.UT_FLOAT3; - case I_VEC3, U_VEC3, B_VEC3 -> Uniform.UT_INT3; - case VEC4 -> Uniform.UT_FLOAT4; - case I_VEC4, U_VEC4, B_VEC4 -> Uniform.UT_INT4; - case MAT2 -> Uniform.UT_MAT2; - case MAT3 -> Uniform.UT_MAT3; - case MAT4 -> Uniform.UT_MAT4; - default -> -1; - }; - } - - @Nullable - public static UniformType parse(String s) { - s = s.toLowerCase(Locale.ROOT); - - // Handle vanilla Matrix names - switch (s) { - case "matrix2x2" -> { return MAT2; } - case "matrix3x3" -> { return MAT3; } - case "matrix4x4" -> { return MAT4; } - } - for (UniformType value : VALUES) { - String n = value.name().toLowerCase(Locale.ROOT); - if (n.equals(s)) { - return value; - } - } - return null; - } - - public enum Carrier { - INT, - U_INT, - FLOAT, - DOUBLE, - MATRIX, - D_MATRIX - } -} diff --git a/src/main/java/codechicken/lib/render/shader/package-info.java b/src/main/java/codechicken/lib/render/shader/package-info.java deleted file mode 100644 index 34e0cfad..00000000 --- a/src/main/java/codechicken/lib/render/shader/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault -package codechicken.lib.render.shader; - -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/src/main/java/codechicken/lib/texture/AtlasRegistrar.java b/src/main/java/codechicken/lib/texture/AtlasRegistrar.java deleted file mode 100644 index d0e627fb..00000000 --- a/src/main/java/codechicken/lib/texture/AtlasRegistrar.java +++ /dev/null @@ -1,44 +0,0 @@ -package codechicken.lib.texture; - -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.ResourceLocation; - -import java.util.function.Consumer; - -/** - * Created by covers1624 on 27/10/19. - */ -public interface AtlasRegistrar { - - /** - * Called to register a sprite and a callback for when the TextureAtlasSprite has been loaded. - * - * @param loc The sprite's ResourceLocation. - * @param onReady The callback for the sprite being ready. - */ - void registerSprite(ResourceLocation loc, Consumer onReady); - - /** - * Same as above, just takes a String for the ResourceLocation instead. - * - * @param loc The sprite's ResourceLocation. - * @param onReady The callback for the sprite being ready. - */ - default void registerSprite(String loc, Consumer onReady) { - registerSprite(new ResourceLocation(loc), onReady); - } - - /** - * Same as above, ignores callback. - * May be useful in _some_ cases. - * - * @param loc The sprite's ResourceLocation. - */ - default void registerSprite(ResourceLocation loc) { - registerSprite(loc, e -> { - }); - } - - void postRegister(Consumer func); -} diff --git a/src/main/java/codechicken/lib/texture/IIconRegister.java b/src/main/java/codechicken/lib/texture/IIconRegister.java deleted file mode 100644 index b0bb8039..00000000 --- a/src/main/java/codechicken/lib/texture/IIconRegister.java +++ /dev/null @@ -1,18 +0,0 @@ -package codechicken.lib.texture; - -/** - * Used for easy persistent TextureAtlasSprite registration. - *

- * See {@link SpriteRegistryHelper} - * Created by covers1624 on 27/10/19. - */ -public interface IIconRegister { - - /** - * Called to register your sprites to the AtlasRegistrar. - * Can be called any number of times at runtime. - * - * @param registrar - */ - void registerIcons(AtlasRegistrar registrar); -} diff --git a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java b/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java deleted file mode 100644 index a5db4f48..00000000 --- a/src/main/java/codechicken/lib/texture/SpriteRegistryHelper.java +++ /dev/null @@ -1,114 +0,0 @@ -package codechicken.lib.texture; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.inventory.InventoryMenu; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.eventbus.api.IEventBus; -import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; - -import java.util.*; -import java.util.function.Consumer; - -/** - * Utilities for persistent TextureAtlasSprite registration. - *

- * Created by covers1624 on 27/10/19. - */ -public class SpriteRegistryHelper { - - public static final ResourceLocation TEXTURES = InventoryMenu.BLOCK_ATLAS; - // public static final ResourceLocation PARTICLE_TEXTURES = "textures/particle"; - // public static final ResourceLocation MOB_EFFECT_TEXTURES = "textures/mob_effect"; - // public static final ResourceLocation PAINTING_TEXTURES = "textures/painting"; - - private final Multimap iconRegisters = HashMultimap.create(); - private final Map atlasRegistrars = new HashMap<>(); - - public SpriteRegistryHelper() { - this(FMLJavaModLoadingContext.get().getModEventBus()); - } - - public SpriteRegistryHelper(IEventBus eventBus) { - eventBus.addListener(this::onTextureStitchPre); - eventBus.addListener(this::onTextureStitchPost); - } - - /** - * Adds an IIconRegister for the given basePath. - * The base path should be that returned by {@link AtlasTexture#location()} - * Some known vanilla defaults are provided above. - * - * @param basePath The base path for the Atlas. - * @param iconRegister The IIconRegister. - */ - public void addIIconRegister(ResourceLocation basePath, IIconRegister iconRegister) { - iconRegisters.put(basePath, iconRegister); - } - - /** - * Adds an IIconRegister for the {@link #TEXTURES} Atlas. - * - * @param iconRegister The IIconRegister. - */ - public void addIIconRegister(IIconRegister iconRegister) { - addIIconRegister(TEXTURES, iconRegister); - } - - //######### INTERNAL - private AtlasRegistrarImpl getRegistrar(TextureAtlas atlas) { - AtlasRegistrarImpl registrar = atlasRegistrars.get(atlas.location()); - if (registrar == null) { - registrar = new AtlasRegistrarImpl(); - atlasRegistrars.put(atlas.location(), registrar); - } - return registrar; - } - - private void onTextureStitchPre(TextureStitchEvent.Pre event) { - TextureAtlas atlas = event.getAtlas(); - AtlasRegistrarImpl registrar = getRegistrar(atlas); - iconRegisters.get(atlas.location()).forEach(e -> e.registerIcons(registrar)); - registrar.processPre(event::addSprite); - } - - private void onTextureStitchPost(TextureStitchEvent.Post event) { - TextureAtlas atlas = event.getAtlas(); - AtlasRegistrarImpl registrar = getRegistrar(atlas); - registrar.processPost(atlas); - } - - private static final class AtlasRegistrarImpl implements AtlasRegistrar { - - private final Multimap> sprites = HashMultimap.create(); - private final List> postCallbacks = new ArrayList<>(); - - @Override - public void registerSprite(ResourceLocation loc, Consumer onReady) { - sprites.put(loc, onReady); - } - - @Override - public void postRegister(Consumer func) { - postCallbacks.add(func); - } - - private void processPre(Consumer register) { - sprites.keySet().forEach(register); - } - - private void processPost(TextureAtlas atlas) { - for (Map.Entry>> entry : sprites.asMap().entrySet()) { - TextureAtlasSprite sprite = atlas.getSprite(entry.getKey()); - entry.getValue().forEach(e -> e.accept(sprite)); - } - for (Consumer callback : postCallbacks) { - callback.accept(atlas); - } - } - } -} diff --git a/src/main/java/codechicken/lib/texture/TextureUtils.java b/src/main/java/codechicken/lib/texture/TextureUtils.java index cae7d73a..ea99a5e0 100644 --- a/src/main/java/codechicken/lib/texture/TextureUtils.java +++ b/src/main/java/codechicken/lib/texture/TextureUtils.java @@ -3,35 +3,24 @@ import codechicken.lib.colour.Colour; import codechicken.lib.colour.ColourARGB; import codechicken.lib.util.ResourceUtils; -import com.mojang.blaze3d.platform.GlStateManager; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.MissingTextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.inventory.InventoryMenu; -import net.minecraft.world.level.block.state.BlockState; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; +import net.minecraft.resources.Identifier; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jetbrains.annotations.Nullable; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; -import java.util.List; -import java.util.Random; public class TextureUtils { + private static final Logger LOGGER = LogManager.getLogger(); + /** * @return an array of ARGB pixel data */ - public static int[] loadTextureData(ResourceLocation resource) { + public static int[] loadTextureData(Identifier resource) { BufferedImage img = loadBufferedImage(resource); if (img == null) { return new int[0]; @@ -43,7 +32,7 @@ public static int[] loadTextureData(ResourceLocation resource) { return data; } - public static Colour[] loadTextureColours(ResourceLocation resource) { + public static Colour[] loadTextureColours(Identifier resource) { int[] idata = loadTextureData(resource); Colour[] data = new Colour[idata.length]; for (int i = 0; i < data.length; i++) { @@ -52,12 +41,11 @@ public static Colour[] loadTextureColours(ResourceLocation resource) { return data; } - public static BufferedImage loadBufferedImage(ResourceLocation textureFile) { + public static @Nullable BufferedImage loadBufferedImage(Identifier textureFile) { try { return loadBufferedImage(ResourceUtils.getResourceAsStream(textureFile)); - } catch (Exception e) { - System.err.println("Failed to load texture file: " + textureFile); - e.printStackTrace(); + } catch (Exception ex) { + LOGGER.error("failed to load texture {}", textureFile, ex); } return null; } @@ -78,105 +66,4 @@ public static void copySubImg(int[] fromTex, int fromWidth, int fromX, int fromY } } } - - public static void prepareTexture(int target, int texture, int min_mag_filter, int wrap) { - GlStateManager._texParameter(target, GL11.GL_TEXTURE_MIN_FILTER, min_mag_filter); - GlStateManager._texParameter(target, GL11.GL_TEXTURE_MAG_FILTER, min_mag_filter); - if (target == GL11.GL_TEXTURE_2D) { - GlStateManager._bindTexture(target); - } else { - GL11.glBindTexture(target, texture); - } - - switch (target) { - case GL12.GL_TEXTURE_3D: - GlStateManager._texParameter(target, GL12.GL_TEXTURE_WRAP_R, wrap); - case GL11.GL_TEXTURE_2D: - GlStateManager._texParameter(target, GL11.GL_TEXTURE_WRAP_T, wrap); - case GL11.GL_TEXTURE_1D: - GlStateManager._texParameter(target, GL11.GL_TEXTURE_WRAP_S, wrap); - } - } - - public static TextureManager getTextureManager() { - return Minecraft.getInstance().getTextureManager(); - } - - public static TextureAtlas getTextureMap() { - return Minecraft.getInstance().getModelManager().getAtlas(InventoryMenu.BLOCK_ATLAS); - } - - public static TextureAtlasSprite getMissingSprite() { - return getTextureMap().getSprite(MissingTextureAtlasSprite.getLocation()); - } - - public static TextureAtlasSprite getTexture(String location) { - return getTextureMap().getSprite(new ResourceLocation(location)); - } - - public static TextureAtlasSprite getTexture(ResourceLocation location) { - return getTextureMap().getSprite(location); - } - - public static TextureAtlasSprite getBlockTexture(String string) { - return getBlockTexture(new ResourceLocation(string)); - } - - public static TextureAtlasSprite getBlockTexture(ResourceLocation location) { - return getTexture(new ResourceLocation(location.getNamespace(), "block/" + location.getPath())); - } - - public static TextureAtlasSprite getItemTexture(String string) { - return getItemTexture(new ResourceLocation(string)); - } - - public static TextureAtlasSprite getItemTexture(ResourceLocation location) { - return getTexture(new ResourceLocation(location.getNamespace(), "items/" + location.getPath())); - } - - @Deprecated - public static TextureAtlasSprite[] getSideIconsForBlock(BlockState state) { - TextureAtlasSprite[] sideSprites = new TextureAtlasSprite[6]; - TextureAtlasSprite missingSprite = getMissingSprite(); - for (int i = 0; i < 6; i++) { - TextureAtlasSprite[] sprites = getIconsForBlock(state, i); - TextureAtlasSprite sideSprite = missingSprite; - if (sprites.length != 0) { - sideSprite = sprites[0]; - } - sideSprites[i] = sideSprite; - } - return sideSprites; - } - - @Deprecated - public static TextureAtlasSprite[] getIconsForBlock(BlockState state, int side) { - return getIconsForBlock(state, Direction.values()[side]); - } - - @Deprecated - public static TextureAtlasSprite[] getIconsForBlock(BlockState state, Direction side) { - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); - if (model != null) { - List quads = model.getQuads(state, side, RandomSource.create(0)); - if (quads != null && quads.size() > 0) { - TextureAtlasSprite[] sprites = new TextureAtlasSprite[quads.size()]; - for (int i = 0; i < quads.size(); i++) { - sprites[i] = quads.get(i).getSprite(); - } - return sprites; - } - } - return new TextureAtlasSprite[0]; - } - - @Deprecated - public static TextureAtlasSprite getParticleIconForBlock(BlockState state) { - BakedModel model = Minecraft.getInstance().getBlockRenderer().getBlockModel(state); - if (model != null) { - return model.getParticleIcon(); - } - return null; - } - } diff --git a/src/main/java/codechicken/lib/texture/package-info.java b/src/main/java/codechicken/lib/texture/package-info.java new file mode 100644 index 00000000..7a9a871d --- /dev/null +++ b/src/main/java/codechicken/lib/texture/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.texture; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/util/ArrayUtils.java b/src/main/java/codechicken/lib/util/ArrayUtils.java index f97717f1..dc6bc67f 100644 --- a/src/main/java/codechicken/lib/util/ArrayUtils.java +++ b/src/main/java/codechicken/lib/util/ArrayUtils.java @@ -1,5 +1,7 @@ package codechicken.lib.util; +import org.jetbrains.annotations.Nullable; + import java.lang.reflect.Array; import java.util.*; import java.util.function.Function; @@ -253,7 +255,7 @@ public static void arrayCopy(Object src, int srcPos, Object dst, int destPos, in * @param What we are dealing with. * @return The index in the array of the object. */ - public static int indexOf(T[] array, T object) { + public static int indexOf(T[] array, @Nullable T object) { if (object == null) { for (int i = 0; i < array.length; i++) { if (array[i] == null) { @@ -366,7 +368,7 @@ public static T[] rollArray(T[] input, int shift) { * @param The thing. * @return If the element exists at all. */ - public static boolean contains(T[] input, T element) { + public static boolean contains(T[] input, @Nullable T element) { for (T test : input) { if (Objects.equals(test, element)) { return true; @@ -403,7 +405,7 @@ public static T[] inverse(T[] input, T[] allElements) { * @param The thing. * @return If the array is null or contains null. */ - public static boolean isNullOrContainsNull(T[] input) { + public static boolean isNullOrContainsNull(T @Nullable [] input) { if (input != null) { for (T t : input) { if (t == null) { diff --git a/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java b/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java deleted file mode 100644 index a7d07a6f..00000000 --- a/src/main/java/codechicken/lib/util/Boolean2ObjectFunction.java +++ /dev/null @@ -1,17 +0,0 @@ -package codechicken.lib.util; - -import java.util.function.Function; - -/** - * Created by covers1624 on 3/17/20. - */ -public interface Boolean2ObjectFunction extends Function { - - R apply(boolean t); - - @Override - @Deprecated - default R apply(Boolean t) { - return apply(t.booleanValue()); - } -} diff --git a/src/main/java/codechicken/lib/util/CCCodecs.java b/src/main/java/codechicken/lib/util/CCCodecs.java new file mode 100644 index 00000000..64ce1049 --- /dev/null +++ b/src/main/java/codechicken/lib/util/CCCodecs.java @@ -0,0 +1,36 @@ +package codechicken.lib.util; + +import com.mojang.serialization.Codec; +import com.mojang.serialization.DataResult; +import com.mojang.serialization.DynamicOps; +import com.mojang.serialization.codecs.PrimitiveCodec; +import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.neoforged.neoforge.network.connection.ConnectionType; + +/** + * Created by covers1624 on 7/26/26. + */ +public class CCCodecs { + + public static Codec embeddedPacket(RegistryAccess registryAccess) { + return new PrimitiveCodec<>() { + @Override + public DataResult read(DynamicOps ops, T input) { + return Codec.BYTE_BUFFER.read(ops, input) + .map(b -> new RegistryFriendlyByteBuf( + Unpooled.wrappedBuffer(b), + registryAccess, + ConnectionType.NEOFORGE + )); + } + + @Override + public T write(DynamicOps ops, RegistryFriendlyByteBuf buf) { + buf.readerIndex(0); + return Codec.BYTE_BUFFER.write(ops, buf.nioBuffer()); + } + }; + } +} diff --git a/src/main/java/codechicken/lib/util/CCLTags.java b/src/main/java/codechicken/lib/util/CCLTags.java index d7b4c1cf..191c36dd 100644 --- a/src/main/java/codechicken/lib/util/CCLTags.java +++ b/src/main/java/codechicken/lib/util/CCLTags.java @@ -1,6 +1,6 @@ package codechicken.lib.util; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; @@ -14,51 +14,51 @@ public class CCLTags { public static class Blocks { - public static TagKey WOOL = forge("wool"); - public static TagKey WOOL_WHITE = forge("wool/white"); - public static TagKey WOOL_ORANGE = forge("wool/orange"); - public static TagKey WOOL_MAGENTA = forge("wool/magenta"); - public static TagKey WOOL_LIGHT_BLUE = forge("wool/light_blue"); - public static TagKey WOOL_YELLOW = forge("wool/yellow"); - public static TagKey WOOL_LIME = forge("wool/lime"); - public static TagKey WOOL_PINK = forge("wool/pink"); - public static TagKey WOOL_GRAY = forge("wool/gray"); - public static TagKey WOOL_LIGHT_GRAY = forge("wool/light_gray"); - public static TagKey WOOL_CYAN = forge("wool/cyan"); - public static TagKey WOOL_PURPLE = forge("wool/purple"); - public static TagKey WOOL_BLUE = forge("wool/blue"); - public static TagKey WOOL_BROWN = forge("wool/brown"); - public static TagKey WOOL_GREEN = forge("wool/green"); - public static TagKey WOOL_RED = forge("wool/red"); - public static TagKey WOOL_BLACK = forge("wool/black"); + public static TagKey WOOLS = common("wools"); + public static TagKey WOOLS_WHITE = common("wools/white"); + public static TagKey WOOLS_ORANGE = common("wools/orange"); + public static TagKey WOOLS_MAGENTA = common("wools/magenta"); + public static TagKey WOOLS_LIGHT_BLUE = common("wools/light_blue"); + public static TagKey WOOLS_YELLOW = common("wools/yellow"); + public static TagKey WOOLS_LIME = common("wools/lime"); + public static TagKey WOOLS_PINK = common("wools/pink"); + public static TagKey WOOLS_GRAY = common("wools/gray"); + public static TagKey WOOLS_LIGHT_GRAY = common("wools/light_gray"); + public static TagKey WOOLS_CYAN = common("wools/cyan"); + public static TagKey WOOLS_PURPLE = common("wools/purple"); + public static TagKey WOOLS_BLUE = common("wools/blue"); + public static TagKey WOOLS_BROWN = common("wools/brown"); + public static TagKey WOOLS_GREEN = common("wools/green"); + public static TagKey WOOLS_RED = common("wools/red"); + public static TagKey WOOLS_BLACK = common("wools/black"); - private static TagKey forge(String path) { - return BlockTags.create(new ResourceLocation("forge", path)); + private static TagKey common(String path) { + return BlockTags.create(Identifier.fromNamespaceAndPath("c", path)); } } public static class Items { - public static TagKey WOOL = forge("wool"); - public static TagKey WOOL_WHITE = forge("wool/white"); - public static TagKey WOOL_ORANGE = forge("wool/orange"); - public static TagKey WOOL_MAGENTA = forge("wool/magenta"); - public static TagKey WOOL_LIGHT_BLUE = forge("wool/light_blue"); - public static TagKey WOOL_YELLOW = forge("wool/yellow"); - public static TagKey WOOL_LIME = forge("wool/lime"); - public static TagKey WOOL_PINK = forge("wool/pink"); - public static TagKey WOOL_GRAY = forge("wool/gray"); - public static TagKey WOOL_LIGHT_GRAY = forge("wool/light_gray"); - public static TagKey WOOL_CYAN = forge("wool/cyan"); - public static TagKey WOOL_PURPLE = forge("wool/purple"); - public static TagKey WOOL_BLUE = forge("wool/blue"); - public static TagKey WOOL_BROWN = forge("wool/brown"); - public static TagKey WOOL_GREEN = forge("wool/green"); - public static TagKey WOOL_RED = forge("wool/red"); - public static TagKey WOOL_BLACK = forge("wool/black"); + public static TagKey WOOLS = common("wools"); + public static TagKey WOOLS_WHITE = common("wools/white"); + public static TagKey WOOLS_ORANGE = common("wools/orange"); + public static TagKey WOOLS_MAGENTA = common("wools/magenta"); + public static TagKey WOOLS_LIGHT_BLUE = common("wools/light_blue"); + public static TagKey WOOLS_YELLOW = common("wools/yellow"); + public static TagKey WOOLS_LIME = common("wools/lime"); + public static TagKey WOOLS_PINK = common("wools/pink"); + public static TagKey WOOLS_GRAY = common("wools/gray"); + public static TagKey WOOLS_LIGHT_GRAY = common("wools/light_gray"); + public static TagKey WOOLS_CYAN = common("wools/cyan"); + public static TagKey WOOLS_PURPLE = common("wools/purple"); + public static TagKey WOOLS_BLUE = common("wools/blue"); + public static TagKey WOOLS_BROWN = common("wools/brown"); + public static TagKey WOOLS_GREEN = common("wools/green"); + public static TagKey WOOLS_RED = common("wools/red"); + public static TagKey WOOLS_BLACK = common("wools/black"); - private static TagKey forge(String path) { - return ItemTags.create(new ResourceLocation("forge", path)); + private static TagKey common(String path) { + return ItemTags.create(Identifier.fromNamespaceAndPath("c", path)); } } } diff --git a/src/main/java/codechicken/lib/util/ClientUtils.java b/src/main/java/codechicken/lib/util/ClientUtils.java index 7f8f87ae..c9e15ccc 100644 --- a/src/main/java/codechicken/lib/util/ClientUtils.java +++ b/src/main/java/codechicken/lib/util/ClientUtils.java @@ -2,14 +2,8 @@ import codechicken.lib.render.CCRenderEventHandler; import net.minecraft.client.Minecraft; -import net.minecraft.network.Connection; -import net.minecraft.world.level.Level; -public class ClientUtils extends CommonUtils { - - public static Level getWorld() { - return Minecraft.getInstance().level; - } +public class ClientUtils { public static boolean inWorld() { return Minecraft.getInstance().getConnection() != null; @@ -22,17 +16,4 @@ public static float getRenderFrame() { public static double getRenderTime() { return CCRenderEventHandler.renderTime + getRenderFrame(); } - - public static String getServerIP() { - try { - Connection networkManager = Minecraft.getInstance().getConnection().getConnection(); - String s = networkManager.getRemoteAddress().toString(); - s = s.substring(s.indexOf("/") + 1); - return s; - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } } diff --git a/src/main/java/codechicken/lib/util/CommonUtils.java b/src/main/java/codechicken/lib/util/CommonUtils.java deleted file mode 100644 index 7d255ae0..00000000 --- a/src/main/java/codechicken/lib/util/CommonUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -package codechicken.lib.util; - -import net.minecraft.world.level.Level; - -public class CommonUtils { - - public static boolean isClientWorld(Level world) { - return world.isClientSide; - } - - public static boolean isServerWorld(Level world) { - return !world.isClientSide; - } -} diff --git a/src/main/java/codechicken/lib/util/FontUtils.java b/src/main/java/codechicken/lib/util/FontUtils.java deleted file mode 100644 index 884b162e..00000000 --- a/src/main/java/codechicken/lib/util/FontUtils.java +++ /dev/null @@ -1,18 +0,0 @@ -package codechicken.lib.util; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; - -public class FontUtils { - - public static Font fontRenderer = Minecraft.getInstance().font; - - public static void drawCenteredString(PoseStack mStack, String s, int xCenter, int y, int colour) { - fontRenderer.drawShadow(mStack, s, xCenter - fontRenderer.width(s) / 2, y, colour); - } - - public static void drawRightString(PoseStack mStack, String s, int xRight, int y, int colour) { - fontRenderer.drawShadow(mStack, s, xRight - fontRenderer.width(s), y, colour); - } -} diff --git a/src/main/java/codechicken/lib/util/FormatUtil.java b/src/main/java/codechicken/lib/util/FormatUtil.java new file mode 100644 index 00000000..5a0100aa --- /dev/null +++ b/src/main/java/codechicken/lib/util/FormatUtil.java @@ -0,0 +1,46 @@ +package codechicken.lib.util; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; + +/** + * Created by brandon3055 on 31/10/2023 + */ +public class FormatUtil { + + private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###,###,###,###,###", DecimalFormatSymbols.getInstance(Locale.ROOT)); + + public static String formatNumber(double value) { + if (Math.abs(value) < 1000D) return String.valueOf(value); + if (Math.abs(value) < 1000000D) return addCommas((int) value); //I mean whats the point of displaying 1.235K instead of 1,235? + if (Math.abs(value) < 1000000000D) return Math.round(value / 1000D) / 1000D + "M"; + if (Math.abs(value) < 1000000000000D) return Math.round(value / 1000000D) / 1000D + "G"; + return Math.round(value / 1000000000D) / 1000D + "T"; + } + + public static String formatNumber(long value) { + if (value == Long.MIN_VALUE) value = Long.MAX_VALUE; + if (Math.abs(value) < 1000L) return String.valueOf(value); + if (Math.abs(value) < 1000000L) return addCommas(value); + if (Math.abs(value) < 1000000000L) return Math.round((double) (value / 100000L)) / 10D + "M"; + if (Math.abs(value) < 1000000000000L) return Math.round((double) (value / 100000000L)) / 10D + "G"; + if (Math.abs(value) < 1000000000000000L) return Math.round((double) (value / 1000000000L)) / 1000D + "T"; + if (Math.abs(value) < 1000000000000000000L) return Math.round((double) (value / 1000000000000L)) / 1000D + "P"; + return Math.round((double) (value / 1000000000000000L)) / 1000D + "E"; + } + + /** + * Add commas to a number e.g. 161253126 > 161,253,126 + */ + public static String addCommas(int value) { + return DECIMAL_FORMAT.format(value); + } + + /** + * Add commas to a number e.g. 161253126 > 161,253,126 + */ + public static String addCommas(long value) { + return DECIMAL_FORMAT.format(value); + } +} diff --git a/src/main/java/codechicken/lib/util/ItemUtils.java b/src/main/java/codechicken/lib/util/ItemUtils.java index 0627df76..e0911fc2 100644 --- a/src/main/java/codechicken/lib/util/ItemUtils.java +++ b/src/main/java/codechicken/lib/util/ItemUtils.java @@ -3,7 +3,6 @@ import codechicken.lib.vec.Vector3; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; import net.minecraft.world.Container; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.LivingEntity; @@ -14,9 +13,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -import javax.annotation.Nonnull; import java.util.List; -import java.util.Set; import java.util.function.Predicate; /** @@ -40,7 +37,6 @@ public static boolean isPlayerHoldingSomething(Player player) { return !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty(); } - @Nonnull public static ItemStack getHeldStack(Player player) { ItemStack stack = player.getMainHandItem(); if (stack.isEmpty()) { @@ -66,7 +62,7 @@ public static void dropItem(ItemStack stack, Level level, Vector3 dropLocation) * @param stack ItemStack to drop. * @param velocity The velocity to add. */ - public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack, double velocity) { + public static void dropItem(Level world, BlockPos pos, ItemStack stack, double velocity) { double xVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; double yVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; double zVelocity = world.random.nextFloat() * velocity + (1.0D - velocity) * 0.5D; @@ -82,7 +78,7 @@ public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack, * @param pos Location to drop item. * @param stack ItemStack to drop. */ - public static void dropItem(Level world, BlockPos pos, @Nonnull ItemStack stack) { + public static void dropItem(Level world, BlockPos pos, ItemStack stack) { dropItem(world, pos, stack, 0.7D); } @@ -109,7 +105,7 @@ public static void dropInventory(Level world, BlockPos pos, Container inventory) * @param quantity Size of the new stack. * @return The new stack. */ - public static ItemStack copyStack(@Nonnull ItemStack stack, int quantity) { + public static ItemStack copyStack(ItemStack stack, int quantity) { if (stack.isEmpty()) { return ItemStack.EMPTY; } @@ -127,10 +123,10 @@ public static ItemStack copyStack(@Nonnull ItemStack stack, int quantity) { * @param stack Stack to spawn. * @param dir Direction to shoot. */ - public static void ejectItem(Level world, BlockPos pos, @Nonnull ItemStack stack, Direction dir) { + public static void ejectItem(Level world, BlockPos pos, ItemStack stack, Direction dir) { pos.relative(dir); ItemEntity entity = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, stack); - entity.setDeltaMovement(Vec3.atLowerCornerOf(dir.getNormal()).scale(0.3)); + entity.setDeltaMovement(Vec3.atLowerCornerOf(dir.getUnitVec3i()).scale(0.3)); entity.setPickUpDelay(10); world.addFreshEntity(entity); } @@ -156,7 +152,7 @@ public static void ejectItems(Level world, BlockPos pos, List stacks, * @param stack2 Second Stack. * @return Returns the difference. */ - public static int compareItemStack(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { + public static int compareItemStack(ItemStack stack1, ItemStack stack2) { int itemStack1ID = Item.getId(stack1.getItem()); int itemStack2ID = Item.getId(stack2.getItem()); return itemStack1ID != itemStack2ID ? itemStack1ID - itemStack2ID : (stack1.getDamageValue() == stack2.getDamageValue() ? 0 : stack1.getDamageValue() - stack2.getDamageValue()); @@ -167,7 +163,8 @@ public static int compareItemStack(@Nonnull ItemStack stack1, @Nonnull ItemStack * @param stack2 The {@link ItemStack} to compare to. * @return whether the two items are the same in terms of damage and itemID. */ - public static boolean areStacksSameType(@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) { - return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.tagMatches(stack2, stack1)); + public static boolean areStacksSameType(ItemStack stack1, ItemStack stack2) { + // TODO this can likely be replaced with `ItemStack.isSameItemSameComponents` + return !stack1.isEmpty() && !stack2.isEmpty() && (stack1.getItem() == stack2.getItem() && (stack2.getDamageValue() == stack1.getDamageValue()) && ItemStack.isSameItemSameComponents(stack2, stack1)); } } diff --git a/src/main/java/codechicken/lib/util/LambdaUtils.java b/src/main/java/codechicken/lib/util/LambdaUtils.java deleted file mode 100644 index 7870ea79..00000000 --- a/src/main/java/codechicken/lib/util/LambdaUtils.java +++ /dev/null @@ -1,89 +0,0 @@ -package codechicken.lib.util; - -import net.covers1624.quack.util.SneakyUtils.ThrowingRunnable; - -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.Supplier; - -/** - * Basically a bunch of lambda helpers. - *

- * Created by covers1624 on 1/06/2017. - */ -public class LambdaUtils { - - /** - * Tests if a predicate holds for all elements of the iterable. - * - * @param iterable The iterable to test. - * @param predicate The predicate. - * @param What we are dealing with. - * @return True if the predicate holds for all elements in the iterable. - */ - //TODO Rename. forAll - public static boolean forEach(Iterable iterable, Predicate predicate) { - for (T e : iterable) { - if (!predicate.test(e)) { - return false; - } - } - return true; - } - - /** - * For Each Array lambda support. Because reasons. - * - * @param elements What to loop. - * @param consumer Lambda. - * @param The thing! - */ - public static void forEach(E[] elements, Consumer consumer) { - for (E element : elements) { - consumer.accept(element); - } - } - - /** - * Provides a predicate callback for checking a condition. - * - * @param argument The thing we are checking. - * @param log What the reason for the predicate failing is. - * @param predicate The predicate callback. - * @param The thing. - */ - public static void checkArgument(E argument, String log, Predicate predicate) { - if (predicate.test(argument)) { - throw new RuntimeException("Argument check failed! Reason: " + log); - } - } - - /** - * Try's the operation quietly, disposing of any exception thrown. - * Useful for things where you literally don't care what the result is. - * - * @param runnable The thing to run. - */ - public static void tryQuietly(ThrowingRunnable runnable) { - try { - runnable.run(); - } catch (Throwable ignored) { - //pokemon - } - } - - /** - * Attempts to run the supplier, returns null on an exception. - * - * @param supplier The supplier to run. - * @param The Generic type. - * @return The thing from the supplier. - */ - public static T tryOrNull(Supplier supplier) { - try { - return supplier.get(); - } catch (Throwable t) { - return null; - } - } -} diff --git a/src/main/java/codechicken/lib/util/LazyValuePair.java b/src/main/java/codechicken/lib/util/LazyValuePair.java deleted file mode 100644 index 928ab8d5..00000000 --- a/src/main/java/codechicken/lib/util/LazyValuePair.java +++ /dev/null @@ -1,39 +0,0 @@ -package codechicken.lib.util; - -import net.minecraft.util.LazyLoadedValue; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.function.Function; - -/** - * Created by covers1624 on 5/1/20. - */ -public class LazyValuePair extends Pair { - - private final K key; - private final LazyLoadedValue value; - - public LazyValuePair(K key, Function func) { - this.key = key; - value = new LazyLoadedValue<>(() -> func.apply(key)); - } - - public static LazyValuePair of(K key, Function func) { - return new LazyValuePair<>(key, func); - } - - @Override - public K getLeft() { - return key; - } - - @Override - public V getRight() { - return value.get(); - } - - @Override - public V setValue(V value) { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/codechicken/lib/util/LogUtils.java b/src/main/java/codechicken/lib/util/LogUtils.java deleted file mode 100644 index 7f05d060..00000000 --- a/src/main/java/codechicken/lib/util/LogUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -package codechicken.lib.util; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.Logger; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.HashSet; -import java.util.Set; - -/** - * Utils for logging things. - *

- * Created by covers1624 on 20/06/2017. - */ -public class LogUtils { - - private static final Set stackTraces = new HashSet<>(); - - public static synchronized void errorOnce(Logger logger, Throwable t, String identifier, String format, Object... data) { - StringWriter sw = new StringWriter(); - t.printStackTrace(new PrintWriter(sw)); - String stackTrace = identifier + sw.toString(); - synchronized (stackTraces) { - if (!stackTraces.contains(stackTrace)) { - logger.log(Level.ERROR, format, data, t); - stackTraces.add(stackTrace); - } - } - } -} diff --git a/src/main/java/codechicken/lib/util/ResourceUtils.java b/src/main/java/codechicken/lib/util/ResourceUtils.java index 9c153cca..fe0d592e 100644 --- a/src/main/java/codechicken/lib/util/ResourceUtils.java +++ b/src/main/java/codechicken/lib/util/ResourceUtils.java @@ -1,11 +1,8 @@ package codechicken.lib.util; import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ReloadableResourceManager; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManagerReloadListener; -import net.minecraft.server.packs.resources.ResourceProvider; +import net.minecraft.resources.Identifier; +import net.minecraft.server.packs.resources.*; import java.io.BufferedReader; import java.io.IOException; @@ -24,7 +21,7 @@ public class ResourceUtils { * @return The InputStream. * @throws IOException If the file is not found or some other IO error occurred. */ - public static InputStream getResourceAsStream(ResourceLocation resource) throws IOException { + public static InputStream getResourceAsStream(Identifier resource) throws IOException { return getResource(resource).open(); } @@ -33,8 +30,8 @@ public static InputStream getResourceAsStream(ResourceLocation resource) throws * * @return The resource manager. */ - public static ReloadableResourceManager getResourceManager() { - return (ReloadableResourceManager) Minecraft.getInstance().getResourceManager(); + public static ResourceManager getResourceManager() { + return Minecraft.getInstance().getResourceManager(); } /** @@ -44,47 +41,26 @@ public static ReloadableResourceManager getResourceManager() { * @return The gotten resource. * @throws IOException If the resource doesn't exist, or some other IO error occurred. */ - public static Resource getResource(String location) throws IOException { - return getResource(new ResourceLocation(location)); - } - - /** - * Get's an IResource from the resource manager. - * - * @param location The resource to get. - * @return The gotten resource. - * @throws IOException If the resource doesn't exist, or some other IO error occurred. - */ - public static Resource getResource(ResourceLocation location) throws IOException { + public static Resource getResource(Identifier location) throws IOException { return getResourceManager().getResourceOrThrow(location); } /** - * Registers a IResourceManagerReloadListener to MC's resource manager. - * - * @param reloadListener The listener. - */ - public static void registerReloadListener(ResourceManagerReloadListener reloadListener) { - getResourceManager().registerReloadListener(reloadListener); - } - - /** - * Loads the given {@link ResourceLocation} with the given {@link ResourceProvider} into + * Loads the given {@link Identifier} with the given {@link ResourceProvider} into * a list of UTF-8 Strings. * * @param resourceProvider The {@link ResourceProvider}. - * @param loc The {@link ResourceLocation}. + * @param loc The {@link Identifier}. * @return The UTF-8 lines of the resource. */ - public static List loadResource(ResourceProvider resourceProvider, ResourceLocation loc) { + public static List loadResource(ResourceProvider resourceProvider, Identifier loc) { try { Resource resource = resourceProvider.getResourceOrThrow(loc); try (BufferedReader reader = resource.openAsReader()) { return reader.lines().toList(); } } catch (IOException ex) { - throw new RuntimeException("Failed to load MTL file: " + loc, ex); + throw new RuntimeException("Failed to load resource: " + loc, ex); } } - } diff --git a/src/main/java/codechicken/lib/util/RotationUtils.java b/src/main/java/codechicken/lib/util/RotationUtils.java index 2c7a17a6..062d307f 100644 --- a/src/main/java/codechicken/lib/util/RotationUtils.java +++ b/src/main/java/codechicken/lib/util/RotationUtils.java @@ -69,18 +69,13 @@ public static Direction getPlacedRotation(BlockPos pos, LivingEntity entity, boo * @return Next facing. */ public static Direction rotateCounterClockwise(Direction facing) { - switch (facing) { - case NORTH: - return Direction.WEST; - case EAST: - return Direction.NORTH; - case SOUTH: - return Direction.EAST; - case WEST: - return Direction.SOUTH; - default: - throw new IllegalStateException("Unable to get CCW facing of " + facing); - } + return switch (facing) { + case NORTH -> Direction.WEST; + case EAST -> Direction.NORTH; + case SOUTH -> Direction.EAST; + case WEST -> Direction.SOUTH; + default -> throw new IllegalStateException("Unable to get CCW facing of " + facing); + }; } /** @@ -90,18 +85,13 @@ public static Direction rotateCounterClockwise(Direction facing) { * @return Next facing. */ public static Direction rotateClockwise(Direction facing) { - switch (facing) { - case NORTH: - return Direction.EAST; - case EAST: - return Direction.SOUTH; - case SOUTH: - return Direction.WEST; - case WEST: - return Direction.NORTH; - default: - throw new IllegalStateException("Unable to get CW facing of " + facing); - } + return switch (facing) { + case NORTH -> Direction.EAST; + case EAST -> Direction.SOUTH; + case SOUTH -> Direction.WEST; + case WEST -> Direction.NORTH; + default -> throw new IllegalStateException("Unable to get CW facing of " + facing); + }; } /** @@ -111,21 +101,14 @@ public static Direction rotateClockwise(Direction facing) { * @return Next facing. */ public static Direction rotateForward(Direction facing) { - switch (facing) { - case NORTH: - return Direction.DOWN; - case DOWN: - return Direction.UP; - case UP: - return Direction.WEST; - case WEST: - return Direction.EAST; - case EAST: - return Direction.SOUTH; - case SOUTH: - return Direction.NORTH; - } - return Direction.NORTH; + return switch (facing) { + case NORTH -> Direction.DOWN; + case DOWN -> Direction.UP; + case UP -> Direction.WEST; + case WEST -> Direction.EAST; + case EAST -> Direction.SOUTH; + case SOUTH -> Direction.NORTH; + }; } /** @@ -135,40 +118,29 @@ public static Direction rotateForward(Direction facing) { * @return Next facing. */ public static Direction rotateBackwards(Direction facing) { - switch (facing) { - case NORTH: - return Direction.SOUTH; - case SOUTH: - return Direction.EAST; - case EAST: - return Direction.WEST; - case WEST: - return Direction.UP; - case UP: - return Direction.DOWN; - case DOWN: - return Direction.NORTH; - } - return Direction.NORTH; + return switch (facing) { + case NORTH -> Direction.SOUTH; + case SOUTH -> Direction.EAST; + case EAST -> Direction.WEST; + case WEST -> Direction.UP; + case UP -> Direction.DOWN; + case DOWN -> Direction.NORTH; + }; } /** * Turns Entity rotation in to Direction. * - * @param rotation The entity rotation, Generally MathHelper.floor_double((entity.rotationYaw * 4F) / 360F + 0.5D) & 3; + * @param rotation The entity rotation, Generally {@code MathHelper.floor_double((entity.rotationYaw * 4F) / 360F + 0.5D) & 3}; * @return The rotation in Direction. */ public static Direction entityRotationToSide(int rotation) { - switch (rotation) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.WEST; - case 2: - return Direction.NORTH; - default: - return Direction.EAST; - } + return switch (rotation) { + case 0 -> Direction.SOUTH; + case 1 -> Direction.WEST; + case 2 -> Direction.NORTH; + default -> Direction.EAST; + }; } } diff --git a/src/main/java/codechicken/lib/util/ServerUtils.java b/src/main/java/codechicken/lib/util/ServerUtils.java index 6d69cdb9..b61967da 100644 --- a/src/main/java/codechicken/lib/util/ServerUtils.java +++ b/src/main/java/codechicken/lib/util/ServerUtils.java @@ -1,116 +1,21 @@ package codechicken.lib.util; -import codechicken.lib.data.MCDataOutput; -import codechicken.lib.internal.network.CCLNetwork; -import codechicken.lib.packet.PacketCustom; -import com.mojang.authlib.GameProfile; import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.players.GameProfileCache; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.LogicalSidedProvider; -import net.minecraftforge.event.entity.player.PlayerContainerEvent; -import net.minecraftforge.fml.LogicalSide; -import net.minecraftforge.registries.ForgeRegistries; +import net.neoforged.neoforge.server.ServerLifecycleHooks; import java.nio.file.Path; -import java.util.List; -import java.util.Locale; -import java.util.UUID; -import java.util.function.Consumer; - -import static codechicken.lib.internal.network.CCLNetwork.C_OPEN_CONTAINER; /** * Created by covers1624 on 22/10/2016. */ public class ServerUtils { - @Deprecated - public static MinecraftServer getServer() { - return (MinecraftServer) LogicalSidedProvider.WORKQUEUE.get(LogicalSide.SERVER); - } - - @Deprecated - public static ServerPlayer getPlayer(String playername) { - return getServer().getPlayerList().getPlayerByName(playername); - } - - public static List getPlayers() { - return getServer().getPlayerList().getPlayers(); - } - - public static boolean isPlayerLoadingChunk(ServerPlayer player, ChunkPos chunk) { - return player.getLevel().getChunkSource().chunkMap.getPlayers(chunk, false).stream().anyMatch(e -> e.getId() == player.getId()); - } - public static Path getSaveDirectory() { return getSaveDirectory(Level.OVERWORLD); } public static Path getSaveDirectory(ResourceKey dimension) { - return getServer().storageSource.getDimensionPath(dimension); - } - - public static GameProfile getGameProfile(String username) { - Player player = getPlayer(username); - if (player != null) { - return player.getGameProfile(); - } - - //try and access it in the cache without forcing a save - username = username.toLowerCase(Locale.ROOT); - GameProfileCache.GameProfileInfo cachedEntry = getServer().getProfileCache().profilesByName.get(username); - if (cachedEntry != null) { - return cachedEntry.getProfile(); - } - - //load it from the cache - return getServer().getProfileCache().get(username).orElse(null); - } - - public static boolean isPlayerOP(UUID uuid) { - GameProfile profile = getServer().getProfileCache().get(uuid).orElse(null); - return profile != null && getServer().getPlayerList().isOp(profile); - } - - public static boolean isPlayerOP(String username) { - GameProfile prof = getGameProfile(username); - return prof != null && getServer().getPlayerList().isOp(prof); - } - - public static void openContainer(ServerPlayer player, MenuProvider containerProvider) { - openContainer(player, containerProvider, e -> { - }); - } - - public static void openContainer(ServerPlayer player, MenuProvider containerProvider, Consumer packetConsumer) { - if (player.level.isClientSide()) { - return; - } - player.doCloseContainer(); - player.nextContainerCounter(); - int containerId = player.containerCounter; - - AbstractContainerMenu container = containerProvider.createMenu(containerId, player.getInventory(), player); - MenuType type = container.getType(); - - PacketCustom packet = new PacketCustom(CCLNetwork.NET_CHANNEL, C_OPEN_CONTAINER); - packet.writeRegistryIdDirect(ForgeRegistries.MENU_TYPES, type); - packet.writeVarInt(containerId); - packet.writeTextComponent(containerProvider.getDisplayName()); - packetConsumer.accept(packet); - - packet.sendToPlayer(player); - player.containerMenu = container; - player.initMenu(player.containerMenu); - MinecraftForge.EVENT_BUS.post(new PlayerContainerEvent.Open(player, container)); + return ServerLifecycleHooks.getCurrentServer().storageSource.getDimensionPath(dimension); } } diff --git a/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java b/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java deleted file mode 100644 index cff9d877..00000000 --- a/src/main/java/codechicken/lib/util/ThrowingBiConsumer.java +++ /dev/null @@ -1,12 +0,0 @@ -package codechicken.lib.util; - -/** - * A simple BiConsumer that has a throws declaration. - *

- * Created by covers1624 on 15/06/18. - */ -@FunctionalInterface -public interface ThrowingBiConsumer { - - void accept(A a, B b) throws E; -} diff --git a/src/main/java/codechicken/lib/util/TransformUtils.java b/src/main/java/codechicken/lib/util/TransformUtils.java deleted file mode 100644 index c5ff13e9..00000000 --- a/src/main/java/codechicken/lib/util/TransformUtils.java +++ /dev/null @@ -1,183 +0,0 @@ -package codechicken.lib.util; - -import codechicken.lib.model.PerspectiveModelState; -import codechicken.lib.vec.Vector3; -import com.google.common.collect.ImmutableMap; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.*; -import net.minecraft.client.renderer.block.model.ItemTransform; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; -import net.minecraft.client.resources.model.ModelState; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by covers1624 on 5/16/2016. - * This is mostly just extracted from the ForgeBlockStateV1 in 1.10. - * Credits to Fry. - *

- * If you have an idea for another transform just make a pull request. - */ -public class TransformUtils { - - private static final Transformation flipX = new Transformation(null, null, new Vector3f(-1, 1, 1), null); - - public static final PerspectiveModelState IDENTITY = PerspectiveModelState.IDENTITY; - public static final PerspectiveModelState DEFAULT_BLOCK; - public static final PerspectiveModelState DEFAULT_ITEM; - public static final PerspectiveModelState DEFAULT_TOOL; - public static final PerspectiveModelState DEFAULT_BOW; - public static final PerspectiveModelState DEFAULT_HANDHELD_ROD; - - static { - Map map; - Transformation thirdPerson; - Transformation firstPerson; - - //@formatter:off - map = new HashMap<>(); - thirdPerson = create(0F,2.5F, 0F,75F, 45F, 0F,0.375F ); - map.put(TransformType.GUI, create(0F, 0F, 0F,30F,225F, 0F,0.625F)); - map.put(TransformType.GROUND, create(0F, 3F, 0F, 0F, 0F, 0F, 0.25F)); - map.put(TransformType.FIXED, create(0F, 0F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(0F, 0F, 0F, 0F, 45F, 0F, 0.4F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(0F, 0F, 0F, 0F, 225F, 0F, 0.4F)); - DEFAULT_BLOCK = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - thirdPerson = create( 0F, 3F, 1F, 0F, 0F, 0F, 0.55F); - firstPerson = create(1.13F,3.2F,1.13F, 0F,-90F,25F, 0.68F); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.HEAD, create( 0F, 13F, 7F, 0F,180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, thirdPerson); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, flipLeft(thirdPerson)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, firstPerson); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, flipLeft(firstPerson)); - DEFAULT_ITEM = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.FIXED, create( 0F, 0F, 0F, 0F,180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create( 0F, 4F, 0.5F, 0F,-90F, 55,0.85F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create( 0F, 4F, 0.5F, 0F, 90F,-55,0.85F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F,-90F, 25,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25,0.68F)); - DEFAULT_TOOL = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(TransformType.GROUND, create( 0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.FIXED, create( 0F, 0F, 0F, 0F, 180F, 0F, 1F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create( -1F, -2F, 2.5F,-80F, 260F,-40F, 0.9F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create( -1F, -2F, 2.5F,-80F,-280F, 40F, 0.9F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(1.13F,3.2F,1.13F, 0F, -90F, 25F,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(1.13F,3.2F,1.13F, 0F, 90F,-25F,0.68F)); - DEFAULT_BOW = new PerspectiveModelState(ImmutableMap.copyOf(map)); - - map = new HashMap<>(); - map.put(TransformType.GROUND, create(0F, 2F, 0F, 0F, 0F, 0F, 0.5F)); - map.put(TransformType.THIRD_PERSON_RIGHT_HAND, create(0F, 4F,2.5F, 0F, 90F, 55F,0.85F)); - map.put(TransformType.THIRD_PERSON_LEFT_HAND, create(0F, 4F,2.5F, 0F,-90F,-55F,0.85F)); - map.put(TransformType.FIRST_PERSON_RIGHT_HAND, create(0F,1.6F,0.8F, 0F, 90F, 25F,0.68F)); - map.put(TransformType.FIRST_PERSON_LEFT_HAND, create(0F,1.6F,0.8F, 0F,-90F,-25F,0.68F)); - DEFAULT_HANDHELD_ROD = new PerspectiveModelState(ImmutableMap.copyOf(map)); - //@formatter:on - } - - /** - * Creates a new TRSRTransformation. - * - * @param tx The x transform. - * @param ty The y transform. - * @param tz The z transform. - * @param rx The x Axis rotation. - * @param ry The y Axis rotation. - * @param rz The z Axis rotation. - * @param s The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(float tx, float ty, float tz, float rx, float ry, float rz, float s) { - return create(new Vector3f(tx / 16, ty / 16, tz / 16), new Vector3f(rx, ry, rz), new Vector3f(s, s, s)); - } - - /** - * Creates a new TRSRTransformation. - * - * @param transform The transform. - * @param rotation The rotation. - * @param scale The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(Vector3 transform, Vector3 rotation, Vector3 scale) { - return create(transform.vector3f(), rotation.vector3f(), scale.vector3f()); - } - - /** - * Creates a new TRSRTransformation. - * - * @param transform The transform. - * @param rotation The rotation. - * @param scale The scale. - * @return The new TRSRTransformation. - */ - public static Transformation create(Vector3f transform, Vector3f rotation, Vector3f scale) { - return new Transformation(transform, new Quaternion(rotation.x(), rotation.y(), rotation.z(), true), scale, null); - } - - public static Transformation create(ItemTransform transform) { - if (ItemTransform.NO_TRANSFORM.equals(transform)) return Transformation.identity(); - - return create(transform.translation, transform.rotation, transform.scale); - } - - /** - * Flips the transform for the left hand. - * - * @param transform The right-hand transform. - * @return The new left-hand transform. - */ - public static Transformation flipLeft(Transformation transform) { - return flipX.compose(transform).compose(flipX); - } - - /** - * Decompose a vanilla {@link ItemTransforms} into a {@link PerspectiveModelState}. - * - * @param itemTransforms the {@link ItemTransforms} to decompose. - * @return The {@link PerspectiveModelState} - */ - public static ModelState stateFromItemTransforms(ItemTransforms itemTransforms) { - if (itemTransforms == ItemTransforms.NO_TRANSFORMS) return IDENTITY; - - ImmutableMap.Builder map = ImmutableMap.builder(); - - for (TransformType value : TransformType.values()) { - map.put(value, create(itemTransforms.getTransform(value))); - } - - return new PerspectiveModelState(map.build()); - } - - /** - * Applies standard lefty flip to a {@link PoseStack}. - * - * @param pStack The {@link PoseStack} to apply to. - */ - public static void applyLeftyFlip(PoseStack pStack) { - if (!pStack.clear()) { - Matrix4f tMat = pStack.last().pose(); - Matrix3f nMat = pStack.last().normal(); - - tMat.multiplyBackward(flipX.getMatrix()); - tMat.multiply(flipX.getMatrix()); - nMat.multiplyBackward(flipX.getNormalMatrix()); - nMat.mul(flipX.getNormalMatrix()); - - pStack.last().pose().multiply(tMat); - pStack.last().normal().mul(nMat); - } - } -} diff --git a/src/main/java/codechicken/lib/util/VectorUtils.java b/src/main/java/codechicken/lib/util/VectorUtils.java index 3272ac28..95b09254 100644 --- a/src/main/java/codechicken/lib/util/VectorUtils.java +++ b/src/main/java/codechicken/lib/util/VectorUtils.java @@ -2,6 +2,7 @@ import codechicken.lib.vec.Vector3; import net.minecraft.core.Direction; +import org.jetbrains.annotations.Nullable; /** * Created by covers1624 on 4/10/2016. @@ -27,25 +28,10 @@ public static Vector3 calculateNormal(Vector3... vertices) { * @return The direction the normal is facing. */ public static int findSide(Vector3 normal) { - if (normal.y <= -0.99) { - return 0; - } - if (normal.y >= 0.99) { - return 1; - } - if (normal.z <= -0.99) { - return 2; - } - if (normal.z >= 0.99) { - return 3; - } - if (normal.x <= -0.99) { - return 4; - } - if (normal.x >= 0.99) { - return 5; - } - return -1; + Direction dir = findSideE(normal); + if (dir == null) return -1; + + return dir.ordinal(); } /** @@ -54,25 +40,14 @@ public static int findSide(Vector3 normal) { * @param normal The normal to calculate from. * @return The direction the normal is facing. */ - public static Direction calcNormalSide(Vector3 normal) { - if (normal.y <= -0.99) { - return Direction.DOWN; - } - if (normal.y >= 0.99) { - return Direction.UP; - } - if (normal.z <= -0.99) { - return Direction.NORTH; - } - if (normal.z >= 0.99) { - return Direction.SOUTH; - } - if (normal.x <= -0.99) { - return Direction.WEST; - } - if (normal.x >= 0.99) { - return Direction.EAST; - } + public static @Nullable Direction findSideE(Vector3 normal) { + if (normal.y <= -0.99) return Direction.DOWN; + if (normal.y >= 0.99) return Direction.UP; + if (normal.z <= -0.99) return Direction.NORTH; + if (normal.z >= 0.99) return Direction.SOUTH; + if (normal.x <= -0.99) return Direction.WEST; + if (normal.x >= 0.99) return Direction.EAST; + return null; } } diff --git a/src/main/java/codechicken/lib/util/VertexUtils.java b/src/main/java/codechicken/lib/util/VertexUtils.java deleted file mode 100644 index 05a35955..00000000 --- a/src/main/java/codechicken/lib/util/VertexUtils.java +++ /dev/null @@ -1,142 +0,0 @@ -package codechicken.lib.util; - -import codechicken.lib.model.IVertexConsumer; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.VertexFormat; -import com.mojang.blaze3d.vertex.VertexFormatElement; -import net.minecraft.client.renderer.block.model.BakedQuad; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * Created by covers1624 on 9/7/22. - */ -public class VertexUtils { - - private static final ConcurrentMap, int[]> formatMaps = new ConcurrentHashMap<>(); - - private static final int[] DEFAULT_MAPPING = generateMapping(DefaultVertexFormat.BLOCK, DefaultVertexFormat.BLOCK); - - public static int[] mapFormats(VertexFormat from, VertexFormat to) { - if (from.equals(DefaultVertexFormat.BLOCK) && to.equals(DefaultVertexFormat.BLOCK)) return DEFAULT_MAPPING; - - return formatMaps.computeIfAbsent(Pair.of(from, to), pair -> generateMapping(pair.getLeft(), pair.getRight())); - } - - public static void putQuad(IVertexConsumer consumer, BakedQuad quad) { - consumer.setTexture(quad.getSprite()); - consumer.setQuadOrientation(quad.getDirection()); - if (quad.isTinted()) { - consumer.setQuadTint(quad.getTintIndex()); - } - consumer.setApplyDiffuseLighting(quad.isShade()); - float[] data = new float[4]; - VertexFormat formatFrom = consumer.getVertexFormat(); - VertexFormat formatTo = DefaultVertexFormat.BLOCK; - int countFrom = formatFrom.getElements().size(); - int countTo = formatTo.getElements().size(); - int[] eMap = mapFormats(formatFrom, formatTo); - for (int v = 0; v < 4; v++) { - for (int e = 0; e < countFrom; e++) { - if (eMap[e] != countTo) { - unpack(quad.getVertices(), data, formatTo, v, eMap[e]); - consumer.put(e, data); - } else { - consumer.put(e); - } - } - } - } - - public static void unpack(int[] from, float[] to, VertexFormat formatFrom, int v, int e) { - int length = Math.min(4, to.length); - VertexFormatElement element = formatFrom.getElements().get(e); - int vertexStart = v * formatFrom.getVertexSize() + formatFrom.getOffset(e); - int count = element.getElementCount(); - VertexFormatElement.Type type = element.getType(); - VertexFormatElement.Usage usage = element.getUsage(); - int size = type.getSize(); - int mask = (256 << (8 * (size - 1))) - 1; - for (int i = 0; i < length; i++) { - if (i < count) { - int pos = vertexStart + size * i; - int index = pos >> 2; - int offset = pos & 3; - int bits = from[index]; - bits = bits >>> (offset * 8); - if ((pos + size - 1) / 4 != index) { - bits |= from[index + 1] << ((4 - offset) * 8); - } - bits &= mask; - if (type == VertexFormatElement.Type.FLOAT) { - to[i] = Float.intBitsToFloat(bits); - } else if (type == VertexFormatElement.Type.UBYTE || type == VertexFormatElement.Type.USHORT) { - to[i] = (float) bits / mask; - } else if (type == VertexFormatElement.Type.UINT) { - to[i] = (float) ((double) (bits & 0xFFFFFFFFL) / 0xFFFFFFFFL); - } else if (type == VertexFormatElement.Type.BYTE) { - to[i] = ((float) (byte) bits) / (mask >> 1); - } else if (type == VertexFormatElement.Type.SHORT) { - to[i] = ((float) (short) bits) / (mask >> 1); - } else if (type == VertexFormatElement.Type.INT) { - to[i] = (float) ((double) (bits & 0xFFFFFFFFL) / (0xFFFFFFFFL >> 1)); - } - } else { - to[i] = (i == 3 && usage == VertexFormatElement.Usage.POSITION) ? 1 : 0; - } - } - } - - public static void pack(float[] from, int[] to, VertexFormat formatTo, int v, int e) { - VertexFormatElement element = formatTo.getElements().get(e); - int vertexStart = v * formatTo.getVertexSize() + formatTo.getOffset(e); - int count = element.getElementCount(); - VertexFormatElement.Type type = element.getType(); - int size = type.getSize(); - int mask = (256 << (8 * (size - 1))) - 1; - for (int i = 0; i < 4; i++) { - if (i < count) { - int pos = vertexStart + size * i; - int index = pos >> 2; - int offset = pos & 3; - int bits = 0; - float f = i < from.length ? from[i] : 0; - if (type == VertexFormatElement.Type.FLOAT) { - bits = Float.floatToRawIntBits(f); - } else if ( - type == VertexFormatElement.Type.UBYTE || - type == VertexFormatElement.Type.USHORT || - type == VertexFormatElement.Type.UINT - ) { - bits = Math.round(f * mask); - } else { - bits = Math.round(f * (mask >> 1)); - } - to[index] &= ~(mask << (offset * 8)); - to[index] |= (((bits & mask) << (offset * 8))); - // TODO handle overflow into to[index + 1] - } - } - } - - private static int[] generateMapping(VertexFormat from, VertexFormat to) { - int fromCount = from.getElements().size(); - int toCount = to.getElements().size(); - int[] eMap = new int[fromCount]; - - for (int e = 0; e < fromCount; e++) { - VertexFormatElement expected = from.getElements().get(e); - int e2; - for (e2 = 0; e2 < toCount; e2++) { - VertexFormatElement current = to.getElements().get(e2); - if (expected.getUsage() == current.getUsage() && expected.getIndex() == current.getIndex()) { - break; - } - } - eMap[e] = e2; - } - return eMap; - } -} diff --git a/src/main/java/codechicken/lib/util/package-info.java b/src/main/java/codechicken/lib/util/package-info.java new file mode 100644 index 00000000..4d81d344 --- /dev/null +++ b/src/main/java/codechicken/lib/util/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.util; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/vec/Cuboid6.java b/src/main/java/codechicken/lib/vec/Cuboid6.java index 4788ea85..d8517ce9 100644 --- a/src/main/java/codechicken/lib/vec/Cuboid6.java +++ b/src/main/java/codechicken/lib/vec/Cuboid6.java @@ -2,13 +2,18 @@ import codechicken.lib.raytracer.VoxelShapeCache; import codechicken.lib.util.Copyable; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.VoxelShape; +import org.joml.Vector3fc; import java.math.BigDecimal; import java.math.MathContext; @@ -16,7 +21,19 @@ public class Cuboid6 implements Copyable { - public static Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1); + public static final Cuboid6 full = new Cuboid6(0, 0, 0, 1, 1, 1); + + public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + Vector3.CODEC.fieldOf("min").forGetter(e -> e.min), + Vector3.CODEC.fieldOf("max").forGetter(e -> e.max) + ).apply(b, Cuboid6::new) + ); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + Vector3.STREAM_CODEC, e -> e.min, + Vector3.STREAM_CODEC, e -> e.max, + Cuboid6::new + ); public Vector3 min; public Vector3 max; @@ -41,7 +58,7 @@ public Cuboid6(AABB aabb) { } public Cuboid6(CompoundTag tag) { - this(Vector3.fromNBT(tag.getCompound("min")), Vector3.fromNBT(tag.getCompound("max"))); + this(Vector3.fromNBT(tag.getCompoundOrEmpty("min")), Vector3.fromNBT(tag.getCompoundOrEmpty("max"))); } public Cuboid6(Cuboid6 cuboid) { @@ -154,8 +171,8 @@ public Cuboid6 expand(Vector3 vec) { public Cuboid6 expandSide(Direction side, int amount) { switch (side.getAxisDirection()) { - case NEGATIVE -> min.add(Vector3.fromVec3i(side.getNormal()).multiply(amount)); - case POSITIVE -> max.add(Vector3.fromVec3i(side.getNormal()).multiply(amount)); + case NEGATIVE -> min.add(Vector3.fromVec3i(side.getUnitVec3i()).multiply(amount)); + case POSITIVE -> max.add(Vector3.fromVec3i(side.getUnitVec3i()).multiply(amount)); } return this; } @@ -201,6 +218,10 @@ public Cuboid6 enclose(Vector3 vec) { return enclose(vec.x, vec.y, vec.z, vec.x, vec.y, vec.z); } + public Cuboid6 enclose(Vector3fc vec) { + return enclose(vec.x(), vec.y(), vec.z(), vec.x(), vec.y(), vec.z()); + } + public Cuboid6 enclose(Cuboid6 c) { return enclose(c.min.x, c.min.y, c.min.z, c.max.x, c.max.y, c.max.z); } @@ -266,18 +287,12 @@ public Cuboid6 setSide(Direction side, double d) { } public int hashCode() { - long i = Double.doubleToLongBits(min.x); - int j = (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(min.y); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(min.z); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.x); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.y); - j = 31 * j + (int) (i ^ i >>> 32); - i = Double.doubleToLongBits(max.z); - j = 31 * j + (int) (i ^ i >>> 32); + int j = Double.hashCode(min.x); + j = 31 * j + Double.hashCode(min.y); + j = 31 * j + Double.hashCode(min.z); + j = 31 * j + Double.hashCode(max.x); + j = 31 * j + Double.hashCode(max.y); + j = 31 * j + Double.hashCode(max.z); return j; } @@ -286,10 +301,9 @@ public boolean equals(Object obj) { if (super.equals(obj)) { return true; } - if (!(obj instanceof Cuboid6)) { + if (!(obj instanceof Cuboid6 c)) { return false; } - Cuboid6 c = (Cuboid6) obj; return min.equals(c.min) && max.equals(c.max); } diff --git a/src/main/java/codechicken/lib/vec/Matrix4.java b/src/main/java/codechicken/lib/vec/Matrix4.java index bdf0550a..271e94e8 100644 --- a/src/main/java/codechicken/lib/vec/Matrix4.java +++ b/src/main/java/codechicken/lib/vec/Matrix4.java @@ -1,9 +1,9 @@ package codechicken.lib.vec; import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector4f; import net.minecraft.core.Vec3i; +import org.joml.Matrix4f; +import org.joml.Vector4f; import java.math.BigDecimal; import java.math.MathContext; @@ -66,6 +66,10 @@ public Matrix4(PoseStack stack) { set(stack); } + public Matrix4(PoseStack.Pose pose) { + set(pose); + } + public Matrix4 setIdentity() { m00 = m11 = m22 = m33 = 1; m01 = m02 = m03 = m10 = m12 = m13 = m20 = m21 = m23 = m30 = m31 = m32 = 0; @@ -416,23 +420,27 @@ public Matrix4 set(PoseStack stack) { return set(stack.last().pose()); } + public Matrix4 set(PoseStack.Pose pose) { + return set(pose.pose()); + } + public Matrix4 set(Matrix4f mat) { - m00 = mat.m00; - m01 = mat.m01; - m02 = mat.m02; - m03 = mat.m03; - m10 = mat.m10; - m11 = mat.m11; - m12 = mat.m12; - m13 = mat.m13; - m20 = mat.m20; - m21 = mat.m21; - m22 = mat.m22; - m23 = mat.m23; - m30 = mat.m30; - m31 = mat.m31; - m32 = mat.m32; - m33 = mat.m33; + m00 = mat.m00(); + m01 = mat.m10(); + m02 = mat.m20(); + m03 = mat.m30(); + m10 = mat.m01(); + m11 = mat.m11(); + m12 = mat.m21(); + m13 = mat.m31(); + m20 = mat.m02(); + m21 = mat.m12(); + m22 = mat.m22(); + m23 = mat.m32(); + m30 = mat.m03(); + m31 = mat.m13(); + m32 = mat.m23(); + m33 = mat.m33(); return this; } @@ -515,22 +523,23 @@ public void save(DoubleBuffer buff) { public Matrix4f toMatrix4f() { Matrix4f mat = new Matrix4f(); - mat.m00 = (float) m00; - mat.m01 = (float) m01; - mat.m02 = (float) m02; - mat.m03 = (float) m03; - mat.m10 = (float) m10; - mat.m11 = (float) m11; - mat.m12 = (float) m12; - mat.m13 = (float) m13; - mat.m20 = (float) m20; - mat.m21 = (float) m21; - mat.m22 = (float) m22; - mat.m23 = (float) m23; - mat.m30 = (float) m30; - mat.m31 = (float) m31; - mat.m32 = (float) m32; - mat.m33 = (float) m33; + mat.m00((float) m00); + mat.m01((float) m01); + mat.m02((float) m02); + mat.m03((float) m03); + mat.m10((float) m10); + mat.m11((float) m11); + mat.m12((float) m12); + mat.m13((float) m13); + mat.m20((float) m20); + mat.m21((float) m21); + mat.m22((float) m22); + mat.m23((float) m23); + mat.m30((float) m30); + mat.m31((float) m31); + mat.m32((float) m32); + mat.m33((float) m33); + mat.transpose(); return mat; } @@ -542,11 +551,11 @@ public static Vector3 gluProject(Vector3 obj, Matrix4 modelMatrix, Matrix4 projM if (o.w() == 0) { return Vector3.ZERO.copy(); } - o.setW((1.0F / o.w()) * 0.5F); + o.w = (1.0F / o.w()) * 0.5F; - o.setX(o.x() * o.w() + 0.5F); - o.setY(o.y() * o.w() + 0.5F); - o.setZ(o.z() * o.w() + 0.5F); + o.x = o.x() * o.w() + 0.5F; + o.y = o.y() * o.w() + 0.5F; + o.z = o.z() * o.w() + 0.5F; Vector3 winPos = new Vector3(); winPos.z = o.z(); @@ -556,6 +565,11 @@ public static Vector3 gluProject(Vector3 obj, Matrix4 modelMatrix, Matrix4 projM return winPos; } + @Override + public Matrix4 compile() { + return copy(); + } + @Override public void apply(Matrix4 mat) { mat.multiply(this); diff --git a/src/main/java/codechicken/lib/vec/Quat.java b/src/main/java/codechicken/lib/vec/Quat.java index 2fda52e4..e0d43c86 100644 --- a/src/main/java/codechicken/lib/vec/Quat.java +++ b/src/main/java/codechicken/lib/vec/Quat.java @@ -1,7 +1,8 @@ package codechicken.lib.vec; import codechicken.lib.util.Copyable; -import com.mojang.math.Quaternion; +import org.joml.Quaterniond; +import org.joml.Quaternionf; import java.math.BigDecimal; import java.math.MathContext; @@ -28,11 +29,18 @@ public Quat(Quat quat) { s = quat.s; } - public Quat(Quaternion quat) { - x = quat.i(); - y = quat.j(); - z = quat.k(); - s = quat.r(); + public Quat(Quaternionf quat) { + x = quat.x; + y = quat.y; + z = quat.z; + s = quat.w; + } + + public Quat(Quaterniond quat) { + x = quat.x; + y = quat.y; + z = quat.z; + s = quat.w; } public Quat(double d, double d1, double d2, double d3) { @@ -104,8 +112,12 @@ public Quat rightMultiply(Quat quat) { return this; } - public Quaternion toQuaternion() { - return new Quaternion((float) x, (float) y, (float) z, (float) s); + public Quaternionf toQuaternionF() { + return new Quaternionf((float) x, (float) y, (float) z, (float) s); + } + + public Quaterniond toQuaternionD() { + return new Quaterniond(x, y, z, s); } public double mag() { diff --git a/src/main/java/codechicken/lib/vec/Transformation.java b/src/main/java/codechicken/lib/vec/Transformation.java index c511671b..9a1c3558 100644 --- a/src/main/java/codechicken/lib/vec/Transformation.java +++ b/src/main/java/codechicken/lib/vec/Transformation.java @@ -32,6 +32,12 @@ public TransformationList with(Transformation t) { return new TransformationList(this, t); } + public Matrix4 compile() { + Matrix4 mat = new Matrix4(); + apply(mat); + return mat; + } + @Override public boolean load(CCRenderState ccrs) { ccrs.pipeline.addRequirement(ccrs.normalAttrib.operationID()); diff --git a/src/main/java/codechicken/lib/vec/TransformationList.java b/src/main/java/codechicken/lib/vec/TransformationList.java index ccd7d421..5064d73d 100644 --- a/src/main/java/codechicken/lib/vec/TransformationList.java +++ b/src/main/java/codechicken/lib/vec/TransformationList.java @@ -1,6 +1,7 @@ package codechicken.lib.vec; import codechicken.lib.util.Copyable; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.collection.StreamableIterable; import org.jetbrains.annotations.Nullable; @@ -32,12 +33,13 @@ public TransformationList(List transforms) { } public TransformationList(TransformationList other) { - transformations = StreamableIterable.of(other.transformations) + transformations = FastStream.of(other.transformations) .map(Copyable::copy) .toList(); mat = other.mat; } + @Override public Matrix4 compile() { if (mat == null) { mat = new Matrix4(); @@ -159,7 +161,7 @@ private void compact() { @Override public boolean isRedundant() { - return transformations.size() == 0; + return transformations.isEmpty(); } @Override diff --git a/src/main/java/codechicken/lib/vec/VariableTransformation.java b/src/main/java/codechicken/lib/vec/VariableTransformation.java index 5cc37cdc..e935b0a1 100644 --- a/src/main/java/codechicken/lib/vec/VariableTransformation.java +++ b/src/main/java/codechicken/lib/vec/VariableTransformation.java @@ -18,6 +18,11 @@ public void apply(Matrix4 mat) { mat.multiply(this.mat); } + @Override + public Matrix4 compile() { + return mat.copy(); + } + @Override public Transformation copy() { return this; diff --git a/src/main/java/codechicken/lib/vec/Vector3.java b/src/main/java/codechicken/lib/vec/Vector3.java index 755d7d97..8495c460 100644 --- a/src/main/java/codechicken/lib/vec/Vector3.java +++ b/src/main/java/codechicken/lib/vec/Vector3.java @@ -2,15 +2,22 @@ import codechicken.lib.math.MathHelper; import codechicken.lib.util.Copyable; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; +import com.mojang.serialization.Codec; +import com.mojang.serialization.codecs.PrimitiveCodec; +import com.mojang.serialization.codecs.RecordCodecBuilder; +import io.netty.buffer.ByteBuf; import net.minecraft.core.BlockPos; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.phys.Vec3; import org.jetbrains.annotations.Nullable; +import org.joml.Vector3f; +import org.joml.Vector3fc; +import org.joml.Vector4f; import java.math.BigDecimal; import java.math.MathContext; @@ -30,6 +37,20 @@ public class Vector3 implements Copyable { public static final Vector3 Z_NEG = new Vector3( 0, 0,-1); //@formatter:on + public static final Codec CODEC = RecordCodecBuilder.create(b -> b.group( + PrimitiveCodec.DOUBLE.fieldOf("x").forGetter(e -> e.x), + PrimitiveCodec.DOUBLE.fieldOf("y").forGetter(e -> e.y), + PrimitiveCodec.DOUBLE.fieldOf("z").forGetter(e -> e.z) + ).apply(b, Vector3::new) + ); + + public static final StreamCodec STREAM_CODEC = StreamCodec.composite( + ByteBufCodecs.DOUBLE, e -> e.x, + ByteBufCodecs.DOUBLE, e -> e.y, + ByteBufCodecs.DOUBLE, e -> e.z, + Vector3::new + ); + public double x; public double y; public double z; @@ -80,7 +101,7 @@ public static Vector3 fromEntity(Entity e) { } public static Vector3 fromEntityCenter(Entity e) { - return new Vector3(e.position()).add(0, e.getMyRidingOffset() + e.getBbHeight() / 2, 0); + return new Vector3(e.position()).add(0, e.getBbHeight() / 2, 0); } public static Vector3 fromTile(BlockEntity tile) { @@ -108,7 +129,7 @@ public static Vector3 fromArray(float[] fa) { } public static Vector3 fromNBT(CompoundTag tag) { - return new Vector3(tag.getDouble("x"), tag.getDouble("y"), tag.getDouble("z")); + return new Vector3(tag.getDoubleOr("x", 0), tag.getDoubleOr("y", 0), tag.getDoubleOr("z", 0)); } public Vec3 vec3() { @@ -116,7 +137,7 @@ public Vec3 vec3() { } public BlockPos pos() { - return new BlockPos(x, y, z); + return new BlockPos(MathHelper.floor(x), MathHelper.floor(y), MathHelper.floor(z)); } public CompoundTag writeToNBT(CompoundTag tag) { @@ -161,6 +182,10 @@ public Vector3 set(Vec3i vec) { return set(vec.getX(), vec.getY(), vec.getZ()); } + public Vector3 set(Vector3fc vec) { + return set(vec.x(), vec.y(), vec.z()); + } + public Vector3 set(double[] da) { return set(da[0], da[1], da[2]); } @@ -188,8 +213,7 @@ public Vector3 add(Vec3 vec) { return add(vec.x, vec.y, vec.z); } - // TODO Move to use Vec3i - public Vector3 add(BlockPos pos) { + public Vector3 add(Vec3i pos) { return add(pos.getX(), pos.getY(), pos.getZ()); } @@ -212,7 +236,7 @@ public Vector3 subtract(Vec3 vec) { return subtract(vec.x, vec.y, vec.z); } - public Vector3 subtract(BlockPos pos) { + public Vector3 subtract(Vec3i pos) { return subtract(pos.getX(), pos.getY(), pos.getZ()); } @@ -246,7 +270,7 @@ public Vector3 divide(Vector3 vec) { return divide(vec.x, vec.y, vec.z); } - public Vector3 divide(BlockPos pos) { + public Vector3 divide(Vec3i pos) { return divide(pos.getX(), pos.getY(), pos.getZ()); } @@ -502,12 +526,9 @@ public Vector3 setSide(int s, double v) { @Override public int hashCode() { - long j = Double.doubleToLongBits(x); - int i = (int) (j ^ j >>> 32); - j = Double.doubleToLongBits(y); - i = 31 * i + (int) (j ^ j >>> 32); - j = Double.doubleToLongBits(z); - i = 31 * i + (int) (j ^ j >>> 32); + int i = Double.hashCode(x); + i = 31 * i + Double.hashCode(y); + i = 31 * i + Double.hashCode(z); return i; } @@ -516,10 +537,9 @@ public boolean equals(Object o) { if (super.equals(o)) { return true; } - if (!(o instanceof Vector3)) { + if (!(o instanceof Vector3 v)) { return false; } - Vector3 v = (Vector3) o; return x == v.x && y == v.y && z == v.z; } diff --git a/src/main/java/codechicken/lib/vec/package-info.java b/src/main/java/codechicken/lib/vec/package-info.java index 86fe172e..4ad9281d 100644 --- a/src/main/java/codechicken/lib/vec/package-info.java +++ b/src/main/java/codechicken/lib/vec/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.vec; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java index 86b78835..d3f10149 100644 --- a/src/main/java/codechicken/lib/vec/uv/IconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/IconTransformation.java @@ -23,8 +23,8 @@ public void operate(CCRenderState ccrs) { @Override public void apply(UV uv) { - uv.u = icon.getU(uv.u * 16); - uv.v = icon.getV(uv.v * 16); + uv.u = icon.getU((float) uv.u); + uv.v = icon.getV((float) uv.v); } @Override @@ -49,8 +49,8 @@ public Inverse(Inverse other) { @Override public void apply(UV uv) { - uv.u = icon.getUOffset((float) uv.u) / 16; - uv.v = icon.getVOffset((float) uv.v) / 16; + uv.u = getUOffset(icon, (float) uv.u); + uv.v = getVOffset(icon, (float) uv.v); } @Override @@ -62,5 +62,13 @@ public UVTransformation inverse() { public IconTransformation copy() { return new Inverse(this); } + + public static float getUOffset(TextureAtlasSprite sprite, float u) { + return (u - sprite.getU0()) / (sprite.getU1() - sprite.getU0()); + } + + public static float getVOffset(TextureAtlasSprite sprite, float v) { + return (v - sprite.getV0()) / (sprite.getV1() - sprite.getV0()); + } } } diff --git a/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java b/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java index 7038bfcc..2f98bc0b 100644 --- a/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/MultiIconTransformation.java @@ -29,8 +29,8 @@ public void operate(CCRenderState ccrs) { @Override public void apply(UV uv) { icon = icons[uv.tex % icons.length]; - uv.u = icon.getU(uv.u * 16); - uv.v = icon.getV(uv.v * 16); + uv.u = icon.getU((float) uv.u); + uv.v = icon.getV((float) uv.v); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java b/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java index 5e2850c9..a77d20ea 100644 --- a/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/ScaledIconTransformation.java @@ -25,8 +25,8 @@ public ScaledIconTransformation(ScaledIconTransformation other) { @Override public void apply(UV uv) { - uv.u = icon.getU(uv.u % 2 * 16) + su * (icon.getU1() - icon.getU0()); - uv.v = icon.getV(uv.v % 2 * 16) + sv * (icon.getV1() - icon.getV0()); + uv.u = icon.getU((float) (uv.u % 2)) + su * (icon.getU1() - icon.getU0()); + uv.v = icon.getV((float) (uv.v % 2)) + sv * (icon.getV1() - icon.getV0()); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/UVTransformation.java b/src/main/java/codechicken/lib/vec/uv/UVTransformation.java index 3854efcf..db52da15 100644 --- a/src/main/java/codechicken/lib/vec/uv/UVTransformation.java +++ b/src/main/java/codechicken/lib/vec/uv/UVTransformation.java @@ -35,5 +35,3 @@ public int operationID() { return operationIndex; } } - - diff --git a/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java b/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java index 9d124cba..08ba7d00 100644 --- a/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java +++ b/src/main/java/codechicken/lib/vec/uv/UVTransformationList.java @@ -1,6 +1,7 @@ package codechicken.lib.vec.uv; import codechicken.lib.util.Copyable; +import net.covers1624.quack.collection.FastStream; import net.covers1624.quack.collection.StreamableIterable; import java.util.ArrayList; @@ -22,7 +23,7 @@ public UVTransformationList(UVTransformation... transforms) { } public UVTransformationList(UVTransformationList other) { - transformations = StreamableIterable.of(other.transformations) + transformations = FastStream.of(other.transformations) .map(Copyable::copy) .toList(); @@ -98,7 +99,7 @@ private void compact() { @Override public boolean isRedundant() { - return transformations.size() == 0; + return transformations.isEmpty(); } @Override diff --git a/src/main/java/codechicken/lib/vec/uv/package-info.java b/src/main/java/codechicken/lib/vec/uv/package-info.java index b36c0aaf..dbaafc4e 100644 --- a/src/main/java/codechicken/lib/vec/uv/package-info.java +++ b/src/main/java/codechicken/lib/vec/uv/package-info.java @@ -1,9 +1,4 @@ -@FieldsAreNonnullByDefault -@ParametersAreNonnullByDefault -@MethodsReturnNonnullByDefault +@NonNullApi package codechicken.lib.vec.uv; -import net.covers1624.quack.annotation.FieldsAreNonnullByDefault; -import net.covers1624.quack.annotation.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/java/codechicken/lib/world/package-info.java b/src/main/java/codechicken/lib/world/package-info.java new file mode 100644 index 00000000..c117001e --- /dev/null +++ b/src/main/java/codechicken/lib/world/package-info.java @@ -0,0 +1,4 @@ +@NonNullApi +package codechicken.lib.world; + +import net.covers1624.quack.annotation.NonNullApi; diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index 0eec72a9..c1deec27 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -1,65 +1,56 @@ # CodeChickenLib Access Transformer -public net.minecraft.core.Direction f_122348_ # BY_3D_DATA -public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;Z)V # -public net.minecraft.server.MinecraftServer f_129744_ # storageSource +public net.minecraft.core.Direction BY_3D_DATA +public net.minecraft.world.phys.BlockHitResult (ZLnet/minecraft/world/phys/Vec3;Lnet/minecraft/core/Direction;Lnet/minecraft/core/BlockPos;ZZ)V +public net.minecraft.server.MinecraftServer storageSource public com.mojang.math.Matrix3f * # All fields. public com.mojang.math.Matrix4f * # All fields. -public com.mojang.blaze3d.vertex.BufferBuilder f_85658_ # format -public com.mojang.blaze3d.vertex.DefaultedVertexConsumer f_85824_ # defaultColorSet -public net.minecraft.world.phys.shapes.VoxelShape f_83211_ # shape -public net.minecraft.world.phys.shapes.VoxelShape (Lnet/minecraft/world/phys/shapes/DiscreteVoxelShape;)V # -public net.minecraft.world.phys.shapes.VoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.SliceShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.ArrayVoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.phys.shapes.CubeVoxelShape m_7700_(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; # getCoords -public net.minecraft.world.inventory.MenuType f_39981_ # constructor -public net.minecraft.server.players.GameProfileCache f_10966_ # profilesByName -public net.minecraft.server.players.GameProfileCache$GameProfileInfo +public com.mojang.blaze3d.vertex.BufferBuilder format +public com.mojang.blaze3d.vertex.DefaultedVertexConsumer defaultColorSet +public net.minecraft.world.phys.shapes.VoxelShape shape +public net.minecraft.world.phys.shapes.VoxelShape (Lnet/minecraft/world/phys/shapes/DiscreteVoxelShape;)V +public net.minecraft.world.phys.shapes.VoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.SliceShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.ArrayVoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.phys.shapes.CubeVoxelShape getCoords(Lnet/minecraft/core/Direction$Axis;)Lit/unimi/dsi/fastutil/doubles/DoubleList; +public net.minecraft.world.inventory.MenuType constructor public net.minecraft.client.renderer.RenderStateShard * # Everything. public net.minecraft.client.renderer.RenderType *() # All Methods public net.minecraft.client.renderer.RenderType * # All Fields. -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110900_ # modelRenderer -public net.minecraft.client.renderer.block.BlockRenderDispatcher f_173397_ # blockEntityRenderer -public-f net.minecraft.client.renderer.block.BlockRenderDispatcher f_110901_ # liquidBlockRenderer -public-f net.minecraft.client.Minecraft f_91052_ # blockRenderer -public net.minecraft.world.item.ArmorMaterials f_40460_ # HEALTH_PER_SLOT +public net.minecraft.client.renderer.RenderType$CompositeRenderType +public net.minecraft.client.renderer.RenderType$CompositeRenderType * +public net.minecraft.client.renderer.RenderType$CompositeRenderType *() +public net.minecraft.client.renderer.RenderType$CompositeState +public net.minecraft.client.renderer.RenderType$CompositeState * +public net.minecraft.client.renderer.RenderType$CompositeState *() +public net.minecraft.world.item.ArmorMaterials HEALTH_FUNCTION_FOR_TYPE -public net.minecraft.commands.arguments.ResourceKeyArgument m_233255_(Lcom/mojang/brigadier/context/CommandContext;Ljava/lang/String;Lnet/minecraft/resources/ResourceKey;Lcom/mojang/brigadier/exceptions/DynamicCommandExceptionType;)Lnet/minecraft/core/Holder; # getRegistryKeyType +public com.mojang.blaze3d.vertex.VertexFormat uploadToBuffer(Lcom/mojang/blaze3d/buffers/GpuBuffer;Ljava/nio/ByteBuffer;ILjava/util/function/Supplier;)Lcom/mojang/blaze3d/buffers/GpuBuffer; -public-f net.minecraft.world.level.block.Block f_49792_ # stateDefinition -public-f net.minecraft.world.level.block.Block m_49966_()Lnet/minecraft/world/level/block/state/BlockState; # defaultBlockState -public net.minecraft.data.tags.TagsProvider m_206424_(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagsProvider$TagAppender; # tag +public-f net.minecraft.world.level.block.Block stateDefinition +public-f net.minecraft.world.level.block.Block defaultBlockState()Lnet/minecraft/world/level/block/state/BlockState; -protected net.minecraft.client.renderer.ShaderInstance f_173331_ # uniforms -protected net.minecraft.client.renderer.ShaderInstance m_173354_(Lcom/google/gson/JsonElement;)V # parseUniformNode -protected-f com.mojang.blaze3d.shaders.Uniform f_85588_ # intValues -protected-f com.mojang.blaze3d.shaders.Uniform f_85589_ # floatValues -protected com.mojang.blaze3d.shaders.Uniform f_85591_ # dirty -public-f com.mojang.blaze3d.shaders.Uniform m_5985_(F)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_7971_(FF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_166700_(IF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5889_(FFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142276_(Lcom/mojang/math/Vector3f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5805_(FFFF)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142558_(Lcom/mojang/math/Vector4f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5808_(FFFF)V # setSafe -public-f com.mojang.blaze3d.shaders.Uniform m_7401_(IIII)V # setSafe -public-f com.mojang.blaze3d.shaders.Uniform m_142617_(I)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142326_(II)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142693_(III)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142492_(IIII)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_5941_([F)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_142588_(FFFF)V # setMat2x2 -public-f com.mojang.blaze3d.shaders.Uniform m_141964_(FFFFFF)V # setMat2x3 -public-f com.mojang.blaze3d.shaders.Uniform m_142005_(FFFFFFFF)V # setMat2x4 -public-f com.mojang.blaze3d.shaders.Uniform m_141963_(FFFFFF)V # setMat3x2 -public-f com.mojang.blaze3d.shaders.Uniform m_142217_(FFFFFFFFF)V # setMat3x3 -public-f com.mojang.blaze3d.shaders.Uniform m_142604_(FFFFFFFFFFFF)V # setMat3x4 -public-f com.mojang.blaze3d.shaders.Uniform m_142004_(FFFFFFFF)V # setMat4x2 -public-f com.mojang.blaze3d.shaders.Uniform m_142605_(FFFFFFFFFFFF)V # setMat4x3 -public-f com.mojang.blaze3d.shaders.Uniform m_141978_(FFFFFFFFFFFFFFFF)V # setMat4x4 -public-f com.mojang.blaze3d.shaders.Uniform m_5679_(Lcom/mojang/math/Matrix4f;)V # set -public-f com.mojang.blaze3d.shaders.Uniform m_200759_(Lcom/mojang/math/Matrix3f;)V # set -public com.mojang.blaze3d.shaders.Program (Lcom/mojang/blaze3d/shaders/Program$Type;ILjava/lang/String;)V # -public com.mojang.blaze3d.shaders.Program$Type m_85571_()I # getGlType +public-f net.minecraft.data.loot.LootTableProvider subProviders +public net.minecraft.data.tags.IntrinsicHolderTagsProvider tag(Lnet/minecraft/tags/TagKey;)Lnet/minecraft/data/tags/TagAppender; + +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderSlot(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/inventory/Slot;)V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen renderFloatingItem(Lnet/minecraft/client/gui/GuiGraphics;Lnet/minecraft/world/item/ItemStack;IILjava/lang/String;)V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen findSlot(DD)Lnet/minecraft/world/inventory/Slot; +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen isHovering(Lnet/minecraft/world/inventory/Slot;DD)Z +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen recalculateQuickCraftRemaining()V +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen clickedSlot +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen draggingItem +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen isSplittingStack +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingType +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen quickCraftingRemainder +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen$SnapbackData +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen snapbackData +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen showTooltipWithItemInHand(Lnet/minecraft/world/item/ItemStack;)Z +public net.minecraft.client.gui.screens.inventory.AbstractContainerScreen getHoveredSlot(DD)Lnet/minecraft/world/inventory/Slot; +public-f net.minecraft.world.inventory.Slot x +public-f net.minecraft.world.inventory.Slot y +public net.minecraft.world.inventory.AbstractContainerMenu addSlot(Lnet/minecraft/world/inventory/Slot;)Lnet/minecraft/world/inventory/Slot; + +public net.minecraft.client.gui.render.state.BlitRenderState getBounds(IIIILorg/joml/Matrix3x2f;Lnet/minecraft/client/gui/navigation/ScreenRectangle;)Lnet/minecraft/client/gui/navigation/ScreenRectangle; + +public net.minecraft.client.gui.GuiGraphics minecraft diff --git a/src/main/resources/META-INF/interfaces.json b/src/main/resources/META-INF/interfaces.json new file mode 100644 index 00000000..f1ff8b0f --- /dev/null +++ b/src/main/resources/META-INF/interfaces.json @@ -0,0 +1,14 @@ +{ + "net/minecraft/network/FriendlyByteBuf": [ + "codechicken/lib/packet/CCFriendlyByteBufExtension" + ], + "net/minecraft/network/RegistryFriendlyByteBuf": [ + "codechicken/lib/packet/CCRegistryFriendlyByteBufExtension" + ], + "net/minecraft/client/renderer/OrderedSubmitNodeCollector": [ + 'codechicken/lib/render/extension/CCOrderedSubmitNodeCollectorExtension' + ], + "net/minecraft/client/gui/GuiGraphics": [ + 'codechicken/lib/gui/render/GuiGraphicsExtension' + ] +} diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/neoforge.mods.toml similarity index 85% rename from src/main/resources/META-INF/mods.toml rename to src/main/resources/META-INF/neoforge.mods.toml index d5bc705c..ef0724b1 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -1,8 +1,11 @@ modLoader="javafml" -loaderVersion="[${lang_version},)" +loaderVersion="[2,)" issueTrackerURL="https://github.com/TheCBProject/CodeChickenLib" license="GNU Lesser General Public License v2.1" +[[mixins]] +config="mixins.codechickenlib.json" + [[mods]] modId="codechickenlib" displayName="CodeChicken Lib" @@ -16,15 +19,15 @@ CodeChickenLib is a library of systems to help make various aspects of minecraft It contains libraries for 3D math and transformations, model rendering, packets, config, colours, asm and a few other things.. ''' [[dependencies.codechickenlib]] - modId="forge" - mandatory=true + modId="neoforge" + type="required" versionRange="[${forge_version},)" ordering="NONE" side="BOTH" [[dependencies.codechickenlib]] modId="minecraft" - mandatory=true - versionRange="[1.19.2]" + type="required" + versionRange="[1.21.11]" ordering="NONE" side="BOTH" diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/drag.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/drag.png new file mode 100644 index 00000000..1e8c3266 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/drag.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_tlbr.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_tlbr.png new file mode 100644 index 00000000..2714f3f8 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_tlbr.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_trbl.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_trbl.png new file mode 100644 index 00000000..b306c6ba Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_diag_trbl.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_h.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_h.png new file mode 100644 index 00000000..07baa61c Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_h.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_v.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_v.png new file mode 100644 index 00000000..363aca47 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/cursors/resize_v.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless.png new file mode 100644 index 00000000..f1484440 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless_pressed.png new file mode 100644 index 00000000..7273c079 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_borderless_pressed.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight.png new file mode 100644 index 00000000..11877644 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_borderless.png new file mode 100644 index 00000000..677d04c1 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_borderless.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_pressed.png new file mode 100644 index 00000000..02dd3d8b Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_highlight_pressed.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_pressed.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_pressed.png new file mode 100644 index 00000000..aab7096a Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_pressed.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla.png new file mode 100644 index 00000000..5e64e34b Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla_disabled.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla_disabled.png new file mode 100644 index 00000000..aa29d997 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/button_vanilla_disabled.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_borderless.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_borderless.png new file mode 100644 index 00000000..87a64d8b Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_borderless.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_vanilla.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_vanilla.png new file mode 100644 index 00000000..3962fe08 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/dynamic/gui_vanilla.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_empty.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_empty.png new file mode 100644 index 00000000..bf499615 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_empty.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_full.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_full.png new file mode 100644 index 00000000..4af15eef Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/energy_full.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_empty.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_empty.png new file mode 100644 index 00000000..7ade208c Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_empty.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_full.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_full.png new file mode 100644 index 00000000..87b54615 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/progress_arrow_full.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot.png new file mode 100644 index 00000000..65ab3081 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot.png differ diff --git a/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot_large.png b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot_large.png new file mode 100644 index 00000000..61c28017 Binary files /dev/null and b/src/main/resources/assets/codechickenlib/textures/gui/sprites/widgets/slot_large.png differ diff --git a/src/main/resources/mixins.codechickenlib.json b/src/main/resources/mixins.codechickenlib.json index 5d495d86..d45f1301 100644 --- a/src/main/resources/mixins.codechickenlib.json +++ b/src/main/resources/mixins.codechickenlib.json @@ -2,13 +2,17 @@ "required": true, "minVersion": "0.8", "package": "codechicken.lib.internal.mixin", - "refmap": "mixins.codechickenlib.refmap.json", + "plugin": "codechicken.lib.internal.mixin.CCLMixinPlugin", "target": "@env(DEFAULT)", "compatibilityLevel": "JAVA_17", + "mixins": [ + "network.FriendlyByteBufMixin", + "network.RegistryFriendlyByteBufMixin" + ], "client": [ - "ItemRendererMixin", - "LevelRendererMixin", + "dev.GameNarratorMixin", "MinecraftMixin", - "ShaderInstanceMixin" + "render.OrderedSubmitNodeCollectorMixin", + "render.GuiGraphicsMixin" ] } diff --git a/src/main/resources/pack.mcmeta b/src/main/resources/pack.mcmeta index 43ef0f5d..8b9bf7cc 100644 --- a/src/main/resources/pack.mcmeta +++ b/src/main/resources/pack.mcmeta @@ -1,6 +1,6 @@ { "pack": { - "pack_format": 4, + "pack_format": 22, "description": "CCL resource pack" } } diff --git a/src/test/java/codechicken/lib/config/ConfigV3Tests.java b/src/test/java/codechicken/lib/config/ConfigV3Tests.java index b44d549c..21b1e544 100644 --- a/src/test/java/codechicken/lib/config/ConfigV3Tests.java +++ b/src/test/java/codechicken/lib/config/ConfigV3Tests.java @@ -14,6 +14,7 @@ import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; +import net.minecraft.network.FriendlyByteBuf; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -931,7 +932,7 @@ public void testCopy() { @Test public void testTagCategoryRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); IllegalStateException ex; ConfigCategoryImpl rootTag = new ConfigCategoryImpl("rootTag", null); @@ -940,7 +941,7 @@ public void testTagCategoryRead() { buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_NO_TAG - 1); - buf.writeString("cat1"); + buf.writeUtf("cat1"); ex = assertThrows(IllegalStateException.class, () -> rootTag.read(buf)); assertEquals("Unknown tag network type: " + (ConfigCategoryImpl.NET_NO_TAG - 1), ex.getMessage()); @@ -964,7 +965,7 @@ public void testTagCategoryRead() { { // Test NET_CAT_TAG behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_CAT_TAG); - buf.writeString("cat1"); + buf.writeUtf("cat1"); buf.writeVarInt(0); rootTag.read(buf); @@ -990,7 +991,7 @@ public void testTagCategoryRead() { { // Test NET_VAL_TAG behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_VAL_TAG); - buf.writeString("val1"); + buf.writeUtf("val1"); buf.writeEnum(ValueType.INT); buf.writeInt(22); rootTag.read(buf); @@ -1017,7 +1018,7 @@ public void testTagCategoryRead() { { // Test NET_VAL_LST behaves as expected. buf.writeVarInt(1); buf.writeByte(ConfigCategoryImpl.NET_VAL_LST); - buf.writeString("lst1"); + buf.writeUtf("lst1"); buf.writeEnum(ValueType.INT); buf.writeVarInt(2); buf.writeInt(22); @@ -1043,7 +1044,7 @@ public void testTagCategoryRead() { @Test public void testTagValueRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); buf.writeEnum(ValueType.INT); buf.writeInt(22); @@ -1074,7 +1075,7 @@ public void testTagValueRead() { @Test public void testTagValueListRead() { ByteBuf buffer = Unpooled.buffer(); - MCDataByteBuf buf = new MCDataByteBuf(buffer); + FriendlyByteBuf buf = new FriendlyByteBuf(buffer); buf.writeEnum(ValueType.INT); buf.writeVarInt(2); buf.writeInt(22); @@ -1125,7 +1126,7 @@ public void testReadWriteEquality() { listCat.getValueList("list5").setHexs(new IntArrayList(List.of(0xFFFFFFFF, 0xFF00FF00))); listCat.getValueList("list6").setDoubles(new DoubleArrayList(List.of(4.20, 6.9))); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); @@ -1149,7 +1150,7 @@ public void testResetFormNetwork() { root.getValue("not_synced"); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); @@ -1192,7 +1193,7 @@ public void testConfigSaveWithNetworkSet() throws Throwable { .syncTagToClient(); listCat.getValueList("list1").setStrings(List.of("World", "Hello")); - MCDataByteBuf buf = new MCDataByteBuf(); + FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); root.write(buf); ConfigCategoryImpl root2 = new ConfigCategoryImpl("rootTag", null); diff --git a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java b/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java deleted file mode 100644 index 58931139..00000000 --- a/src/test/java/codechicken/lib/render/BakedVertexSourceTests.java +++ /dev/null @@ -1,76 +0,0 @@ -package codechicken.lib.render; - -import codechicken.lib.model.CachedFormat; -import codechicken.lib.model.Quad; -import net.minecraft.client.renderer.block.model.BakedQuad; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * Created by covers1624 on 1/1/22. - */ -public class BakedVertexSourceTests { - - static { - // Init vertex attributes. - CCRenderState.instance(); - } - - @Test - public void testExpand() { - BakedVertexSource source = new BakedVertexSource(); - assertEquals(0, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - source.ensureSpace(32); - assertEquals(32, source.getVertices().length); - source.ensureSpace(2048); - assertEquals(2048, source.getVertices().length); - source.ensureSpace(2048); - assertEquals(2048, source.getVertices().length); - } - - @Test - public void testExpandWithQuad() { - Quad unbaked = new Quad(); - unbaked.reset(CachedFormat.BLOCK); - BakedQuad quad = unbaked.bake(); - - BakedVertexSource source = new BakedVertexSource(); - source.reset(CachedFormat.BLOCK); - assertEquals(0, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(4, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(8, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(12, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(16, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(20, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(24, source.getVertexCount()); - assertEquals(24, source.getVertices().length); - - source.put(quad); - assertEquals(28, source.getVertexCount()); - assertEquals(28, source.getVertices().length); - - source.reset(CachedFormat.BLOCK); - assertEquals(0, source.getVertexCount()); - assertEquals(28, source.getVertices().length); - } -} diff --git a/src/test/java/codechicken/lib/render/model/MatLibTests.java b/src/test/java/codechicken/lib/render/model/MatLibTests.java index 8b00ab95..6d12c702 100644 --- a/src/test/java/codechicken/lib/render/model/MatLibTests.java +++ b/src/test/java/codechicken/lib/render/model/MatLibTests.java @@ -2,7 +2,7 @@ import codechicken.lib.colour.ColourRGBA; import codechicken.lib.test.TestResourceProvider; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +15,7 @@ public class MatLibTests { @Test public void testMatLibParse() { - MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test.mtl")); + MatLib matLib = MatLib.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test.mtl")); assertEquals(1, matLib.materials.size()); ModelMaterial material = matLib.getMaterial("Material"); assertNotNull(material); diff --git a/src/test/java/codechicken/lib/render/model/OBJParserTests.java b/src/test/java/codechicken/lib/render/model/OBJParserTests.java index 1dafb099..98c0d455 100644 --- a/src/test/java/codechicken/lib/render/model/OBJParserTests.java +++ b/src/test/java/codechicken/lib/render/model/OBJParserTests.java @@ -3,11 +3,10 @@ import codechicken.lib.render.CCModel; import codechicken.lib.test.TestResourceProvider; import com.mojang.blaze3d.vertex.VertexFormat; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import org.junit.jupiter.api.Test; import java.util.Map; -import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -19,7 +18,7 @@ public class OBJParserTests { @Test public void testObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -28,7 +27,7 @@ public void testObject() { @Test public void testGroup() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_group.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -37,7 +36,7 @@ public void testGroup() { @Test public void testGroupObject() { - Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, new ResourceLocation("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); + Map modelMap = OBJParser.parse(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_group_object.obj"), VertexFormat.Mode.QUADS, null, false); CCModel model = modelMap.get("Group/Cube"); assertNotNull(model); ModelMaterial material = model.material(); @@ -46,8 +45,7 @@ public void testGroupObject() { @Test public void testMultiObject() { - Map modelMap = new OBJParser(new ResourceLocation("test:model/test_multi_object.obj")) - .provider(TestResourceProvider.INSTANCE) + Map modelMap = new OBJParser(TestResourceProvider.INSTANCE, Identifier.parse("test:model/test_multi_object.obj")) .ignoreMtl() .quads() .parse(); diff --git a/src/test/java/codechicken/lib/test/TestResourceProvider.java b/src/test/java/codechicken/lib/test/TestResourceProvider.java index 3b6ceccf..2adbd7e3 100644 --- a/src/test/java/codechicken/lib/test/TestResourceProvider.java +++ b/src/test/java/codechicken/lib/test/TestResourceProvider.java @@ -1,7 +1,7 @@ package codechicken.lib.test; import codechicken.lib.render.model.OBJParserTests; -import net.minecraft.resources.ResourceLocation; +import net.minecraft.resources.Identifier; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceProvider; @@ -21,7 +21,7 @@ private TestResourceProvider() { } @Override - public Optional getResource(ResourceLocation resource) { - return Optional.of(new Resource("test", () -> Objects.requireNonNull(OBJParserTests.class.getResourceAsStream("/" + resource.getPath()), "Resource " + resource + " doesnt exist."))); + public Optional getResource(Identifier resource) { + return Optional.of(new Resource(null, () -> Objects.requireNonNull(OBJParserTests.class.getResourceAsStream("/" + resource.getPath()), "Resource " + resource + " doesnt exist."))); } }