diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudDisc.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudDisc.java
new file mode 100644
index 000000000..9cfebb1de
--- /dev/null
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudDisc.java
@@ -0,0 +1,98 @@
+package com.gtnewhorizons.angelica.render;
+
+/**
+ * The shape of the drawn disc, how it splits into wedges, and how far out each kind of geometry should
+ * really be worth building.
+ */
+final class CloudDisc {
+
+ static final int CELLS_PER_CHUNK = 8;
+ static final int MARGIN_CELLS = 16;
+ static final int WEDGE_COUNT = 32;
+ static final double WEDGES_PER_RADIAN = WEDGE_COUNT / (2.0 * Math.PI);
+ static final int ALWAYS_DRAWN_CELLS = Math.max(CELLS_PER_CHUNK, 4 * MARGIN_CELLS);
+ static final float SCROLL_SPEED = 1.0f / 256.0f;
+ private static final double WALL_CUT_PIXELS = 0.625;
+ private static final double PLATE_LOD_PIXELS = 0.35;
+ private static final double TAN_11_25_DEG = 0.19891236737965800; // √(4+2√2)−√2−1
+ private static final double TAN_22_5_DEG = 0.41421356237309503; // √2−1
+ private static final double TAN_33_75_DEG = 0.66817863791929892; // √(4−2√2)+1−√2
+ private static final int DISTANCE_STEP_CELLS = 32;
+
+ static {
+ if (WEDGE_COUNT != 32) {
+ throw new AssertionError("wedgeOf splits four quadrants into eight; WEDGE_COUNT must be 32");
+ }
+ }
+
+ private CloudDisc() {
+ }
+
+ static double pixelsPerRadian(int displayHeight, float fovDegrees) {
+ if (!(fovDegrees > 0.0f) || fovDegrees >= 180.0f) return 0.0;
+ return (displayHeight * 0.5) / Math.tan(Math.toRadians(fovDegrees) * 0.5);
+ }
+
+ static int wallCutCells(double pixelsPerRadian, boolean platesInFront) {
+ if (!platesInFront || pixelsPerRadian <= 0.0) return Integer.MAX_VALUE;
+
+ return roundUpToStep(pixelsPerRadian / (3.0 * WALL_CUT_PIXELS));
+ }
+
+ static int plateLodCells(double pixelsPerRadian, float cloudBaseRelativeY, float cellWidthBlocks, boolean coarseCoverUsable) {
+ if (!coarseCoverUsable || pixelsPerRadian <= 0.0) return Integer.MAX_VALUE;
+
+ final double heightBlocks = Math.max(1.0, Math.abs(cloudBaseRelativeY));
+ return roundUpToStep(Math.sqrt(heightBlocks * pixelsPerRadian / (cellWidthBlocks * PLATE_LOD_PIXELS)));
+ }
+
+ private static int roundUpToStep(double cells) {
+ final long steps = (long) (cells / DISTANCE_STEP_CELLS) + 1;
+ return (int) Math.min(steps * DISTANCE_STEP_CELLS, Integer.MAX_VALUE);
+ }
+
+ static int wedgeOf(int x, int z) {
+ int foldedX = -x;
+ int foldedZ = -z;
+ if (foldedX == 0 && foldedZ == 0) return WEDGE_COUNT / 2;
+
+ final int quadrant;
+ if (foldedX > 0 && foldedZ >= 0) {
+ quadrant = 0;
+ } else if (foldedX <= 0 && foldedZ > 0) {
+ quadrant = 1;
+ final int oldX = foldedX;
+ foldedX = foldedZ;
+ foldedZ = -oldX;
+ } else if (foldedX < 0) {
+ quadrant = 2;
+ foldedX = -foldedX;
+ foldedZ = -foldedZ;
+ } else {
+ quadrant = 3;
+ final int oldX = foldedX;
+ foldedX = -foldedZ;
+ foldedZ = oldX;
+ }
+
+ final int withinQuadrant;
+ if (foldedZ < foldedX) {
+ if (foldedZ < TAN_11_25_DEG * foldedX) withinQuadrant = 0;
+ else if (foldedZ < TAN_22_5_DEG * foldedX) withinQuadrant = 1;
+ else if (foldedZ < TAN_33_75_DEG * foldedX) withinQuadrant = 2;
+ else withinQuadrant = 3;
+ } else {
+ if (foldedX > TAN_33_75_DEG * foldedZ) withinQuadrant = 4;
+ else if (foldedX > TAN_22_5_DEG * foldedZ) withinQuadrant = 5;
+ else if (foldedX > TAN_11_25_DEG * foldedZ) withinQuadrant = 6;
+ else withinQuadrant = 7;
+ }
+
+ return quadrant * 8 + withinQuadrant;
+ }
+
+ static double driftAngle(double driftCells) {
+ final double nearestCulledCells = ALWAYS_DRAWN_CELLS - driftCells;
+ return nearestCulledCells <= driftCells ? Math.PI / 2.0 : Math.asin(driftCells / nearestCulledCells);
+ }
+}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java
deleted file mode 100644
index 868933f19..000000000
--- a/src/main/java/com/gtnewhorizons/angelica/render/CloudEdges.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.gtnewhorizons.angelica.render;
-
-import java.nio.ByteBuffer;
-
-final class CloudEdges {
- private static final int CELL_EMPTY_THRESHOLD = 10;
-
- final int width, height;
- private final int wMask, hMask;
- private final boolean whPow2;
- private final long[] opaqueBits;
- final int opaqueCount;
-
- CloudEdges(int width, int height, ByteBuffer rgba) {
- this.width = width;
- this.height = height;
- this.wMask = width - 1;
- this.hMask = height - 1;
- this.whPow2 = (width & wMask) == 0 && (height & hMask) == 0;
- final int total = width * height;
- final long[] bits = new long[(total + 63) >>> 6];
- int op = 0;
- for (int i = 0; i < total; i++) {
- if ((rgba.get(i * 4 + 3) & 0xFF) >= CELL_EMPTY_THRESHOLD) {
- bits[i >>> 6] |= 1L << (i & 63);
- op++;
- }
- }
- this.opaqueBits = bits;
- this.opaqueCount = op;
- }
-
- boolean cellOpaque(int x, int z) {
- final int xw, zh;
- if (whPow2) {
- xw = x & wMask;
- zh = z & hMask;
- } else {
- xw = Math.floorMod(x, width);
- zh = Math.floorMod(z, height);
- }
- final int idx = xw + zh * width;
- return ((opaqueBits[idx >>> 6] >>> (idx & 63)) & 1L) != 0L;
- }
-
- long readOpaqueRowBits(int x0, int z) {
- final int zMod, x0Mod;
- if (whPow2) {
- zMod = z & hMask;
- x0Mod = x0 & wMask;
- } else {
- zMod = Math.floorMod(z, height);
- x0Mod = Math.floorMod(x0, width);
- }
- if (x0Mod + 10 <= width) {
- return readContigBits(opaqueBits, (long) zMod * width + x0Mod, 10);
- }
- final int colsBeforeWrap = width - x0Mod;
- final long firstPart = readContigBits(opaqueBits, (long) zMod * width + x0Mod, colsBeforeWrap);
- final long secondPart = readContigBits(opaqueBits, (long) zMod * width, 10 - colsBeforeWrap);
- return firstPart | (secondPart << colsBeforeWrap);
- }
-
- private static long readContigBits(long[] bits, long startBitIdx, int count) {
- final int wordIdx = (int) (startBitIdx >>> 6);
- final int bitOff = (int) (startBitIdx & 63);
- final long mask = count == 64 ? -1L : (1L << count) - 1L;
- final long w0 = bits[wordIdx];
- if (bitOff + count <= 64) {
- return (w0 >>> bitOff) & mask;
- }
- final long w1 = bits[wordIdx + 1];
- return ((w0 >>> bitOff) | (w1 << (64 - bitOff))) & mask;
- }
-}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudFaceMesh.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudFaceMesh.java
new file mode 100644
index 000000000..2dea9ea07
--- /dev/null
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudFaceMesh.java
@@ -0,0 +1,304 @@
+package com.gtnewhorizons.angelica.render;
+
+import com.gtnewhorizons.angelica.glsm.GLStateManager;
+import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
+import org.lwjgl.BufferUtils;
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL15;
+
+import java.nio.ByteBuffer;
+import java.nio.IntBuffer;
+import java.util.Arrays;
+
+import static com.gtnewhorizons.angelica.render.CloudDisc.ALWAYS_DRAWN_CELLS;
+import static com.gtnewhorizons.angelica.render.CloudDisc.MARGIN_CELLS;
+import static com.gtnewhorizons.angelica.render.CloudDisc.WEDGE_COUNT;
+import static com.gtnewhorizons.angelica.render.CloudDisc.wedgeOf;
+
+/**
+ * Walls as one instanced face each.
+ */
+final class CloudFaceMesh {
+
+ static final int DIR_DOWN = 0, DIR_UP = 1, DIR_NORTH = 2, DIR_SOUTH = 3, DIR_WEST = 4, DIR_EAST = 5;
+ static final int CELL_LIMIT = 511;
+ private static final int FLAG_INSIDE = 1;
+ private static final int FACE_ATTRIB = 0;
+ /** cellX 10b | cellZ 10b | dir 3b | flags 2b. */
+ private static final int FACE_BYTES = 4;
+ private static final int INTERIOR_FACES = 6;
+ private static final int BUCKET_COUNT = WEDGE_COUNT + 1;
+ private static final int BUCKET_ALWAYS_DRAWN = 0;
+ private static final int BUCKET_WALL_WEDGE = 1;
+
+ private static final Tracy.ZoneId Z_STAMP_WALLS = Tracy.zoneId("cloudFaceStampWalls", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_UPLOAD = Tracy.zoneId("cloudFaceUpload", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_REORDER = Tracy.zoneId("cloudFaceReorder", Tracy.COLOR_CLIENT);
+ private final int[] wallStart = new int[WEDGE_COUNT + 1];
+ private final int[] plateStart = new int[WEDGE_COUNT + 1];
+ private int vao = -1;
+ private int vbo = -1;
+ private int ebo = -1;
+ private int vboCapacityBytes;
+ private int uploadedCount;
+ private int stampedCount;
+ private int interiorCount;
+ private int[] faceData = new int[4096];
+ private int[] faceSortKey = new int[4096];
+ private int[] sortKeyStart = new int[0];
+ private int ringsPerBucket = 1;
+ private int buildAnchorX = Integer.MIN_VALUE, buildAnchorZ = Integer.MIN_VALUE;
+ private int orderAnchorX = Integer.MIN_VALUE, orderAnchorZ = Integer.MIN_VALUE;
+ private CloudShape shape;
+ private ByteBuffer uploadBuffer;
+
+ int uploadedCount() {
+ return uploadedCount;
+ }
+
+ int interiorCount() {
+ return interiorCount;
+ }
+
+ int buildAnchorX() {
+ return buildAnchorX;
+ }
+
+ int buildAnchorZ() {
+ return buildAnchorZ;
+ }
+
+ void clear() {
+ uploadedCount = 0;
+ interiorCount = 0;
+ }
+
+ void build(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq, int wallCutCells) {
+ stampedCount = 0;
+ this.shape = shape;
+ ringsPerBucket = 2 * (radiusCells + MARGIN_CELLS) + 1;
+ buildAnchorX = anchorX;
+ buildAnchorZ = anchorZ;
+ orderAnchorX = anchorX;
+ orderAnchorZ = anchorZ;
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_STAMP_WALLS);
+ addWalls(shape, anchorX, anchorZ, radiusCells, radiusCellsSq, wallCutCells);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_UPLOAD);
+ finishBuild();
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+
+ private static int packFace(int cellX, int cellZ, int dir, int flags) {
+ return ((cellX + 512) & 0x3FF)
+ | (((cellZ + 512) & 0x3FF) << 10)
+ | (dir << 20)
+ | (flags << 23);
+ }
+
+ private void addFace(int cellX, int cellZ, int dir, int bucket, int ring) {
+ if (stampedCount + INTERIOR_FACES == faceSortKey.length) {
+ faceSortKey = Arrays.copyOf(faceSortKey, faceSortKey.length * 2);
+ faceData = Arrays.copyOf(faceData, faceData.length * 2);
+ }
+ faceData[stampedCount] = packFace(cellX, cellZ, dir, 0);
+ faceSortKey[stampedCount] = bucket * ringsPerBucket + ring;
+ stampedCount++;
+ }
+
+ private void stampInterior(int anchorX, int anchorZ) {
+ interiorCount = 0;
+ if (shape == null || (shape.cellFlagsAt(anchorX, anchorZ) & CloudShape.OPAQUE) == 0) return;
+
+ final int driftX = anchorX - buildAnchorX;
+ final int driftZ = anchorZ - buildAnchorZ;
+ for (int dir = DIR_DOWN; dir <= DIR_EAST; dir++) {
+ faceData[uploadedCount + dir] = packFace(driftX, driftZ, dir, FLAG_INSIDE);
+ }
+ interiorCount = INTERIOR_FACES;
+ }
+
+ private void addWalls(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq, int wallCutCells) {
+ stampWallRuns(shape, shape.westRuns, DIR_WEST, true, anchorX, anchorZ, radiusCells, radiusCellsSq, wallCutCells);
+ stampWallRuns(shape, shape.eastRuns, DIR_EAST, true, anchorX, anchorZ, radiusCells, radiusCellsSq, wallCutCells);
+ stampWallRuns(shape, shape.northRuns, DIR_NORTH, false, anchorX, anchorZ, radiusCells, radiusCellsSq, wallCutCells);
+ stampWallRuns(shape, shape.southRuns, DIR_SOUTH, false, anchorX, anchorZ, radiusCells, radiusCellsSq, wallCutCells);
+ }
+
+ private void stampWallRuns(CloudShape shape, int[] runs, int dir, boolean alongZ, int anchorX, int anchorZ,
+ int radiusCells, int radiusCellsSq, int wallCutCells) {
+ final int texW = shape.width;
+ final int texH = shape.height;
+ final int minCell = -radiusCells;
+ final int maxCell = radiusCells;
+ final int nearAlwaysSq = ALWAYS_DRAWN_CELLS * ALWAYS_DRAWN_CELLS;
+ final int wallCutSq = wallCutCells >= radiusCells ? Integer.MAX_VALUE : wallCutCells * wallCutCells;
+
+ for (int r = 0; r < runs.length; r += 3) {
+ final int runLength = runs[r + 2];
+ final int baseX = Math.floorMod(runs[r] - anchorX, texW);
+ final int baseZ = Math.floorMod(runs[r + 1] - anchorZ, texH);
+
+ for (int kz = Math.floorDiv(minCell - baseZ - (alongZ ? runLength - 1 : 0), texH); kz <= Math.floorDiv(maxCell - baseZ, texH); kz++) {
+ final int runZ = baseZ + kz * texH;
+ for (int kx = Math.floorDiv(minCell - baseX - (alongZ ? 0 : runLength - 1), texW); kx <= Math.floorDiv(maxCell - baseX, texW); kx++) {
+ final int runX = baseX + kx * texW;
+
+ for (int step = 0; step < runLength; step++) {
+ final int cellX = alongZ ? runX : runX + step;
+ final int cellZ = alongZ ? runZ + step : runZ;
+
+ if (dir == DIR_WEST ? cellX < 1 - MARGIN_CELLS
+ : dir == DIR_EAST ? cellX > MARGIN_CELLS - 1
+ : dir == DIR_NORTH ? cellZ < 1 - MARGIN_CELLS
+ : cellZ > MARGIN_CELLS - 1) {
+ continue;
+ }
+
+ final int distSq = cellX * cellX + cellZ * cellZ;
+ if (distSq > radiusCellsSq) continue;
+ final boolean near = distSq <= nearAlwaysSq;
+ if (!near && distSq > wallCutSq) continue;
+
+ final int bucket = near ? BUCKET_ALWAYS_DRAWN : BUCKET_WALL_WEDGE + wedgeOf(cellX, cellZ);
+ addFace(cellX, cellZ, dir, bucket, Math.abs(cellX) + Math.abs(cellZ));
+ }
+ }
+ }
+ }
+ }
+
+ boolean orderStale(int anchorX, int anchorZ) {
+ return anchorX != orderAnchorX || anchorZ != orderAnchorZ;
+ }
+
+ void reorder(int anchorX, int anchorZ) {
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_REORDER);
+ try {
+ final int driftX = anchorX - buildAnchorX;
+ final int driftZ = anchorZ - buildAnchorZ;
+ final int nearAlwaysSq = ALWAYS_DRAWN_CELLS * ALWAYS_DRAWN_CELLS;
+ for (int i = 0; i < uploadedCount; i++) {
+ final int packed = faceData[i];
+ final int cellX = (packed & 0x3FF) - 512 - driftX;
+ final int cellZ = ((packed >> 10) & 0x3FF) - 512 - driftZ;
+ final int distSq = cellX * cellX + cellZ * cellZ;
+ final int bucket = distSq <= nearAlwaysSq ? BUCKET_ALWAYS_DRAWN : BUCKET_WALL_WEDGE + wedgeOf(cellX, cellZ);
+ final int ring = Math.min(Math.abs(cellX) + Math.abs(cellZ), ringsPerBucket - 1);
+ faceSortKey[i] = bucket * ringsPerBucket + ring;
+ }
+ stampInterior(anchorX, anchorZ);
+ sortAndUpload();
+ orderAnchorX = anchorX;
+ orderAnchorZ = anchorZ;
+ } finally {
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+ }
+
+ private void finishBuild() {
+ uploadedCount = stampedCount;
+ stampInterior(buildAnchorX, buildAnchorZ);
+ if (uploadedCount == 0) Arrays.fill(wallStart, 0);
+ sortAndUpload();
+ }
+
+ private void sortAndUpload() {
+ final int sortKeyCount = BUCKET_COUNT * ringsPerBucket;
+ if (sortKeyStart.length < sortKeyCount + 1) sortKeyStart = new int[sortKeyCount + 1];
+ else Arrays.fill(sortKeyStart, 0, sortKeyCount + 1, 0);
+
+ for (int i = 0; i < uploadedCount; i++) sortKeyStart[faceSortKey[i]]++;
+ int acc = 0;
+ for (int k = 0; k < sortKeyCount; k++) {
+ final int keyTotal = sortKeyStart[k];
+ sortKeyStart[k] = acc;
+ acc += keyTotal;
+ }
+ sortKeyStart[sortKeyCount] = acc;
+
+ for (int w = 0; w < WEDGE_COUNT; w++) wallStart[w] = sortKeyStart[(BUCKET_WALL_WEDGE + w) * ringsPerBucket];
+ wallStart[WEDGE_COUNT] = uploadedCount;
+
+ final int totalFaces = uploadedCount + interiorCount;
+ if (totalFaces == 0) return;
+
+ final int uploadBytes = totalFaces * FACE_BYTES;
+ if (uploadBuffer == null || uploadBuffer.capacity() < uploadBytes) {
+ uploadBuffer = BufferUtils.createByteBuffer(Math.max(uploadBytes, 8192));
+ }
+ uploadBuffer.clear();
+ final IntBuffer ints = uploadBuffer.asIntBuffer();
+ for (int i = 0; i < uploadedCount; i++) {
+ ints.put(sortKeyStart[faceSortKey[i]]++, faceData[i]);
+ }
+ for (int i = 0; i < interiorCount; i++) {
+ ints.put(uploadedCount + i, faceData[uploadedCount + i]);
+ }
+ uploadBuffer.position(0).limit(uploadBytes);
+
+ final boolean freshBuffers = vbo == -1;
+ if (freshBuffers) vbo = GLStateManager.glGenBuffers();
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
+ if (uploadBytes > vboCapacityBytes) {
+ GLStateManager.glBufferData(GL15.GL_ARRAY_BUFFER, uploadBuffer, GL15.GL_DYNAMIC_DRAW);
+ vboCapacityBytes = uploadBytes;
+ } else {
+ GLStateManager.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, uploadBuffer);
+ }
+
+ if (freshBuffers) {
+ ensureQuadIndices();
+ if (vao == -1) vao = GLStateManager.glGenVertexArrays();
+ GLStateManager.glBindVertexArray(vao);
+ GLStateManager.glEnableVertexAttribArray(FACE_ATTRIB);
+ GLStateManager.glVertexAttribDivisor(FACE_ATTRIB, 1);
+ GLStateManager.glVertexAttribIPointer(FACE_ATTRIB, 1, GL11.GL_INT, FACE_BYTES, 0L);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ebo);
+ GLStateManager.glBindVertexArray(0);
+ }
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
+ }
+
+ private void ensureQuadIndices() {
+ if (ebo != -1) return;
+ ebo = GLStateManager.glGenBuffers();
+ final IntBuffer indices = BufferUtils.createIntBuffer(6);
+ indices.put(0).put(1).put(2).put(0).put(2).put(3);
+ indices.flip();
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, ebo);
+ GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indices, GL15.GL_STATIC_DRAW);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
+ }
+
+ void bind() {
+ GLStateManager.glBindVertexArray(vao);
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
+ }
+
+ void unbind() {
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
+ GLStateManager.glBindVertexArray(0);
+ }
+
+ void drawRange(int startFace, int endFace) {
+ final int faces = endFace - startFace;
+ if (faces <= 0) return;
+ GLStateManager.glVertexAttribIPointer(FACE_ATTRIB, 1, GL11.GL_INT, FACE_BYTES, (long) startFace * FACE_BYTES);
+ GLStateManager.glDrawElementsInstanced(GL11.GL_TRIANGLES, 6, GL11.GL_UNSIGNED_INT, 0L, faces);
+ }
+
+ void drawInterior() {
+ drawRange(uploadedCount, uploadedCount + interiorCount);
+ }
+
+ int[] plateStarts() {
+ return plateStart;
+ }
+
+ int[] wallStarts() {
+ return wallStart;
+ }
+}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudPlateCover.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudPlateCover.java
new file mode 100644
index 000000000..f4176ee60
--- /dev/null
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudPlateCover.java
@@ -0,0 +1,179 @@
+package com.gtnewhorizons.angelica.render;
+
+import java.util.Arrays;
+
+import static com.gtnewhorizons.angelica.render.CloudDisc.ALWAYS_DRAWN_CELLS;
+import static com.gtnewhorizons.angelica.render.CloudDisc.WEDGE_COUNT;
+import static com.gtnewhorizons.angelica.render.CloudDisc.wedgeOf;
+
+/**
+ * The plate rectangles that land inside the disc for one anchor.
+ */
+final class CloudPlateCover {
+
+ private final int[] wedgeBucketCount = new int[WEDGE_COUNT + 2];
+ private int[] rects = new int[4096 * 4];
+ private int[] rectWedgeBucket = new int[4096];
+ private int[] orderedRects = new int[4096];
+ private int count;
+ private boolean groupByWedge = true;
+
+ int count() {
+ return count;
+ }
+
+ int orderedRect(int order) {
+ return orderedRects[order];
+ }
+
+ int minX(int rect) {
+ return rects[rect * 4];
+ }
+
+ int minZ(int rect) {
+ return rects[rect * 4 + 1];
+ }
+
+ int maxX(int rect) {
+ return rects[rect * 4 + 2];
+ }
+
+ int maxZ(int rect) {
+ return rects[rect * 4 + 3];
+ }
+
+ int wedgeBucket(int rect) {
+ return rectWedgeBucket[rect];
+ }
+
+ void build(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq, int lodCells, boolean groupByWedge) {
+ count = 0;
+ this.groupByWedge = groupByWedge;
+ Arrays.fill(wedgeBucketCount, 0);
+
+ final int texW = shape.width;
+ final int texH = shape.height;
+ final int[] coarseRects = shape.coarsePlateRects;
+
+ if (coarseRects == null || lodCells >= radiusCells) {
+ stampRects(shape.plateRects, anchorX, anchorZ, texW, texH, radiusCells, radiusCellsSq, 0, 0, -1, -1, false);
+ } else {
+ final int fineX0 = 2 * Math.floorDiv(anchorX - lodCells, 2) - anchorX;
+ final int fineZ0 = 2 * Math.floorDiv(anchorZ - lodCells, 2) - anchorZ;
+ final int fineX1 = 2 * Math.floorDiv(anchorX + lodCells, 2) + 1 - anchorX;
+ final int fineZ1 = 2 * Math.floorDiv(anchorZ + lodCells, 2) + 1 - anchorZ;
+ stampRects(shape.plateRects, anchorX, anchorZ, texW, texH, radiusCells, radiusCellsSq, fineX0, fineZ0, fineX1, fineZ1, false);
+ stampRects(coarseRects, anchorX, anchorZ, texW, texH, radiusCells, radiusCellsSq, fineX0, fineZ0, fineX1, fineZ1, true);
+ }
+
+ if (groupByWedge) orderByWedge();
+ }
+
+ private void stampRects(int[] sourceRects, int anchorX, int anchorZ, int texW, int texH, int radiusCells, int radiusCellsSq,
+ int fineX0, int fineZ0, int fineX1, int fineZ1, boolean outsideFineBox) {
+ final int minCell = -radiusCells;
+ final int maxCell = radiusCells;
+
+ for (int r = 0; r < sourceRects.length; r += 4) {
+ final int rectW = sourceRects[r + 2];
+ final int rectH = sourceRects[r + 3];
+ final int baseX = Math.floorMod(sourceRects[r] - anchorX, texW);
+ final int baseZ = Math.floorMod(sourceRects[r + 1] - anchorZ, texH);
+
+ for (int kz = Math.floorDiv(minCell - rectH + 1 - baseZ, texH); kz <= Math.floorDiv(maxCell - baseZ, texH); kz++) {
+ final int cellZ0 = Math.max(baseZ + kz * texH, minCell);
+ final int cellZ1 = Math.min(baseZ + kz * texH + rectH - 1, maxCell);
+ if (cellZ0 > cellZ1) continue;
+
+ for (int kx = Math.floorDiv(minCell - rectW + 1 - baseX, texW); kx <= Math.floorDiv(maxCell - baseX, texW); kx++) {
+ final int cellX0 = Math.max(baseX + kx * texW, minCell);
+ final int cellX1 = Math.min(baseX + kx * texW + rectW - 1, maxCell);
+ if (cellX0 > cellX1) continue;
+
+ final boolean touchesFineBox = fineX1 >= fineX0
+ && cellX1 >= fineX0 && cellX0 <= fineX1 && cellZ1 >= fineZ0 && cellZ0 <= fineZ1;
+
+ if (fineX1 < fineX0) {
+ clipToDisc(cellX0, cellZ0, cellX1, cellZ1, radiusCellsSq);
+ } else if (!touchesFineBox) {
+ if (outsideFineBox) clipToDisc(cellX0, cellZ0, cellX1, cellZ1, radiusCellsSq);
+ } else if (!outsideFineBox) {
+ clipToDisc(Math.max(cellX0, fineX0), Math.max(cellZ0, fineZ0),
+ Math.min(cellX1, fineX1), Math.min(cellZ1, fineZ1), radiusCellsSq);
+ } else {
+ clipToDisc(cellX0, cellZ0, cellX1, Math.min(cellZ1, fineZ0 - 1), radiusCellsSq);
+ clipToDisc(cellX0, Math.max(cellZ0, fineZ1 + 1), cellX1, cellZ1, radiusCellsSq);
+ final int midZ0 = Math.max(cellZ0, fineZ0);
+ final int midZ1 = Math.min(cellZ1, fineZ1);
+ clipToDisc(cellX0, midZ0, Math.min(cellX1, fineX0 - 1), midZ1, radiusCellsSq);
+ clipToDisc(Math.max(cellX0, fineX1 + 1), midZ0, cellX1, midZ1, radiusCellsSq);
+ }
+ }
+ }
+ }
+ }
+
+ private void clipToDisc(int cellX0, int cellZ0, int cellX1, int cellZ1, int radiusCellsSq) {
+ if (cellX0 > cellX1 || cellZ0 > cellZ1) return;
+
+ final int farthestX = Math.max(Math.abs(cellX0), Math.abs(cellX1));
+ final int farthestZ = Math.max(Math.abs(cellZ0), Math.abs(cellZ1));
+ if (farthestX * farthestX + farthestZ * farthestZ <= radiusCellsSq) {
+ addRect(cellX0, cellZ0, cellX1, cellZ1);
+ return;
+ }
+
+ final int nearestX = (cellX0 <= 0 && cellX1 >= 0) ? 0 : Math.min(Math.abs(cellX0), Math.abs(cellX1));
+ final int nearestZ = (cellZ0 <= 0 && cellZ1 >= 0) ? 0 : Math.min(Math.abs(cellZ0), Math.abs(cellZ1));
+ if (nearestX * nearestX + nearestZ * nearestZ > radiusCellsSq) return;
+
+ for (int cellZ = cellZ0; cellZ <= cellZ1; cellZ++) {
+ final int halfWidth = (int) Math.sqrt(radiusCellsSq - cellZ * cellZ);
+ final int rowX0 = Math.max(cellX0, -halfWidth);
+ final int rowX1 = Math.min(cellX1, halfWidth);
+ if (rowX0 > rowX1) continue;
+ addRect(rowX0, cellZ, rowX1, cellZ);
+ }
+ }
+
+ private void addRect(int cellX0, int cellZ0, int cellX1, int cellZ1) {
+ int bucket = 0;
+ if (groupByWedge) {
+ final int nearestX = (cellX0 <= 0 && cellX1 >= 0) ? 0 : Math.min(Math.abs(cellX0), Math.abs(cellX1));
+ final int nearestZ = (cellZ0 <= 0 && cellZ1 >= 0) ? 0 : Math.min(Math.abs(cellZ0), Math.abs(cellZ1));
+ final boolean near = nearestX * nearestX + nearestZ * nearestZ <= ALWAYS_DRAWN_CELLS * ALWAYS_DRAWN_CELLS;
+
+ final int wedge = wedgeOf(cellX0, cellZ0);
+ if (!near
+ && wedge == wedgeOf(cellX1 + 1, cellZ0) && wedge == wedgeOf(cellX0, cellZ1 + 1) && wedge == wedgeOf(cellX1 + 1, cellZ1 + 1)) {
+ bucket = wedge + 1;
+ }
+ }
+
+ if (count * 4 + 4 > rects.length) {
+ rects = Arrays.copyOf(rects, rects.length * 2);
+ rectWedgeBucket = Arrays.copyOf(rectWedgeBucket, rectWedgeBucket.length * 2);
+ }
+ final int slot = count * 4;
+ rects[slot] = cellX0;
+ rects[slot + 1] = cellZ0;
+ rects[slot + 2] = cellX1;
+ rects[slot + 3] = cellZ1;
+ rectWedgeBucket[count] = bucket;
+ wedgeBucketCount[bucket]++;
+ count++;
+ }
+
+ private void orderByWedge() {
+ int acc = 0;
+ for (int b = 0; b <= WEDGE_COUNT + 1; b++) {
+ final int bucketTotal = wedgeBucketCount[b];
+ wedgeBucketCount[b] = acc;
+ acc += bucketTotal;
+ }
+ if (orderedRects.length < count) orderedRects = new int[count];
+ for (int i = 0; i < count; i++) {
+ orderedRects[wedgeBucketCount[rectWedgeBucket[i]]++] = i;
+ }
+ }
+}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java
index f19aa13f7..17a141469 100644
--- a/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudRenderer.java
@@ -21,11 +21,8 @@
package com.gtnewhorizons.angelica.render;
-import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
-import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
-import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType;
-import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
import com.gtnewhorizons.angelica.glsm.GLStateManager;
+import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
import com.gtnewhorizons.angelica.glsm.states.FogState;
import jss.notfine.core.Settings;
import jss.notfine.gui.options.named.GraphicsQualityOff;
@@ -54,112 +51,117 @@ import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
-import org.lwjgl.opengl.GL15;
import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import static com.gtnewhorizons.angelica.render.CloudDisc.CELLS_PER_CHUNK;
+import static com.gtnewhorizons.angelica.render.CloudDisc.MARGIN_CELLS;
+import static com.gtnewhorizons.angelica.render.CloudDisc.SCROLL_SPEED;
+import static com.gtnewhorizons.angelica.render.CloudDisc.WEDGE_COUNT;
+import static com.gtnewhorizons.angelica.render.CloudDisc.WEDGES_PER_RADIAN;
+
+/**
+ * Draws the cloud layer.
+ *
+ *
Per frame, in {@link #render}
+ *
+ * - Reduce the texture to cells, plate rectangles and wall runs into {@link CloudShape}.
+ *
- Convert the camera position to cell space: the anchor cell, the fraction across it, and how far the
+ * cloud base sits above the camera.
+ *
- Work out which faces the view needs: the underside, the top surface, or both when the camera is
+ * inside the deck.
+ *
- Get the two detail distances from {@link CloudDisc}: where walls stop being built, and where
+ * {@link CloudPlateCover} switches to coarse plate rectangles.
+ *
- Choose the mesher: {@link CloudFaceMesh} inside the deck, {@link CloudVertexMesh} elsewhere and
+ * always for shader packs.
+ *
- Pick the matching program depending on whether every solid texel is plain white.
+ *
- Rebuild when the cache is stale. {@link CloudVertexMesh} builds on a worker thread.
+ *
- Reorder near-to-far on every cell crossed, and keep the cell the camera sits in up to date.
+ *
- Upload matrices, fog and the texture scroll into {@link CloudUniforms}, then
+ * {@link #drawVisibleWedges}.
+ *
+ */
public class CloudRenderer implements IResourceManagerReloadListener {
- private static final byte F_TOP = 0, F_BOTTOM = 1, F_X = 2, F_Z = 3;
- private static final float[] FACTOR_VALUES = {0.7f, 1.0f, 0.9f, 0.8f}; // {top, bottom, X, Z}
- private static final int[] FACTOR_BYTE_SHIFTED;
- static {
- FACTOR_BYTE_SHIFTED = new int[4];
- for (int i = 0; i < 4; i++) {
- final int b = Math.round(FACTOR_VALUES[i] * 255f) & 0xFF;
- FACTOR_BYTE_SHIFTED[i] = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN) ? b : (b << 24);
- }
- }
- private static final int FACTOR_ATTRIB_LOC = 5;
-
- private static final int VERTEX_STRIDE = 24;
- private static final int NORMAL_OFFSET = 20;
- private static final int QUAD_BYTES = 4 * VERTEX_STRIDE;
-
- private static final int CELLS_PER_CHUNK = 8;
-
- private static final float SCROLL_SPEED = 1.0f / 256.0f;
- private static final float EDGE_OVERLAP = 0.0001f;
- private static final float INTERIOR_INSET = EDGE_OVERLAP * 8.0f;
+ private static final int MODE_FAST = 1;
+ private static final int MODE_FANCY = 2;
private static final float MAX_FAR_PLANE_DISTANCE = 65536.0f;
+ private static final int UPLOAD_SLICE_BYTES = 256 * 1024;
- private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
-
- private static final int N_POS_X = packNormalInt((byte) 127, (byte) 0, (byte) 0);
- private static final int N_NEG_X = packNormalInt((byte) -127, (byte) 0, (byte) 0);
- private static final int N_POS_Y = packNormalInt((byte) 0, (byte) 127, (byte) 0);
- private static final int N_NEG_Y = packNormalInt((byte) 0, (byte) -127, (byte) 0);
- private static final int N_POS_Z = packNormalInt((byte) 0, (byte) 0, (byte) 127);
- private static final int N_NEG_Z = packNormalInt((byte) 0, (byte) 0, (byte) -127);
-
+ private static final Tracy.ZoneId Z_RENDER = Tracy.zoneId("cloudRender", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_SUBMIT = Tracy.zoneId("cloudSubmit", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_DRAW = Tracy.zoneId("cloudDraw", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_ASYNC_BUILD = Tracy.zoneId("cloudAsyncBuild", Tracy.COLOR_CLIENT);
+ private static final Executor BUILD_THREAD = Executors.newSingleThreadExecutor(task -> {
+ final Thread thread = new Thread(task, "Angelica Cloud Builder");
+ thread.setDaemon(true);
+ thread.setPriority(Thread.NORM_PRIORITY - 1);
+ return thread;
+ });
+ private static CloudRenderer instance;
private final Minecraft mc = Minecraft.getMinecraft();
private final ResourceLocation texture = new ResourceLocation("textures/environment/clouds.png");
-
- private CloudEdges edges;
- private int edgesGeneration;
- private int texW, texH;
- private int mipmapTexId = -1;
+ private final CloudFaceMesh faceMesh = new CloudFaceMesh();
+ private CloudVertexMesh vertexMesh = new CloudVertexMesh();
+ private CloudVertexMesh spareMesh = new CloudVertexMesh();
+ private final CloudVertexMesh interiorMesh = new CloudVertexMesh();
+ private int interiorAnchorX = Integer.MIN_VALUE, interiorAnchorZ = Integer.MIN_VALUE;
+ private int interiorShapeGeneration = Integer.MIN_VALUE;
+ private float interiorCellHeight = Float.NaN;
+ private boolean interiorShadersActive, interiorActive;
+ private float interiorDriftX, interiorDriftZ;
+ private CompletableFuture buildInFlight;
+ private CompletableFuture reorderInFlight;
+ private CloudVertexMesh reorderMesh;
+ private BuildParams buildParams;
+ private BuildParams uploadParams;
+ private final Matrix4f mvpScratch = new Matrix4f();
+ private final Matrix4f mvpInteriorScratch = new Matrix4f();
+ private final Matrix4f modelViewScratch = new Matrix4f();
+ private CloudShape shape;
+ private int shapeGeneration;
+ private int cloudTextureWidth;
+ private int mipmappedTexId = -1;
private int cloudTexId = -1;
-
- private IVertexArrayObject vao;
- private int cachedVertexCount;
- private int eboId = -1;
- private int eboQuadCapacity;
-
+ private ByteBuffer texelStagingBuffer;
+ private boolean faceMeshActive;
private int anchorCellX = Integer.MIN_VALUE, anchorCellZ = Integer.MIN_VALUE;
- private int anchorMarginCells = 0;
- private int cachedEdgesGeneration = Integer.MIN_VALUE;
- private boolean cachedEmitTopFace, cachedEmitBottomFace;
- private int cachedRenderRadius = -1;
- private float cachedCloudInteriorHeight = Float.NaN;
- private boolean geomBuilt;
-
+ private int cachedShapeGeneration = Integer.MIN_VALUE;
+ private boolean cachedEmitUnderside, cachedEmitTopSurface;
+ private int cachedRenderRadiusChunks = -1;
+ private float cachedCellHeightBlocks = Float.NaN;
+ private boolean cachedShadersActive;
+ private int cachedWallCutCells = -1;
+ private int cachedPlateLodCells = -1;
+ private boolean geometryBuilt;
+ private int wallCutCells = Integer.MAX_VALUE;
+ private int plateLodCells = Integer.MAX_VALUE;
+ private int cachedFovDisplayHeight = -1;
+ private float cachedFovDegrees = Float.NaN;
+ private double cachedPixelsPerRadian;
private int cloudMode = -1, renderDistance = -1, cloudElevation = -1, scaleMult = -1;
private boolean enabled;
-
- private ByteBuffer emitBuffer;
- private long emitBufferAddr;
- private int emitBufferCapacity;
- private long writeAddr, writeEnd;
-
- private ByteBuffer sortedBuffer;
- private long sortedBufferAddr;
- private int sortedBufferCapacity;
-
- private ByteBuffer edgeStagingBuffer;
- private int edgeStagingCapacity;
-
- private byte[] quadFactor = new byte[2048];
- private int quadCount;
-
- private final int[] factorQuadCount = new int[4];
- private final int[] factorVertOffset = new int[4];
- private final long[] factorWriteAddr = new long[4];
-
- private final int[] chunkOpaqueRows = new int[10];
- private long[] globalEmit;
- private long[] globalEmitTodo;
- private int gridRows, gridCols, gridLongsPerRow, gridMinX, gridMinZ;
- private long[] runMaskScratch = new long[8];
-
+ private double driftCells;
+ private int arcFrom, arcTo;
+ private int drawCalls;
+ private boolean programUntextured, programFacesUntextured;
private GlProgram program;
- private final Matrix4f mvpScratch = new Matrix4f();
- private final Matrix4f mvScratch = new Matrix4f();
+ private GlProgram programVertex, programFaces;
public CloudRenderer() {
((IReloadableResourceManager) mc.getResourceManager()).registerReloadListener(this);
}
- private static CloudRenderer instance;
-
public static CloudRenderer getCloudRenderer() {
if (instance == null) instance = new CloudRenderer();
return instance;
}
public static int getCloudTextureWidth() {
- return instance != null && instance.texW > 0 ? instance.texW : 256;
+ return instance != null && instance.cloudTextureWidth > 0 ? instance.cloudTextureWidth : 256;
}
public static int getScaleMult() {
@@ -168,8 +170,8 @@ public class CloudRenderer implements IResourceManagerReloadListener {
public void checkSettings() {
final GraphicsQualityOff cloudGraphicsQuality = (GraphicsQualityOff) Settings.MODE_CLOUDS.option.getStore();
- final int cloudQualitySetting = cloudGraphicsQuality == GraphicsQualityOff.FANCY
- || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics ? 2 : 1;
+ final int newCloudMode = cloudGraphicsQuality == GraphicsQualityOff.FANCY
+ || cloudGraphicsQuality == GraphicsQualityOff.DEFAULT && mc.gameSettings.fancyGraphics ? MODE_FANCY : MODE_FAST;
final float dimCloudHeight = mc.theWorld == null ? 128.0f : mc.theWorld.provider.getCloudHeight();
final boolean finiteCloudHeight = Float.isFinite(dimCloudHeight);
final boolean newEnabled = cloudGraphicsQuality != GraphicsQualityOff.OFF
@@ -177,20 +179,20 @@ public class CloudRenderer implements IResourceManagerReloadListener {
&& mc.theWorld != null
&& mc.theWorld.provider.isSurfaceWorld()
&& finiteCloudHeight;
- final int targetDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int) Settings.RENDER_DISTANCE_CLOUDS.option.getStore());
- final int cloudScaleMult = (int) Settings.CLOUD_SCALE.option.getStore();
+ final int newRenderDistance = Math.max(mc.gameSettings.renderDistanceChunks, (int) Settings.RENDER_DISTANCE_CLOUDS.option.getStore());
+ final int newScaleMult = (int) Settings.CLOUD_SCALE.option.getStore();
if (!newEnabled
- || cloudQualitySetting != cloudMode
- || targetDistance != renderDistance
- || cloudScaleMult != scaleMult) {
+ || newCloudMode != cloudMode
+ || newRenderDistance != renderDistance
+ || newScaleMult != scaleMult) {
invalidateGeometry();
}
enabled = newEnabled;
- cloudMode = cloudQualitySetting;
- renderDistance = targetDistance;
- scaleMult = cloudScaleMult;
+ cloudMode = newCloudMode;
+ renderDistance = newRenderDistance;
+ scaleMult = newScaleMult;
cloudElevation = finiteCloudHeight ? (int) dimCloudHeight : 128;
}
@@ -201,12 +203,12 @@ public class CloudRenderer implements IResourceManagerReloadListener {
public float getRequiredFarPlaneDistance() {
if (!enabled || scaleMult <= 0 || renderDistance <= 0) return 0.0f;
if (mc.theWorld == null) return 0.0f;
- final float cloudInteriorWidth = 12.0f * scaleMult;
- final int renderRadius = (int) Math.ceil(renderDistance * 64.0f / (CELLS_PER_CHUNK * cloudInteriorWidth));
- final int marginCells = Math.max(CELLS_PER_CHUNK, renderRadius * CELLS_PER_CHUNK / 4);
- final int marginChunks = (marginCells + CELLS_PER_CHUNK - 1) / CELLS_PER_CHUNK;
- float radiusBlocks = (renderRadius + marginChunks) * CELLS_PER_CHUNK * cloudInteriorWidth;
- if (cloudMode != 2) radiusBlocks *= (float) Math.sqrt(2);
+ final float cellWidthBlocks = 12.0f * scaleMult;
+ final int renderRadiusChunks = (int) Math.ceil(renderDistance * 64.0f / (CELLS_PER_CHUNK * cellWidthBlocks));
+ final int marginChunks = (MARGIN_CELLS + CELLS_PER_CHUNK - 1) / CELLS_PER_CHUNK;
+ float radiusBlocks = (renderRadiusChunks + marginChunks) * CELLS_PER_CHUNK * cellWidthBlocks;
+ if (cloudMode != MODE_FANCY) radiusBlocks *= (float) Math.sqrt(2);
+ radiusBlocks += MARGIN_CELLS * cellWidthBlocks;
float verticalSlack = cloudElevation;
final Entity view = mc.renderViewEntity;
if (view != null) {
@@ -215,23 +217,65 @@ public class CloudRenderer implements IResourceManagerReloadListener {
return Math.min(radiusBlocks + verticalSlack, MAX_FAR_PLANE_DISTANCE);
}
+ private static boolean withinMargin(int driftX, int driftZ) {
+ return driftX * driftX + driftZ * driftZ <= MARGIN_CELLS * MARGIN_CELLS;
+ }
+
private void invalidateGeometry() {
anchorCellX = Integer.MIN_VALUE;
anchorCellZ = Integer.MIN_VALUE;
- cachedRenderRadius = -1;
- cachedEdgesGeneration = Integer.MIN_VALUE;
- cachedCloudInteriorHeight = Float.NaN;
- cachedVertexCount = 0;
- geomBuilt = false;
+ cachedRenderRadiusChunks = -1;
+ cachedShapeGeneration = Integer.MIN_VALUE;
+ cachedCellHeightBlocks = Float.NaN;
+ cancelAsyncBuild();
+ vertexMesh.clear();
+ spareMesh.clear();
+ interiorMesh.clear();
+ interiorAnchorX = Integer.MIN_VALUE;
+ interiorAnchorZ = Integer.MIN_VALUE;
+ interiorActive = false;
+ faceMesh.clear();
+ geometryBuilt = false;
}
- private void initProgram() {
- if (program != null) return;
+ private void initProgram(boolean useFaceMesh) {
+ final boolean untextured = untextured();
+ if (programFaces != null && programFacesUntextured != untextured) {
+ programFaces.delete();
+ programFaces = null;
+ }
+ if (programFaces == null) {
+ programFaces = buildProgram(true, untextured);
+ programFacesUntextured = untextured;
+ }
- final GlShader vert = ShaderLoader.loadShader(ShaderType.VERTEX, "angelica:cloud.vert", ShaderConstants.EMPTY);
- final GlShader frag = ShaderLoader.loadShader(ShaderType.FRAGMENT, "angelica:cloud.frag", ShaderConstants.EMPTY);
+ if (programVertex != null && programUntextured != untextured) {
+ programVertex.delete();
+ programVertex = null;
+ }
+ if (programVertex == null) {
+ programVertex = buildProgram(false, untextured);
+ programUntextured = untextured;
+ }
+
+ program = useFaceMesh ? programFaces : programVertex;
+ }
+
+ private boolean untextured() {
+ return cloudMode == MODE_FANCY && shape != null && shape.opaqueTexelsAllWhite;
+ }
+
+ private GlProgram buildProgram(boolean forFaceMesh, boolean untextured) {
+ final ShaderConstants.Builder builder = ShaderConstants.builder();
+ if (untextured) builder.add("UNTEXTURED");
+ final ShaderConstants constants = builder.build();
+ final String vertName = forFaceMesh ? "angelica:cloud_faces.vert" : "angelica:cloud.vert";
+ final String fragName = forFaceMesh ? "angelica:cloud_faces.frag" : "angelica:cloud.frag";
+ final GlShader vert = ShaderLoader.loadShader(ShaderType.VERTEX, vertName, constants);
+ final GlShader frag = ShaderLoader.loadShader(ShaderType.FRAGMENT, fragName, constants);
+ final GlProgram built;
try {
- program = GlProgram.builder("angelica:cloud")
+ built = GlProgram.builder("angelica:cloud")
.attachShader(vert)
.attachShader(frag)
.link(CloudUniforms::new);
@@ -240,30 +284,40 @@ public class CloudRenderer implements IResourceManagerReloadListener {
frag.delete();
}
- program.bind();
- program.getInterface().tex.setInt(0);
- program.unbind();
+ built.bind();
+ if (!untextured) built.getInterface().textureUnit.setInt(0);
+ built.unbind();
+ return built;
}
- private void uploadFogUniforms() {
- final CloudUniforms u = program.getInterface();
+ private void uploadFogUniforms(CloudUniforms uniforms, float fogStart, float fogEnd) {
final boolean fogEnabled = GLStateManager.getFogMode().isEnabled();
- u.setFogEnabled(fogEnabled);
+ uniforms.setFogEnabled(fogEnabled);
if (!fogEnabled) return;
final FogState fog = GLStateManager.getFogState();
final Vector3d color = fog.getFogColor();
- u.setFogColor((float) color.x, (float) color.y, (float) color.z);
+ uniforms.setFogColor((float) color.x, (float) color.y, (float) color.z);
switch (fog.getFogMode()) {
case GL11.GL_LINEAR -> {
- final float range = fog.getEnd() - fog.getStart();
- u.setFogParams(range != 0.0f ? -1.0f / range : 0.0f, range != 0.0f ? fog.getEnd() / range : 1.0f, 0.0f, 0.0f);
+ final float range = fogEnd - fogStart;
+ uniforms.setFogParams(range != 0.0f ? -1.0f / range : 0.0f, range != 0.0f ? fogEnd / range : 1.0f, 0.0f, 0.0f);
}
- case GL11.GL_EXP -> u.setFogParams(0.0f, 0.0f, fog.getDensity(), 1.0f);
- default -> u.setFogParams(0.0f, 0.0f, fog.getDensity(), 2.0f);
+ case GL11.GL_EXP -> uniforms.setFogParams(0.0f, 0.0f, fog.getDensity(), 1.0f);
+ default -> uniforms.setFogParams(0.0f, 0.0f, fog.getDensity(), 2.0f);
}
}
public boolean render(int cloudTicks, float partialTicks) {
+ if (!Tracy.ENABLED) return renderInner(cloudTicks, partialTicks);
+ Tracy.beginZone(Z_RENDER);
+ try {
+ return renderInner(cloudTicks, partialTicks);
+ } finally {
+ Tracy.endZone();
+ }
+ }
+
+ private boolean renderInner(int cloudTicks, float partialTicks) {
if (mc.theWorld == null || mc.renderViewEntity == null) return false;
if (!enabled || scaleMult <= 0) return false;
@@ -271,70 +325,134 @@ public class CloudRenderer implements IResourceManagerReloadListener {
if (pipeline != null && pipeline.getCloudSetting() == CloudSetting.OFF) return false;
boolean textureSetupDone = false;
- if (edges == null) {
+ if (shape == null) {
if (mc.renderEngine == null) return false;
mc.renderEngine.bindTexture(texture);
setupCloudTexture();
textureSetupDone = true;
- if (edges == null) return false;
- }
- if (program == null) {
- initProgram();
- if (program == null) return false;
+ if (shape == null) return false;
}
- final Entity entity = mc.renderViewEntity;
- final float cloudInteriorWidth = 12.0f * scaleMult;
- final float cloudInteriorHeight = 4.0f * scaleMult;
+ final Entity viewEntity = mc.renderViewEntity;
+ final float cellWidthBlocks = 12.0f * scaleMult;
+ final float cellHeightBlocks = 4.0f * scaleMult;
final double cloudTick = cloudTicks + (double) partialTicks;
- final float cameraOffsetY = (float) (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks);
- double cameraOffsetX = (entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks + cloudTick * 0.03D) / cloudInteriorWidth;
- double cameraOffsetZ = (entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks) / cloudInteriorWidth;
- cameraOffsetX -= MathHelper.floor_double(cameraOffsetX / 2048.0D) * 2048;
- cameraOffsetZ -= MathHelper.floor_double(cameraOffsetZ / 2048.0D) * 2048;
+ final float cameraY = (float) (viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks);
+ double cameraCellX = (viewEntity.prevPosX + (viewEntity.posX - viewEntity.prevPosX) * partialTicks + cloudTick * 0.03D) / cellWidthBlocks;
+ double cameraCellZ = (viewEntity.prevPosZ + (viewEntity.posZ - viewEntity.prevPosZ) * partialTicks) / cellWidthBlocks
+ + 0.33000001311302185D;
+ cameraCellX -= MathHelper.floor_double(cameraCellX / 2048.0D) * 2048;
+ cameraCellZ -= MathHelper.floor_double(cameraCellZ / 2048.0D) * 2048;
- final float cameraRelativeY = cloudElevation - cameraOffsetY + 0.33F;
- final float cameraRelativeX = (float) (cameraOffsetX - MathHelper.floor_double(cameraOffsetX));
- final float cameraRelativeZ = (float) (cameraOffsetZ - MathHelper.floor_double(cameraOffsetZ));
+ final float cloudBaseRelativeY = cloudElevation - cameraY + 0.33F;
+ final float cellFractionX = (float) (cameraCellX - MathHelper.floor_double(cameraCellX));
+ final float cellFractionZ = (float) (cameraCellZ - MathHelper.floor_double(cameraCellZ));
- final int anchorX = MathHelper.floor_double(cameraOffsetX);
- final int anchorZ = MathHelper.floor_double(cameraOffsetZ);
+ final int anchorX = MathHelper.floor_double(cameraCellX);
+ final int anchorZ = MathHelper.floor_double(cameraCellZ);
- final boolean emitTopFace = cameraRelativeY + cloudInteriorHeight >= 0.0F;
- final boolean emitBottomFace = cameraRelativeY <= 0.0F;
+ final boolean emitUnderside = cloudBaseRelativeY + cellHeightBlocks >= 0.0F;
+ final boolean emitTopSurface = cloudBaseRelativeY <= 0.0F;
+ final boolean insideDeck = emitUnderside && emitTopSurface;
- final int renderRadius = (int) Math.ceil(renderDistance * 64.0f / (CELLS_PER_CHUNK * cloudInteriorWidth));
+ final int renderRadiusChunks = (int) Math.ceil(renderDistance * 64.0f / (CELLS_PER_CHUNK * cellWidthBlocks));
- final boolean insideBand = cloudMode == 2 && emitTopFace && emitBottomFace;
- final boolean anchorInRange = geomBuilt
- && (insideBand
- ? anchorX == anchorCellX && anchorZ == anchorCellZ
- : Math.abs(anchorX - anchorCellX) <= anchorMarginCells
- && Math.abs(anchorZ - anchorCellZ) <= anchorMarginCells);
- final boolean geomCacheValid = anchorInRange
- && cachedEdgesGeneration == edgesGeneration
- && cachedEmitTopFace == emitTopFace
- && cachedEmitBottomFace == emitBottomFace
- && cachedRenderRadius == renderRadius
- && cachedCloudInteriorHeight == cloudInteriorHeight;
+ final boolean shadersActive = IrisApi.getInstance().isShaderPackInUse();
+ final boolean backFaceCulling = cullBackFaces();
- if (!geomCacheValid) {
- final int marginCells = Math.max(CELLS_PER_CHUNK, renderRadius * CELLS_PER_CHUNK / 4);
- rebuildGeometry(anchorX, anchorZ, renderRadius, cloudInteriorHeight, emitTopFace, emitBottomFace, marginCells);
- anchorCellX = anchorX;
- anchorCellZ = anchorZ;
- anchorMarginCells = marginCells;
- cachedEdgesGeneration = edgesGeneration;
- cachedEmitTopFace = emitTopFace;
- cachedEmitBottomFace = emitBottomFace;
- cachedRenderRadius = renderRadius;
- cachedCloudInteriorHeight = cloudInteriorHeight;
- geomBuilt = true;
+ final float fovDegrees = mc.gameSettings == null ? 70.0f : mc.gameSettings.fovSetting;
+ if (mc.displayHeight != cachedFovDisplayHeight || fovDegrees != cachedFovDegrees) {
+ cachedPixelsPerRadian = CloudDisc.pixelsPerRadian(mc.displayHeight, fovDegrees);
+ cachedFovDisplayHeight = mc.displayHeight;
+ cachedFovDegrees = fovDegrees;
+ }
+ final double pixelsPerRadian = cachedPixelsPerRadian;
+ wallCutCells = CloudDisc.wallCutCells(pixelsPerRadian, !(backFaceCulling && insideDeck));
+ plateLodCells = CloudDisc.plateLodCells(pixelsPerRadian, cloudBaseRelativeY, cellWidthBlocks,
+ shape.coarsePlateRects != null && shape.opaqueTexelsAllWhite);
+
+ final int marginChunks = (MARGIN_CELLS + CELLS_PER_CHUNK - 1) / CELLS_PER_CHUNK;
+ final int radiusChunks = renderRadiusChunks + marginChunks;
+ final int radiusCells = radiusChunks * CELLS_PER_CHUNK;
+ faceMeshActive = !shadersActive && insideDeck && radiusCells <= CloudFaceMesh.CELL_LIMIT;
+
+ initProgram(faceMeshActive);
+ if (program == null) return false;
+
+ final boolean anchorInRange = geometryBuilt
+ && withinMargin(anchorX - anchorCellX, anchorZ - anchorCellZ);
+ final boolean settingsUnchanged = geometryBuilt
+ && cachedShapeGeneration == shapeGeneration
+ && cachedEmitUnderside == emitUnderside
+ && cachedEmitTopSurface == emitTopSurface
+ && cachedRenderRadiusChunks == renderRadiusChunks
+ && cachedCellHeightBlocks == cellHeightBlocks
+ && cachedShadersActive == shadersActive
+ && cachedWallCutCells == wallCutCells
+ && (faceMeshActive || cachedPlateLodCells == plateLodCells);
+ final boolean geomCacheValid = anchorInRange && settingsUnchanged;
+
+ final boolean canBuildAsync = settingsUnchanged && !faceMeshActive && vertexMesh.built();
+
+ final boolean builderBusy = buildInFlight != null || uploadParams != null;
+ if (!geomCacheValid && !(canBuildAsync && builderBusy)) {
+ final BuildParams params = captureBuildParams(anchorX, anchorZ, radiusCells, renderRadiusChunks,
+ cellHeightBlocks, emitUnderside, emitTopSurface, shadersActive, backFaceCulling);
+ if (canBuildAsync) {
+ startAsyncBuild(params);
+ } else {
+ cancelAsyncBuild();
+ if (faceMeshActive) {
+ faceMesh.build(shape, anchorX, anchorZ, radiusCells, radiusCells * radiusCells, wallCutCells);
+ } else {
+ buildVertexMesh(vertexMesh, params);
+ vertexMesh.uploadBuilt();
+ }
+ markGeometryCached(params);
+ }
}
- if (vao == null || cachedVertexCount == 0) return true;
+ collectFinishedBuild();
+ final boolean wantInterior = insideDeck && cloudMode == MODE_FANCY && !faceMeshActive;
+ if (wantInterior && (interiorAnchorX != anchorX || interiorAnchorZ != anchorZ
+ || interiorShapeGeneration != shapeGeneration || interiorCellHeight != cellHeightBlocks
+ || interiorShadersActive != shadersActive)) {
+ interiorMesh.buildInterior(shape, anchorX, anchorZ, cellHeightBlocks,
+ anchorX * SCROLL_SPEED, anchorZ * SCROLL_SPEED, untextured() && !shadersActive, shadersActive);
+ interiorMesh.uploadBuilt();
+ interiorAnchorX = anchorX;
+ interiorAnchorZ = anchorZ;
+ interiorShapeGeneration = shapeGeneration;
+ interiorCellHeight = cellHeightBlocks;
+ interiorShadersActive = shadersActive;
+ }
+ interiorActive = wantInterior && interiorMesh.built();
+
+ if (faceMeshActive) {
+ if (faceMesh.orderStale(anchorX, anchorZ)) faceMesh.reorder(anchorX, anchorZ);
+ if (faceMesh.uploadedCount() == 0 && faceMesh.interiorCount() == 0) return true;
+ } else if (!vertexMesh.built()) {
+ return true;
+ }
+
+ if (!faceMeshActive && !shadersActive && cloudMode == MODE_FANCY) {
+ if (reorderInFlight != null && reorderInFlight.isDone()) {
+ final boolean usable = !reorderInFlight.isCompletedExceptionally() && reorderMesh == vertexMesh;
+ reorderInFlight = null;
+ reorderMesh = null;
+ if (usable) vertexMesh.reorderUpload();
+ else vertexMesh.discardPendingReorder();
+ }
+ if (reorderInFlight == null && vertexMesh.orderStale(anchorX, anchorZ)) {
+ final CloudVertexMesh target = vertexMesh;
+ reorderMesh = target;
+ reorderInFlight = CompletableFuture.runAsync(() -> target.reorder(anchorX, anchorZ), BUILD_THREAD);
+ }
+ }
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_SUBMIT);
GLStateManager.glActiveTexture(GL13.GL_TEXTURE0);
if (cloudTexId != -1 && !textureSetupDone) {
GLStateManager.glBindTexture(GL11.GL_TEXTURE_2D, cloudTexId);
@@ -356,42 +474,59 @@ public class CloudRenderer implements IResourceManagerReloadListener {
b = tempB;
}
- final boolean shadersActive = IrisApi.getInstance().isShaderPackInUse();
-
final float origFogStart = GLStateManager.getFogState().getStart();
final float origFogEnd = GLStateManager.getFogState().getEnd();
- final float cloudExtentBlocks = renderRadius * CELLS_PER_CHUNK * cloudInteriorWidth;
- final boolean pushFog = GLStateManager.getFogMode().isEnabled() && GLStateManager.getFogState().getFogMode() == GL11.GL_LINEAR && origFogEnd < cloudExtentBlocks;
+ final float cloudExtentBlocks = renderRadiusChunks * CELLS_PER_CHUNK * cellWidthBlocks;
+ final boolean stretchFog = GLStateManager.getFogMode().isEnabled()
+ && GLStateManager.getFogState().getFogMode() == GL11.GL_LINEAR
+ && origFogEnd > 0.0f
+ && origFogEnd < cloudExtentBlocks;
+ final float fogStart = stretchFog ? origFogStart * (cloudExtentBlocks / origFogEnd) : origFogStart;
+ final float fogEnd = stretchFog ? cloudExtentBlocks : origFogEnd;
+
+ final boolean pushFog = stretchFog && shadersActive;
if (pushFog) {
- final float ratio = cloudExtentBlocks / origFogEnd;
- GLStateManager.glFogf(GL11.GL_FOG_START, origFogStart * ratio);
- GLStateManager.glFogf(GL11.GL_FOG_END, cloudExtentBlocks);
+ GLStateManager.glFogf(GL11.GL_FOG_START, fogStart);
+ GLStateManager.glFogf(GL11.GL_FOG_END, fogEnd);
}
final float anchorDriftX = (float) (anchorX - anchorCellX);
final float anchorDriftZ = (float) (anchorZ - anchorCellZ);
+ driftCells = Math.sqrt(anchorDriftX * anchorDriftX + anchorDriftZ * anchorDriftZ);
+
+ interiorDriftX = anchorDriftX;
+ interiorDriftZ = anchorDriftZ;
if (!shadersActive) {
program.bind();
- final CloudUniforms u = program.getInterface();
- final Matrix4fStack mv = GLStateManager.getModelViewMatrix();
- mv.pushMatrix();
- mv.scale(cloudInteriorWidth, 1.0f, cloudInteriorWidth);
- mv.translate(-(cameraRelativeX + anchorDriftX), cameraRelativeY, -(cameraRelativeZ + anchorDriftZ));
- mvScratch.set(mv);
- GLStateManager.getProjectionMatrix().mul(mv, mvpScratch);
- mv.popMatrix();
- u.mvp.set(mvpScratch);
- u.mv.set(mvScratch);
- uploadFogUniforms();
-
- drawAllFactors(r, g, b, false);
+ final CloudUniforms uniforms = program.getInterface();
+ final Matrix4fStack modelView = GLStateManager.getModelViewMatrix();
+ modelView.pushMatrix();
+ modelView.scale(cellWidthBlocks, 1.0f, cellWidthBlocks);
+ if (interiorActive) {
+ modelView.pushMatrix();
+ modelView.translate(-cellFractionX, cloudBaseRelativeY, -cellFractionZ);
+ GLStateManager.getProjectionMatrix().mul(modelView, mvpInteriorScratch);
+ modelView.popMatrix();
+ }
+ modelView.translate(-(cellFractionX + anchorDriftX), cloudBaseRelativeY, -(cellFractionZ + anchorDriftZ));
+ modelViewScratch.set(modelView);
+ GLStateManager.getProjectionMatrix().mul(modelView, mvpScratch);
+ modelView.popMatrix();
+ uniforms.mvp.set(mvpScratch);
+ uniforms.modelView.set(modelViewScratch);
+ if (faceMeshActive) {
+ uniforms.setCellHeight(cellHeightBlocks);
+ uniforms.setScroll(faceMesh.buildAnchorX() * SCROLL_SPEED, faceMesh.buildAnchorZ() * SCROLL_SPEED);
+ }
+ uploadFogUniforms(uniforms, fogStart, fogEnd);
+ drawClouds(r, g, b, false);
program.unbind();
} else {
GLStateManager.glPushMatrix();
- GLStateManager.glScalef(cloudInteriorWidth, 1.0f, cloudInteriorWidth);
- GLStateManager.glTranslatef(-(cameraRelativeX + anchorDriftX), cameraRelativeY, -(cameraRelativeZ + anchorDriftZ));
- drawAllFactors(r, g, b, true);
+ GLStateManager.glScalef(cellWidthBlocks, 1.0f, cellWidthBlocks);
+ GLStateManager.glTranslatef(-(cellFractionX + anchorDriftX), cloudBaseRelativeY, -(cellFractionZ + anchorDriftZ));
+ drawClouds(r, g, b, true);
GLStateManager.glPopMatrix();
}
@@ -399,606 +534,393 @@ public class CloudRenderer implements IResourceManagerReloadListener {
GLStateManager.glFogf(GL11.GL_FOG_START, origFogStart);
GLStateManager.glFogf(GL11.GL_FOG_END, origFogEnd);
}
+ if (Tracy.FINE_ZONES) Tracy.endZone();
return true;
}
- private void drawAllFactors(float r, float g, float b, boolean shadersActive) {
- vao.bind();
- GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId);
- GLStateManager.disableCull();
+ private record BuildParams(CloudShape shape, boolean fancy, int anchorX, int anchorZ, int radiusCells,
+ float cellHeightBlocks, boolean emitUnderside, boolean emitTopSurface, boolean emitPlates,
+ boolean shadersActive, int wallCutCells, int plateLodCells, boolean untextured,
+ int shapeGeneration, int renderRadiusChunks) {}
- GLStateManager.disableBlend();
- GLStateManager.glDepthMask(true);
- GLStateManager.glColorMask(false, false, false, false);
- if (shadersActive) {
- GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, CloudUniforms.ALPHA);
+ private BuildParams captureBuildParams(int anchorX, int anchorZ, int radiusCells, int renderRadiusChunks,
+ float cellHeightBlocks, boolean emitUnderside, boolean emitTopSurface,
+ boolean shadersActive, boolean backFaceCulling) {
+ return new BuildParams(shape, cloudMode == MODE_FANCY, anchorX, anchorZ, radiusCells, cellHeightBlocks,
+ emitUnderside, emitTopSurface, !(backFaceCulling && emitUnderside && emitTopSurface), shadersActive,
+ wallCutCells, plateLodCells, untextured() && !shadersActive, shapeGeneration, renderRadiusChunks);
+ }
+
+ private static void buildVertexMesh(CloudVertexMesh mesh, BuildParams p) {
+ final float scrollX = p.anchorX() * SCROLL_SPEED;
+ final float scrollZ = p.anchorZ() * SCROLL_SPEED;
+
+ if (!p.fancy()) {
+ mesh.buildFast(p.radiusCells(), scrollX, scrollZ, p.shadersActive());
+ return;
}
- final int totalQuads = cachedVertexCount / 4;
- GLStateManager.glDrawElements(GL11.GL_TRIANGLES, totalQuads * 6, GL11.GL_UNSIGNED_INT, 0L);
- if (!mc.gameSettings.anaglyph) {
- GLStateManager.glColorMask(true, true, true, true);
- } else {
- switch (EntityRenderer.anaglyphField) {
- case 0 -> GLStateManager.glColorMask(false, true, true, true);
- case 1 -> GLStateManager.glColorMask(true, false, false, true);
- default -> GLStateManager.glColorMask(true, true, true, true);
+ mesh.build(p.shape(), p.anchorX(), p.anchorZ(), p.radiusCells(), p.radiusCells() * p.radiusCells(),
+ p.cellHeightBlocks(), scrollX, scrollZ, p.emitUnderside(), p.emitTopSurface(), p.emitPlates(),
+ p.wallCutCells(), p.plateLodCells(), p.untextured(), p.shadersActive());
+ }
+
+ private void markGeometryCached(BuildParams p) {
+ anchorCellX = p.anchorX();
+ anchorCellZ = p.anchorZ();
+ cachedShapeGeneration = p.shapeGeneration();
+ cachedEmitUnderside = p.emitUnderside();
+ cachedEmitTopSurface = p.emitTopSurface();
+ cachedRenderRadiusChunks = p.renderRadiusChunks();
+ cachedCellHeightBlocks = p.cellHeightBlocks();
+ cachedShadersActive = p.shadersActive();
+ cachedWallCutCells = p.wallCutCells();
+ cachedPlateLodCells = p.plateLodCells();
+ geometryBuilt = true;
+ }
+
+ private void startAsyncBuild(BuildParams p) {
+ if (buildInFlight != null || uploadParams != null) return;
+ final CloudVertexMesh target = spareMesh;
+ buildParams = p;
+ buildInFlight = CompletableFuture.runAsync(() -> {
+ if (Tracy.ENABLED) Tracy.beginZone(Z_ASYNC_BUILD);
+ try {
+ buildVertexMesh(target, p);
+ } finally {
+ if (Tracy.ENABLED) Tracy.endZone();
+ }
+ }, BUILD_THREAD);
+ }
+
+ private void collectFinishedBuild() {
+ if (buildInFlight != null) {
+ if (!buildInFlight.isDone()) return;
+
+ final boolean usable = !buildInFlight.isCompletedExceptionally()
+ && buildParams.shapeGeneration() == shapeGeneration;
+ buildInFlight = null;
+ if (!usable) {
+ spareMesh.discardPendingUpload();
+ buildParams = null;
+ return;
+ }
+ uploadParams = buildParams;
+ buildParams = null;
+ if (!spareMesh.beginUpload()) {
+ swapMeshes();
+ return;
}
}
+
+ if (uploadParams == null) return;
+ if (!spareMesh.uploadSlice(UPLOAD_SLICE_BYTES)) return;
+ swapMeshes();
+ }
+
+ private void swapMeshes() {
+ discardReorder();
+ final CloudVertexMesh finished = spareMesh;
+ spareMesh = vertexMesh;
+ vertexMesh = finished;
+ markGeometryCached(uploadParams);
+ uploadParams = null;
+ }
+
+ private void discardReorder() {
+ if (reorderInFlight != null) {
+ reorderInFlight.join();
+ reorderInFlight = null;
+ }
+ if (reorderMesh != null) {
+ reorderMesh.discardPendingReorder();
+ reorderMesh = null;
+ }
+ }
+
+ private void cancelAsyncBuild() {
+ discardReorder();
+ if (buildInFlight != null) {
+ buildInFlight.join();
+ buildInFlight = null;
+ }
+ buildParams = null;
+ uploadParams = null;
+ spareMesh.discardPendingUpload();
+ }
+
+ private void drawClouds(float r, float g, float b, boolean shadersActive) {
+ if (Tracy.ENABLED) Tracy.beginZone(Z_DRAW);
+ try {
+ drawCloudsInner(r, g, b, shadersActive);
+ } finally {
+ if (Tracy.ENABLED) Tracy.endZone();
+ }
+ }
+
+ private void drawCloudsInner(float r, float g, float b, boolean shadersActive) {
+ drawCalls = 0;
+
+ if (faceMeshActive) {
+ drawFaces(r, g, b);
+ } else {
+ drawVertices(r, g, b, shadersActive);
+ }
+ }
+
+ private void drawFaces(float r, float g, float b) {
+ GLStateManager.enableCull();
+ applyAnaglyphColorMask();
GLStateManager.enableBlend();
GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
- GLStateManager.glDepthMask(false);
+ GLStateManager.glDepthMask(true);
- if (shadersActive) {
- for (int f = 0; f < 4; f++) {
- final int qc = factorQuadCount[f];
- if (qc == 0) continue;
- final float v = FACTOR_VALUES[f];
- GLStateManager.glColor4f(v * r, v * g, v * b, CloudUniforms.ALPHA);
- final long byteOffset = (long) (factorVertOffset[f] / 4) * 6L * 4L;
- GLStateManager.glDrawElements(GL11.GL_TRIANGLES, qc * 6, GL11.GL_UNSIGNED_INT, byteOffset);
+ program.getInterface().setColorMult(r, g, b);
+
+ faceMesh.bind();
+ final int interiorFaces = faceMesh.interiorCount();
+ if (interiorFaces > 0) {
+ faceMesh.drawInterior();
+ drawCalls++;
+ }
+ drawVisibleWedges(faceMesh.plateStarts(), faceMesh.wallStarts(), faceMesh.uploadedCount(), true);
+ faceMesh.unbind();
+
+ GLStateManager.glDepthMask(true);
+ GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
+ GLStateManager.disableBlend();
+ }
+
+ private void drawVertices(float r, float g, float b, boolean depthPrepass) {
+ vertexMesh.bind();
+ final int totalQuads = vertexMesh.quadCount();
+
+ if (cullBackFaces()) {
+ GLStateManager.enableCull();
+ } else {
+ GLStateManager.disableCull();
+ }
+
+ if (depthPrepass) {
+ GLStateManager.disableBlend();
+ GLStateManager.glDepthMask(true);
+ GLStateManager.glColorMask(false, false, false, false);
+ GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, CloudUniforms.ALPHA);
+ vertexMesh.drawAll();
+ drawCalls++;
+ if (interiorActive) {
+ vertexMesh.unbind();
+ pushInteriorTransform(true);
+ interiorMesh.bind();
+ interiorMesh.drawAll();
+ interiorMesh.unbind();
+ popInteriorTransform(true);
+ vertexMesh.bind();
+ drawCalls++;
+ }
+ }
+
+ applyAnaglyphColorMask();
+ GLStateManager.enableBlend();
+ GLStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
+ GLStateManager.glDepthMask(!depthPrepass);
+
+ if (depthPrepass) {
+ for (int face = 0; face < 4; face++) {
+ if (vertexMesh.faceEmpty(face)) continue;
+ final float shade = CloudVertexMesh.FACE_SHADE[face];
+ GLStateManager.glColor4f(shade * r, shade * g, shade * b, CloudUniforms.ALPHA);
+ vertexMesh.drawFace(face);
+ drawCalls++;
}
} else {
program.getInterface().setColorMult(r, g, b);
- GLStateManager.glDrawElements(GL11.GL_TRIANGLES, totalQuads * 6, GL11.GL_UNSIGNED_INT, 0L);
+ if (cloudMode == MODE_FANCY && vertexMesh.orderPublished()) {
+ drawVisibleWedges(vertexMesh.plateStarts(), vertexMesh.wallStarts(), totalQuads, false);
+ } else {
+ drawRange(0, totalQuads, false);
+ }
+ }
+
+ vertexMesh.unbind();
+
+ if (interiorActive) {
+ pushInteriorTransform(depthPrepass);
+ interiorMesh.bind();
+ if (depthPrepass) {
+ for (int face = 0; face < 4; face++) {
+ if (interiorMesh.faceEmpty(face)) continue;
+ final float shade = CloudVertexMesh.FACE_SHADE[face];
+ GLStateManager.glColor4f(shade * r, shade * g, shade * b, CloudUniforms.ALPHA);
+ interiorMesh.drawFace(face);
+ drawCalls++;
+ }
+ } else {
+ drawCalls++;
+ interiorMesh.drawRange(0, interiorMesh.quadCount());
+ }
+ interiorMesh.unbind();
+ popInteriorTransform(depthPrepass);
}
- vao.unbind();
GLStateManager.enableCull();
GLStateManager.glDepthMask(true);
GLStateManager.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
GLStateManager.disableBlend();
}
- private void rebuildGeometry(int anchorX, int anchorZ, int renderRadius, float cloudInteriorHeight, boolean emitTopFace, boolean emitBottomFace, int marginCells) {
- prepareEmitBuffer();
-
- final int marginChunks = (marginCells + CELLS_PER_CHUNK - 1) / CELLS_PER_CHUNK;
- final int chunkRange = renderRadius + marginChunks;
- final int outerLo = -chunkRange;
- final int outerHi = chunkRange;
-
- final int radiusCellsWithMargin = chunkRange * CELLS_PER_CHUNK;
- final int radiusCellsSq = radiusCellsWithMargin * radiusCellsWithMargin;
-
- final float scrollX = anchorX * SCROLL_SPEED;
- final float scrollZ = anchorZ * SCROLL_SPEED;
-
- if (cloudMode != 2) {
- emitFastLayer(chunkRange * CELLS_PER_CHUNK, scrollX, scrollZ);
- finishGeometry();
- return;
- }
-
- final int rows = (outerHi - outerLo + 1) * CELLS_PER_CHUNK;
- final int lpr = (rows + 63) >>> 6;
- final int minX = outerLo * CELLS_PER_CHUNK;
- final int minZ = outerLo * CELLS_PER_CHUNK;
- final int gridSize = rows * lpr;
- if (emitTopFace || emitBottomFace) {
- if (globalEmit == null || globalEmit.length < gridSize) {
- globalEmit = new long[gridSize];
- globalEmitTodo = new long[gridSize];
- } else {
- java.util.Arrays.fill(globalEmit, 0, gridSize, 0L);
- }
- this.gridRows = rows;
- this.gridCols = rows;
- this.gridLongsPerRow = lpr;
- this.gridMinX = minX;
- this.gridMinZ = minZ;
- }
-
- final double y1 = cloudInteriorHeight;
- final double ye = y1 - EDGE_OVERLAP;
-
- for (int chunkX = outerLo; chunkX <= outerHi; chunkX++) {
- for (int chunkZ = outerLo; chunkZ <= outerHi; chunkZ++) {
- emitChunk(chunkX, chunkZ, anchorX, anchorZ, radiusCellsSq, emitTopFace, emitBottomFace, y1, ye, scrollX, scrollZ);
- }
- }
-
- if (emitTopFace || emitBottomFace) {
- emitTopBottomGlobalGreedy(emitTopFace, emitBottomFace, ye, scrollX, scrollZ);
- }
-
- if (emitTopFace && emitBottomFace) {
- emitInteriorFaces(anchorX, anchorZ, y1, scrollX, scrollZ);
- }
-
- finishGeometry();
- }
-
- private void emitInteriorFaces(int anchorX, int anchorZ, double y1, float scrollX, float scrollZ) {
- for (int dz = -1; dz <= 1; dz++) {
- for (int dx = -1; dx <= 1; dx++) {
- if (!edges.cellOpaque(anchorX + dx, anchorZ + dz)) continue;
- final double x0 = dx + INTERIOR_INSET;
- final double x1 = dx + 1 - INTERIOR_INSET;
- final double z0 = dz + INTERIOR_INSET;
- final double z1 = dz + 1 - INTERIOR_INSET;
- final double yb = INTERIOR_INSET;
- final double yt = y1 - INTERIOR_INSET;
- final float uL = dx * SCROLL_SPEED + scrollX;
- final float uR = (dx + 1) * SCROLL_SPEED + scrollX;
- final float uC = (dx + 0.5F) * SCROLL_SPEED + scrollX;
- final float vN = dz * SCROLL_SPEED + scrollZ;
- final float vS = (dz + 1) * SCROLL_SPEED + scrollZ;
- final float vC = (dz + 0.5F) * SCROLL_SPEED + scrollZ;
-
- ensureEmitCapacity(6 * QUAD_BYTES);
- emitCloudQuad(x0, yb, z1, uL, vS, x1, yb, z1, uR, vS, x1, yb, z0, uR, vN, x0, yb, z0, uL, vN, F_TOP, N_POS_Y);
- emitCloudQuad(x0, yt, z0, uL, vN, x1, yt, z0, uR, vN, x1, yt, z1, uR, vS, x0, yt, z1, uL, vS, F_BOTTOM, N_NEG_Y);
- emitCloudQuad(x0, yb, z0, uC, vN, x0, yt, z0, uC, vN, x0, yt, z1, uC, vS, x0, yb, z1, uC, vS, F_X, N_POS_X);
- emitCloudQuad(x1, yb, z1, uC, vS, x1, yt, z1, uC, vS, x1, yt, z0, uC, vN, x1, yb, z0, uC, vN, F_X, N_NEG_X);
- emitCloudQuad(x0, yb, z0, uL, vC, x1, yb, z0, uR, vC, x1, yt, z0, uR, vC, x0, yt, z0, uL, vC, F_Z, N_POS_Z);
- emitCloudQuad(x0, yt, z1, uL, vC, x1, yt, z1, uR, vC, x1, yb, z1, uR, vC, x0, yb, z1, uL, vC, F_Z, N_NEG_Z);
- }
- }
- }
-
- private void emitFastLayer(int radiusCells, float scrollX, float scrollZ) {
- final double r0 = -radiusCells;
- final double r1 = radiusCells;
- final float u0 = -radiusCells * SCROLL_SPEED + scrollX;
- final float u1 = radiusCells * SCROLL_SPEED + scrollX;
- final float v0 = -radiusCells * SCROLL_SPEED + scrollZ;
- final float v1 = radiusCells * SCROLL_SPEED + scrollZ;
- ensureEmitCapacity(QUAD_BYTES);
- emitCloudQuad(r0, 0.0, r0, u0, v0, r1, 0.0, r0, u1, v0, r1, 0.0, r1, u1, v1, r0, 0.0, r1, u0, v1, F_BOTTOM, N_POS_Y);
- }
-
- private void finishGeometry() {
- final int totalBytes = (int) (writeAddr - emitBufferAddr);
- final int vertexCount = totalBytes / VERTEX_STRIDE;
- if (vertexCount == 0) {
- if (vao != null) {
- vao.delete();
- vao = null;
- }
- cachedVertexCount = 0;
- return;
- }
-
- sortQuadsByFactor();
-
- if (vao == null) {
- vao = VertexBufferType.MUTABLE_RESIZABLE.allocate(
- DefaultVertexFormat.POSITION_TEXTURE_NORMAL, GL11.GL_TRIANGLES,
- sortedBuffer, vertexCount);
- setupFactorAttrib();
+ private void pushInteriorTransform(boolean shadersActive) {
+ if (shadersActive) {
+ GLStateManager.glPushMatrix();
+ GLStateManager.glTranslatef(interiorDriftX, 0.0f, interiorDriftZ);
} else {
- vao.getVBO().allocate(sortedBuffer, vertexCount);
- }
- cachedVertexCount = vertexCount;
- ensureEbo(vertexCount / 4);
- }
-
- private void setupFactorAttrib() {
- vao.bind();
- GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vao.getVBO().getId());
- GLStateManager.glEnableVertexAttribArray(FACTOR_ATTRIB_LOC);
- GLStateManager.glVertexAttribPointer(FACTOR_ATTRIB_LOC, 1, GL11.GL_UNSIGNED_BYTE, true, VERTEX_STRIDE, NORMAL_OFFSET + 3);
- GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
- vao.unbind();
- }
-
- private void ensureEbo(int quadCount) {
- if (eboId == -1) {
- eboId = GLStateManager.glGenBuffers();
- }
- if (quadCount <= eboQuadCapacity) return;
- final java.nio.IntBuffer ib = BufferUtils.createIntBuffer(quadCount * 6);
- for (int q = 0; q < quadCount; q++) {
- final int v = q * 4;
- ib.put(v).put(v + 1).put(v + 2);
- ib.put(v).put(v + 2).put(v + 3);
- }
- ib.flip();
- GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId);
- GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, ib, GL15.GL_STATIC_DRAW);
- GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
- eboQuadCapacity = quadCount;
- }
-
- private void deleteEbo() {
- if (eboId != -1) {
- GLStateManager.glDeleteBuffers(eboId);
- eboId = -1;
- eboQuadCapacity = 0;
+ program.getInterface().mvp.set(mvpInteriorScratch);
}
}
- private void emitChunk(int chunkX, int chunkZ, int anchorX, int anchorZ, int radiusCellsSq, boolean emitTopFace, boolean emitBottomFace, double y1, double ye, float scrollX, float scrollZ) {
- final float chunkOffsetX = chunkX * (float) CELLS_PER_CHUNK;
- final float chunkOffsetZ = chunkZ * (float) CELLS_PER_CHUNK;
- final int baseU = chunkX * CELLS_PER_CHUNK + anchorX;
- final int baseV = chunkZ * CELLS_PER_CHUNK + anchorZ;
-
- final int[] opaqueRows = this.chunkOpaqueRows;
- for (int row = 0; row < 10; row++) {
- opaqueRows[row] = (int) edges.readOpaqueRowBits(baseU - 1, baseV + row - 1);
- }
-
- long emittableBits = 0L;
- for (int j = 0; j < CELLS_PER_CHUNK; j++) {
- int rowOpaque = (opaqueRows[j + 1] >>> 1) & 0xFF;
- while (rowOpaque != 0) {
- final int k = Integer.numberOfTrailingZeros(rowOpaque);
- rowOpaque &= rowOpaque - 1;
- final int relX = chunkX * CELLS_PER_CHUNK + k;
- final int relZ = chunkZ * CELLS_PER_CHUNK + j;
- if (relX * relX + relZ * relZ > radiusCellsSq) continue;
- emittableBits |= 1L << (j * CELLS_PER_CHUNK + k);
- }
- }
- if (emittableBits == 0L) return;
-
- if (emitTopFace || emitBottomFace) {
- final int globalColStart = chunkX * CELLS_PER_CHUNK - gridMinX;
- final int globalRowStart = chunkZ * CELLS_PER_CHUNK - gridMinZ;
- final int wordIdx = globalColStart >>> 6;
- final int bitOff = globalColStart & 63;
- final long[] gE = this.globalEmit;
- final int lpr = this.gridLongsPerRow;
- if (bitOff <= 56) {
- for (int j = 0; j < CELLS_PER_CHUNK; j++) {
- final long row8 = (emittableBits >>> (j * CELLS_PER_CHUNK)) & 0xFFL;
- if (row8 == 0L) continue;
- gE[(globalRowStart + j) * lpr + wordIdx] |= row8 << bitOff;
- }
- } else {
- final int hiShift = 64 - bitOff;
- for (int j = 0; j < CELLS_PER_CHUNK; j++) {
- final long row8 = (emittableBits >>> (j * CELLS_PER_CHUNK)) & 0xFFL;
- if (row8 == 0L) continue;
- final int gRowOff = (globalRowStart + j) * lpr;
- gE[gRowOff + wordIdx] |= row8 << bitOff;
- gE[gRowOff + wordIdx + 1] |= row8 >>> hiShift;
- }
- }
- }
-
- int rowsAnd = 0x3FF;
- for (int r = 0; r < 10 && rowsAnd == 0x3FF; r++) rowsAnd &= opaqueRows[r];
- final boolean hasBoundary = rowsAnd != 0x3FF;
-
- long westFace = 0L, eastFace = 0L, northFace = 0L, southFace = 0L;
- if (hasBoundary) {
- long westOpaque = 0L, eastOpaque = 0L, northOpaque = 0L, southOpaque = 0L;
- for (int j = 0; j < CELLS_PER_CHUNK; j++) {
- final int rowShift = j * CELLS_PER_CHUNK;
- westOpaque |= ((long) (opaqueRows[j + 1] & 0xFF)) << rowShift;
- eastOpaque |= ((long) ((opaqueRows[j + 1] >>> 2) & 0xFF)) << rowShift;
- northOpaque |= ((long) ((opaqueRows[j] >>> 1) & 0xFF)) << rowShift;
- southOpaque |= ((long) ((opaqueRows[j + 2] >>> 1) & 0xFF)) << rowShift;
- }
- westFace = emittableBits & ~westOpaque;
- eastFace = emittableBits & ~eastOpaque;
- northFace = emittableBits & ~northOpaque;
- southFace = emittableBits & ~southOpaque;
- }
-
- emitZRun(westFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 0.0, N_NEG_X, false);
- emitZRun(eastFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 1.0 - EDGE_OVERLAP, N_POS_X, true);
- emitXRun(northFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 0.0, N_NEG_Z, false);
- emitXRun(southFace, chunkOffsetX, chunkOffsetZ, y1, scrollX, scrollZ, 1.0 - EDGE_OVERLAP, N_POS_Z, true);
- }
-
- private void emitZRun(long faceBits, float chunkOffsetX, float chunkOffsetZ, double y1, float scrollX, float scrollZ, double xOffset, int normalInt, boolean flip) {
- while (faceBits != 0L) {
- final int bit = Long.numberOfTrailingZeros(faceBits);
- final int k = bit & 7;
- final int j0 = bit >>> 3;
- int h = 1;
- while (j0 + h < CELLS_PER_CHUNK && ((faceBits >>> ((j0 + h) * CELLS_PER_CHUNK + k)) & 1L) != 0L) h++;
- long mask = 0L;
- for (int dh = 0; dh < h; dh++) mask |= 1L << ((j0 + dh) * CELLS_PER_CHUNK + k);
- faceBits &= ~mask;
-
- final double x = chunkOffsetX + k + xOffset;
- final double z0 = chunkOffsetZ + j0;
- final double z1 = chunkOffsetZ + j0 + h;
- final float uC = (chunkOffsetX + k + 0.5F) * SCROLL_SPEED + scrollX;
- final float vN = (chunkOffsetZ + j0) * SCROLL_SPEED + scrollZ;
- final float vS = (chunkOffsetZ + j0 + h) * SCROLL_SPEED + scrollZ;
- final double za = flip ? z0 : z1;
- final double zb = flip ? z1 : z0;
- final float va = flip ? vN : vS;
- final float vb = flip ? vS : vN;
-
- ensureEmitCapacity(QUAD_BYTES);
- emitCloudQuad(x, 0.0, za, uC, va, x, y1, za, uC, va, x, y1, zb, uC, vb, x, 0.0, zb, uC, vb, F_X, normalInt);
+ private void popInteriorTransform(boolean shadersActive) {
+ if (shadersActive) {
+ GLStateManager.glPopMatrix();
+ } else {
+ program.getInterface().mvp.set(mvpScratch);
}
}
- private void emitXRun(long faceBits, float chunkOffsetX, float chunkOffsetZ, double y1, float scrollX, float scrollZ, double zOffset, int normalInt, boolean flip) {
- while (faceBits != 0L) {
- final int bit = Long.numberOfTrailingZeros(faceBits);
- final int k0 = bit & 7;
- final int j = bit >>> 3;
- int w = 1;
- while (k0 + w < CELLS_PER_CHUNK && ((faceBits >>> (j * CELLS_PER_CHUNK + k0 + w)) & 1L) != 0L) w++;
- faceBits &= ~(((1L << w) - 1L) << (j * CELLS_PER_CHUNK + k0));
+ private boolean cullBackFaces() {
+ return cloudMode == MODE_FANCY;
+ }
- final double x0 = chunkOffsetX + k0;
- final double x1 = chunkOffsetX + k0 + w;
- final double z = chunkOffsetZ + j + zOffset;
- final float uL = (chunkOffsetX + k0) * SCROLL_SPEED + scrollX;
- final float uR = (chunkOffsetX + k0 + w) * SCROLL_SPEED + scrollX;
- final float vC = (chunkOffsetZ + j + 0.5F) * SCROLL_SPEED + scrollZ;
- final double ya = flip ? 0.0 : y1;
- final double yb = flip ? y1 : 0.0;
+ private void drawVisibleWedges(int[] plateStarts, int[] wallStarts, int total, boolean fromFaceMesh) {
+ final Entity view = mc.renderViewEntity;
+ if (view == null) {
+ drawRange(0, total, fromFaceMesh);
+ return;
+ }
+ final int callsBefore = drawCalls;
- ensureEmitCapacity(QUAD_BYTES);
- emitCloudQuad(x0, ya, z, uL, vC, x1, ya, z, uR, vC, x1, yb, z, uR, vC, x0, yb, z, uL, vC, F_Z, normalInt);
+ drawRange(0, plateStarts[0], fromFaceMesh);
+
+ if (!computeVisibleArc(view)) {
+ drawRange(plateStarts[0], total, fromFaceMesh);
+ return;
+ }
+
+ if (arcFrom <= arcTo) {
+ drawRange(plateStarts[arcFrom], plateStarts[arcTo + 1], fromFaceMesh);
+ drawRange(plateStarts[WEDGE_COUNT], wallStarts[0], fromFaceMesh);
+ drawRange(wallStarts[arcFrom], wallStarts[arcTo + 1], fromFaceMesh);
+ } else {
+ drawRange(plateStarts[arcFrom], plateStarts[WEDGE_COUNT], fromFaceMesh);
+ drawRange(plateStarts[0], plateStarts[arcTo + 1], fromFaceMesh);
+ drawRange(plateStarts[WEDGE_COUNT], wallStarts[0], fromFaceMesh);
+ drawRange(wallStarts[arcFrom], wallStarts[WEDGE_COUNT], fromFaceMesh);
+ drawRange(wallStarts[0], wallStarts[arcTo + 1], fromFaceMesh);
+ }
+
+ if (drawCalls == callsBefore && total > 0) {
+ drawRange(0, total, fromFaceMesh);
}
}
- private void emitTopBottomGlobalGreedy(boolean emitTopFace, boolean emitBottomFace, double ye, float scrollX, float scrollZ) {
- final int rows = this.gridRows;
- final int cols = this.gridCols;
- final int lpr = this.gridLongsPerRow;
- final int minX = this.gridMinX;
- final int minZ = this.gridMinZ;
- final long[] todo = this.globalEmitTodo;
- System.arraycopy(this.globalEmit, 0, todo, 0, rows * lpr);
-
- final int bytesPerCell = (emitTopFace ? QUAD_BYTES : 0) + (emitBottomFace ? QUAD_BYTES : 0);
-
- for (int row = 0; row < rows; row++) {
- final int rowOff = row * lpr;
- for (int wi = 0; wi < lpr; wi++) {
- long word = todo[rowOff + wi];
- while (word != 0L) {
- final int bit = Long.numberOfTrailingZeros(word);
- final int col0 = wi * 64 + bit;
- if (col0 >= cols) break;
-
- final int w = measureRowRun(todo, rowOff, lpr, cols, col0);
- final int wiStart = col0 >>> 6;
- final int wiLast = (col0 + w - 1) >>> 6;
- final int spanWords = wiLast - wiStart + 1;
- if (runMaskScratch.length < spanWords) {
- runMaskScratch = new long[Math.max(spanWords, runMaskScratch.length * 2)];
- }
- final long[] mask = runMaskScratch;
- for (int s = 0; s < spanWords; s++) {
- final int wIdx = wiStart + s;
- final int wordColStart = wIdx * 64;
- final int loBit = Math.max(0, col0 - wordColStart);
- final int hiBit = Math.min(63, col0 + w - 1 - wordColStart);
- final int bitsInWord = hiBit - loBit + 1;
- mask[s] = (bitsInWord == 64) ? -1L : (((1L << bitsInWord) - 1L) << loBit);
- }
-
- int h = 1;
- extendRow:
- while (row + h < rows) {
- final int rOff = (row + h) * lpr;
- for (int s = 0; s < spanWords; s++) {
- final long m = mask[s];
- if ((todo[rOff + wiStart + s] & m) != m) break extendRow;
- }
- h++;
- }
- for (int rr = 0; rr < h; rr++) {
- final int rOff = (row + rr) * lpr;
- for (int s = 0; s < spanWords; s++) {
- todo[rOff + wiStart + s] &= ~mask[s];
- }
- }
-
- final int relX0 = col0 + minX;
- final int relX1 = relX0 + w;
- final int relZ0 = row + minZ;
- final int relZ1 = relZ0 + h;
- final double x0 = relX0, x1 = relX1, z0 = relZ0, z1 = relZ1;
- final float uL = relX0 * SCROLL_SPEED + scrollX;
- final float uR = relX1 * SCROLL_SPEED + scrollX;
- final float vN = relZ0 * SCROLL_SPEED + scrollZ;
- final float vS = relZ1 * SCROLL_SPEED + scrollZ;
-
- if (bytesPerCell > 0) ensureEmitCapacity(bytesPerCell);
-
- if (emitTopFace) {
- emitCloudQuad(x0, 0.0, z0, uL, vN, x1, 0.0, z0, uR, vN, x1, 0.0, z1, uR, vS, x0, 0.0, z1, uL, vS, F_TOP, N_NEG_Y);
- }
- if (emitBottomFace) {
- emitCloudQuad(x0, ye, z1, uL, vS, x1, ye, z1, uR, vS, x1, ye, z0, uR, vN, x0, ye, z0, uL, vN, F_BOTTOM, N_POS_Y);
- }
-
- word = todo[rowOff + wi];
- }
- }
+ private void drawRange(int start, int end, boolean fromFaceMesh) {
+ final int count = end - start;
+ if (count <= 0) return;
+ drawCalls++;
+ if (fromFaceMesh) {
+ faceMesh.drawRange(start, end);
+ } else {
+ vertexMesh.drawRange(start, end);
}
}
- private static int measureRowRun(long[] arr, int rowOff, int lpr, int stride, int col0) {
- int wi = col0 >>> 6;
- final int bit = col0 & 63;
- final long highMask = -1L << bit;
- final long inv = ~arr[rowOff + wi] & highMask;
- if (inv != 0L) {
- final int zeroBit = Long.numberOfTrailingZeros(inv);
- return Math.min(zeroBit - bit, stride - col0);
- }
- int run = 64 - bit;
- wi++;
- while (wi < lpr) {
- final long w = arr[rowOff + wi];
- if (w != -1L) {
- run += Long.numberOfTrailingZeros(~w);
- return Math.min(run, stride - col0);
- }
- run += 64;
- wi++;
- }
- return Math.min(run, stride - col0);
+ private boolean computeVisibleArc(Entity view) {
+ final double yaw = Math.toRadians(view.rotationYaw);
+ final double facing = Math.atan2(Math.cos(yaw), -Math.sin(yaw));
+ final float m00 = GLStateManager.getProjectionMatrix().m00();
+ final double halfFov = m00 > 0.0f ? Math.atan(1.0 / m00) : Math.PI;
+
+ final double halfSpan = (halfFov + CloudDisc.driftAngle(driftCells)) * WEDGES_PER_RADIAN + 0.25;
+ if (halfSpan * 2.0 + 1.0 >= WEDGE_COUNT) return false;
+
+ final double centre = (facing + Math.PI) * WEDGES_PER_RADIAN;
+ arcFrom = Math.floorMod((int) Math.floor(centre - halfSpan), WEDGE_COUNT);
+ arcTo = Math.floorMod((int) Math.ceil(centre + halfSpan), WEDGE_COUNT);
+ return true;
}
- private void prepareEmitBuffer() {
- if (emitBuffer == null) {
- emitBufferCapacity = 256 * 1024;
- emitBuffer = MemoryUtilities.memRealloc((ByteBuffer) null, emitBufferCapacity);
- emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0);
+ private void applyAnaglyphColorMask() {
+ if (!mc.gameSettings.anaglyph) {
+ GLStateManager.glColorMask(true, true, true, true);
+ return;
}
- writeAddr = emitBufferAddr;
- writeEnd = emitBufferAddr + emitBufferCapacity;
- quadCount = 0;
- }
-
- private void growEmitBuffer(int neededBytes) {
- final long oldBytes = writeAddr - emitBufferAddr;
- int newCap = emitBufferCapacity;
- while (newCap < neededBytes) newCap *= 2;
- emitBuffer = MemoryUtilities.memRealloc(emitBuffer, newCap);
- emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0);
- emitBufferCapacity = newCap;
- writeAddr = emitBufferAddr + oldBytes;
- writeEnd = emitBufferAddr + newCap;
- }
-
- private void ensureEmitCapacity(int bytes) {
- if (writeAddr + bytes > writeEnd) {
- growEmitBuffer((int) (writeAddr - emitBufferAddr) + bytes);
+ switch (EntityRenderer.anaglyphField) {
+ case 0 -> GLStateManager.glColorMask(false, true, true, true);
+ case 1 -> GLStateManager.glColorMask(true, false, false, true);
+ default -> GLStateManager.glColorMask(true, true, true, true);
}
}
- private void emitCloudQuad(double x0, double y0, double z0, float u0, float v0, double x1, double y1, double z1, float u1, float v1, double x2, double y2, double z2, float u2, float v2, double x3, double y3, double z3, float u3, float v3, byte factorIdx, int normalInt) {
- if (quadCount == quadFactor.length) {
- quadFactor = java.util.Arrays.copyOf(quadFactor, quadFactor.length * 2);
- }
- quadFactor[quadCount++] = factorIdx;
-
- final int packedNormal = normalInt | FACTOR_BYTE_SHIFTED[factorIdx];
- long a = writeAddr;
- a = writeCloudVertex(a, x0, y0, z0, u0, v0, packedNormal);
- a = writeCloudVertex(a, x1, y1, z1, u1, v1, packedNormal);
- a = writeCloudVertex(a, x2, y2, z2, u2, v2, packedNormal);
- a = writeCloudVertex(a, x3, y3, z3, u3, v3, packedNormal);
- writeAddr = a;
- }
-
- private static long writeCloudVertex(long addr, double x, double y, double z, float u, float v, int normalInt) {
- MemoryUtilities.memPutFloat(addr, (float) x);
- MemoryUtilities.memPutFloat(addr + 4, (float) y);
- MemoryUtilities.memPutFloat(addr + 8, (float) z);
- MemoryUtilities.memPutFloat(addr + 12, u);
- MemoryUtilities.memPutFloat(addr + 16, v);
- MemoryUtilities.memPutInt(addr + NORMAL_OFFSET, normalInt);
- return addr + VERTEX_STRIDE;
- }
-
- private static int packNormalInt(byte nx, byte ny, byte nz) {
- final int x = nx & 0xFF, y = ny & 0xFF, z = nz & 0xFF;
- return BIG_ENDIAN ? (x << 24) | (y << 16) | (z << 8) : x | (y << 8) | (z << 16);
- }
-
- private void sortQuadsByFactor() {
- final int qc = quadCount;
- final int[] cnt = factorQuadCount;
- cnt[0] = 0;
- cnt[1] = 0;
- cnt[2] = 0;
- cnt[3] = 0;
- final byte[] qf = quadFactor;
- for (int q = 0; q < qc; q++) cnt[qf[q]]++;
-
- final int totalBytes = qc * QUAD_BYTES;
- if (sortedBuffer == null || sortedBufferCapacity < totalBytes) {
- int rounded = Math.max(totalBytes, 64 * 1024);
- int pow2 = Integer.highestOneBit(rounded - 1) << 1;
- if (pow2 <= 0) pow2 = rounded;
- sortedBuffer = MemoryUtilities.memRealloc(sortedBuffer, pow2);
- sortedBufferAddr = MemoryUtilities.memAddress(sortedBuffer, 0);
- sortedBufferCapacity = pow2;
- }
-
- final int[] off = factorVertOffset;
- off[0] = 0;
- off[1] = cnt[0] * 4;
- off[2] = (cnt[0] + cnt[1]) * 4;
- off[3] = (cnt[0] + cnt[1] + cnt[2]) * 4;
-
- final long[] dst = factorWriteAddr;
- dst[0] = sortedBufferAddr;
- dst[1] = dst[0] + (long) cnt[0] * QUAD_BYTES;
- dst[2] = dst[1] + (long) cnt[1] * QUAD_BYTES;
- dst[3] = dst[2] + (long) cnt[2] * QUAD_BYTES;
-
- final long src0 = emitBufferAddr;
- int q = 0;
- while (q < qc) {
- final int f = qf[q];
- int runEnd = q + 1;
- while (runEnd < qc && qf[runEnd] == f) runEnd++;
- final int runLen = runEnd - q;
- final long runBytes = (long) runLen * QUAD_BYTES;
- MemoryUtilities.memCopy(src0 + (long) q * QUAD_BYTES, dst[f], runBytes);
- dst[f] += runBytes;
- q = runEnd;
- }
-
- sortedBuffer.position(0).limit(totalBytes);
- }
-
private void setupCloudTexture() {
- final int bound = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
- if (bound != mipmapTexId) {
+ final int boundTexId = GLStateManager.glGetInteger(GL11.GL_TEXTURE_BINDING_2D);
+ if (boundTexId != mipmappedTexId) {
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL12.GL_TEXTURE_MAX_LEVEL, 4);
GLStateManager.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST_MIPMAP_LINEAR);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GLStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
- mipmapTexId = bound;
+ mipmappedTexId = boundTexId;
}
- if (bound != cloudTexId || edges == null) {
- extractCloudEdges();
- cloudTexId = bound;
+ if (boundTexId != cloudTexId || shape == null) {
+ extractCloudShape();
+ cloudTexId = boundTexId;
}
}
- private void extractCloudEdges() {
- final int w = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
- final int h = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
- if (w <= 0 || h <= 0) return;
- final int needed = w * h * 4;
- if (edgeStagingBuffer == null || edgeStagingCapacity < needed) {
- edgeStagingBuffer = BufferUtils.createByteBuffer(needed);
- edgeStagingCapacity = needed;
+ private void extractCloudShape() {
+ final int texWidth = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
+ final int texHeight = GLStateManager.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
+ if (texWidth <= 0 || texHeight <= 0) return;
+ final int neededBytes = texWidth * texHeight * 4;
+ if (texelStagingBuffer == null || texelStagingBuffer.capacity() < neededBytes) {
+ texelStagingBuffer = BufferUtils.createByteBuffer(neededBytes);
} else {
- edgeStagingBuffer.clear();
+ texelStagingBuffer.clear();
}
- final ByteBuffer buf = edgeStagingBuffer;
- GLStateManager.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
- texW = w;
- texH = h;
- edges = new CloudEdges(w, h, buf);
- edgesGeneration++;
+ final ByteBuffer pixels = texelStagingBuffer;
+ GLStateManager.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, pixels);
+ cloudTextureWidth = texWidth;
+ shape = new CloudShape(texWidth, texHeight, pixels);
+ shapeGeneration++;
invalidateGeometry();
}
private void reloadTextures() {
if (mc.renderEngine == null) return;
mc.renderEngine.bindTexture(texture);
- extractCloudEdges();
- if (vao != null) {
- vao.delete();
- vao = null;
- }
- deleteEbo();
- mipmapTexId = -1;
+ extractCloudShape();
+ invalidateGeometry();
+ vertexMesh.deleteVao();
+ vertexMesh.deleteEbo();
+ spareMesh.deleteVao();
+ spareMesh.deleteEbo();
+ interiorMesh.deleteVao();
+ interiorMesh.deleteEbo();
+ mipmappedTexId = -1;
cloudTexId = -1;
}
@Override
public void onResourceManagerReload(IResourceManager resourceManager) {
reloadTextures();
- if (program != null) {
- program.delete();
- program = null;
+ if (programVertex != null) {
+ programVertex.delete();
+ programVertex = null;
}
+ if (programFaces != null) {
+ programFaces.delete();
+ programFaces = null;
+ }
+ program = null;
}
}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudShape.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudShape.java
new file mode 100644
index 000000000..82946ded5
--- /dev/null
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudShape.java
@@ -0,0 +1,193 @@
+package com.gtnewhorizons.angelica.render;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+/**
+ * Takes {@code clouds.png}, figures out which cells are cloud cells, precomputes greedy rectangles for the
+ * plates, and merges the exposed edges into wall runs.
+ */
+final class CloudShape {
+ static final int OPAQUE = 1 << 4;
+ static final int WEST_EMPTY = 1;
+ static final int EAST_EMPTY = 1 << 1;
+ static final int NORTH_EMPTY = 1 << 2;
+ static final int SOUTH_EMPTY = 1 << 3;
+ private static final int MIN_OPAQUE_ALPHA = 10;
+ final int width, height;
+ final int[] plateRects;
+ final int[] coarsePlateRects;
+ final int[] westRuns, eastRuns, northRuns, southRuns;
+ final boolean opaqueTexelsAllWhite;
+ private final int widthMask, heightMask;
+ private final boolean sizeIsPowerOfTwo;
+ private final byte[] cellFlags;
+
+ CloudShape(int width, int height, ByteBuffer rgba) {
+ this.width = width;
+ this.height = height;
+ this.widthMask = width - 1;
+ this.heightMask = height - 1;
+ this.sizeIsPowerOfTwo = (width & widthMask) == 0 && (height & heightMask) == 0;
+ final int cellCount = width * height;
+ final boolean[] opaque = new boolean[cellCount];
+ boolean allWhite = true;
+ for (int i = 0; i < cellCount; i++) {
+ final int alpha = rgba.get(i * 4 + 3) & 0xFF;
+ if (alpha < MIN_OPAQUE_ALPHA) continue;
+ opaque[i] = true;
+ if (allWhite && (alpha != 0xFF
+ || (rgba.get(i * 4) & 0xFF) != 0xFF
+ || (rgba.get(i * 4 + 1) & 0xFF) != 0xFF
+ || (rgba.get(i * 4 + 2) & 0xFF) != 0xFF)) {
+ allWhite = false;
+ }
+ }
+ this.opaqueTexelsAllWhite = allWhite;
+
+ final byte[] cellFlags = new byte[cellCount];
+ for (int z = 0; z < height; z++) {
+ final int rowStart = z * width;
+ final int northRowStart = Math.floorMod(z - 1, height) * width;
+ final int southRowStart = Math.floorMod(z + 1, height) * width;
+ for (int x = 0; x < width; x++) {
+ if (!opaque[rowStart + x]) continue;
+ int flagBits = OPAQUE;
+ if (!opaque[rowStart + Math.floorMod(x - 1, width)]) flagBits |= WEST_EMPTY;
+ if (!opaque[rowStart + Math.floorMod(x + 1, width)]) flagBits |= EAST_EMPTY;
+ if (!opaque[northRowStart + x]) flagBits |= NORTH_EMPTY;
+ if (!opaque[southRowStart + x]) flagBits |= SOUTH_EMPTY;
+ cellFlags[rowStart + x] = (byte) flagBits;
+ }
+ }
+ this.cellFlags = cellFlags;
+ this.plateRects = buildPlateRects(opaque, width, height);
+ this.coarsePlateRects = (width % 2 == 0 && height % 2 == 0) ? buildCoarsePlateRects(opaque, width, height) : null;
+
+ this.westRuns = buildRunsAlongZ(cellFlags, width, height, WEST_EMPTY);
+ this.eastRuns = buildRunsAlongZ(cellFlags, width, height, EAST_EMPTY);
+ this.northRuns = buildRunsAlongX(cellFlags, width, height, NORTH_EMPTY);
+ this.southRuns = buildRunsAlongX(cellFlags, width, height, SOUTH_EMPTY);
+ }
+
+ private static int[] buildPlateRects(boolean[] opaque, int width, int height) {
+ final boolean[] uncovered = opaque.clone();
+ int[] rects = new int[256];
+ int count = 0;
+
+ for (int z = 0; z < height; z++) {
+ final int rowStart = z * width;
+ for (int x = 0; x < width; x++) {
+ if (!uncovered[rowStart + x]) continue;
+
+ int rectW = 1;
+ while (x + rectW < width && uncovered[rowStart + x + rectW]) rectW++;
+
+ int rectH = 1;
+ extend:
+ while (z + rectH < height) {
+ final int nextRowStart = (z + rectH) * width;
+ for (int dx = 0; dx < rectW; dx++) {
+ if (!uncovered[nextRowStart + x + dx]) break extend;
+ }
+ rectH++;
+ }
+
+ for (int dz = 0; dz < rectH; dz++) {
+ final int coveredRowStart = (z + dz) * width;
+ for (int dx = 0; dx < rectW; dx++) uncovered[coveredRowStart + x + dx] = false;
+ }
+
+ if (count * 4 + 4 > rects.length) rects = Arrays.copyOf(rects, rects.length * 2);
+ rects[count * 4] = x;
+ rects[count * 4 + 1] = z;
+ rects[count * 4 + 2] = rectW;
+ rects[count * 4 + 3] = rectH;
+ count++;
+ x += rectW - 1;
+ }
+ }
+ return Arrays.copyOf(rects, count * 4);
+ }
+
+ private static int[] buildCoarsePlateRects(boolean[] opaque, int width, int height) {
+ final int coarseWidth = width / 2;
+ final int coarseHeight = height / 2;
+ final boolean[] coarseOpaque = new boolean[coarseWidth * coarseHeight];
+ for (int z = 0; z < coarseHeight; z++) {
+ final int topRowStart = (z * 2) * width;
+ final int bottomRowStart = (z * 2 + 1) * width;
+ for (int x = 0; x < coarseWidth; x++) {
+ int filled = 0;
+ if (opaque[topRowStart + x * 2]) filled++;
+ if (opaque[topRowStart + x * 2 + 1]) filled++;
+ if (opaque[bottomRowStart + x * 2]) filled++;
+ if (opaque[bottomRowStart + x * 2 + 1]) filled++;
+ coarseOpaque[z * coarseWidth + x] = filled >= 2;
+ }
+ }
+
+ final int[] rects = buildPlateRects(coarseOpaque, coarseWidth, coarseHeight);
+ for (int i = 0; i < rects.length; i++) rects[i] *= 2;
+ return rects;
+ }
+
+ private static int[] buildRunsAlongZ(byte[] cellFlags, int width, int height, int emptyBit) {
+ int[] runs = new int[192];
+ int count = 0;
+ for (int x = 0; x < width; x++) {
+ int z = 0;
+ while (z < height) {
+ if ((cellFlags[x + z * width] & emptyBit) == 0) {
+ z++;
+ continue;
+ }
+ int runLength = 1;
+ while (z + runLength < height && (cellFlags[x + (z + runLength) * width] & emptyBit) != 0) runLength++;
+ if (count * 3 + 3 > runs.length) runs = Arrays.copyOf(runs, runs.length * 2);
+ runs[count * 3] = x;
+ runs[count * 3 + 1] = z;
+ runs[count * 3 + 2] = runLength;
+ count++;
+ z += runLength;
+ }
+ }
+ return Arrays.copyOf(runs, count * 3);
+ }
+
+ private static int[] buildRunsAlongX(byte[] cellFlags, int width, int height, int emptyBit) {
+ int[] runs = new int[192];
+ int count = 0;
+ for (int z = 0; z < height; z++) {
+ final int rowStart = z * width;
+ int x = 0;
+ while (x < width) {
+ if ((cellFlags[rowStart + x] & emptyBit) == 0) {
+ x++;
+ continue;
+ }
+ int runLength = 1;
+ while (x + runLength < width && (cellFlags[rowStart + x + runLength] & emptyBit) != 0) runLength++;
+ if (count * 3 + 3 > runs.length) runs = Arrays.copyOf(runs, runs.length * 2);
+ runs[count * 3] = x;
+ runs[count * 3 + 1] = z;
+ runs[count * 3 + 2] = runLength;
+ count++;
+ x += runLength;
+ }
+ }
+ return Arrays.copyOf(runs, count * 3);
+ }
+
+ int cellFlagsAt(int x, int z) {
+ final int wrappedX, wrappedZ;
+ if (sizeIsPowerOfTwo) {
+ wrappedX = x & widthMask;
+ wrappedZ = z & heightMask;
+ } else {
+ wrappedX = Math.floorMod(x, width);
+ wrappedZ = Math.floorMod(z, height);
+ }
+ return cellFlags[wrappedX + wrappedZ * width] & 0xFF;
+ }
+}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java
index 901921636..56960dc43 100644
--- a/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudUniforms.java
@@ -1,42 +1,68 @@
package com.gtnewhorizons.angelica.render;
import org.embeddedt.embeddium.impl.gl.shader.ShaderBindingContext;
+import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformFloat4v;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformInt;
import org.embeddedt.embeddium.impl.gl.shader.uniform.GlUniformMatrix4f;
+/**
+ * The uniform handles both cloud programs bind.
+ */
final class CloudUniforms {
static final float ALPHA = 0.8f;
final GlUniformMatrix4f mvp;
- final GlUniformMatrix4f mv;
+ final GlUniformMatrix4f modelView;
final GlUniformFloat4v colorMult;
final GlUniformFloat4v fogParams;
final GlUniformFloat4v fogColor;
final GlUniformInt fogEnabled;
- final GlUniformInt tex;
-
+ final GlUniformInt textureUnit;
+ final GlUniformFloat cellHeight;
+ final GlUniformFloat4v scroll;
+ private final float[] vec4Buf = new float[4];
+ private float lastScrollX = Float.NaN, lastScrollZ = Float.NaN;
private int lastFogEnabled = -1;
private float lastFogR = Float.NaN, lastFogG = Float.NaN, lastFogB = Float.NaN;
private float lastColorR = Float.NaN, lastColorG = Float.NaN, lastColorB = Float.NaN;
private float lastFogParamX = Float.NaN, lastFogParamY = Float.NaN, lastFogParamZ = Float.NaN, lastFogParamW = Float.NaN;
- private final float[] uploadBuf = new float[4];
+ private float lastCellHeight = Float.NaN;
- CloudUniforms(ShaderBindingContext ctx) {
- mvp = ctx.bindUniform("u_MVPMatrix", GlUniformMatrix4f::new);
- mv = ctx.bindUniform("u_MVMatrix", GlUniformMatrix4f::new);
- colorMult = ctx.bindUniform("u_ColorMult", GlUniformFloat4v::new);
- fogParams = ctx.bindUniform("u_FogParams", GlUniformFloat4v::new);
- fogColor = ctx.bindUniform("u_FogColor", GlUniformFloat4v::new);
- fogEnabled = ctx.bindUniform("u_FogEnabled", GlUniformInt::new);
- tex = ctx.bindUniform("u_Tex", GlUniformInt::new);
+ CloudUniforms(ShaderBindingContext context) {
+ mvp = context.bindUniform("u_MVPMatrix", GlUniformMatrix4f::new);
+ modelView = context.bindUniform("u_MVMatrix", GlUniformMatrix4f::new);
+ colorMult = context.bindUniform("u_ColorMult", GlUniformFloat4v::new);
+ fogParams = context.bindUniform("u_FogParams", GlUniformFloat4v::new);
+ fogColor = context.bindUniform("u_FogColor", GlUniformFloat4v::new);
+ fogEnabled = context.bindUniform("u_FogEnabled", GlUniformInt::new);
+ textureUnit = context.bindUniformIfPresent("u_Tex", GlUniformInt::new);
+ cellHeight = context.bindUniformIfPresent("u_CellHeight", GlUniformFloat::new);
+ scroll = context.bindUniformIfPresent("u_Scroll", GlUniformFloat4v::new);
+ }
+
+ void setScroll(float x, float z) {
+ if (scroll == null || (x == lastScrollX && z == lastScrollZ)) return;
+ lastScrollX = x;
+ lastScrollZ = z;
+ vec4Buf[0] = x;
+ vec4Buf[1] = z;
+ vec4Buf[2] = 0.0f;
+ vec4Buf[3] = 0.0f;
+ scroll.set(vec4Buf);
+ }
+
+ void setCellHeight(float blocks) {
+ if (blocks == lastCellHeight) return;
+ lastCellHeight = blocks;
+ cellHeight.setFloat(blocks);
}
void setFogEnabled(boolean enabled) {
- final int val = enabled ? 1 : 0;
- if (val != lastFogEnabled) {
- lastFogEnabled = val;
- fogEnabled.setInt(val);
+ final int enabledValue = enabled ? 1 : 0;
+ if (enabledValue != lastFogEnabled) {
+ lastFogEnabled = enabledValue;
+ fogEnabled.setInt(enabledValue);
}
}
@@ -45,11 +71,11 @@ final class CloudUniforms {
lastFogR = r;
lastFogG = g;
lastFogB = b;
- uploadBuf[0] = r;
- uploadBuf[1] = g;
- uploadBuf[2] = b;
- uploadBuf[3] = 1.0f;
- fogColor.set(uploadBuf);
+ vec4Buf[0] = r;
+ vec4Buf[1] = g;
+ vec4Buf[2] = b;
+ vec4Buf[3] = 1.0f;
+ fogColor.set(vec4Buf);
}
}
@@ -59,11 +85,11 @@ final class CloudUniforms {
lastFogParamY = y;
lastFogParamZ = z;
lastFogParamW = w;
- uploadBuf[0] = x;
- uploadBuf[1] = y;
- uploadBuf[2] = z;
- uploadBuf[3] = w;
- fogParams.set(uploadBuf);
+ vec4Buf[0] = x;
+ vec4Buf[1] = y;
+ vec4Buf[2] = z;
+ vec4Buf[3] = w;
+ fogParams.set(vec4Buf);
}
}
@@ -72,11 +98,11 @@ final class CloudUniforms {
lastColorR = r;
lastColorG = g;
lastColorB = b;
- uploadBuf[0] = r;
- uploadBuf[1] = g;
- uploadBuf[2] = b;
- uploadBuf[3] = ALPHA;
- colorMult.set(uploadBuf);
+ vec4Buf[0] = r;
+ vec4Buf[1] = g;
+ vec4Buf[2] = b;
+ vec4Buf[3] = ALPHA;
+ colorMult.set(vec4Buf);
}
}
}
diff --git a/src/main/java/com/gtnewhorizons/angelica/render/CloudVertexMesh.java b/src/main/java/com/gtnewhorizons/angelica/render/CloudVertexMesh.java
new file mode 100644
index 000000000..ecd215cce
--- /dev/null
+++ b/src/main/java/com/gtnewhorizons/angelica/render/CloudVertexMesh.java
@@ -0,0 +1,969 @@
+package com.gtnewhorizons.angelica.render;
+
+import com.gtnewhorizon.gtnhlib.bytebuf.MemoryUtilities;
+import com.gtnewhorizon.gtnhlib.client.renderer.vao.IVertexArrayObject;
+import com.gtnewhorizon.gtnhlib.client.renderer.vao.VertexBufferType;
+import com.gtnewhorizon.gtnhlib.client.renderer.vertex.DefaultVertexFormat;
+import com.gtnewhorizons.angelica.glsm.GLStateManager;
+import com.gtnewhorizons.angelica.glsm.profiling.Tracy;
+import org.lwjgl.BufferUtils;
+import org.lwjgl.opengl.GL11;
+import org.lwjgl.opengl.GL15;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.IntBuffer;
+import java.util.Arrays;
+
+import static com.gtnewhorizons.angelica.render.CloudDisc.ALWAYS_DRAWN_CELLS;
+import static com.gtnewhorizons.angelica.render.CloudDisc.SCROLL_SPEED;
+import static com.gtnewhorizons.angelica.render.CloudDisc.WEDGE_COUNT;
+import static com.gtnewhorizons.angelica.render.CloudDisc.wedgeOf;
+import static org.joml.Math.clamp;
+
+/**
+ * Plates and walls as vertices.
+ */
+final class CloudVertexMesh {
+
+ static final byte FACE_DOWN = 0, FACE_UP = 1, FACE_SIDE_X = 2, FACE_SIDE_Z = 3;
+ static final float[] FACE_SHADE = {0.7f, 1.0f, 0.9f, 0.8f};
+ private static final int[] FACE_SHADE_PACKED;
+ private static final int FACE_SHADE_ATTRIB = 5;
+ private static final int STRIDE_WITH_UV = 24;
+ private static final int NORMAL_OFFSET_WITH_UV = 20;
+ private static final int STRIDE_NO_UV = 16;
+ private static final int NORMAL_OFFSET_NO_UV = 12;
+ private static final float EDGE_OVERLAP = 0.0001f;
+ private static final boolean BIG_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN;
+ private static final int NORMAL_POS_X = packNormal((byte) 127, (byte) 0, (byte) 0);
+ private static final int NORMAL_NEG_X = packNormal((byte) -127, (byte) 0, (byte) 0);
+ private static final int NORMAL_POS_Y = packNormal((byte) 0, (byte) 127, (byte) 0);
+ private static final int NORMAL_NEG_Y = packNormal((byte) 0, (byte) -127, (byte) 0);
+ private static final int NORMAL_POS_Z = packNormal((byte) 0, (byte) 0, (byte) 127);
+ private static final int NORMAL_NEG_Z = packNormal((byte) 0, (byte) 0, (byte) -127);
+ private static final int DIR_WEST = 0, DIR_EAST = 1, DIR_NORTH = 2, DIR_SOUTH = 3;
+ private static final int DIR_NONE = 4;
+ private static final int GROUP_PLATE_ALWAYS = 0, GROUP_PLATE_WEDGE = 1, GROUP_ALWAYS_DRAWN = 2, GROUP_WALL_WEDGE = 3;
+ private static final int ORDER_GROUP_COUNT = 2 * WEDGE_COUNT + 3;
+ private static final int ORDER_BANDS_PER_CELL = 4;
+ private static final int WEDGE_BUCKETS = WEDGE_COUNT + 1;
+ private static final int FACE_WEDGE_BUCKETS = 4 * WEDGE_BUCKETS;
+ private static final int WALL_SORT_INDEX_BITS = 26;
+ private static final int WALL_SORT_DISTANCE_BITS = 20;
+ private static final int WALL_SORT_BUCKET_SHIFT = WALL_SORT_INDEX_BITS + WALL_SORT_DISTANCE_BITS;
+ private static final long WALL_SORT_INDEX_MASK = (1L << WALL_SORT_INDEX_BITS) - 1;
+ private static final int WALL_SORT_MAX_RUNS = 1 << WALL_SORT_INDEX_BITS;
+ private static final int WALL_SORT_MAX_DISTANCE = (1 << WALL_SORT_DISTANCE_BITS) - 1;
+ private static final int RADIX_BITS = 10;
+ private static final int RADIX_SIZE = 1 << RADIX_BITS;
+ private static final int RADIX_MASK = RADIX_SIZE - 1;
+ private static final Tracy.ZoneId Z_STAMP_PLATES = Tracy.zoneId("cloudVertexStampPlates", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_PLATE_COVER = Tracy.zoneId("cloudPlateCover", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_STAMP_WALLS = Tracy.zoneId("cloudVertexStampWalls", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_UPLOAD = Tracy.zoneId("cloudVertexUpload", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_GEOMETRY = Tracy.zoneId("cloudVertexGeometry", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_REORDER = Tracy.zoneId("cloudVertexReorder", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_WALL_SORT = Tracy.zoneId("cloudVertexWallSort", Tracy.COLOR_CLIENT);
+ private static final Tracy.ZoneId Z_REORDER_UPLOAD = Tracy.zoneId("cloudVertexReorderUpload", Tracy.COLOR_CLIENT);
+
+ static {
+ FACE_SHADE_PACKED = new int[4];
+ for (int i = 0; i < 4; i++) {
+ final int shadeByte = Math.round(FACE_SHADE[i] * 255f) & 0xFF;
+ FACE_SHADE_PACKED[i] = BIG_ENDIAN ? shadeByte : (shadeByte << 24);
+ }
+ }
+
+ private final int[] faceWedgeStart = new int[FACE_WEDGE_BUCKETS + 1];
+ private final int[] faceWedgeCursor = new int[FACE_WEDGE_BUCKETS];
+ private final int[] wallStart = new int[WEDGE_COUNT + 1];
+ private final int[] plateStart = new int[WEDGE_COUNT + 1];
+ private final int[] wallStartScratch = new int[WEDGE_COUNT + 1];
+ private final int[] plateStartScratch = new int[WEDGE_COUNT + 1];
+ private int orderPendingQuads;
+ private int orderPendingAnchorX, orderPendingAnchorZ;
+ private final CloudPlateCover plates = new CloudPlateCover();
+ private IVertexArrayObject vao;
+ private int vertexCount;
+ private int eboId = -1;
+ private int eboQuadCapacity;
+ private boolean eboIsSequential;
+ private boolean vaoHasUv = true;
+ private int vertexStride = STRIDE_WITH_UV;
+ private int normalOffset = NORMAL_OFFSET_WITH_UV;
+ private int quadBytes = 4 * STRIDE_WITH_UV;
+ private ByteBuffer emitBuffer;
+ private long emitBufferAddr;
+ private int emitBufferCapacity;
+ private long writeAddr, writeEnd;
+ private ByteBuffer sortedBuffer;
+ private long sortedBufferAddr;
+ private int sortedBufferCapacity;
+ private byte[] quadFace = new byte[2048];
+ private int quadCount;
+ private int[] quadCell = new int[2048];
+ private short[] quadGroupBits = new short[2048];
+ private int nextQuadCellX, nextQuadCellZ, nextQuadGroup, nextQuadWedge, nextQuadDir = DIR_NONE;
+ private int buildAnchorX = Integer.MIN_VALUE, buildAnchorZ = Integer.MIN_VALUE;
+ private int orderAnchorX = Integer.MIN_VALUE, orderAnchorZ = Integer.MIN_VALUE;
+ private int buildRadiusCells;
+ private int[] orderBucketCount = new int[0];
+ private int[] quadBucket = new int[0];
+ private IntBuffer orderIndexBuffer;
+ private int[] orderIndexScratch = new int[0];
+ private int[] quadSortKey = new int[0];
+ private int[] wallRuns = new int[4096 * 4];
+ private int wallRunCount;
+ private int[] wallRunBucket = new int[4096];
+ private int[] wallRunDistance = new int[4096];
+ private long[] wallSortKey = new long[4096];
+ private long[] wallSortScratch = new long[4096];
+ private final int[] radixCounts = new int[RADIX_SIZE];
+ private boolean forPackShader;
+ private int wallCutCells = Integer.MAX_VALUE;
+ private int wallClipRadiusSq;
+ private ByteBuffer pendingUpload;
+ private int pendingVertices = -1;
+ private int vboCapacityVertices;
+ private int uploadCursorBytes = -1;
+ private int uploadTotalBytes;
+ private int uploadVertices;
+ private static final Tracy.ZoneId Z_EBO = Tracy.zoneId("cloudVertexEbo", Tracy.COLOR_CLIENT);
+ private static IntBuffer sharedSequentialIndices;
+ private static int sharedSequentialQuads;
+
+ private static int packNormal(byte nx, byte ny, byte nz) {
+ final int x = nx & 0xFF, y = ny & 0xFF, z = nz & 0xFF;
+ return BIG_ENDIAN ? (x << 24) | (y << 16) | (z << 8) : x | (y << 8) | (z << 16);
+ }
+
+ int quadCount() {
+ return vertexCount / 4;
+ }
+
+ boolean built() {
+ return vao != null && vertexCount != 0;
+ }
+
+ void clear() {
+ vertexCount = 0;
+ orderAnchorX = Integer.MIN_VALUE;
+ orderAnchorZ = Integer.MIN_VALUE;
+ }
+
+ int[] plateStarts() {
+ return plateStart;
+ }
+
+ int[] wallStarts() {
+ return wallStart;
+ }
+
+ void buildFast(int radiusCells, float scrollX, float scrollZ, boolean forPackShader) {
+ beginBuild(false, forPackShader);
+
+ nextQuadDir = DIR_NONE;
+ nextQuadGroup = GROUP_PLATE_ALWAYS;
+ nextQuadWedge = 0;
+ nextQuadCellX = 0;
+ nextQuadCellZ = 0;
+ final double minCell = -radiusCells;
+ final double maxCell = radiusCells;
+ final float uWest = -radiusCells * SCROLL_SPEED + scrollX;
+ final float uEast = radiusCells * SCROLL_SPEED + scrollX;
+ final float vNorth = -radiusCells * SCROLL_SPEED + scrollZ;
+ final float vSouth = radiusCells * SCROLL_SPEED + scrollZ;
+ ensureEmitCapacity(quadBytes);
+ emitQuad(minCell, 0.0, minCell, uWest, vNorth, maxCell, 0.0, minCell, uEast, vNorth,
+ maxCell, 0.0, maxCell, uEast, vSouth, minCell, 0.0, maxCell, uWest, vSouth, FACE_UP, NORMAL_POS_Y);
+
+ finishGeometry();
+ }
+
+ void build(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq,
+ double cellHeightBlocks, float scrollX, float scrollZ,
+ boolean emitUnderside, boolean emitTopSurface, boolean emitPlates,
+ int wallCut, int plateLodCells, boolean untextured, boolean forPack) {
+ beginBuild(untextured, forPack);
+ this.wallCutCells = wallCut;
+ buildAnchorX = anchorX;
+ buildAnchorZ = anchorZ;
+ buildRadiusCells = radiusCells;
+
+ final double deckTopY = cellHeightBlocks;
+ final double plateTopY = deckTopY - EDGE_OVERLAP;
+
+ if (emitPlates) {
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_STAMP_PLATES);
+ addPlates(shape, anchorX, anchorZ, radiusCells, radiusCellsSq, emitUnderside, emitTopSurface, plateTopY, scrollX, scrollZ, plateLodCells);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_STAMP_WALLS);
+ addWalls(shape, anchorX, anchorZ, radiusCells, radiusCellsSq, deckTopY, scrollX, scrollZ);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_GEOMETRY);
+ finishGeometry();
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+
+ void buildInterior(CloudShape shape, int anchorX, int anchorZ, double deckTopY,
+ float scrollX, float scrollZ, boolean untextured, boolean forPack) {
+ beginBuild(untextured, forPack);
+ addInteriorFaces(shape, anchorX, anchorZ, deckTopY, scrollX, scrollZ);
+ finishGeometry();
+ }
+
+ private void beginBuild(boolean untextured, boolean forPack) {
+ forPackShader = forPack;
+ if (!forPack && quadCell.length < quadFace.length) {
+ quadCell = new int[quadFace.length];
+ quadGroupBits = new short[quadFace.length];
+ }
+ final boolean withUv = !untextured;
+ vertexStride = withUv ? STRIDE_WITH_UV : STRIDE_NO_UV;
+ normalOffset = withUv ? NORMAL_OFFSET_WITH_UV : NORMAL_OFFSET_NO_UV;
+ quadBytes = 4 * vertexStride;
+ prepareEmitBuffer();
+ }
+
+ private void addPlates(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq,
+ boolean emitUnderside, boolean emitTopSurface, double plateTopY, float scrollX, float scrollZ, int plateLodCells) {
+ final int bytesPerRect = (emitUnderside ? quadBytes : 0) + (emitTopSurface ? quadBytes : 0);
+ if (bytesPerRect == 0) return;
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_PLATE_COVER);
+ plates.build(shape, anchorX, anchorZ, radiusCells, radiusCellsSq, plateLodCells, !forPackShader);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+
+ if (forPackShader) {
+ nextQuadDir = DIR_NONE;
+ nextQuadGroup = GROUP_PLATE_ALWAYS;
+ nextQuadWedge = 0;
+ if (emitUnderside) emitPlatePass(true, false, plateTopY, scrollX, scrollZ);
+ if (emitTopSurface) emitPlatePass(false, true, plateTopY, scrollX, scrollZ);
+ return;
+ }
+
+ for (int i = 0; i < plates.count(); i++) {
+ final int rect = plates.orderedRect(i);
+ final int wedgeBucket = plates.wedgeBucket(rect);
+ nextQuadDir = DIR_NONE;
+ nextQuadGroup = wedgeBucket == 0 ? GROUP_PLATE_ALWAYS : GROUP_PLATE_WEDGE;
+ nextQuadWedge = wedgeBucket == 0 ? 0 : wedgeBucket - 1;
+ nextQuadCellX = plates.minX(rect);
+ nextQuadCellZ = plates.minZ(rect);
+ emitPlateRect(plates.minX(rect), plates.minZ(rect), plates.maxX(rect) + 1, plates.maxZ(rect) + 1,
+ emitUnderside, emitTopSurface, plateTopY, scrollX, scrollZ, bytesPerRect);
+ }
+ }
+
+ private void emitPlatePass(boolean emitUnderside, boolean emitTopSurface, double plateTopY, float scrollX, float scrollZ) {
+ for (int rect = 0; rect < plates.count(); rect++) {
+ nextQuadCellX = plates.minX(rect);
+ nextQuadCellZ = plates.minZ(rect);
+ emitPlateRect(plates.minX(rect), plates.minZ(rect), plates.maxX(rect) + 1, plates.maxZ(rect) + 1,
+ emitUnderside, emitTopSurface, plateTopY, scrollX, scrollZ, quadBytes);
+ }
+ }
+
+ private void addWalls(CloudShape shape, int anchorX, int anchorZ, int radiusCells, int radiusCellsSq,
+ double deckTopY, float scrollX, float scrollZ) {
+ final int texW = shape.width;
+ final int texH = shape.height;
+
+ final int bandsPerWedge = radiusCells + 1;
+ final long cutCellsSq = (long) wallCutCells * wallCutCells;
+ wallClipRadiusSq = forPackShader && cutCellsSq < radiusCellsSq ? (int) cutCellsSq : radiusCellsSq;
+ wallRunCount = 0;
+ collectWallRuns(shape.westRuns, DIR_WEST, anchorX, anchorZ, texW, texH, bandsPerWedge);
+ collectWallRuns(shape.eastRuns, DIR_EAST, anchorX, anchorZ, texW, texH, bandsPerWedge);
+ collectWallRuns(shape.northRuns, DIR_NORTH, anchorX, anchorZ, texW, texH, bandsPerWedge);
+ collectWallRuns(shape.southRuns, DIR_SOUTH, anchorX, anchorZ, texW, texH, bandsPerWedge);
+ final int found = wallRunCount;
+
+ if (found == 0) return;
+
+ if (forPackShader) {
+ nextQuadGroup = GROUP_ALWAYS_DRAWN;
+ nextQuadWedge = 0;
+ for (int i = 0; i < found; i++) {
+ final int run = i * 4;
+ nextQuadDir = wallRuns[run];
+ nextQuadCellX = wallRuns[run + 1];
+ nextQuadCellZ = wallRuns[run + 2];
+ emitWallRun(wallRuns[run], wallRuns[run + 1], wallRuns[run + 2], wallRuns[run + 3], deckTopY, scrollX, scrollZ);
+ }
+ return;
+ }
+
+ if (wallSortKey.length < found) wallSortKey = new long[found];
+ for (int i = 0; i < found; i++) {
+ wallSortKey[i] = ((long) wallRunBucket[i] << WALL_SORT_BUCKET_SHIFT)
+ | ((long) wallRunDistance[i] << WALL_SORT_INDEX_BITS)
+ | i;
+ }
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_WALL_SORT);
+ radixSortWallKeys(found);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+
+ for (int i = 0; i < found; i++) {
+ final long key = wallSortKey[i];
+ final int bucket = (int) (key >>> WALL_SORT_BUCKET_SHIFT);
+ final int wedge = bucket == 0 ? -1 : (bucket - 1) / bandsPerWedge;
+ final int run = (int) (key & WALL_SORT_INDEX_MASK) * 4;
+ nextQuadGroup = bucket == 0 ? GROUP_ALWAYS_DRAWN : GROUP_WALL_WEDGE;
+ nextQuadWedge = bucket == 0 ? 0 : wedge;
+ nextQuadDir = wallRuns[run];
+ nextQuadCellX = wallRuns[run + 1];
+ nextQuadCellZ = wallRuns[run + 2];
+ emitWallRun(wallRuns[run], wallRuns[run + 1], wallRuns[run + 2], wallRuns[run + 3], deckTopY, scrollX, scrollZ);
+ }
+ }
+
+ private void collectWallRuns(int[] runs, int dir, int anchorX, int anchorZ, int texW, int texH, int bandsPerWedge) {
+ final boolean alongZ = dir == DIR_WEST || dir == DIR_EAST;
+ final int clipRadiusCells = (int) Math.sqrt(wallClipRadiusSq);
+ final int minCell = -clipRadiusCells;
+ final int maxCell = clipRadiusCells;
+
+ for (int r = 0; r < runs.length; r += 3) {
+ final int len = runs[r + 2];
+ final int baseX = Math.floorMod(runs[r] - anchorX, texW);
+ final int baseZ = Math.floorMod(runs[r + 1] - anchorZ, texH);
+
+ for (int kz = Math.floorDiv(minCell - baseZ - (alongZ ? len - 1 : 0), texH); kz <= Math.floorDiv(maxCell - baseZ, texH); kz++) {
+ final int runZ = baseZ + kz * texH;
+ for (int kx = Math.floorDiv(minCell - baseX - (alongZ ? 0 : len - 1), texW); kx <= Math.floorDiv(maxCell - baseX, texW); kx++) {
+ final int runX = baseX + kx * texW;
+
+ final int startX, startZ, span;
+ if (alongZ) {
+ if (runX * runX > wallClipRadiusSq) continue;
+ final int halfSpan = (int) Math.sqrt(wallClipRadiusSq - runX * runX);
+ final int z0 = Math.max(runZ, -halfSpan);
+ final int z1 = Math.min(runZ + len - 1, halfSpan);
+ if (z0 > z1) continue;
+ startX = runX;
+ startZ = z0;
+ span = z1 - z0 + 1;
+ } else {
+ if (runZ * runZ > wallClipRadiusSq) continue;
+ final int halfSpan = (int) Math.sqrt(wallClipRadiusSq - runZ * runZ);
+ final int x0 = Math.max(runX, -halfSpan);
+ final int x1 = Math.min(runX + len - 1, halfSpan);
+ if (x0 > x1) continue;
+ startX = x0;
+ startZ = runZ;
+ span = x1 - x0 + 1;
+ }
+
+ if (forPackShader) {
+ recordWallRun(dir, startX, startZ, span, 0, 0);
+ continue;
+ }
+
+ int pieceStart = 0;
+ int pieceWedge = wedgeOf(startX, startZ);
+ double pieceDist = Math.sqrt(startX * startX + startZ * startZ);
+ int pieceBand = (int) pieceDist;
+ for (int c = 1; c <= span; c++) {
+ final int cX = alongZ ? startX : startX + c;
+ final int cZ = alongZ ? startZ + c : startZ;
+ final boolean last = c == span;
+ final int wedgeHere = last ? -1 : wedgeOf(cX, cZ);
+ final double distHere = last ? -1.0 : Math.sqrt(cX * cX + cZ * cZ);
+ final int bandHere = last ? -1 : (int) distHere;
+ if (wedgeHere == pieceWedge && bandHere == pieceBand) {
+ if (distHere < pieceDist) pieceDist = distHere;
+ continue;
+ }
+
+ if (pieceBand <= wallCutCells) {
+ recordWallRun(dir,
+ alongZ ? startX : startX + pieceStart,
+ alongZ ? startZ + pieceStart : startZ,
+ c - pieceStart,
+ pieceBand <= ALWAYS_DRAWN_CELLS ? 0 : 1 + pieceWedge * bandsPerWedge + pieceBand,
+ (int) (pieceDist * 256.0));
+ }
+
+ pieceStart = c;
+ pieceWedge = wedgeHere;
+ pieceDist = distHere;
+ pieceBand = bandHere;
+ }
+ }
+ }
+ }
+ }
+
+ private void radixSortWallKeys(int count) {
+ if (count < 2) return;
+ if (wallSortScratch.length < count) wallSortScratch = new long[count];
+
+ long[] src = wallSortKey;
+ long[] dst = wallSortScratch;
+ final int[] counts = radixCounts;
+
+ for (int shift = WALL_SORT_INDEX_BITS; shift < Long.SIZE; shift += RADIX_BITS) {
+ Arrays.fill(counts, 0);
+ for (int i = 0; i < count; i++) counts[(int) ((src[i] >>> shift) & RADIX_MASK)]++;
+
+ boolean uniform = false;
+ int acc = 0;
+ for (int d = 0; d < RADIX_SIZE; d++) {
+ final int c = counts[d];
+ if (c == count) uniform = true;
+ counts[d] = acc;
+ acc += c;
+ }
+ if (uniform) continue;
+
+ for (int i = 0; i < count; i++) dst[counts[(int) ((src[i] >>> shift) & RADIX_MASK)]++] = src[i];
+ final long[] swap = src;
+ src = dst;
+ dst = swap;
+ }
+
+ if (src != wallSortKey) System.arraycopy(src, 0, wallSortKey, 0, count);
+ }
+
+ private void recordWallRun(int dir, int relX, int relZ, int span, int bucket, int distance256ths) {
+ if (wallRunCount == WALL_SORT_MAX_RUNS) return;
+ if (wallRunCount * 4 + 4 > wallRuns.length) {
+ wallRuns = Arrays.copyOf(wallRuns, wallRuns.length * 2);
+ wallRunBucket = Arrays.copyOf(wallRunBucket, wallRunBucket.length * 2);
+ wallRunDistance = Arrays.copyOf(wallRunDistance, wallRunDistance.length * 2);
+ }
+ final int slot = wallRunCount * 4;
+ wallRuns[slot] = dir;
+ wallRuns[slot + 1] = relX;
+ wallRuns[slot + 2] = relZ;
+ wallRuns[slot + 3] = span;
+ wallRunBucket[wallRunCount] = bucket;
+ wallRunDistance[wallRunCount] = Math.min(distance256ths, WALL_SORT_MAX_DISTANCE);
+ wallRunCount++;
+ }
+
+ private void emitWallRun(int dir, int relX, int relZ, int span, double deckTopY, float scrollX, float scrollZ) {
+ ensureEmitCapacity(quadBytes);
+ final double x0 = relX;
+ final double z0 = relZ;
+
+ if (dir == DIR_WEST || dir == DIR_EAST) {
+ final double z1 = relZ + span;
+ final float uCentre = (relX + 0.5F) * SCROLL_SPEED + scrollX;
+ final float vNorth = relZ * SCROLL_SPEED + scrollZ;
+ final float vSouth = (relZ + span) * SCROLL_SPEED + scrollZ;
+ if (dir == DIR_WEST) {
+ emitQuad(x0, 0.0, z1, uCentre, vSouth, x0, deckTopY, z1, uCentre, vSouth,
+ x0, deckTopY, z0, uCentre, vNorth, x0, 0.0, z0, uCentre, vNorth, FACE_SIDE_X, NORMAL_NEG_X);
+ } else {
+ final double xEast = relX + 1 - EDGE_OVERLAP;
+ emitQuad(xEast, 0.0, z0, uCentre, vNorth, xEast, deckTopY, z0, uCentre, vNorth,
+ xEast, deckTopY, z1, uCentre, vSouth, xEast, 0.0, z1, uCentre, vSouth, FACE_SIDE_X, NORMAL_POS_X);
+ }
+ } else {
+ final double x1 = relX + span;
+ final float uLeft = relX * SCROLL_SPEED + scrollX;
+ final float uRight = (relX + span) * SCROLL_SPEED + scrollX;
+ final float vCentre = (relZ + 0.5F) * SCROLL_SPEED + scrollZ;
+ if (dir == DIR_NORTH) {
+ emitQuad(x0, deckTopY, z0, uLeft, vCentre, x1, deckTopY, z0, uRight, vCentre,
+ x1, 0.0, z0, uRight, vCentre, x0, 0.0, z0, uLeft, vCentre, FACE_SIDE_Z, NORMAL_NEG_Z);
+ } else {
+ final double zSouth = relZ + 1 - EDGE_OVERLAP;
+ emitQuad(x0, 0.0, zSouth, uLeft, vCentre, x1, 0.0, zSouth, uRight, vCentre,
+ x1, deckTopY, zSouth, uRight, vCentre, x0, deckTopY, zSouth, uLeft, vCentre, FACE_SIDE_Z, NORMAL_POS_Z);
+ }
+ }
+ }
+
+ private void emitPlateRect(int relX0, int relZ0, int relX1, int relZ1, boolean emitUnderside, boolean emitTopSurface,
+ double plateTopY, float scrollX, float scrollZ, int bytesPerRect) {
+ final double x0 = relX0, x1 = relX1, z0 = relZ0, z1 = relZ1;
+ final float uLeft = relX0 * SCROLL_SPEED + scrollX;
+ final float uRight = relX1 * SCROLL_SPEED + scrollX;
+ final float vNorth = relZ0 * SCROLL_SPEED + scrollZ;
+ final float vSouth = relZ1 * SCROLL_SPEED + scrollZ;
+
+ ensureEmitCapacity(bytesPerRect);
+ if (emitUnderside) {
+ emitQuad(x0, 0.0, z0, uLeft, vNorth, x1, 0.0, z0, uRight, vNorth,
+ x1, 0.0, z1, uRight, vSouth, x0, 0.0, z1, uLeft, vSouth, FACE_DOWN, NORMAL_NEG_Y);
+ }
+ if (emitTopSurface) {
+ emitQuad(x0, plateTopY, z1, uLeft, vSouth, x1, plateTopY, z1, uRight, vSouth,
+ x1, plateTopY, z0, uRight, vNorth, x0, plateTopY, z0, uLeft, vNorth, FACE_UP, NORMAL_POS_Y);
+ }
+ }
+
+ private void addInteriorFaces(CloudShape shape, int anchorX, int anchorZ, double deckTopY, float scrollX, float scrollZ) {
+ if ((shape.cellFlagsAt(anchorX, anchorZ) & CloudShape.OPAQUE) == 0) return;
+
+ nextQuadDir = DIR_NONE;
+ nextQuadGroup = GROUP_ALWAYS_DRAWN;
+ nextQuadWedge = 0;
+ nextQuadCellX = 0;
+ nextQuadCellZ = 0;
+
+ final float uLeft = scrollX;
+ final float uRight = SCROLL_SPEED + scrollX;
+ final float uCentre = 0.5F * SCROLL_SPEED + scrollX;
+ final float vNorth = scrollZ;
+ final float vSouth = SCROLL_SPEED + scrollZ;
+ final float vCentre = 0.5F * SCROLL_SPEED + scrollZ;
+
+ final double x0 = 0.0;
+ final double x1 = 1.0;
+ final double z0 = 0.0;
+ final double z1 = 1.0;
+ final double yBottom = 0.0;
+ final double yTop = deckTopY;
+
+ ensureEmitCapacity(6 * quadBytes);
+ emitQuad(x0, yBottom, z1, uLeft, vSouth, x1, yBottom, z1, uRight, vSouth, x1, yBottom, z0, uRight, vNorth, x0, yBottom, z0, uLeft, vNorth, FACE_DOWN, NORMAL_POS_Y);
+ emitQuad(x0, yTop, z0, uLeft, vNorth, x1, yTop, z0, uRight, vNorth, x1, yTop, z1, uRight, vSouth, x0, yTop, z1, uLeft, vSouth, FACE_UP, NORMAL_NEG_Y);
+ emitQuad(x0, yBottom, z0, uCentre, vNorth, x0, yTop, z0, uCentre, vNorth, x0, yTop, z1, uCentre, vSouth, x0, yBottom, z1, uCentre, vSouth, FACE_SIDE_X, NORMAL_POS_X);
+ emitQuad(x1, yBottom, z1, uCentre, vSouth, x1, yTop, z1, uCentre, vSouth, x1, yTop, z0, uCentre, vNorth, x1, yBottom, z0, uCentre, vNorth, FACE_SIDE_X, NORMAL_NEG_X);
+ emitQuad(x0, yBottom, z0, uLeft, vCentre, x1, yBottom, z0, uRight, vCentre, x1, yTop, z0, uRight, vCentre, x0, yTop, z0, uLeft, vCentre, FACE_SIDE_Z, NORMAL_POS_Z);
+ emitQuad(x0, yTop, z1, uLeft, vCentre, x1, yTop, z1, uRight, vCentre, x1, yBottom, z1, uRight, vCentre, x0, yBottom, z1, uLeft, vCentre, FACE_SIDE_Z, NORMAL_NEG_Z);
+ }
+
+ private void finishGeometry() {
+ final int totalBytes = (int) (writeAddr - emitBufferAddr);
+ final int vertices = totalBytes / vertexStride;
+ pendingVertices = vertices;
+ if (vertices == 0) {
+ pendingUpload = null;
+ return;
+ }
+ if (forPackShader) {
+ pendingUpload = sortQuadsByFace(totalBytes);
+ } else {
+ emitBuffer.position(0).limit(totalBytes);
+ pendingUpload = emitBuffer;
+ }
+ }
+
+ void discardPendingUpload() {
+ pendingVertices = -1;
+ pendingUpload = null;
+ uploadCursorBytes = -1;
+ }
+
+ void uploadBuilt() {
+ if (beginUpload()) uploadSlice(Integer.MAX_VALUE);
+ }
+
+ boolean beginUpload() {
+ final int vertices = pendingVertices;
+ pendingVertices = -1;
+ if (vertices <= 0) {
+ pendingUpload = null;
+ if (vao != null) {
+ vao.delete();
+ vao = null;
+ }
+ vboCapacityVertices = 0;
+ vertexCount = 0;
+ return false;
+ }
+
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_UPLOAD);
+ try {
+ final boolean wantUv = vertexStride == STRIDE_WITH_UV;
+ if (vao != null && vaoHasUv != wantUv) {
+ vao.delete();
+ vao = null;
+ vboCapacityVertices = 0;
+ }
+
+ uploadVertices = vertices;
+ uploadTotalBytes = vertices * vertexStride;
+
+ if (vao != null && vertices <= vboCapacityVertices) {
+ uploadCursorBytes = 0;
+ return true;
+ }
+
+ final ByteBuffer source = pendingUpload;
+ final int roomyVertices = clamp(vertices, vertices + (vertices >> 1), source.capacity() / vertexStride);
+ source.position(0).limit(roomyVertices * vertexStride);
+ if (vao == null) {
+ vao = VertexBufferType.MUTABLE_RESIZABLE.allocate(
+ wantUv ? DefaultVertexFormat.POSITION_TEXTURE_NORMAL : DefaultVertexFormat.POSITION_NORMAL,
+ GL11.GL_TRIANGLES, source, roomyVertices);
+ vaoHasUv = wantUv;
+ setupShadeAttrib();
+ } else {
+ vao.getVBO().allocate(source, roomyVertices);
+ }
+ vboCapacityVertices = roomyVertices;
+ uploadCursorBytes = uploadTotalBytes;
+ return true;
+ } finally {
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+ }
+
+ boolean uploadSlice(int maxBytes) {
+ if (uploadCursorBytes < 0) return true;
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_UPLOAD);
+ try {
+ if (uploadCursorBytes < uploadTotalBytes) {
+ final int sliceBytes = Math.min(maxBytes, uploadTotalBytes - uploadCursorBytes);
+ final ByteBuffer source = pendingUpload;
+ source.position(uploadCursorBytes).limit(uploadCursorBytes + sliceBytes);
+ vao.getVBO().update(source, uploadCursorBytes);
+ uploadCursorBytes += sliceBytes;
+ if (uploadCursorBytes < uploadTotalBytes) return false;
+ }
+ finishUpload();
+ return true;
+ } finally {
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+ }
+
+ private void finishUpload() {
+ uploadCursorBytes = -1;
+ pendingUpload = null;
+ vertexCount = uploadVertices;
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_EBO);
+ ensureEbo(uploadVertices / 4);
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ orderAnchorX = Integer.MIN_VALUE;
+ orderAnchorZ = Integer.MIN_VALUE;
+ }
+
+ private void setupShadeAttrib() {
+ vao.bind();
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, vao.getVBO().getId());
+ GLStateManager.glEnableVertexAttribArray(FACE_SHADE_ATTRIB);
+ GLStateManager.glVertexAttribPointer(FACE_SHADE_ATTRIB, 1, GL11.GL_UNSIGNED_BYTE, true, vertexStride, normalOffset + 3);
+ GLStateManager.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
+ vao.unbind();
+ }
+
+ boolean orderStale(int anchorX, int anchorZ) {
+ return anchorX != orderAnchorX || anchorZ != orderAnchorZ;
+ }
+
+ boolean orderPublished() {
+ return orderAnchorX != Integer.MIN_VALUE;
+ }
+
+ void reorder(int anchorX, int anchorZ) {
+ final int quads = vertexCount / 4;
+ if (quads == 0) return;
+ if (quads > quadCell.length) return;
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_REORDER);
+
+ final int dx = anchorX - buildAnchorX;
+ final int dz = anchorZ - buildAnchorZ;
+ final int bands = (buildRadiusCells + 2) * ORDER_BANDS_PER_CELL;
+ final int bucketCount = ORDER_GROUP_COUNT * bands;
+
+ if (orderBucketCount.length < bucketCount + 1) orderBucketCount = new int[bucketCount + 1];
+ else Arrays.fill(orderBucketCount, 0, bucketCount + 1, 0);
+
+ if (quadBucket.length < quads) quadBucket = new int[quads];
+
+ for (int q = 0; q < quads; q++) {
+ final int cell = quadCell[q];
+ final int cx = (short) (cell >> 16) - dx;
+ final int cz = (short) cell - dz;
+ final int groupBits = quadGroupBits[q];
+ final int group = (groupBits >> 5) & 3;
+ final int wedge = groupBits & 31;
+
+ final boolean facingAway = group == GROUP_WALL_WEDGE && switch ((groupBits >> 7) & 7) {
+ case DIR_WEST -> cx < 1;
+ case DIR_EAST -> cx > -1;
+ case DIR_NORTH -> cz < 1;
+ case DIR_SOUTH -> cz > -1;
+ default -> false;
+ };
+
+ int band = (int) (Math.sqrt(cx * cx + cz * cz) * ORDER_BANDS_PER_CELL);
+ if (band >= bands) band = bands - 1;
+
+ final int groupSlot = facingAway ? 2 + 2 * WEDGE_COUNT : switch (group) {
+ case GROUP_PLATE_ALWAYS -> 0;
+ case GROUP_PLATE_WEDGE -> 1 + wedge;
+ case GROUP_ALWAYS_DRAWN -> 1 + WEDGE_COUNT;
+ default -> 2 + WEDGE_COUNT + wedge;
+ };
+ final int bucket = groupSlot * bands + band;
+ quadBucket[q] = bucket;
+ orderBucketCount[bucket]++;
+ }
+
+ int acc = 0;
+ for (int b = 0; b < bucketCount; b++) {
+ final int count = orderBucketCount[b];
+ orderBucketCount[b] = acc;
+ acc += count;
+ }
+ orderBucketCount[bucketCount] = acc;
+
+ for (int w = 0; w < WEDGE_COUNT; w++) plateStartScratch[w] = orderBucketCount[(1 + w) * bands];
+ plateStartScratch[WEDGE_COUNT] = orderBucketCount[(1 + WEDGE_COUNT) * bands];
+ for (int w = 0; w < WEDGE_COUNT; w++) wallStartScratch[w] = orderBucketCount[(2 + WEDGE_COUNT + w) * bands];
+ wallStartScratch[WEDGE_COUNT] = orderBucketCount[(2 + 2 * WEDGE_COUNT) * bands];
+
+ final int needed = quads * 6;
+ if (orderIndexBuffer == null || orderIndexBuffer.capacity() < needed) {
+ orderIndexBuffer = BufferUtils.createIntBuffer(Math.max(needed, 4096));
+ }
+
+ if (orderIndexScratch.length < needed) orderIndexScratch = new int[needed];
+ final int[] out = orderIndexScratch;
+ for (int q = 0; q < quads; q++) {
+ final int slot = orderBucketCount[quadBucket[q]]++;
+ final int v = q * 4;
+ final int base = slot * 6;
+ out[base] = v;
+ out[base + 1] = v + 1;
+ out[base + 2] = v + 2;
+ out[base + 3] = v;
+ out[base + 4] = v + 2;
+ out[base + 5] = v + 3;
+ }
+
+ final IntBuffer indices = orderIndexBuffer;
+ indices.clear();
+ indices.put(out, 0, needed);
+ indices.flip();
+
+ orderPendingQuads = quads;
+ orderPendingAnchorX = anchorX;
+ orderPendingAnchorZ = anchorZ;
+
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+
+ void reorderUpload() {
+ if (orderPendingQuads <= 0) return;
+ if (Tracy.FINE_ZONES) Tracy.beginZone(Z_REORDER_UPLOAD);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId);
+ GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, orderIndexBuffer, GL15.GL_DYNAMIC_DRAW);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
+ System.arraycopy(plateStartScratch, 0, plateStart, 0, plateStart.length);
+ System.arraycopy(wallStartScratch, 0, wallStart, 0, wallStart.length);
+ eboQuadCapacity = orderPendingQuads;
+ eboIsSequential = false;
+ orderAnchorX = orderPendingAnchorX;
+ orderAnchorZ = orderPendingAnchorZ;
+ orderPendingQuads = 0;
+ if (Tracy.FINE_ZONES) Tracy.endZone();
+ }
+
+ void discardPendingReorder() {
+ orderPendingQuads = 0;
+ }
+
+ private void ensureEbo(int quads) {
+ if (eboId == -1) {
+ eboId = GLStateManager.glGenBuffers();
+ }
+
+ if (quads <= eboQuadCapacity && eboIsSequential) return;
+ eboIsSequential = true;
+ final int capacity = Math.max(quads + (quads >> 1), 4096);
+ final IntBuffer indices = sequentialIndices(capacity);
+ indices.position(0).limit(capacity * 6);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId);
+ GLStateManager.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indices, GL15.GL_STATIC_DRAW);
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
+ eboQuadCapacity = capacity;
+ }
+
+ private static IntBuffer sequentialIndices(int quads) {
+ if (sharedSequentialIndices != null && sharedSequentialQuads >= quads) return sharedSequentialIndices;
+
+ final IntBuffer indices = BufferUtils.createIntBuffer(quads * 6);
+ for (int q = 0; q < quads; q++) {
+ final int v = q * 4;
+ indices.put(v).put(v + 1).put(v + 2);
+ indices.put(v).put(v + 2).put(v + 3);
+ }
+ indices.flip();
+ sharedSequentialIndices = indices;
+ sharedSequentialQuads = quads;
+ return indices;
+ }
+
+ void deleteEbo() {
+ if (eboId != -1) {
+ GLStateManager.glDeleteBuffers(eboId);
+ eboId = -1;
+ eboQuadCapacity = 0;
+ }
+ }
+
+ void deleteVao() {
+ if (vao != null) {
+ vao.delete();
+ vao = null;
+ }
+ vboCapacityVertices = 0;
+ vertexCount = 0;
+ }
+
+ void bind() {
+ vao.bind();
+ GLStateManager.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, eboId);
+ }
+
+ void unbind() {
+ vao.unbind();
+ }
+
+ void drawRange(int startQuad, int endQuad) {
+ final int quads = endQuad - startQuad;
+ if (quads <= 0) return;
+ GLStateManager.glDrawElements(GL11.GL_TRIANGLES, quads * 6, GL11.GL_UNSIGNED_INT, (long) startQuad * 6L * 4L);
+ }
+
+ void drawAll() {
+ GLStateManager.glDrawElements(GL11.GL_TRIANGLES, (vertexCount / 4) * 6, GL11.GL_UNSIGNED_INT, 0L);
+ }
+
+ boolean faceEmpty(int face) {
+ final int base = face * WEDGE_BUCKETS;
+ return faceWedgeStart[base + WEDGE_BUCKETS] == faceWedgeStart[base];
+ }
+
+ void drawFace(int face) {
+ final int base = face * WEDGE_BUCKETS;
+ drawRange(faceWedgeStart[base], faceWedgeStart[base + WEDGE_BUCKETS]);
+ }
+
+ private void prepareEmitBuffer() {
+ if (emitBuffer == null) {
+ emitBufferCapacity = 256 * 1024;
+ emitBuffer = MemoryUtilities.memRealloc((ByteBuffer) null, emitBufferCapacity);
+ emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0);
+ }
+
+ emitBuffer.clear();
+ writeAddr = emitBufferAddr;
+ writeEnd = emitBufferAddr + emitBufferCapacity;
+ quadCount = 0;
+ }
+
+ private void growEmitBuffer(int neededBytes) {
+ final long oldBytes = writeAddr - emitBufferAddr;
+ int newCap = emitBufferCapacity;
+ while (newCap < neededBytes) newCap *= 2;
+ emitBuffer = MemoryUtilities.memRealloc(emitBuffer, newCap);
+ emitBufferAddr = MemoryUtilities.memAddress(emitBuffer, 0);
+ emitBufferCapacity = newCap;
+ writeAddr = emitBufferAddr + oldBytes;
+ writeEnd = emitBufferAddr + newCap;
+ }
+
+ private void ensureEmitCapacity(int bytes) {
+ if (writeAddr + bytes > writeEnd) {
+ growEmitBuffer((int) (writeAddr - emitBufferAddr) + bytes);
+ }
+ }
+
+ private void emitQuad(double x0, double y0, double z0, float u0, float v0, double x1, double y1, double z1, float u1, float v1, double x2, double y2, double z2, float u2, float v2, double x3, double y3, double z3, float u3, float v3, byte face, int packedNormal) {
+ if (quadCount == quadFace.length) {
+ quadFace = Arrays.copyOf(quadFace, quadFace.length * 2);
+ if (!forPackShader) {
+ quadCell = Arrays.copyOf(quadCell, quadCell.length * 2);
+ quadGroupBits = Arrays.copyOf(quadGroupBits, quadGroupBits.length * 2);
+ }
+ }
+ if (!forPackShader) {
+ quadCell[quadCount] = (nextQuadCellX << 16) | (nextQuadCellZ & 0xFFFF);
+ quadGroupBits[quadCount] = (short) ((nextQuadDir << 7) | (nextQuadGroup << 5) | nextQuadWedge);
+ }
+ quadFace[quadCount++] = face;
+
+ final int normalAndShade = packedNormal | FACE_SHADE_PACKED[face];
+ long addr = writeAddr;
+ addr = writeVertex(addr, x0, y0, z0, u0, v0, normalAndShade);
+ addr = writeVertex(addr, x1, y1, z1, u1, v1, normalAndShade);
+ addr = writeVertex(addr, x2, y2, z2, u2, v2, normalAndShade);
+ addr = writeVertex(addr, x3, y3, z3, u3, v3, normalAndShade);
+ writeAddr = addr;
+ }
+
+ private long writeVertex(long addr, double x, double y, double z, float u, float v, int normalAndShade) {
+ MemoryUtilities.memPutFloat(addr, (float) x);
+ MemoryUtilities.memPutFloat(addr + 4, (float) y);
+ MemoryUtilities.memPutFloat(addr + 8, (float) z);
+ if (normalOffset == NORMAL_OFFSET_WITH_UV) {
+ MemoryUtilities.memPutFloat(addr + 12, u);
+ MemoryUtilities.memPutFloat(addr + 16, v);
+ }
+ MemoryUtilities.memPutInt(addr + normalOffset, normalAndShade);
+ return addr + vertexStride;
+ }
+
+ private ByteBuffer sortQuadsByFace(int emittedBytes) {
+ final int quadTotal = quadCount;
+ Arrays.fill(faceWedgeStart, 0);
+
+ if (quadSortKey.length < quadTotal) quadSortKey = new int[quadTotal];
+ final byte[] faces = quadFace;
+ boolean alreadyGrouped = true;
+ int previousKey = 0;
+ for (int q = 0; q < quadTotal; q++) {
+ final int key = faces[q] * WEDGE_BUCKETS;
+ if (key < previousKey) alreadyGrouped = false;
+ previousKey = key;
+ quadSortKey[q] = key;
+ faceWedgeStart[key]++;
+ }
+
+ int acc = 0;
+ for (int b = 0; b < FACE_WEDGE_BUCKETS; b++) {
+ final int count = faceWedgeStart[b];
+ faceWedgeStart[b] = acc;
+ faceWedgeCursor[b] = acc;
+ acc += count;
+ }
+ faceWedgeStart[FACE_WEDGE_BUCKETS] = acc;
+
+ if (alreadyGrouped) {
+ emitBuffer.position(0).limit(emittedBytes);
+ return emitBuffer;
+ }
+
+ final int totalBytes = quadTotal * quadBytes;
+ if (sortedBuffer == null || sortedBufferCapacity < totalBytes) {
+ int rounded = Math.max(totalBytes, 64 * 1024);
+ int pow2 = Integer.highestOneBit(rounded - 1) << 1;
+ if (pow2 <= 0) pow2 = rounded;
+ sortedBuffer = MemoryUtilities.memRealloc(sortedBuffer, pow2);
+ sortedBufferAddr = MemoryUtilities.memAddress(sortedBuffer, 0);
+ sortedBufferCapacity = pow2;
+ }
+
+ final long srcBase = emitBufferAddr;
+ int q = 0;
+ while (q < quadTotal) {
+ final int key = quadSortKey[q];
+ int runEnd = q + 1;
+ while (runEnd < quadTotal && quadSortKey[runEnd] == key) runEnd++;
+ final int runLen = runEnd - q;
+ final long runBytes = (long) runLen * quadBytes;
+ MemoryUtilities.memCopy(srcBase + (long) q * quadBytes,
+ sortedBufferAddr + (long) faceWedgeCursor[key] * quadBytes, runBytes);
+ faceWedgeCursor[key] += runLen;
+ q = runEnd;
+ }
+
+ sortedBuffer.position(0).limit(totalBytes);
+ return sortedBuffer;
+ }
+}
diff --git a/src/main/resources/assets/angelica/shaders/cloud.frag b/src/main/resources/assets/angelica/shaders/cloud.frag
index 6b8772909..245537a0b 100644
--- a/src/main/resources/assets/angelica/shaders/cloud.frag
+++ b/src/main/resources/assets/angelica/shaders/cloud.frag
@@ -1,36 +1,30 @@
#version 330 core
-in vec2 v_UV;
-in vec3 v_EyePos;
-in float v_Factor;
+#import
+#ifndef UNTEXTURED
+in vec2 v_UV;
+#endif
+in vec3 v_EyePos;
+in float v_Shade;
+
+#ifndef UNTEXTURED
uniform sampler2D u_Tex;
+#endif
uniform vec4 u_ColorMult;
-uniform vec4 u_FogParams; // linear: x=-1/(end-start), y=end/(end-start); exp/exp2: z=density; w=mode (0=linear, 1=exp, 2=exp2)
-uniform vec4 u_FogColor;
-uniform bool u_FogEnabled;
out vec4 fragColor;
void main() {
+#ifdef UNTEXTURED
+ vec4 color = u_ColorMult;
+#else
vec4 texel = texture(u_Tex, v_UV);
if (texel.a < 0.1) discard;
vec4 color = texel * u_ColorMult;
- color.rgb *= v_Factor;
-
- if (u_FogEnabled) {
- float fogCoord = length(v_EyePos);
- float f;
- if (u_FogParams.w == 0.0) {
- f = fogCoord * u_FogParams.x + u_FogParams.y;
- } else if (u_FogParams.w == 1.0) {
- f = exp(-u_FogParams.z * fogCoord);
- } else {
- float d = u_FogParams.z * fogCoord;
- f = exp(-d * d);
- }
- color.rgb = mix(u_FogColor.rgb, color.rgb, clamp(f, 0.0, 1.0));
- }
+#endif
+ color.rgb *= v_Shade;
+ color.rgb = applyCloudFog(color.rgb, v_EyePos);
fragColor = color;
}
diff --git a/src/main/resources/assets/angelica/shaders/cloud.vert b/src/main/resources/assets/angelica/shaders/cloud.vert
index 5d10643a0..f448f6be4 100644
--- a/src/main/resources/assets/angelica/shaders/cloud.vert
+++ b/src/main/resources/assets/angelica/shaders/cloud.vert
@@ -1,19 +1,25 @@
#version 330 core
layout(location = 0) in vec3 a_Position;
+#ifndef UNTEXTURED
layout(location = 2) in vec2 a_UV;
-layout(location = 5) in float a_Factor;
+#endif
+layout(location = 5) in float a_Shade;
uniform mat4 u_MVPMatrix;
uniform mat4 u_MVMatrix;
+#ifndef UNTEXTURED
out vec2 v_UV;
+#endif
out vec3 v_EyePos;
-out float v_Factor;
+out float v_Shade;
void main() {
gl_Position = u_MVPMatrix * vec4(a_Position, 1.0);
+#ifndef UNTEXTURED
v_UV = a_UV;
+#endif
v_EyePos = (u_MVMatrix * vec4(a_Position, 1.0)).xyz;
- v_Factor = a_Factor;
+ v_Shade = a_Shade;
}
diff --git a/src/main/resources/assets/angelica/shaders/cloud_faces.frag b/src/main/resources/assets/angelica/shaders/cloud_faces.frag
new file mode 100644
index 000000000..00bc8bd26
--- /dev/null
+++ b/src/main/resources/assets/angelica/shaders/cloud_faces.frag
@@ -0,0 +1,29 @@
+#version 330 core
+
+#import
+
+in vec3 v_EyePos;
+flat in float v_Shade;
+
+#ifndef UNTEXTURED
+in vec2 v_UV;
+uniform sampler2D u_Tex;
+#endif
+
+uniform vec4 u_ColorMult;
+
+out vec4 fragColor;
+
+void main() {
+#ifdef UNTEXTURED
+ vec4 color = u_ColorMult;
+#else
+ vec4 texel = texture(u_Tex, v_UV);
+ if (texel.a < 0.1) discard;
+ vec4 color = texel * u_ColorMult;
+#endif
+ color.rgb *= v_Shade;
+ color.rgb = applyCloudFog(color.rgb, v_EyePos);
+
+ fragColor = color;
+}
diff --git a/src/main/resources/assets/angelica/shaders/cloud_faces.vert b/src/main/resources/assets/angelica/shaders/cloud_faces.vert
new file mode 100644
index 000000000..2dec14732
--- /dev/null
+++ b/src/main/resources/assets/angelica/shaders/cloud_faces.vert
@@ -0,0 +1,59 @@
+#version 330 core
+
+layout(location = 0) in int a_Face;
+
+uniform mat4 u_MVPMatrix;
+uniform mat4 u_MVMatrix;
+uniform float u_CellHeight;
+
+out vec3 v_EyePos;
+flat out float v_Shade;
+
+#ifndef UNTEXTURED
+uniform vec4 u_Scroll;
+out vec2 v_UV;
+const float SCROLL_SPEED = 1.0 / 256.0;
+const int DIR_NORTH = 2;
+const int DIR_WEST = 4;
+#endif
+
+const int FLAG_INSIDE = 1;
+
+const vec3 CORNERS[24] = vec3[24](
+ vec3(1, 0, 0), vec3(1, 0, 1), vec3(0, 0, 1), vec3(0, 0, 0),
+ vec3(0, 1, 0), vec3(0, 1, 1), vec3(1, 1, 1), vec3(1, 1, 0),
+ vec3(0, 0, 0), vec3(0, 1, 0), vec3(1, 1, 0), vec3(1, 0, 0),
+ vec3(1, 0, 1), vec3(1, 1, 1), vec3(0, 1, 1), vec3(0, 0, 1),
+ vec3(0, 0, 1), vec3(0, 1, 1), vec3(0, 1, 0), vec3(0, 0, 0),
+ vec3(1, 0, 0), vec3(1, 1, 0), vec3(1, 1, 1), vec3(1, 0, 1)
+);
+
+const float FACE_SHADE[6] = float[6](0.7, 1.0, 0.8, 0.8, 0.9, 0.9);
+
+void main() {
+ int faceBits = a_Face;
+
+ int cellX = (faceBits & 0x3FF) - 512;
+ int cellZ = ((faceBits >> 10) & 0x3FF) - 512;
+ int dir = (faceBits >> 20) & 7;
+ int flags = (faceBits >> 23) & 3;
+
+ vec3 extent = vec3(1.0, u_CellHeight, 1.0);
+
+ int corner = gl_VertexID;
+ if ((flags & FLAG_INSIDE) != 0) corner = 3 - corner;
+ vec3 unit = vec3(CORNERS[dir * 4 + corner]);
+
+ vec3 pos = vec3(float(cellX), 0.0, float(cellZ)) + unit * extent;
+
+#ifndef UNTEXTURED
+ vec2 uvCell = vec2(float(cellX), float(cellZ)) + unit.xz;
+ if (dir >= DIR_WEST) uvCell.x = float(cellX) + 0.5;
+ else if (dir >= DIR_NORTH) uvCell.y = float(cellZ) + 0.5;
+ v_UV = uvCell * SCROLL_SPEED + u_Scroll.xy;
+#endif
+
+ gl_Position = u_MVPMatrix * vec4(pos, 1.0);
+ v_EyePos = (u_MVMatrix * vec4(pos, 1.0)).xyz;
+ v_Shade = FACE_SHADE[dir];
+}
diff --git a/src/main/resources/assets/angelica/shaders/include/cloud_fog.glsl b/src/main/resources/assets/angelica/shaders/include/cloud_fog.glsl
new file mode 100644
index 000000000..752f95b40
--- /dev/null
+++ b/src/main/resources/assets/angelica/shaders/include/cloud_fog.glsl
@@ -0,0 +1,19 @@
+uniform vec4 u_FogParams; // linear: x=-1/(end-start), y=end/(end-start); exp/exp2: z=density; w=mode (0=linear, 1=exp, 2=exp2)
+uniform vec4 u_FogColor;
+uniform bool u_FogEnabled;
+
+vec3 applyCloudFog(vec3 color, vec3 eyePos) {
+ if (!u_FogEnabled) return color;
+
+ float fogCoord = length(eyePos);
+ float f;
+ if (u_FogParams.w == 0.0) {
+ f = fogCoord * u_FogParams.x + u_FogParams.y;
+ } else if (u_FogParams.w == 1.0) {
+ f = exp(-u_FogParams.z * fogCoord);
+ } else {
+ float d = u_FogParams.z * fogCoord;
+ f = exp(-d * d);
+ }
+ return mix(u_FogColor.rgb, color, clamp(f, 0.0, 1.0));
+}