Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
# mesher
|
||||
|
||||
- Only `java.lang`, `java.util` and `org.jspecify.*`: no game types, no TeaVM, no other module.
|
||||
It's compiled on its own into the page's worker module (`mesher.wasm`), and it must stay small.
|
||||
`BoundaryTest` fails otherwise.
|
||||
- Worker-side code: no game objects, nothing but the flat formats defined here (`MeshTables`,
|
||||
`Snapshot`, `MeshResult`, `MeshJobs`' messages). A change to a format changes both sides:
|
||||
`client`'s `incari.client.render.mesher` fills and reads them.
|
||||
- The mesher writes exactly what the game's section compiler writes, vertex for vertex. A change
|
||||
to what it writes must still pass `./gradlew :app-desktop:smokeMesher` (a display and the game's
|
||||
assets: every section meshed both ways and compared, the debug world's every block state
|
||||
included).
|
||||
- Hot paths (`SectionMesher`, `FluidMesher`, `VertexFormats`, `QuadSorter`) don't allocate once
|
||||
their scratch space has grown.
|
||||
- Test: `./gradlew :mesher:check`, then `smokeMesher` for anything that changes a mesh.
|
||||
@@ -0,0 +1,30 @@
|
||||
# mesher: the terrain mesher
|
||||
|
||||
Turns a section of terrain into vertex data, off the game's thread (ADR 0023). The game copies a
|
||||
section and its border into a flat `Snapshot`; the mesher builds the block and fluid quads, lighting,
|
||||
face culling, visibility and the sorted translucent layer from `MeshTables` (built once from the
|
||||
game's models). The output is byte-identical to the game's own section compiler.
|
||||
|
||||
In the browser it runs in Web Workers as `mesher.wasm` (~120 KB). On the desktop, and for meshes
|
||||
needed at once, it runs in the game.
|
||||
|
||||
## Code map
|
||||
|
||||
- `SectionMesher`: meshes a `Snapshot` into a `MeshResult`.
|
||||
- `MeshTables` and its `Builder`: the tables, as the game's side fills them.
|
||||
- `MeshJobs`: a worker's side of the conversation (tables, meshes, re-sorts).
|
||||
- `GameMath`: the game's position hash, random and table trigonometry, which meshes depend on.
|
||||
- `VertexFormats`: the game's 28-byte block vertex and Incari's 16-byte compact one.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Depends on nothing** but the JDK's basics and JSpecify (`BoundaryTest`).
|
||||
- **Exact**: the desktop's `smokeMesher` compares every section with the game's compiler.
|
||||
- **Allocation-free once warm** on the hot paths.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :mesher:check
|
||||
./gradlew :app-desktop:smokeMesher # a display: the game meshes varied worlds both ways
|
||||
```
|
||||
@@ -0,0 +1,17 @@
|
||||
plugins {
|
||||
`java-library`
|
||||
}
|
||||
|
||||
// The terrain mesher (ADR 0023): turns a flat snapshot of a section and its surroundings into
|
||||
// vertex data, using tables built from the game's models. No game types and no dependencies, so it
|
||||
// compiles on its own into the small WebAssembly module the page's mesher workers run, and runs in
|
||||
// the game itself where there are no workers (the desktop, or a mesh the render thread needs now).
|
||||
dependencies {
|
||||
api(libs.jspecify)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testImplementation(libs.archunit)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* The fixed geometry of the game's smooth lighting: for each face direction, the four neighbors
|
||||
* around the face that are sampled (in the order the game samples them), which pair of them each of
|
||||
* the four blended corner samples combines, and which of the quad's vertices each of the face's
|
||||
* corners lights.
|
||||
*/
|
||||
final class AmbientOcclusion {
|
||||
|
||||
private AmbientOcclusion() {}
|
||||
|
||||
/** Per face direction, the four directions around it that are sampled. */
|
||||
static final int[][] CORNERS = {
|
||||
{Dirs.WEST, Dirs.EAST, Dirs.NORTH, Dirs.SOUTH}, // down
|
||||
{Dirs.EAST, Dirs.WEST, Dirs.NORTH, Dirs.SOUTH}, // up
|
||||
{Dirs.UP, Dirs.DOWN, Dirs.EAST, Dirs.WEST}, // north
|
||||
{Dirs.WEST, Dirs.EAST, Dirs.DOWN, Dirs.UP}, // south
|
||||
{Dirs.UP, Dirs.DOWN, Dirs.NORTH, Dirs.SOUTH}, // west
|
||||
{Dirs.DOWN, Dirs.UP, Dirs.NORTH, Dirs.SOUTH}, // east
|
||||
};
|
||||
|
||||
/**
|
||||
* The four blended samples, each the pair of {@link #CORNERS} entries whose diagonal it sits on
|
||||
* (first the one across the face's second axis, then the first).
|
||||
*/
|
||||
static final int[][] SAMPLE_CORNERS = {{3, 0}, {2, 0}, {2, 1}, {3, 1}};
|
||||
|
||||
/** Per face direction, the quad vertex each of the four face corners (samples) lights. */
|
||||
static final int[][] VERTEX_OF_CORNER = {
|
||||
{0, 1, 2, 3}, // down
|
||||
{2, 3, 0, 1}, // up
|
||||
{3, 0, 1, 2}, // north
|
||||
{0, 1, 2, 3}, // south
|
||||
{3, 0, 1, 2}, // west
|
||||
{1, 2, 3, 0}, // east
|
||||
};
|
||||
|
||||
/**
|
||||
* The game's smooth blend of three neighbors' light with the center's: a dark neighbor
|
||||
* (nothing, or no sky light) borrows the center's where the center is lit, then the four are
|
||||
* averaged, block and sky light separately.
|
||||
*/
|
||||
static int blend(int neighbor1, int neighbor2, int neighbor3, int center) {
|
||||
if (sky(center) > 2 || block(center) > 2) {
|
||||
neighbor1 = borrow(neighbor1, center);
|
||||
neighbor2 = borrow(neighbor2, center);
|
||||
neighbor3 = borrow(neighbor3, center);
|
||||
}
|
||||
return ((neighbor1 + neighbor2 + neighbor3 + center) >> 2) & 0xFF00FF;
|
||||
}
|
||||
|
||||
private static int borrow(int neighbor, int center) {
|
||||
if (neighbor == 0) {
|
||||
return center;
|
||||
}
|
||||
return sky(neighbor) == 0 ? neighbor | (center & 0xFF0000) : neighbor;
|
||||
}
|
||||
|
||||
/** The four blended corners weighted by where a vertex sits between them. */
|
||||
static int weightedBlend(int c1, int c2, int c3, int c4, float w1, float w2, float w3, float w4) {
|
||||
int sky = (int)
|
||||
((c1 >> 16 & 0xFF) * w1 + (c2 >> 16 & 0xFF) * w2 + (c3 >> 16 & 0xFF) * w3 + (c4 >> 16 & 0xFF) * w4);
|
||||
int block = (int) ((c1 & 0xFF) * w1 + (c2 & 0xFF) * w2 + (c3 & 0xFF) * w3 + (c4 & 0xFF) * w4);
|
||||
return (block & 0xFF) | (sky & 0xFF) << 16;
|
||||
}
|
||||
|
||||
/** The block light level of packed light coordinates. */
|
||||
static int block(int packed) {
|
||||
return packed >> 4 & 15;
|
||||
}
|
||||
|
||||
/** The sky light level of packed light coordinates. */
|
||||
static int sky(int packed) {
|
||||
return packed >> 20 & 15;
|
||||
}
|
||||
|
||||
static int pack(int block, int sky) {
|
||||
return block << 4 | sky << 20;
|
||||
}
|
||||
|
||||
/** Light coordinates raised to a quad's own light emission. */
|
||||
static int withEmission(int packed, int emission) {
|
||||
if (emission == 0) {
|
||||
return packed;
|
||||
}
|
||||
return pack(Math.max(block(packed), emission), Math.max(sky(packed), emission));
|
||||
}
|
||||
|
||||
/** Light coordinates with each of block and sky light the brighter of the two. */
|
||||
static int max(int a, int b) {
|
||||
return pack(Math.max(block(a), block(b)), Math.max(sky(a), sky(b)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Little-endian bytes for the formats that cross into a worker: the tables, snapshots and results.
|
||||
* Plain arrays rather than {@code ByteBuffer}s, so the worker's module needs nothing from the class
|
||||
* library but arrays.
|
||||
*/
|
||||
public final class Bytes {
|
||||
|
||||
private Bytes() {}
|
||||
|
||||
/** A growable byte array written from the front. */
|
||||
public static final class Out {
|
||||
|
||||
private byte[] data;
|
||||
private int size;
|
||||
|
||||
public Out(int capacity) {
|
||||
data = new byte[Math.max(16, capacity)];
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
/** The bytes written so far; valid until the next write. */
|
||||
public byte[] array() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public byte[] toArray() {
|
||||
return Arrays.copyOf(data, size);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
size = 0;
|
||||
}
|
||||
|
||||
private void ensure(int more) {
|
||||
if (size + more > data.length) {
|
||||
data = Arrays.copyOf(data, Math.max(size + more, data.length * 2));
|
||||
}
|
||||
}
|
||||
|
||||
/** Makes room for {@code count} bytes and returns where they start in {@link #array}. */
|
||||
public int reserve(int count) {
|
||||
ensure(count);
|
||||
int at = size;
|
||||
size += count;
|
||||
return at;
|
||||
}
|
||||
|
||||
public void putByte(int value) {
|
||||
ensure(1);
|
||||
data[size++] = (byte) value;
|
||||
}
|
||||
|
||||
public void putShort(int value) {
|
||||
ensure(2);
|
||||
data[size] = (byte) value;
|
||||
data[size + 1] = (byte) (value >> 8);
|
||||
size += 2;
|
||||
}
|
||||
|
||||
public void putInt(int value) {
|
||||
ensure(4);
|
||||
putIntAt(data, size, value);
|
||||
size += 4;
|
||||
}
|
||||
|
||||
public void putLong(long value) {
|
||||
putInt((int) value);
|
||||
putInt((int) (value >>> 32));
|
||||
}
|
||||
|
||||
public void putFloat(float value) {
|
||||
putInt(Float.floatToRawIntBits(value));
|
||||
}
|
||||
|
||||
public void putBytes(byte[] source, int offset, int length) {
|
||||
ensure(length);
|
||||
System.arraycopy(source, offset, data, size, length);
|
||||
size += length;
|
||||
}
|
||||
|
||||
public void putInts(int[] values, int count) {
|
||||
putInt(count);
|
||||
ensure(count * 4);
|
||||
for (int i = 0; i < count; i++) {
|
||||
putIntAt(data, size, values[i]);
|
||||
size += 4;
|
||||
}
|
||||
}
|
||||
|
||||
public void putFloats(float[] values, int count) {
|
||||
putInt(count);
|
||||
ensure(count * 4);
|
||||
for (int i = 0; i < count; i++) {
|
||||
putIntAt(data, size, Float.floatToRawIntBits(values[i]));
|
||||
size += 4;
|
||||
}
|
||||
}
|
||||
|
||||
public void putShorts(short[] values, int count) {
|
||||
putInt(count);
|
||||
ensure(count * 2);
|
||||
for (int i = 0; i < count; i++) {
|
||||
data[size] = (byte) values[i];
|
||||
data[size + 1] = (byte) (values[i] >> 8);
|
||||
size += 2;
|
||||
}
|
||||
}
|
||||
|
||||
public void putChars(char[] values, int count) {
|
||||
putInt(count);
|
||||
ensure(count * 2);
|
||||
for (int i = 0; i < count; i++) {
|
||||
data[size] = (byte) values[i];
|
||||
data[size + 1] = (byte) (values[i] >> 8);
|
||||
size += 2;
|
||||
}
|
||||
}
|
||||
|
||||
public void putByteArray(byte[] values, int count) {
|
||||
putInt(count);
|
||||
putBytes(values, 0, count);
|
||||
}
|
||||
|
||||
public void putLongs(long[] values, int count) {
|
||||
putInt(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
putLong(values[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads what {@link Out} wrote. */
|
||||
public static final class In {
|
||||
|
||||
private final byte[] data;
|
||||
private int position;
|
||||
private final int end;
|
||||
|
||||
public In(byte[] data, int offset, int length) {
|
||||
this.data = data;
|
||||
this.position = offset;
|
||||
this.end = offset + length;
|
||||
}
|
||||
|
||||
public int position() {
|
||||
return position;
|
||||
}
|
||||
|
||||
private void need(int count) {
|
||||
if (position + count > end) {
|
||||
throw new IllegalStateException("Read past the end: " + (position + count) + " > " + end);
|
||||
}
|
||||
}
|
||||
|
||||
public int getByte() {
|
||||
need(1);
|
||||
return data[position++];
|
||||
}
|
||||
|
||||
public int getUnsignedByte() {
|
||||
return getByte() & 0xFF;
|
||||
}
|
||||
|
||||
public int getShort() {
|
||||
need(2);
|
||||
int value = (data[position] & 0xFF) | data[position + 1] << 8;
|
||||
position += 2;
|
||||
return value;
|
||||
}
|
||||
|
||||
public int getInt() {
|
||||
need(4);
|
||||
int value = intAt(data, position);
|
||||
position += 4;
|
||||
return value;
|
||||
}
|
||||
|
||||
public long getLong() {
|
||||
long low = getInt() & 0xFFFFFFFFL;
|
||||
long high = getInt() & 0xFFFFFFFFL;
|
||||
return low | high << 32;
|
||||
}
|
||||
|
||||
public float getFloat() {
|
||||
return Float.intBitsToFloat(getInt());
|
||||
}
|
||||
|
||||
public void getBytes(byte[] target, int offset, int length) {
|
||||
need(length);
|
||||
System.arraycopy(data, position, target, offset, length);
|
||||
position += length;
|
||||
}
|
||||
|
||||
public int[] getInts() {
|
||||
int count = getInt();
|
||||
need(count * 4);
|
||||
int[] values = new int[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
values[i] = intAt(data, position);
|
||||
position += 4;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
public float[] getFloats() {
|
||||
int count = getInt();
|
||||
need(count * 4);
|
||||
float[] values = new float[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
values[i] = Float.intBitsToFloat(intAt(data, position));
|
||||
position += 4;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
public short[] getShorts() {
|
||||
int count = getInt();
|
||||
need(count * 2);
|
||||
short[] values = new short[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
values[i] = (short) ((data[position] & 0xFF) | (data[position + 1] << 8));
|
||||
position += 2;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** Reads chars into {@code target}, which must be exactly as long as what was written. */
|
||||
public void getChars(char[] target) {
|
||||
int count = getInt();
|
||||
if (count != target.length) {
|
||||
throw new IllegalStateException("Expected " + target.length + " chars, found " + count);
|
||||
}
|
||||
need(count * 2);
|
||||
for (int i = 0; i < count; i++) {
|
||||
target[i] = (char) ((data[position] & 0xFF) | (data[position + 1] & 0xFF) << 8);
|
||||
position += 2;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] getByteArray() {
|
||||
int count = getInt();
|
||||
byte[] values = new byte[count];
|
||||
getBytes(values, 0, count);
|
||||
return values;
|
||||
}
|
||||
|
||||
/** Reads bytes into {@code target}, which must be exactly as long as what was written. */
|
||||
public void getByteArray(byte[] target) {
|
||||
int count = getInt();
|
||||
if (count != target.length) {
|
||||
throw new IllegalStateException("Expected " + target.length + " bytes, found " + count);
|
||||
}
|
||||
getBytes(target, 0, count);
|
||||
}
|
||||
|
||||
public long[] getLongs() {
|
||||
int count = getInt();
|
||||
long[] values = new long[count];
|
||||
for (int i = 0; i < count; i++) {
|
||||
values[i] = getLong();
|
||||
}
|
||||
return values;
|
||||
}
|
||||
}
|
||||
|
||||
static void putIntAt(byte[] data, int at, int value) {
|
||||
data[at] = (byte) value;
|
||||
data[at + 1] = (byte) (value >> 8);
|
||||
data[at + 2] = (byte) (value >> 16);
|
||||
data[at + 3] = (byte) (value >> 24);
|
||||
}
|
||||
|
||||
static void putShortAt(byte[] data, int at, int value) {
|
||||
data[at] = (byte) value;
|
||||
data[at + 1] = (byte) (value >> 8);
|
||||
}
|
||||
|
||||
static void putFloatAt(byte[] data, int at, float value) {
|
||||
putIntAt(data, at, Float.floatToRawIntBits(value));
|
||||
}
|
||||
|
||||
static int intAt(byte[] data, int at) {
|
||||
return (data[at] & 0xFF) | (data[at + 1] & 0xFF) << 8 | (data[at + 2] & 0xFF) << 16 | data[at + 3] << 24;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package incari.mesher;
|
||||
|
||||
/** The six directions as indices, in the game's order: down, up, north, south, west, east. */
|
||||
final class Dirs {
|
||||
|
||||
private Dirs() {}
|
||||
|
||||
static final int DOWN = 0;
|
||||
static final int UP = 1;
|
||||
static final int NORTH = 2;
|
||||
static final int SOUTH = 3;
|
||||
static final int WEST = 4;
|
||||
static final int EAST = 5;
|
||||
|
||||
static final int[] STEP_X = {0, 0, 0, 0, -1, 1};
|
||||
static final int[] STEP_Y = {-1, 1, 0, 0, 0, 0};
|
||||
static final int[] STEP_Z = {0, 0, -1, 1, 0, 0};
|
||||
|
||||
/** The horizontal directions in the game's order for them: north, east, south, west. */
|
||||
static final int[] HORIZONTAL = {NORTH, EAST, SOUTH, WEST};
|
||||
|
||||
static int opposite(int direction) {
|
||||
return direction ^ 1;
|
||||
}
|
||||
|
||||
/** The direction's axis as x = 0, y = 1, z = 2. */
|
||||
static int axisXyz(int direction) {
|
||||
return switch (direction) {
|
||||
case DOWN, UP -> 1;
|
||||
case NORTH, SOUTH -> 2;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
/** Up, south and east point along their axis; the others against it. */
|
||||
static boolean positive(int direction) {
|
||||
return (direction & 1) == 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* Which way a quad faces, for drawing only the quads a camera can see the front of (ADR 0030).
|
||||
*
|
||||
* <p>A quad whose corners lie in one plane across an axis faces along that axis, toward its front
|
||||
* (counter-clockwise winding, as the terrain pipelines cull). The solid and cutout layers group
|
||||
* their quads by facing ({@link #runOf}'s order), so the quads facing away from the camera are one
|
||||
* range the draw can skip; the GPU would cull them all anyway. Anything else (tilted quads, crossed
|
||||
* plants, sloped fluid, planes far outside the section) is {@link #UNASSIGNED} and always drawn.
|
||||
*
|
||||
* <p>Decided from a quad's positions alone, the same way for the game's mesh and Incari's, so the
|
||||
* desktop's comparison of the two can group the game's quads as the mesher does.
|
||||
*/
|
||||
public final class Facings {
|
||||
|
||||
private Facings() {}
|
||||
|
||||
/** The six directions, in the game's order (down, up, north, south, west, east), then this. */
|
||||
public static final int UNASSIGNED = 6;
|
||||
|
||||
public static final int COUNT = 7;
|
||||
|
||||
/**
|
||||
* A facing's run: where its quads come in a layer grouped by facing. Unassigned first, then the
|
||||
* directions in the game's order.
|
||||
*/
|
||||
public static int runOf(int facing) {
|
||||
return facing == UNASSIGNED ? 0 : facing + 1;
|
||||
}
|
||||
|
||||
/** The facing of a run: the inverse of {@link #runOf}. */
|
||||
public static int facingOfRun(int run) {
|
||||
return run == 0 ? UNASSIGNED : run - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far outside its section, in blocks, a quad's plane may lie and still be assigned a facing.
|
||||
* Block models reach at most a block past their own (elements from -16 to 32), and plant
|
||||
* offsets a quarter more.
|
||||
*/
|
||||
public static final float PLANE_MARGIN = 2.0F;
|
||||
|
||||
/**
|
||||
* How far past {@link #PLANE_MARGIN} the camera must be before a section's away-facing quads
|
||||
* are skipped: room for view bobbing (the eye moves off the camera's position) and rounding.
|
||||
* Closer than that, a section draws them all.
|
||||
*/
|
||||
public static final float CAMERA_MARGIN = 1.0F;
|
||||
|
||||
/**
|
||||
* The facing of the quad with these corners (section-relative block coordinates, in the order
|
||||
* they're written: triangles 0 1 2 and 2 3 0).
|
||||
*/
|
||||
@SuppressWarnings("ParameterNumber") // one quad's twelve coordinates, unboxed: a hot path
|
||||
public static int of(
|
||||
float x0,
|
||||
float y0,
|
||||
float z0,
|
||||
float x1,
|
||||
float y1,
|
||||
float z1,
|
||||
float x2,
|
||||
float y2,
|
||||
float z2,
|
||||
float x3,
|
||||
float y3,
|
||||
float z3) {
|
||||
boolean flatX = x0 == x1 && x0 == x2 && x0 == x3;
|
||||
boolean flatY = y0 == y1 && y0 == y2 && y0 == y3;
|
||||
boolean flatZ = z0 == z1 && z0 == z2 && z0 == z3;
|
||||
// The normals of both triangles: (p1 - p0) x (p2 - p0) and (p2 - p0) x (p3 - p0).
|
||||
float ax = x1 - x0;
|
||||
float ay = y1 - y0;
|
||||
float az = z1 - z0;
|
||||
float bx = x2 - x0;
|
||||
float by = y2 - y0;
|
||||
float bz = z2 - z0;
|
||||
float cx = x3 - x0;
|
||||
float cy = y3 - y0;
|
||||
float cz = z3 - z0;
|
||||
if (flatX && !flatY && !flatZ) {
|
||||
return facing(ay * bz - az * by, by * cz - bz * cy, x0, 5, 4);
|
||||
}
|
||||
if (flatY && !flatX && !flatZ) {
|
||||
return facing(az * bx - ax * bz, bz * cx - bx * cz, y0, 1, 0);
|
||||
}
|
||||
if (flatZ && !flatX && !flatY) {
|
||||
return facing(ax * by - ay * bx, bx * cy - by * cx, z0, 3, 2);
|
||||
}
|
||||
return UNASSIGNED;
|
||||
}
|
||||
|
||||
/**
|
||||
* The facing of a flat quad from its triangles' normals along its axis: both toward the same
|
||||
* side (or one degenerate), and its plane near the section.
|
||||
*/
|
||||
private static int facing(float first, float second, float plane, int positive, int negative) {
|
||||
if (plane < -PLANE_MARGIN || plane > 16.0F + PLANE_MARGIN) {
|
||||
return UNASSIGNED;
|
||||
}
|
||||
if (first >= 0.0F && second >= 0.0F && (first > 0.0F || second > 0.0F)) {
|
||||
return positive;
|
||||
}
|
||||
if (first <= 0.0F && second <= 0.0F && (first < 0.0F || second < 0.0F)) {
|
||||
return negative;
|
||||
}
|
||||
return UNASSIGNED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which facings a camera at these section-relative coordinates may see the front of, as bits
|
||||
* (bit {@code f} for facing {@code f}, {@link #UNASSIGNED} always set).
|
||||
*/
|
||||
public static int visible(float cameraX, float cameraY, float cameraZ) {
|
||||
float low = -PLANE_MARGIN - CAMERA_MARGIN;
|
||||
float high = 16.0F + PLANE_MARGIN + CAMERA_MARGIN;
|
||||
int bits = 1 << UNASSIGNED;
|
||||
// A face toward +axis has its front on the +axis side of its plane, which lies at or above
|
||||
// -PLANE_MARGIN: from below `low` none of them can be seen.
|
||||
bits |= cameraY < high ? 1 : 0; // down
|
||||
bits |= cameraY > low ? 1 << 1 : 0; // up
|
||||
bits |= cameraZ < high ? 1 << 2 : 0; // north
|
||||
bits |= cameraZ > low ? 1 << 3 : 0; // south
|
||||
bits |= cameraX < high ? 1 << 4 : 0; // west
|
||||
bits |= cameraX > low ? 1 << 5 : 0; // east
|
||||
return bits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ranges of a layer's quads to draw for a camera that sees {@code facings} (bits from
|
||||
* {@link #visible}): its runs ({@code runs[base]} to {@code runs[base + COUNT - 1]}, in
|
||||
* {@link #runOf}'s order) whose facing is seen, runs next to each other merged into one range.
|
||||
*
|
||||
* @param ranges filled with each range's first quad and quad count, in pairs; at least
|
||||
* {@code 2 * COUNT} long
|
||||
* @return how many ranges
|
||||
*/
|
||||
public static int visibleRanges(int[] runs, int base, int facings, int[] ranges) {
|
||||
int count = 0;
|
||||
int quad = 0;
|
||||
int start = -1;
|
||||
int end = -1;
|
||||
for (int run = 0; run < COUNT; run++) {
|
||||
int quads = runs[base + run];
|
||||
if (quads == 0) {
|
||||
continue;
|
||||
}
|
||||
if ((facings & 1 << facingOfRun(run)) != 0) {
|
||||
if (start != -1 && end != quad) {
|
||||
ranges[count * 2] = start;
|
||||
ranges[count * 2 + 1] = end - start;
|
||||
count++;
|
||||
start = -1;
|
||||
}
|
||||
if (start == -1) {
|
||||
start = quad;
|
||||
}
|
||||
end = quad + quads;
|
||||
}
|
||||
quad += quads;
|
||||
}
|
||||
if (start != -1) {
|
||||
ranges[count * 2] = start;
|
||||
ranges[count * 2 + 1] = end - start;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* A translucent layer's order that holds from every camera, so it never needs sorting again
|
||||
* (Sodium's static translucency sorting, written fresh).
|
||||
*
|
||||
* <p>The game sorts a section's translucent quads back to front by their centers, again whenever
|
||||
* the camera crosses a block near the section or moves to another side of it. But when every quad
|
||||
* lies flat across one axis (the still water of a lake or the sea: its surface, and the surface
|
||||
* seen from below), one order is right for any camera, because the terrain pipelines cull back
|
||||
* faces:
|
||||
*
|
||||
* <ul>
|
||||
* <li>A quad facing +axis is drawn only while the camera is on its + side, and a ray from the
|
||||
* camera meets the lower of two such planes later: it's farther, and drawn first. So quads
|
||||
* facing +axis go in rising order of their plane, and quads facing -axis in falling order.
|
||||
* <li>A quad facing +axis that's drawn lies below the camera's plane across the axis, and one
|
||||
* facing -axis above it, so the two never cover each other on screen: how they interleave
|
||||
* doesn't matter.
|
||||
* <li>Quads in one plane facing one way don't cover each other (blocks don't overlap), so they
|
||||
* keep the order they were written in.
|
||||
* </ul>
|
||||
*
|
||||
* <p>The game's order by centers can differ only where quads don't cover each other on screen (so
|
||||
* order doesn't matter), or where centers put a nearer overlapping quad first, which this order
|
||||
* gets right.
|
||||
*
|
||||
* <p>Worker-side, no game objects.
|
||||
*/
|
||||
final class FixedOrder {
|
||||
|
||||
private FixedOrder() {}
|
||||
|
||||
/**
|
||||
* Whether {@code count} quads of these facings ({@link Facings}) all lie across one axis: then
|
||||
* {@link #keys} gives their order.
|
||||
*/
|
||||
static boolean holds(byte[] facings, int count) {
|
||||
if (count == 0) {
|
||||
return false;
|
||||
}
|
||||
int axis = -1;
|
||||
for (int q = 0; q < count; q++) {
|
||||
int facing = facings[q];
|
||||
if (facing == Facings.UNASSIGNED) {
|
||||
return false;
|
||||
}
|
||||
if (axis == -1) {
|
||||
axis = facing >> 1;
|
||||
} else if (facing >> 1 != axis) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes each quad's sort key into {@code keys}, larger first ({@link QuadSorter}'s rule): a quad
|
||||
* facing +axis by its plane rising, one facing -axis by its plane falling.
|
||||
*/
|
||||
static void keys(byte[] facings, float[] planes, int count, float[] keys) {
|
||||
for (int q = 0; q < count; q++) {
|
||||
// Up, south and east (odd facings) face +axis.
|
||||
keys[q] = (facings[q] & 1) != 0 ? -planes[q] : planes[q];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* A block's fluid surfaces, as the game draws them: a top sloped by the heights of the fluid around
|
||||
* it and textured along its flow, a bottom, and sides against whatever isn't the same fluid, each
|
||||
* hidden where a neighbor's shape covers it.
|
||||
*
|
||||
* <p>Worker-side, no game objects; part of {@link SectionMesher}, whose snapshot it reads.
|
||||
*/
|
||||
final class FluidMesher {
|
||||
|
||||
/** The height of a fluid block that isn't full: what its own height is when it's a source. */
|
||||
private static final float SOURCE_HEIGHT = 0.8888889F;
|
||||
/** How far a fluid's faces are pulled in from its block's faces, against z-fighting. */
|
||||
private static final float INSET = 0.001F;
|
||||
|
||||
private final MeshTables t;
|
||||
private final SectionMesher m;
|
||||
private float weightedSum;
|
||||
private float weightTotal;
|
||||
|
||||
FluidMesher(MeshTables tables, SectionMesher mesher) {
|
||||
t = tables;
|
||||
m = mesher;
|
||||
}
|
||||
|
||||
void mesh(int x, int y, int z, int index, int state) {
|
||||
Snapshot s = m.snapshot();
|
||||
char[] states = s.states;
|
||||
int group = t.fluidGroup[state];
|
||||
int down = index + m.step(Dirs.DOWN);
|
||||
int up = index + m.step(Dirs.UP);
|
||||
int north = index + m.step(Dirs.NORTH);
|
||||
int south = index + m.step(Dirs.SOUTH);
|
||||
int west = index + m.step(Dirs.WEST);
|
||||
int east = index + m.step(Dirs.EAST);
|
||||
int downState = states[down];
|
||||
int upState = states[up];
|
||||
int northState = states[north];
|
||||
int southState = states[south];
|
||||
int westState = states[west];
|
||||
int eastState = states[east];
|
||||
|
||||
boolean showUp = t.fluidGroup[upState] != group;
|
||||
boolean showDown =
|
||||
sideShows(state, Dirs.DOWN, downState, group) && !covered(Dirs.DOWN, SOURCE_HEIGHT, downState);
|
||||
boolean showNorth = sideShows(state, Dirs.NORTH, northState, group);
|
||||
boolean showSouth = sideShows(state, Dirs.SOUTH, southState, group);
|
||||
boolean showWest = sideShows(state, Dirs.WEST, westState, group);
|
||||
boolean showEast = sideShows(state, Dirs.EAST, eastState, group);
|
||||
if (!(showUp || showDown || showEast || showWest || showNorth || showSouth)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int model = t.fluidModel[state];
|
||||
int layer = t.fluidModelLayer[model];
|
||||
int flags = t.fluidModelFlags[model];
|
||||
int blockIndex = Snapshot.blockIndex(x, y, z);
|
||||
int tint = (flags & MeshTables.FLUID_MODEL_TINTED) != 0 ? m.fluidTint(blockIndex) : -1;
|
||||
float[] light = s.cardinalLighting;
|
||||
|
||||
float self = height(group, index, state);
|
||||
float northEast;
|
||||
float northWest;
|
||||
float southEast;
|
||||
float southWest;
|
||||
if (self >= 1.0F) {
|
||||
northEast = 1.0F;
|
||||
northWest = 1.0F;
|
||||
southEast = 1.0F;
|
||||
southWest = 1.0F;
|
||||
} else {
|
||||
float heightNorth = height(group, north, northState);
|
||||
float heightSouth = height(group, south, southState);
|
||||
float heightEast = height(group, east, eastState);
|
||||
float heightWest = height(group, west, westState);
|
||||
northEast = cornerHeight(group, self, heightNorth, heightEast, north + m.step(Dirs.EAST));
|
||||
northWest = cornerHeight(group, self, heightNorth, heightWest, north + m.step(Dirs.WEST));
|
||||
southEast = cornerHeight(group, self, heightSouth, heightEast, south + m.step(Dirs.EAST));
|
||||
southWest = cornerHeight(group, self, heightSouth, heightWest, south + m.step(Dirs.WEST));
|
||||
}
|
||||
|
||||
float fx = x;
|
||||
float fy = y;
|
||||
float fz = z;
|
||||
float bottom = showDown ? INSET : 0.0F;
|
||||
int sprites = model * 12;
|
||||
float[] sprite = t.fluidSprites;
|
||||
// Which of the fluid's animated sprites the section draws: all three, whichever faces show
|
||||
// (ADR 0030; one more marked than drawn only animates a sprite nobody sees).
|
||||
for (int i = 0; i < 3; i++) {
|
||||
int animated = t.fluidAnimated[model * 3 + i];
|
||||
if (animated != 0) {
|
||||
m.markAnimated(animated - 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (showUp
|
||||
&& !covered(
|
||||
Dirs.UP, Math.min(Math.min(northWest, southWest), Math.min(southEast, northEast)), upState)) {
|
||||
northWest -= INSET;
|
||||
southWest -= INSET;
|
||||
southEast -= INSET;
|
||||
northEast -= INSET;
|
||||
double[] flow = flow(index, state, group);
|
||||
float u00;
|
||||
float u01;
|
||||
float u10;
|
||||
float u11;
|
||||
float v00;
|
||||
float v01;
|
||||
float v10;
|
||||
float v11;
|
||||
if (flow[0] == 0.0 && flow[2] == 0.0) {
|
||||
float u0 = sprite[sprites];
|
||||
float u1 = sprite[sprites + 1];
|
||||
float v0 = sprite[sprites + 2];
|
||||
float v1 = sprite[sprites + 3];
|
||||
u00 = u0;
|
||||
v00 = v0;
|
||||
u01 = u0;
|
||||
v01 = v1;
|
||||
u10 = u1;
|
||||
v10 = v1;
|
||||
u11 = u1;
|
||||
v11 = v0;
|
||||
} else {
|
||||
float angle = (float) GameMath.atan2(flow[2], flow[0]) - (float) (Math.PI / 2);
|
||||
float sin = GameMath.sin(angle) * 0.25F;
|
||||
float cos = GameMath.cos(angle) * 0.25F;
|
||||
int flowing = sprites + 4;
|
||||
u00 = spriteU(sprite, flowing, 0.5F + (-cos - sin));
|
||||
v00 = spriteV(sprite, flowing, 0.5F + (-cos + sin));
|
||||
u01 = spriteU(sprite, flowing, 0.5F + (-cos + sin));
|
||||
v01 = spriteV(sprite, flowing, 0.5F + (cos + sin));
|
||||
u10 = spriteU(sprite, flowing, 0.5F + (cos + sin));
|
||||
v10 = spriteV(sprite, flowing, 0.5F + (cos - sin));
|
||||
u11 = spriteU(sprite, flowing, 0.5F + (cos - sin));
|
||||
v11 = spriteV(sprite, flowing, 0.5F + (-cos - sin));
|
||||
}
|
||||
int topLight = brighter(index, up);
|
||||
int topColor = SectionMesher.scale(tint, light[Dirs.UP]);
|
||||
face(
|
||||
layer,
|
||||
fx,
|
||||
fy + northWest,
|
||||
fz,
|
||||
u00,
|
||||
v00,
|
||||
fx,
|
||||
fy + southWest,
|
||||
fz + 1.0F,
|
||||
u01,
|
||||
v01,
|
||||
fx + 1.0F,
|
||||
fy + southEast,
|
||||
fz + 1.0F,
|
||||
u10,
|
||||
v10,
|
||||
fx + 1.0F,
|
||||
fy + northEast,
|
||||
fz,
|
||||
u11,
|
||||
v11,
|
||||
topColor,
|
||||
topLight,
|
||||
backwardUpFace(up, group));
|
||||
}
|
||||
|
||||
if (showDown) {
|
||||
float u0 = sprite[sprites];
|
||||
float u1 = sprite[sprites + 1];
|
||||
float v0 = sprite[sprites + 2];
|
||||
float v1 = sprite[sprites + 3];
|
||||
int downLight = brighter(down, index);
|
||||
int downColor = SectionMesher.scale(tint, light[Dirs.DOWN]);
|
||||
face(
|
||||
layer,
|
||||
fx,
|
||||
fy + bottom,
|
||||
fz,
|
||||
u0,
|
||||
v0,
|
||||
fx + 1.0F,
|
||||
fy + bottom,
|
||||
fz,
|
||||
u1,
|
||||
v0,
|
||||
fx + 1.0F,
|
||||
fy + bottom,
|
||||
fz + 1.0F,
|
||||
u1,
|
||||
v1,
|
||||
fx,
|
||||
fy + bottom,
|
||||
fz + 1.0F,
|
||||
u0,
|
||||
v1,
|
||||
downColor,
|
||||
downLight,
|
||||
false);
|
||||
}
|
||||
|
||||
int sideLight = brighter(index, up);
|
||||
for (int direction : Dirs.HORIZONTAL) {
|
||||
float h0;
|
||||
float h1;
|
||||
float x0;
|
||||
float z0;
|
||||
float x1;
|
||||
float z1;
|
||||
boolean show;
|
||||
int faceState;
|
||||
switch (direction) {
|
||||
case Dirs.NORTH -> {
|
||||
h0 = northWest;
|
||||
h1 = northEast;
|
||||
x0 = fx;
|
||||
x1 = fx + 1.0F;
|
||||
z0 = fz + INSET;
|
||||
z1 = fz + INSET;
|
||||
show = showNorth;
|
||||
faceState = northState;
|
||||
}
|
||||
case Dirs.SOUTH -> {
|
||||
h0 = southEast;
|
||||
h1 = southWest;
|
||||
x0 = fx + 1.0F;
|
||||
x1 = fx;
|
||||
z0 = fz + 1.0F - INSET;
|
||||
z1 = fz + 1.0F - INSET;
|
||||
show = showSouth;
|
||||
faceState = southState;
|
||||
}
|
||||
case Dirs.WEST -> {
|
||||
h0 = southWest;
|
||||
h1 = northWest;
|
||||
x0 = fx + INSET;
|
||||
x1 = fx + INSET;
|
||||
z0 = fz + 1.0F;
|
||||
z1 = fz;
|
||||
show = showWest;
|
||||
faceState = westState;
|
||||
}
|
||||
default -> {
|
||||
h0 = northEast;
|
||||
h1 = southEast;
|
||||
x0 = fx + 1.0F - INSET;
|
||||
x1 = fx + 1.0F - INSET;
|
||||
z0 = fz;
|
||||
z1 = fz + 1.0F;
|
||||
show = showEast;
|
||||
faceState = eastState;
|
||||
}
|
||||
}
|
||||
if (show && !covered(direction, Math.max(h0, h1), faceState)) {
|
||||
int at = sprites + 4;
|
||||
boolean overlay = false;
|
||||
if ((flags & MeshTables.FLUID_MODEL_OVERLAY) != 0
|
||||
&& (t.stateFlags[faceState] & StateFlags.FLUID_OVERLAY) != 0) {
|
||||
at = sprites + 8;
|
||||
overlay = true;
|
||||
}
|
||||
float u0 = spriteU(sprite, at, 0.0F);
|
||||
float u1 = spriteU(sprite, at, 0.5F);
|
||||
float v01 = spriteV(sprite, at, (1.0F - h0) * 0.5F);
|
||||
float v02 = spriteV(sprite, at, (1.0F - h1) * 0.5F);
|
||||
float v1 = spriteV(sprite, at, 0.5F);
|
||||
float sideShade = Dirs.axisXyz(direction) == 2 ? light[Dirs.NORTH] : light[Dirs.WEST];
|
||||
int color = SectionMesher.scale(tint, light[Dirs.UP] * sideShade);
|
||||
face(
|
||||
layer,
|
||||
x0,
|
||||
fy + h0,
|
||||
z0,
|
||||
u0,
|
||||
v01,
|
||||
x1,
|
||||
fy + h1,
|
||||
z1,
|
||||
u1,
|
||||
v02,
|
||||
x1,
|
||||
fy + bottom,
|
||||
z1,
|
||||
u1,
|
||||
v1,
|
||||
x0,
|
||||
fy + bottom,
|
||||
z0,
|
||||
u0,
|
||||
v1,
|
||||
color,
|
||||
sideLight,
|
||||
!overlay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A face toward {@code direction} shows: the neighbor isn't the same fluid, nor hidden by the block. */
|
||||
private boolean sideShows(int state, int direction, int neighborState, int group) {
|
||||
return t.fluidGroup[neighborState] != group
|
||||
&& (t.stateFlags[state] >> StateFlags.HIDES_OWN_FLUID_SHIFT & 1 << direction) == 0;
|
||||
}
|
||||
|
||||
/** Whether a neighbor's shape covers a fluid face toward it, the fluid being {@code height} high. */
|
||||
private boolean covered(int direction, float height, int neighborState) {
|
||||
int at = neighborState * 6 + direction;
|
||||
return switch (t.fluidCoverKind[at]) {
|
||||
case MeshTables.FLUID_COVER_NONE -> false;
|
||||
case MeshTables.FLUID_COVER_FULL_BLOCK -> direction != Dirs.UP || height == 1.0F;
|
||||
default -> {
|
||||
float cover = t.fluidCoverHeight[at];
|
||||
yield switch (direction) {
|
||||
case Dirs.UP -> cover > 0.0F && Math.abs(height - 1.0) <= 1.0E-7;
|
||||
case Dirs.DOWN -> cover > 0.0F;
|
||||
default -> height <= cover;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The fluid's height at a neighbor: 1 under the same fluid, its own if the same, else 0 or -1. */
|
||||
private float height(int group, int index, int state) {
|
||||
if (t.fluidGroup[state] == group) {
|
||||
return t.fluidGroup[m.snapshot().states[index + m.step(Dirs.UP)]] == group ? 1.0F : t.fluidHeight[state];
|
||||
}
|
||||
return (t.stateFlags[state] & StateFlags.LEGACY_SOLID) == 0 ? 0.0F : -1.0F;
|
||||
}
|
||||
|
||||
/** A top corner's height: the fluid's and its neighbors', solid ones counting ten times over. */
|
||||
private float cornerHeight(int group, float self, float height2, float height1, int corner) {
|
||||
if (height1 >= 1.0F || height2 >= 1.0F) {
|
||||
return 1.0F;
|
||||
}
|
||||
weightedSum = 0.0F;
|
||||
weightTotal = 0.0F;
|
||||
if (height1 > 0.0F || height2 > 0.0F) {
|
||||
float cornerHeight = height(group, corner, m.snapshot().states[corner]);
|
||||
if (cornerHeight >= 1.0F) {
|
||||
return 1.0F;
|
||||
}
|
||||
addHeight(cornerHeight);
|
||||
}
|
||||
addHeight(self);
|
||||
addHeight(height1);
|
||||
addHeight(height2);
|
||||
return weightedSum / weightTotal;
|
||||
}
|
||||
|
||||
private void addHeight(float height) {
|
||||
if (height >= 0.8F) {
|
||||
weightedSum += height * 10.0F;
|
||||
weightTotal += 10.0F;
|
||||
} else if (height >= 0.0F) {
|
||||
weightedSum += height;
|
||||
weightTotal++;
|
||||
}
|
||||
}
|
||||
|
||||
private final double[] flow = new double[3];
|
||||
|
||||
/** The direction the fluid flows in, normalized: down the slope, and down a falling fluid's walls. */
|
||||
private double[] flow(int index, int state, int group) {
|
||||
char[] states = m.snapshot().states;
|
||||
double flowX = 0.0;
|
||||
double flowZ = 0.0;
|
||||
float own = t.fluidHeight[state];
|
||||
for (int direction : Dirs.HORIZONTAL) {
|
||||
int neighbor = index + m.step(direction);
|
||||
int neighborState = states[neighbor];
|
||||
if (affectsFlow(neighborState, group)) {
|
||||
float neighborHeight = t.fluidHeight[neighborState];
|
||||
float distance = 0.0F;
|
||||
if (neighborHeight == 0.0F) {
|
||||
if ((t.stateFlags[neighborState] & StateFlags.BLOCKS_FLUID_FLOW) == 0) {
|
||||
int below = states[neighbor + m.step(Dirs.DOWN)];
|
||||
if (affectsFlow(below, group)) {
|
||||
neighborHeight = t.fluidHeight[below];
|
||||
if (neighborHeight > 0.0F) {
|
||||
distance = own - (neighborHeight - SOURCE_HEIGHT);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (neighborHeight > 0.0F) {
|
||||
distance = own - neighborHeight;
|
||||
}
|
||||
if (distance != 0.0F) {
|
||||
flowX += Dirs.STEP_X[direction] * distance;
|
||||
flowZ += Dirs.STEP_Z[direction] * distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
flow[0] = flowX;
|
||||
flow[1] = 0.0;
|
||||
flow[2] = flowZ;
|
||||
if ((t.stateFlags[state] & StateFlags.FLUID_FALLING) != 0) {
|
||||
for (int direction : Dirs.HORIZONTAL) {
|
||||
int neighbor = index + m.step(direction);
|
||||
if (solidFace(neighbor, direction, group) || solidFace(neighbor + m.step(Dirs.UP), direction, group)) {
|
||||
normalize(flow);
|
||||
flow[0] += 0.0;
|
||||
flow[1] += -6.0;
|
||||
flow[2] += 0.0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
normalize(flow);
|
||||
return flow;
|
||||
}
|
||||
|
||||
private static void normalize(double[] v) {
|
||||
double length = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
|
||||
if (length < 1.0E-5F) {
|
||||
v[0] = 0.0;
|
||||
v[1] = 0.0;
|
||||
v[2] = 0.0;
|
||||
} else {
|
||||
v[0] /= length;
|
||||
v[1] /= length;
|
||||
v[2] /= length;
|
||||
}
|
||||
}
|
||||
|
||||
/** A neighbor takes part in the flow if it holds no fluid or the same fluid. */
|
||||
private boolean affectsFlow(int neighborState, int group) {
|
||||
int neighborGroup = t.fluidGroup[neighborState];
|
||||
return neighborGroup == 0 || neighborGroup == group;
|
||||
}
|
||||
|
||||
private boolean solidFace(int index, int direction, int group) {
|
||||
int state = m.snapshot().states[index];
|
||||
if (t.fluidGroup[state] == group) {
|
||||
return false;
|
||||
}
|
||||
if (direction == Dirs.UP) {
|
||||
return true;
|
||||
}
|
||||
if ((t.stateFlags[state] & StateFlags.ICE) != 0) {
|
||||
return false;
|
||||
}
|
||||
return m.sturdy(state, index, direction);
|
||||
}
|
||||
|
||||
/** Whether the top shows from below too: some block around above lets the surface be seen. */
|
||||
private boolean backwardUpFace(int above, int group) {
|
||||
char[] states = m.snapshot().states;
|
||||
for (int ox = -1; ox <= 1; ox++) {
|
||||
for (int oz = -1; oz <= 1; oz++) {
|
||||
int state = states[above + ox * Snapshot.STEP_X + oz * Snapshot.STEP_Z];
|
||||
if (t.fluidGroup[state] != group && (t.stateFlags[state] & StateFlags.SOLID_RENDER) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The brighter, for block and sky light each, of two positions' light. */
|
||||
private int brighter(int a, int b) {
|
||||
char[] states = m.snapshot().states;
|
||||
return AmbientOcclusion.max(m.lightCoords(states[a], a), m.lightCoords(states[b], b));
|
||||
}
|
||||
|
||||
private static float spriteU(float[] sprites, int at, float offset) {
|
||||
float u0 = sprites[at];
|
||||
return u0 + (sprites[at + 1] - u0) * offset;
|
||||
}
|
||||
|
||||
private static float spriteV(float[] sprites, int at, float offset) {
|
||||
float v0 = sprites[at + 2];
|
||||
return v0 + (sprites[at + 3] - v0) * offset;
|
||||
}
|
||||
|
||||
private void face(
|
||||
int layer,
|
||||
float x0,
|
||||
float y0,
|
||||
float z0,
|
||||
float u0,
|
||||
float v0,
|
||||
float x1,
|
||||
float y1,
|
||||
float z1,
|
||||
float u1,
|
||||
float v1,
|
||||
float x2,
|
||||
float y2,
|
||||
float z2,
|
||||
float u2,
|
||||
float v2,
|
||||
float x3,
|
||||
float y3,
|
||||
float z3,
|
||||
float u3,
|
||||
float v3,
|
||||
int color,
|
||||
int light,
|
||||
boolean backFace) {
|
||||
m.vertex(layer, x0, y0, z0, color, u0, v0, light);
|
||||
m.vertex(layer, x1, y1, z1, color, u1, v1, light);
|
||||
m.vertex(layer, x2, y2, z2, color, u2, v2, light);
|
||||
m.vertex(layer, x3, y3, z3, color, u3, v3, light);
|
||||
if (backFace) {
|
||||
m.vertex(layer, x0, y0, z0, color, u0, v0, light);
|
||||
m.vertex(layer, x3, y3, z3, color, u3, v3, light);
|
||||
m.vertex(layer, x2, y2, z2, color, u2, v2, light);
|
||||
m.vertex(layer, x1, y1, z1, color, u1, v1, light);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* The few pieces of the game's arithmetic a mesh depends on, computed the same way so a mesh comes
|
||||
* out the same: the position hash that picks model variants and plant offsets, the game's random
|
||||
* number generator (Java's 48-bit linear congruential one), and its table-driven sine and
|
||||
* arctangent, which the flow of fluids is drawn with.
|
||||
*
|
||||
* <p>The table builder checks these against the game itself before any mesh is made
|
||||
* ({@code incari.client.render.mesher.MeshTableExport}), so a change in a new game version fails
|
||||
* loudly instead of drawing wrong.
|
||||
*/
|
||||
public final class GameMath {
|
||||
|
||||
private GameMath() {}
|
||||
|
||||
/** The game's hash of a block position: model variants and plant offsets are drawn from it. */
|
||||
public static long positionSeed(int x, int y, int z) {
|
||||
// x's product overflows as an int before it's widened, as the game computes it.
|
||||
int scaledX = x * 3129871;
|
||||
long mixed = scaledX ^ z * 116129781L ^ y;
|
||||
mixed = mixed * mixed * 42317861L + mixed * 11L;
|
||||
return mixed >> 16;
|
||||
}
|
||||
|
||||
/** Java's linear congruential generator, as the game's single-threaded random source runs it. */
|
||||
public static final class Random {
|
||||
|
||||
private static final long MULTIPLIER = 0x5DEECE66DL;
|
||||
private static final long MASK = (1L << 48) - 1;
|
||||
|
||||
private long state;
|
||||
|
||||
public void setSeed(long seed) {
|
||||
state = (seed ^ MULTIPLIER) & MASK;
|
||||
}
|
||||
|
||||
int next(int bits) {
|
||||
state = state * MULTIPLIER + 11L & MASK;
|
||||
return (int) (state >> (48 - bits));
|
||||
}
|
||||
|
||||
public int nextInt(int bound) {
|
||||
if ((bound & (bound - 1)) == 0) {
|
||||
return (int) (((long) bound * next(31)) >> 31);
|
||||
}
|
||||
int sample;
|
||||
int remainder;
|
||||
do {
|
||||
sample = next(31);
|
||||
remainder = sample % bound;
|
||||
} while (sample - remainder + (bound - 1) < 0);
|
||||
return remainder;
|
||||
}
|
||||
|
||||
public long nextLong() {
|
||||
int high = next(32);
|
||||
int low = next(32);
|
||||
return ((long) high << 32) + low;
|
||||
}
|
||||
}
|
||||
|
||||
// 65536 steps a turn, as the game rounds it.
|
||||
private static final double SINE_STEPS_PER_RADIAN = 10430.378350470453;
|
||||
private static final float[] SINE = new float[65536];
|
||||
// Arctangent: a table of arcsines at 1/256 steps and a cubic correction between them.
|
||||
private static final double ARCSINE_BIAS = Double.longBitsToDouble(0x42B0000000000000L);
|
||||
private static final double[] ARCSINE = new double[257];
|
||||
private static final double[] COSINE_OF_ARCSINE = new double[257];
|
||||
|
||||
static {
|
||||
for (int i = 0; i < SINE.length; i++) {
|
||||
SINE[i] = (float) Math.sin(i / SINE_STEPS_PER_RADIAN);
|
||||
}
|
||||
for (int i = 0; i <= 256; i++) {
|
||||
double arcsine = Math.asin(i / 256.0);
|
||||
ARCSINE[i] = arcsine;
|
||||
COSINE_OF_ARCSINE[i] = Math.cos(arcsine);
|
||||
}
|
||||
}
|
||||
|
||||
/** The game's table sine. */
|
||||
public static float sin(double radians) {
|
||||
return SINE[(int) ((long) (radians * SINE_STEPS_PER_RADIAN) & 0xFFFFL)];
|
||||
}
|
||||
|
||||
/** The game's table cosine: the sine a quarter turn on. */
|
||||
public static float cos(double radians) {
|
||||
return SINE[(int) ((long) (radians * SINE_STEPS_PER_RADIAN + 16384.0) & 0xFFFFL)];
|
||||
}
|
||||
|
||||
/** The game's fast arctangent of {@code y / x}. */
|
||||
public static double atan2(double y, double x) {
|
||||
double lengthSquared = x * x + y * y;
|
||||
if (Double.isNaN(lengthSquared)) {
|
||||
return Double.NaN;
|
||||
}
|
||||
boolean flipY = y < 0.0;
|
||||
if (flipY) {
|
||||
y = -y;
|
||||
}
|
||||
boolean flipX = x < 0.0;
|
||||
if (flipX) {
|
||||
x = -x;
|
||||
}
|
||||
boolean swapped = y > x;
|
||||
if (swapped) {
|
||||
double t = x;
|
||||
x = y;
|
||||
y = t;
|
||||
}
|
||||
double inverseLength = inverseSqrt(lengthSquared);
|
||||
x *= inverseLength;
|
||||
y *= inverseLength;
|
||||
double biased = ARCSINE_BIAS + y;
|
||||
int step = (int) Double.doubleToRawLongBits(biased);
|
||||
double nearest = ARCSINE[step];
|
||||
double nearestCosine = COSINE_OF_ARCSINE[step];
|
||||
double nearestSine = biased - ARCSINE_BIAS;
|
||||
double remainder = y * nearestCosine - x * nearestSine;
|
||||
double correction = (6.0 + remainder * remainder) * remainder * (1.0 / 6.0);
|
||||
double angle = nearest + correction;
|
||||
if (swapped) {
|
||||
angle = Math.PI / 2 - angle;
|
||||
}
|
||||
if (flipX) {
|
||||
angle = Math.PI - angle;
|
||||
}
|
||||
if (flipY) {
|
||||
angle = -angle;
|
||||
}
|
||||
return angle;
|
||||
}
|
||||
|
||||
/** One Newton step from the bit-trick estimate, as the game's arctangent uses. */
|
||||
private static double inverseSqrt(double value) {
|
||||
double half = 0.5 * value;
|
||||
long bits = 0x5FE6EB50C7B537AAL - (Double.doubleToRawLongBits(value) >> 1);
|
||||
double estimate = Double.longBitsToDouble(bits);
|
||||
return estimate * (1.5 - half * estimate * estimate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package incari.mesher;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A mesher worker's side of the conversation: it takes messages (new tables, a section to mesh, a
|
||||
* translucent layer to sort again) and answers each with bytes. The page's workers run it inside
|
||||
* their own WebAssembly module ({@code incari.app.web.mesher.MesherWorker}); the game's own side of
|
||||
* the messages is {@code incari.client.render.mesher.WorkerMeshing}.
|
||||
*
|
||||
* <p>Messages start with a kind. {@link #TABLES}: the encoded {@link MeshTables}, no answer.
|
||||
* {@link #MESH}: an encoded {@link Snapshot}, answered with a status and, if it's {@link #OK} or
|
||||
* {@link #UNSUPPORTED}, the encoded {@link MeshResult}. {@link #SORT}: the count of quads, the
|
||||
* camera (three floats), whether indices are 32-bit, and the quads' centers; answered with a status
|
||||
* and the index buffer. A failure answers {@link #FAILED} and the error's description.
|
||||
*/
|
||||
public final class MeshJobs {
|
||||
|
||||
public static final int TABLES = 1;
|
||||
public static final int MESH = 2;
|
||||
public static final int SORT = 3;
|
||||
|
||||
public static final int OK = 0;
|
||||
/** Meshed, but the section holds a state the tables couldn't describe. */
|
||||
public static final int UNSUPPORTED = 1;
|
||||
|
||||
public static final int FAILED = 2;
|
||||
/** A mesh or sort before any tables arrived. */
|
||||
public static final int NO_TABLES = 3;
|
||||
|
||||
private @Nullable SectionMesher mesher;
|
||||
private final QuadSorter sorter = new QuadSorter();
|
||||
private final Snapshot snapshot = new Snapshot();
|
||||
private final MeshResult result = new MeshResult();
|
||||
private final Bytes.Out reply = new Bytes.Out(256 * 1024);
|
||||
private final Bytes.Out indices = new Bytes.Out(16 * 1024);
|
||||
private float[] centroids = new float[768];
|
||||
|
||||
/**
|
||||
* Handles one message.
|
||||
*
|
||||
* @return the answer, valid until the next call, or null for a message that has none
|
||||
*/
|
||||
public Bytes.@Nullable Out handle(byte[] message, int offset, int length) {
|
||||
reply.clear();
|
||||
Bytes.In in = new Bytes.In(message, offset, length);
|
||||
int kind = in.getInt();
|
||||
try {
|
||||
if (kind == TABLES) {
|
||||
mesher = new SectionMesher(MeshTables.decode(in));
|
||||
return null;
|
||||
}
|
||||
SectionMesher current = mesher;
|
||||
if (current == null) {
|
||||
reply.putInt(NO_TABLES);
|
||||
} else if (kind == MESH) {
|
||||
mesh(current, in);
|
||||
} else if (kind == SORT) {
|
||||
sort(in);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unknown mesher message " + kind);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
reply.clear();
|
||||
reply.putInt(FAILED);
|
||||
String description = String.valueOf(e);
|
||||
byte[] text = new byte[description.length()];
|
||||
for (int i = 0; i < text.length; i++) {
|
||||
char c = description.charAt(i);
|
||||
text[i] = (byte) (c < 128 ? c : '?');
|
||||
}
|
||||
reply.putByteArray(text, text.length);
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
private void mesh(SectionMesher current, Bytes.In in) {
|
||||
snapshot.decode(in);
|
||||
boolean supported = current.mesh(snapshot, result);
|
||||
reply.putInt(supported ? OK : UNSUPPORTED);
|
||||
result.encode(reply);
|
||||
}
|
||||
|
||||
private void sort(Bytes.In in) {
|
||||
int count = in.getInt();
|
||||
float x = in.getFloat();
|
||||
float y = in.getFloat();
|
||||
float z = in.getFloat();
|
||||
boolean intIndices = in.getByte() != 0;
|
||||
if (centroids.length < count * 3) {
|
||||
centroids = new float[count * 3];
|
||||
}
|
||||
for (int i = 0; i < count * 3; i++) {
|
||||
centroids[i] = in.getFloat();
|
||||
}
|
||||
sorter.sortInto(centroids, count, x, y, z, intIndices, indices);
|
||||
reply.putInt(OK);
|
||||
reply.putByteArray(indices.array(), indices.size());
|
||||
}
|
||||
|
||||
/** Encodes a sort request for {@link #handle}. */
|
||||
public static void encodeSort(
|
||||
Bytes.Out out, float[] centroids, int count, float x, float y, float z, boolean intIndices) {
|
||||
out.putInt(SORT);
|
||||
out.putInt(count);
|
||||
out.putFloat(x);
|
||||
out.putFloat(y);
|
||||
out.putFloat(z);
|
||||
out.putByte(intIndices ? 1 : 0);
|
||||
for (int i = 0; i < count * 3; i++) {
|
||||
out.putFloat(centroids[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* What meshing a section produced: each layer's vertices in the snapshot's vertex format, which
|
||||
* faces of the section can see each other (for the game's occlusion graph), and for translucent
|
||||
* geometry, each quad's center and an index buffer sorted back to front from the camera.
|
||||
*
|
||||
* <p>Reused from one mesh to the next: {@link #clear} keeps the buffers.
|
||||
*/
|
||||
public final class MeshResult {
|
||||
|
||||
/** Bit {@code a + 6 * b}: section face a can see face b (the game's {@code VisibilitySet}). */
|
||||
public long visibility;
|
||||
|
||||
final Bytes.Out[] vertices = {new Bytes.Out(64 * 1024), new Bytes.Out(16 * 1024), new Bytes.Out(16 * 1024)};
|
||||
final int[] vertexCounts = new int[MeshTables.LAYER_COUNT];
|
||||
|
||||
/** The translucent quads' centers, x y z each, in the order their vertices were written. */
|
||||
float[] centroids = new float[3 * 256];
|
||||
|
||||
int translucentQuads;
|
||||
final Bytes.Out sortedIndices = new Bytes.Out(4 * 1024);
|
||||
boolean intIndices;
|
||||
/** Whether the translucent layer is in its {@link FixedOrder}, which no camera needs re-sorted. */
|
||||
boolean fixedOrder;
|
||||
|
||||
int vertexSize;
|
||||
|
||||
/**
|
||||
* Per layer, how many quads each of its runs holds, in {@link Facings#runOf}'s order: the solid and
|
||||
* cutout layers are written grouped by facing (ADR 0030). The translucent layer keeps the order
|
||||
* it's sorted in, so all its quads count as unassigned.
|
||||
*/
|
||||
final int[] facingRuns = new int[MeshTables.LAYER_COUNT * Facings.COUNT];
|
||||
|
||||
/** Bit {@code id}: the section draws animated sprite {@code id} of the tables (ADR 0030). */
|
||||
long[] animatedSprites = new long[4];
|
||||
|
||||
public void clear() {
|
||||
visibility = 0;
|
||||
for (Bytes.Out out : vertices) {
|
||||
out.clear();
|
||||
}
|
||||
Arrays.fill(vertexCounts, 0);
|
||||
translucentQuads = 0;
|
||||
sortedIndices.clear();
|
||||
intIndices = false;
|
||||
fixedOrder = false;
|
||||
Arrays.fill(facingRuns, 0);
|
||||
Arrays.fill(animatedSprites, 0L);
|
||||
}
|
||||
|
||||
public int vertexCount(int layer) {
|
||||
return vertexCounts[layer];
|
||||
}
|
||||
|
||||
/** The layer's vertex bytes: {@link #vertexCount} times the vertex size. */
|
||||
public byte[] vertexBytes(int layer) {
|
||||
return vertices[layer].array();
|
||||
}
|
||||
|
||||
public int vertexByteCount(int layer) {
|
||||
return vertices[layer].size();
|
||||
}
|
||||
|
||||
public int translucentQuadCount() {
|
||||
return translucentQuads;
|
||||
}
|
||||
|
||||
/** The translucent quads' centers, three floats each. */
|
||||
public float[] centroids() {
|
||||
return centroids;
|
||||
}
|
||||
|
||||
/** The translucent layer's index buffer, sorted back to front. */
|
||||
public byte[] sortedIndexBytes() {
|
||||
return sortedIndices.array();
|
||||
}
|
||||
|
||||
public int sortedIndexByteCount() {
|
||||
return sortedIndices.size();
|
||||
}
|
||||
|
||||
/** Whether the sorted indices are 32-bit (more than 65535 vertices); else 16-bit. */
|
||||
public boolean intIndices() {
|
||||
return intIndices;
|
||||
}
|
||||
|
||||
/** Whether the translucent layer's order holds from every camera ({@link FixedOrder}). */
|
||||
public boolean fixedOrder() {
|
||||
return fixedOrder;
|
||||
}
|
||||
|
||||
/** How many quads run {@code run} (see {@link Facings#runOf}) of a layer holds. */
|
||||
public int facingRun(int layer, int run) {
|
||||
return facingRuns[layer * Facings.COUNT + run];
|
||||
}
|
||||
|
||||
/** The animated sprites the section draws, as bits by the tables' sprite id. */
|
||||
public long[] animatedSprites() {
|
||||
return animatedSprites;
|
||||
}
|
||||
|
||||
void markAnimated(int id) {
|
||||
if (id >> 6 >= animatedSprites.length) {
|
||||
animatedSprites = Arrays.copyOf(animatedSprites, Math.max(animatedSprites.length * 2, (id >> 6) + 1));
|
||||
}
|
||||
animatedSprites[id >> 6] |= 1L << id;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return vertexCounts[0] == 0 && vertexCounts[1] == 0 && vertexCounts[2] == 0;
|
||||
}
|
||||
|
||||
void addCentroid(float x, float y, float z) {
|
||||
if (translucentQuads * 3 + 3 > centroids.length) {
|
||||
centroids = Arrays.copyOf(centroids, centroids.length * 2);
|
||||
}
|
||||
centroids[translucentQuads * 3] = x;
|
||||
centroids[translucentQuads * 3 + 1] = y;
|
||||
centroids[translucentQuads * 3 + 2] = z;
|
||||
translucentQuads++;
|
||||
}
|
||||
|
||||
public void encode(Bytes.Out out) {
|
||||
out.putLong(visibility);
|
||||
out.putByte(vertexSize);
|
||||
for (int layer = 0; layer < MeshTables.LAYER_COUNT; layer++) {
|
||||
out.putInt(vertexCounts[layer]);
|
||||
out.putByteArray(vertices[layer].array(), vertices[layer].size());
|
||||
}
|
||||
out.putFloats(centroids, translucentQuads * 3);
|
||||
out.putByte(intIndices ? 1 : 0);
|
||||
out.putByteArray(sortedIndices.array(), sortedIndices.size());
|
||||
out.putByte(fixedOrder ? 1 : 0);
|
||||
out.putInts(facingRuns, facingRuns.length);
|
||||
out.putLongs(animatedSprites, animatedSprites.length);
|
||||
}
|
||||
|
||||
public void decode(Bytes.In in) {
|
||||
clear();
|
||||
visibility = in.getLong();
|
||||
vertexSize = in.getUnsignedByte();
|
||||
for (int layer = 0; layer < MeshTables.LAYER_COUNT; layer++) {
|
||||
vertexCounts[layer] = in.getInt();
|
||||
byte[] bytes = in.getByteArray();
|
||||
vertices[layer].putBytes(bytes, 0, bytes.length);
|
||||
}
|
||||
centroids = in.getFloats();
|
||||
translucentQuads = centroids.length / 3;
|
||||
intIndices = in.getByte() != 0;
|
||||
byte[] indices = in.getByteArray();
|
||||
sortedIndices.putBytes(indices, 0, indices.length);
|
||||
fixedOrder = in.getByte() != 0;
|
||||
int[] runs = in.getInts();
|
||||
System.arraycopy(runs, 0, facingRuns, 0, facingRuns.length);
|
||||
animatedSprites = in.getLongs();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Everything the mesher needs to know about the game's blocks, as flat arrays indexed by block
|
||||
* state id: flags, light emission, shade, the shapes that hide faces, fluid heights, and every
|
||||
* model's quads. Built from the game's baked models when they load or a mesh setting changes, then
|
||||
* sent once to each worker.
|
||||
*
|
||||
* <p>Worker-side, no game objects. {@link Builder} is how the game's side fills it
|
||||
* ({@code incari.client.render.mesher.MeshTableExport}).
|
||||
*/
|
||||
public final class MeshTables {
|
||||
|
||||
/** Bumped when the encoding changes; a worker refuses tables of another version. */
|
||||
static final int ENCODING = 2;
|
||||
|
||||
/** A quad's layer: the game's {@code ChunkSectionLayer} ordinals. */
|
||||
public static final int LAYER_SOLID = 0;
|
||||
|
||||
public static final int LAYER_CUTOUT = 1;
|
||||
public static final int LAYER_TRANSLUCENT = 2;
|
||||
public static final int LAYER_COUNT = 3;
|
||||
|
||||
/** Face shape ids ({@link #faceShape}): the empty shape and the full block, by identity. */
|
||||
public static final int SHAPE_EMPTY = 0;
|
||||
|
||||
public static final int SHAPE_FULL = 1;
|
||||
|
||||
/** How a state's face hides a fluid face against it ({@link #fluidCoverKind}). */
|
||||
public static final int FLUID_COVER_NONE = 0;
|
||||
|
||||
public static final int FLUID_COVER_FULL_BLOCK = 1;
|
||||
public static final int FLUID_COVER_PARTIAL = 2;
|
||||
|
||||
static final int NODE_SINGLE = 0;
|
||||
static final int NODE_WEIGHTED = 1;
|
||||
static final int NODE_MULTIPART = 2;
|
||||
static final int NODE_LIST = 3;
|
||||
|
||||
final boolean ambientOcclusion;
|
||||
final int stateCount;
|
||||
final int[] stateFlags;
|
||||
final byte[] lightEmission;
|
||||
final float[] shade;
|
||||
/** Per state and direction: the id of the face's occlusion shape. */
|
||||
final short[] faceShape;
|
||||
/** 0 for none; states whose fluids are the "same" fluid share a group. */
|
||||
final byte[] fluidGroup;
|
||||
|
||||
final float[] fluidHeight;
|
||||
final byte[] fluidModel;
|
||||
/** Per state and direction: how the state's face toward that direction hides a fluid face. */
|
||||
final byte[] fluidCoverKind;
|
||||
/** Per state and direction: with a partial cover, the fluid height up to which it hides it. */
|
||||
final float[] fluidCoverHeight;
|
||||
|
||||
final int[] modelNode;
|
||||
final short[] skipClass;
|
||||
final short[] offsetTable;
|
||||
final byte[] seedOffset;
|
||||
|
||||
final int shapeCount;
|
||||
/** Bit {@code a * shapeCount + b}: face shape a is entirely behind occluding shape b. */
|
||||
final long[] shapeCovered;
|
||||
|
||||
final int skipClassCount;
|
||||
/** Bit {@code (a * skipClassCount + b) * 6 + direction}: a's face hides against b. */
|
||||
final long[] skipTable;
|
||||
|
||||
final int[] nodes;
|
||||
/** Per part: the start of each face's quad list (6 directions, then unculled), then the end. */
|
||||
final int[] partFaces;
|
||||
|
||||
final int[] partQuads;
|
||||
final byte[] partAmbientOcclusion;
|
||||
|
||||
final float[] quadPositions;
|
||||
final float[] quadUvs;
|
||||
/** Direction, layer, tint index, shade direction, light emission and shape bits; see {@link Quads}. */
|
||||
final int[] quadInfo;
|
||||
/** Per quad, per vertex in the lighter's order, the weights of the four corner samples. */
|
||||
final float[] quadAoWeights;
|
||||
/** Per quad: its bounding box, min x y z then max x y z. */
|
||||
final float[] quadBounds;
|
||||
/** Per quad: 1 + the id of the animated sprite it's textured with, or 0 (ADR 0030). */
|
||||
final short[] quadAnimated;
|
||||
|
||||
/** Per offset table: x, y and z offsets for each of the 16 values of their seed's nibble. */
|
||||
final float[] offsets;
|
||||
|
||||
final int fluidModelCount;
|
||||
final byte[] fluidModelLayer;
|
||||
/** Per fluid model: still, flowing and overlay sprites' u0, u1, v0, v1. */
|
||||
final float[] fluidSprites;
|
||||
|
||||
final byte[] fluidModelFlags;
|
||||
/** Per fluid model: 1 + the animated sprite id of its still, flowing and overlay sprites, or 0. */
|
||||
final short[] fluidAnimated;
|
||||
|
||||
static final int FLUID_MODEL_OVERLAY = 1;
|
||||
static final int FLUID_MODEL_TINTED = 2;
|
||||
|
||||
private MeshTables(Builder b) {
|
||||
ambientOcclusion = b.ambientOcclusion;
|
||||
stateCount = b.stateCount;
|
||||
stateFlags = b.stateFlags;
|
||||
lightEmission = b.lightEmission;
|
||||
shade = b.shade;
|
||||
faceShape = b.faceShape;
|
||||
fluidGroup = b.fluidGroup;
|
||||
fluidHeight = b.fluidHeight;
|
||||
fluidModel = b.fluidModel;
|
||||
fluidCoverKind = b.fluidCoverKind;
|
||||
fluidCoverHeight = b.fluidCoverHeight;
|
||||
modelNode = b.modelNode;
|
||||
skipClass = b.skipClass;
|
||||
offsetTable = b.offsetTable;
|
||||
seedOffset = b.seedOffset;
|
||||
shapeCount = b.shapeCount;
|
||||
shapeCovered = b.shapeCovered;
|
||||
skipClassCount = b.skipClassCount;
|
||||
skipTable = b.skipTable;
|
||||
nodes = Arrays.copyOf(b.nodes, b.nodeSize);
|
||||
partFaces = Arrays.copyOf(b.partFaces, b.partCount * 8);
|
||||
partQuads = Arrays.copyOf(b.partQuads, b.partQuadSize);
|
||||
partAmbientOcclusion = Arrays.copyOf(b.partAo, b.partCount);
|
||||
quadPositions = Arrays.copyOf(b.quadPositions, b.quadCount * 12);
|
||||
quadUvs = Arrays.copyOf(b.quadUvs, b.quadCount * 8);
|
||||
quadInfo = Arrays.copyOf(b.quadInfo, b.quadCount);
|
||||
offsets = Arrays.copyOf(b.offsets, b.offsetCount * 48);
|
||||
fluidModelCount = b.fluidModelCount;
|
||||
fluidModelLayer = Arrays.copyOf(b.fluidModelLayer, b.fluidModelCount);
|
||||
fluidSprites = Arrays.copyOf(b.fluidSprites, b.fluidModelCount * 12);
|
||||
fluidModelFlags = Arrays.copyOf(b.fluidModelFlags, b.fluidModelCount);
|
||||
quadAnimated = Arrays.copyOf(b.quadAnimated, b.quadCount);
|
||||
fluidAnimated = Arrays.copyOf(b.fluidAnimated, b.fluidModelCount * 3);
|
||||
quadBounds = new float[quadInfo.length * 6];
|
||||
quadAoWeights = new float[quadInfo.length * 16];
|
||||
Quads.derive(this);
|
||||
}
|
||||
|
||||
public int stateCount() {
|
||||
return stateCount;
|
||||
}
|
||||
|
||||
public int flags(int state) {
|
||||
return stateFlags[state];
|
||||
}
|
||||
|
||||
/** The state's fluid group: 0 for no fluid; the same for fluids that count as the same. */
|
||||
public int fluidGroup(int state) {
|
||||
return fluidGroup[state];
|
||||
}
|
||||
|
||||
/** Whether the state's fluid is drawn with a tint (the snapshot then carries its color). */
|
||||
public boolean fluidTinted(int state) {
|
||||
return fluidGroup[state] != 0 && (fluidModelFlags[fluidModel[state]] & FLUID_MODEL_TINTED) != 0;
|
||||
}
|
||||
|
||||
public boolean ambientOcclusion() {
|
||||
return ambientOcclusion;
|
||||
}
|
||||
|
||||
public int quadCount() {
|
||||
return quadInfo.length;
|
||||
}
|
||||
|
||||
public void encode(Bytes.Out out) {
|
||||
out.putInt(ENCODING);
|
||||
out.putByte(ambientOcclusion ? 1 : 0);
|
||||
out.putInt(stateCount);
|
||||
out.putInts(stateFlags, stateCount);
|
||||
out.putByteArray(lightEmission, stateCount);
|
||||
out.putFloats(shade, stateCount);
|
||||
out.putShorts(faceShape, stateCount * 6);
|
||||
out.putByteArray(fluidGroup, stateCount);
|
||||
out.putFloats(fluidHeight, stateCount);
|
||||
out.putByteArray(fluidModel, stateCount);
|
||||
out.putByteArray(fluidCoverKind, stateCount * 6);
|
||||
out.putFloats(fluidCoverHeight, stateCount * 6);
|
||||
out.putInts(modelNode, stateCount);
|
||||
out.putShorts(skipClass, stateCount);
|
||||
out.putShorts(offsetTable, stateCount);
|
||||
out.putByteArray(seedOffset, stateCount);
|
||||
out.putInt(shapeCount);
|
||||
out.putLongs(shapeCovered, shapeCovered.length);
|
||||
out.putInt(skipClassCount);
|
||||
out.putLongs(skipTable, skipTable.length);
|
||||
out.putInts(nodes, nodes.length);
|
||||
out.putInts(partFaces, partFaces.length);
|
||||
out.putInts(partQuads, partQuads.length);
|
||||
out.putByteArray(partAmbientOcclusion, partAmbientOcclusion.length);
|
||||
out.putFloats(quadPositions, quadPositions.length);
|
||||
out.putFloats(quadUvs, quadUvs.length);
|
||||
out.putInts(quadInfo, quadInfo.length);
|
||||
out.putFloats(offsets, offsets.length);
|
||||
out.putInt(fluidModelCount);
|
||||
out.putByteArray(fluidModelLayer, fluidModelCount);
|
||||
out.putFloats(fluidSprites, fluidSprites.length);
|
||||
out.putByteArray(fluidModelFlags, fluidModelCount);
|
||||
out.putShorts(quadAnimated, quadAnimated.length);
|
||||
out.putShorts(fluidAnimated, fluidAnimated.length);
|
||||
}
|
||||
|
||||
public static MeshTables decode(Bytes.In in) {
|
||||
int encoding = in.getInt();
|
||||
if (encoding != ENCODING) {
|
||||
throw new IllegalStateException("Mesh tables of encoding " + encoding + ", expected " + ENCODING);
|
||||
}
|
||||
boolean ambientOcclusion = in.getByte() != 0;
|
||||
Builder b = new Builder(in.getInt(), ambientOcclusion);
|
||||
b.stateFlags = in.getInts();
|
||||
b.lightEmission = in.getByteArray();
|
||||
b.shade = in.getFloats();
|
||||
b.faceShape = in.getShorts();
|
||||
b.fluidGroup = in.getByteArray();
|
||||
b.fluidHeight = in.getFloats();
|
||||
b.fluidModel = in.getByteArray();
|
||||
b.fluidCoverKind = in.getByteArray();
|
||||
b.fluidCoverHeight = in.getFloats();
|
||||
b.modelNode = in.getInts();
|
||||
b.skipClass = in.getShorts();
|
||||
b.offsetTable = in.getShorts();
|
||||
b.seedOffset = in.getByteArray();
|
||||
b.shapeCount = in.getInt();
|
||||
b.shapeCovered = in.getLongs();
|
||||
b.skipClassCount = in.getInt();
|
||||
b.skipTable = in.getLongs();
|
||||
b.nodes = in.getInts();
|
||||
b.nodeSize = b.nodes.length;
|
||||
b.partFaces = in.getInts();
|
||||
b.partCount = b.partFaces.length / 8;
|
||||
b.partQuads = in.getInts();
|
||||
b.partQuadSize = b.partQuads.length;
|
||||
b.partAo = in.getByteArray();
|
||||
b.quadPositions = in.getFloats();
|
||||
b.quadUvs = in.getFloats();
|
||||
b.quadInfo = in.getInts();
|
||||
b.quadCount = b.quadInfo.length;
|
||||
b.offsets = in.getFloats();
|
||||
b.offsetCount = b.offsets.length / 48;
|
||||
b.fluidModelCount = in.getInt();
|
||||
b.fluidModelLayer = in.getByteArray();
|
||||
b.fluidSprites = in.getFloats();
|
||||
b.fluidModelFlags = in.getByteArray();
|
||||
b.quadAnimated = in.getShorts();
|
||||
b.fluidAnimated = in.getShorts();
|
||||
return new MeshTables(b);
|
||||
}
|
||||
|
||||
/** Fills the tables from the game's side. Every state starts as air with no model. */
|
||||
public static final class Builder {
|
||||
|
||||
final boolean ambientOcclusion;
|
||||
final int stateCount;
|
||||
int[] stateFlags;
|
||||
byte[] lightEmission;
|
||||
float[] shade;
|
||||
short[] faceShape;
|
||||
byte[] fluidGroup;
|
||||
float[] fluidHeight;
|
||||
byte[] fluidModel;
|
||||
byte[] fluidCoverKind;
|
||||
float[] fluidCoverHeight;
|
||||
int[] modelNode;
|
||||
short[] skipClass;
|
||||
short[] offsetTable;
|
||||
byte[] seedOffset;
|
||||
int shapeCount = 2;
|
||||
long[] shapeCovered = new long[1];
|
||||
int skipClassCount;
|
||||
long[] skipTable = new long[0];
|
||||
int[] nodes = new int[1024];
|
||||
int nodeSize;
|
||||
int[] partFaces = new int[1024];
|
||||
int partCount;
|
||||
int[] partQuads = new int[1024];
|
||||
int partQuadSize;
|
||||
byte[] partAo = new byte[128];
|
||||
float[] quadPositions = new float[12 * 1024];
|
||||
float[] quadUvs = new float[8 * 1024];
|
||||
int[] quadInfo = new int[1024];
|
||||
int quadCount;
|
||||
float[] offsets = new float[48 * 16];
|
||||
int offsetCount;
|
||||
int fluidModelCount;
|
||||
byte[] fluidModelLayer = new byte[8];
|
||||
float[] fluidSprites = new float[12 * 8];
|
||||
byte[] fluidModelFlags = new byte[8];
|
||||
short[] quadAnimated = new short[1024];
|
||||
short[] fluidAnimated = new short[3 * 8];
|
||||
|
||||
public Builder(int stateCount, boolean ambientOcclusion) {
|
||||
this.stateCount = stateCount;
|
||||
this.ambientOcclusion = ambientOcclusion;
|
||||
stateFlags = new int[stateCount];
|
||||
Arrays.fill(stateFlags, StateFlags.AIR);
|
||||
lightEmission = new byte[stateCount];
|
||||
shade = new float[stateCount];
|
||||
Arrays.fill(shade, 1.0F);
|
||||
faceShape = new short[stateCount * 6];
|
||||
fluidGroup = new byte[stateCount];
|
||||
fluidHeight = new float[stateCount];
|
||||
fluidModel = new byte[stateCount];
|
||||
fluidCoverKind = new byte[stateCount * 6];
|
||||
fluidCoverHeight = new float[stateCount * 6];
|
||||
modelNode = new int[stateCount];
|
||||
Arrays.fill(modelNode, -1);
|
||||
skipClass = new short[stateCount];
|
||||
Arrays.fill(skipClass, (short) -1);
|
||||
offsetTable = new short[stateCount];
|
||||
Arrays.fill(offsetTable, (short) -1);
|
||||
seedOffset = new byte[stateCount];
|
||||
Arrays.fill(seedOffset, (byte) (1 | 1 << 2 | 1 << 4));
|
||||
}
|
||||
|
||||
public void state(int state, int flags, int lightEmission, float shade) {
|
||||
stateFlags[state] = flags;
|
||||
this.lightEmission[state] = (byte) lightEmission;
|
||||
this.shade[state] = shade;
|
||||
}
|
||||
|
||||
public void faceShape(int state, int direction, int shapeId) {
|
||||
faceShape[state * 6 + direction] = (short) shapeId;
|
||||
}
|
||||
|
||||
public void fluid(int state, int group, float ownHeight, int model) {
|
||||
fluidGroup[state] = (byte) group;
|
||||
fluidHeight[state] = ownHeight;
|
||||
fluidModel[state] = (byte) model;
|
||||
}
|
||||
|
||||
public void fluidCover(int state, int direction, int kind, float height) {
|
||||
fluidCoverKind[state * 6 + direction] = (byte) kind;
|
||||
fluidCoverHeight[state * 6 + direction] = height;
|
||||
}
|
||||
|
||||
public void model(int state, int node) {
|
||||
modelNode[state] = node;
|
||||
}
|
||||
|
||||
public void skipClass(int state, int skipClass) {
|
||||
this.skipClass[state] = (short) skipClass;
|
||||
}
|
||||
|
||||
public void offsetTable(int state, int table) {
|
||||
offsetTable[state] = (short) table;
|
||||
}
|
||||
|
||||
/** Where the state's position seed is taken from, relative to its own position (-1 to 1). */
|
||||
public void seedOffset(int state, int dx, int dy, int dz) {
|
||||
seedOffset[state] = (byte) ((dx + 1) | (dy + 1) << 2 | (dz + 1) << 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* The face shapes: ids from 2 up are the distinct shapes other than the empty one and the
|
||||
* full block, and {@code covered.test(a, b)} says whether shape a is entirely behind b
|
||||
* (for every pair of ids, 0 and 1 included).
|
||||
*/
|
||||
public void faceShapes(int count, ShapePairs covered) {
|
||||
shapeCount = count;
|
||||
shapeCovered = new long[(count * count + 63) >> 6];
|
||||
for (int a = 0; a < count; a++) {
|
||||
for (int b = 0; b < count; b++) {
|
||||
if (covered.test(a, b)) {
|
||||
int bit = a * count + b;
|
||||
shapeCovered[bit >> 6] |= 1L << bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The skip classes, and whether a face of class a hides against class b toward a direction. */
|
||||
public void skipClasses(int count, SkipRule rule) {
|
||||
skipClassCount = count;
|
||||
skipTable = new long[(count * count * 6 + 63) >> 6];
|
||||
for (int a = 0; a < count; a++) {
|
||||
for (int b = 0; b < count; b++) {
|
||||
for (int d = 0; d < 6; d++) {
|
||||
if (rule.skips(a, b, d)) {
|
||||
int bit = (a * count + b) * 6 + d;
|
||||
skipTable[bit >> 6] |= 1L << bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds a quad and returns its index. */
|
||||
public int quad(
|
||||
float[] positions,
|
||||
float[] uvs,
|
||||
int direction,
|
||||
int layer,
|
||||
int tintIndex,
|
||||
int shadeDirection,
|
||||
int lightEmission) {
|
||||
if (quadCount == quadInfo.length) {
|
||||
quadInfo = Arrays.copyOf(quadInfo, quadCount * 2);
|
||||
quadPositions = Arrays.copyOf(quadPositions, quadCount * 2 * 12);
|
||||
quadUvs = Arrays.copyOf(quadUvs, quadCount * 2 * 8);
|
||||
quadAnimated = Arrays.copyOf(quadAnimated, quadCount * 2);
|
||||
}
|
||||
System.arraycopy(positions, 0, quadPositions, quadCount * 12, 12);
|
||||
System.arraycopy(uvs, 0, quadUvs, quadCount * 8, 8);
|
||||
quadInfo[quadCount] = Quads.pack(direction, layer, tintIndex, shadeDirection, lightEmission);
|
||||
return quadCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a model part: its quads for each face (index 0 to 5 by direction, 6 for the ones
|
||||
* never culled), and returns its index.
|
||||
*/
|
||||
public int part(int[][] quadsByFace, boolean ambientOcclusion) {
|
||||
if ((partCount + 1) * 8 > partFaces.length) {
|
||||
partFaces = Arrays.copyOf(partFaces, partFaces.length * 2);
|
||||
partAo = Arrays.copyOf(partAo, partAo.length * 2);
|
||||
}
|
||||
for (int face = 0; face < 7; face++) {
|
||||
partFaces[partCount * 8 + face] = partQuadSize;
|
||||
for (int quad : quadsByFace[face]) {
|
||||
if (partQuadSize == partQuads.length) {
|
||||
partQuads = Arrays.copyOf(partQuads, partQuadSize * 2);
|
||||
}
|
||||
partQuads[partQuadSize++] = quad;
|
||||
}
|
||||
}
|
||||
partFaces[partCount * 8 + 7] = partQuadSize;
|
||||
partAo[partCount] = (byte) (ambientOcclusion ? 1 : 0);
|
||||
return partCount++;
|
||||
}
|
||||
|
||||
public int singleNode(int part) {
|
||||
int at = reserveNodes(2);
|
||||
nodes[at] = NODE_SINGLE;
|
||||
nodes[at + 1] = part;
|
||||
return at;
|
||||
}
|
||||
|
||||
/** A weighted choice: {@code children[i]} with {@code weights[i]}, drawn from the random. */
|
||||
public int weightedNode(int[] weights, int[] children) {
|
||||
int at = reserveNodes(3 + 2 * weights.length);
|
||||
int total = 0;
|
||||
for (int weight : weights) {
|
||||
total += weight;
|
||||
}
|
||||
nodes[at] = NODE_WEIGHTED;
|
||||
nodes[at + 1] = total;
|
||||
nodes[at + 2] = weights.length;
|
||||
for (int i = 0; i < weights.length; i++) {
|
||||
nodes[at + 3 + 2 * i] = weights[i];
|
||||
nodes[at + 4 + 2 * i] = children[i];
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
/** Parts that are always there, drawing nothing from the random. */
|
||||
public int listNode(int[] parts) {
|
||||
int at = reserveNodes(2 + parts.length);
|
||||
nodes[at] = NODE_LIST;
|
||||
nodes[at + 1] = parts.length;
|
||||
System.arraycopy(parts, 0, nodes, at + 2, parts.length);
|
||||
return at;
|
||||
}
|
||||
|
||||
/** Every child, each from the same seed drawn once from the random. */
|
||||
public int multipartNode(int[] children) {
|
||||
int at = reserveNodes(2 + children.length);
|
||||
nodes[at] = NODE_MULTIPART;
|
||||
nodes[at + 1] = children.length;
|
||||
System.arraycopy(children, 0, nodes, at + 2, children.length);
|
||||
return at;
|
||||
}
|
||||
|
||||
private int reserveNodes(int count) {
|
||||
if (nodeSize + count > nodes.length) {
|
||||
nodes = Arrays.copyOf(nodes, Math.max(nodeSize + count, nodes.length * 2));
|
||||
}
|
||||
int at = nodeSize;
|
||||
nodeSize += count;
|
||||
return at;
|
||||
}
|
||||
|
||||
/** Adds an offset table (16 x, then 16 y, then 16 z offsets) and returns its index. */
|
||||
public int offsets(float[] table) {
|
||||
if ((offsetCount + 1) * 48 > offsets.length) {
|
||||
offsets = Arrays.copyOf(offsets, offsets.length * 2);
|
||||
}
|
||||
System.arraycopy(table, 0, offsets, offsetCount * 48, 48);
|
||||
return offsetCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a fluid model: its layer and sprites (still, flowing, overlay: u0, u1, v0, v1 each).
|
||||
*/
|
||||
public int fluidModel(int layer, float[] sprites, boolean overlay, boolean tinted) {
|
||||
if (fluidModelCount == fluidModelLayer.length) {
|
||||
fluidModelLayer = Arrays.copyOf(fluidModelLayer, fluidModelCount * 2);
|
||||
fluidSprites = Arrays.copyOf(fluidSprites, fluidModelCount * 2 * 12);
|
||||
fluidModelFlags = Arrays.copyOf(fluidModelFlags, fluidModelCount * 2);
|
||||
fluidAnimated = Arrays.copyOf(fluidAnimated, fluidModelCount * 2 * 3);
|
||||
}
|
||||
fluidModelLayer[fluidModelCount] = (byte) layer;
|
||||
System.arraycopy(sprites, 0, fluidSprites, fluidModelCount * 12, 12);
|
||||
fluidModelFlags[fluidModelCount] =
|
||||
(byte) ((overlay ? FLUID_MODEL_OVERLAY : 0) | (tinted ? FLUID_MODEL_TINTED : 0));
|
||||
return fluidModelCount++;
|
||||
}
|
||||
|
||||
/** Marks a quad as textured with animated sprite {@code id} (0 up). */
|
||||
public void animatedQuad(int quad, int id) {
|
||||
quadAnimated[quad] = (short) (id + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The animated sprite ids of a fluid model's still, flowing and overlay sprites, -1 for one
|
||||
* that isn't animated.
|
||||
*/
|
||||
public void animatedFluid(int model, int still, int flowing, int overlay) {
|
||||
fluidAnimated[model * 3] = (short) (still + 1);
|
||||
fluidAnimated[model * 3 + 1] = (short) (flowing + 1);
|
||||
fluidAnimated[model * 3 + 2] = (short) (overlay + 1);
|
||||
}
|
||||
|
||||
public MeshTables build() {
|
||||
return new MeshTables(this);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether face shape a is entirely behind shape b. */
|
||||
@FunctionalInterface
|
||||
public interface ShapePairs {
|
||||
boolean test(int a, int b);
|
||||
}
|
||||
|
||||
/** Whether a face of skip class a toward a direction hides against a neighbor of class b. */
|
||||
@FunctionalInterface
|
||||
public interface SkipRule {
|
||||
boolean skips(int a, int b, int direction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Sorts translucent quads back to front from the camera, as the game does: by the squared distance
|
||||
* of each quad's center, farthest first, quads at the same distance keeping their order. The result
|
||||
* is an index buffer of two triangles per quad, 16-bit unless the layer has more vertices than
|
||||
* that allows.
|
||||
*
|
||||
* <p>Worker-side, no game objects. Reuses its scratch arrays; hot path.
|
||||
*/
|
||||
public final class QuadSorter {
|
||||
|
||||
private float[] keys = new float[256];
|
||||
private int[] order = new int[256];
|
||||
private int[] scratch = new int[256];
|
||||
|
||||
/** Sorts {@code result}'s translucent quads for a camera at x y z (section-relative). */
|
||||
void sortInto(MeshResult result, float cameraX, float cameraY, float cameraZ) {
|
||||
int quads = result.translucentQuads;
|
||||
sort(result.centroids, quads, cameraX, cameraY, cameraZ);
|
||||
int vertices = result.vertexCounts[MeshTables.LAYER_TRANSLUCENT];
|
||||
result.intIndices = (vertices & -65536) != 0;
|
||||
writeIndices(result.sortedIndices, quads, result.intIndices);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code result}'s translucent quads in their {@link FixedOrder}, given each one's facing
|
||||
* and plane.
|
||||
*/
|
||||
void fixedInto(MeshResult result, byte[] facings, float[] planes) {
|
||||
int quads = result.translucentQuads;
|
||||
grow(quads);
|
||||
FixedOrder.keys(facings, planes, quads, keys);
|
||||
for (int i = 0; i < quads; i++) {
|
||||
order[i] = i;
|
||||
}
|
||||
mergeSort(0, quads);
|
||||
int vertices = result.vertexCounts[MeshTables.LAYER_TRANSLUCENT];
|
||||
result.intIndices = (vertices & -65536) != 0;
|
||||
writeIndices(result.sortedIndices, quads, result.intIndices);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts {@code count} quads by their centers ({@code centroids}, x y z each) and writes the
|
||||
* index buffer to {@code out}.
|
||||
*/
|
||||
public void sortInto(
|
||||
float[] centroids,
|
||||
int count,
|
||||
float cameraX,
|
||||
float cameraY,
|
||||
float cameraZ,
|
||||
boolean intIndices,
|
||||
Bytes.Out out) {
|
||||
sort(centroids, count, cameraX, cameraY, cameraZ);
|
||||
writeIndices(out, count, intIndices);
|
||||
}
|
||||
|
||||
private void sort(float[] centroids, int count, float cameraX, float cameraY, float cameraZ) {
|
||||
grow(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
float dx = cameraX - centroids[i * 3];
|
||||
float dy = cameraY - centroids[i * 3 + 1];
|
||||
float dz = cameraZ - centroids[i * 3 + 2];
|
||||
keys[i] = dx * dx + (dy * dy + dz * dz);
|
||||
order[i] = i;
|
||||
}
|
||||
mergeSort(0, count);
|
||||
}
|
||||
|
||||
private void grow(int count) {
|
||||
if (keys.length < count) {
|
||||
int grown = Math.max(count, keys.length * 2);
|
||||
keys = new float[grown];
|
||||
order = new int[grown];
|
||||
scratch = new int[grown];
|
||||
}
|
||||
}
|
||||
|
||||
/** A stable merge sort of {@link #order}[from, to), farthest (largest key) first. */
|
||||
private void mergeSort(int from, int to) {
|
||||
int length = to - from;
|
||||
if (length < 16) {
|
||||
for (int i = from + 1; i < to; i++) {
|
||||
int value = order[i];
|
||||
int j = i - 1;
|
||||
while (j >= from && before(value, order[j])) {
|
||||
order[j + 1] = order[j];
|
||||
j--;
|
||||
}
|
||||
order[j + 1] = value;
|
||||
}
|
||||
return;
|
||||
}
|
||||
int middle = (from + to) >>> 1;
|
||||
mergeSort(from, middle);
|
||||
mergeSort(middle, to);
|
||||
if (!before(order[middle], order[middle - 1])) {
|
||||
return;
|
||||
}
|
||||
System.arraycopy(order, from, scratch, from, length);
|
||||
int left = from;
|
||||
int right = middle;
|
||||
for (int i = from; i < to; i++) {
|
||||
if (right >= to || (left < middle && !before(scratch[right], scratch[left]))) {
|
||||
order[i] = scratch[left++];
|
||||
} else {
|
||||
order[i] = scratch[right++];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether quad a sorts strictly before quad b: it's farther from the camera. */
|
||||
private boolean before(int a, int b) {
|
||||
return Float.compare(keys[b], keys[a]) < 0;
|
||||
}
|
||||
|
||||
private void writeIndices(Bytes.Out out, int count, boolean intIndices) {
|
||||
out.clear();
|
||||
int size = intIndices ? 4 : 2;
|
||||
int at = out.reserve(count * 6 * size);
|
||||
byte[] data = out.array();
|
||||
for (int i = 0; i < count; i++) {
|
||||
int first = order[i] * 4;
|
||||
at = index(data, at, first, intIndices);
|
||||
at = index(data, at, first + 1, intIndices);
|
||||
at = index(data, at, first + 2, intIndices);
|
||||
at = index(data, at, first + 2, intIndices);
|
||||
at = index(data, at, first + 3, intIndices);
|
||||
at = index(data, at, first, intIndices);
|
||||
}
|
||||
}
|
||||
|
||||
private static int index(byte[] data, int at, int value, boolean intIndices) {
|
||||
if (intIndices) {
|
||||
Bytes.putIntAt(data, at, value);
|
||||
return at + 4;
|
||||
}
|
||||
Bytes.putShortAt(data, at, value);
|
||||
return at + 2;
|
||||
}
|
||||
|
||||
int[] orderForTest(int count) {
|
||||
return Arrays.copyOf(order, count);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* A model quad's fixed facts, packed in {@link MeshTables#quadInfo}, and what the lighter derives
|
||||
* from its shape once, when the tables are built, rather than for every block: its bounds, whether
|
||||
* it covers its whole face, and the weights smooth lighting blends its corners with.
|
||||
*/
|
||||
final class Quads {
|
||||
|
||||
private Quads() {}
|
||||
|
||||
private static final int DIRECTION_MASK = 0x7;
|
||||
private static final int LAYER_SHIFT = 3;
|
||||
private static final int TINT_SHIFT = 5;
|
||||
private static final int SHADE_SHIFT = 13;
|
||||
private static final int EMISSION_SHIFT = 16;
|
||||
/** Its four corners lie in one plane across its direction's axis. */
|
||||
static final int FLAT = 1 << 20;
|
||||
/** It lies on its block's face: at 0 for down, north and west, at 1 for the others. */
|
||||
static final int ON_EDGE = 1 << 21;
|
||||
/** It doesn't cover its face's whole square. */
|
||||
static final int PARTIAL = 1 << 22;
|
||||
|
||||
static int pack(int direction, int layer, int tintIndex, int shadeDirection, int lightEmission) {
|
||||
if (tintIndex < -1 || tintIndex > 254) {
|
||||
throw new IllegalArgumentException("Tint index out of range: " + tintIndex);
|
||||
}
|
||||
return direction
|
||||
| layer << LAYER_SHIFT
|
||||
| (tintIndex + 1) << TINT_SHIFT
|
||||
| (shadeDirection + 1) << SHADE_SHIFT
|
||||
| lightEmission << EMISSION_SHIFT;
|
||||
}
|
||||
|
||||
static int direction(int info) {
|
||||
return info & DIRECTION_MASK;
|
||||
}
|
||||
|
||||
static int layer(int info) {
|
||||
return info >> LAYER_SHIFT & 0x3;
|
||||
}
|
||||
|
||||
/** The tint index, or -1 for none. */
|
||||
static int tintIndex(int info) {
|
||||
return (info >> TINT_SHIFT & 0xFF) - 1;
|
||||
}
|
||||
|
||||
/** The direction whose shade the quad takes: its own unless the model overrides it. */
|
||||
static int shadeDirection(int info) {
|
||||
int override = (info >> SHADE_SHIFT & 0x7) - 1;
|
||||
return override >= 0 ? override : direction(info);
|
||||
}
|
||||
|
||||
static int lightEmission(int info) {
|
||||
return info >> EMISSION_SHIFT & 0xF;
|
||||
}
|
||||
|
||||
private static final float EDGE_LOW = 1.0E-4F;
|
||||
private static final float EDGE_HIGH = 0.9999F;
|
||||
|
||||
/**
|
||||
* Where each of a face's four corners sits in the quad's bounding box, in the lighter's vertex
|
||||
* order: for each direction and corner, whether the first and the second axis in the face's
|
||||
* plane take the box's maximum (1) or minimum (0). The planes' axes are x and z for down and
|
||||
* up, x and y for north and south, y and z for west and east.
|
||||
*/
|
||||
private static final int[][] CORNER_AT_MAX = {
|
||||
{0, 1, 0, 0, 1, 0, 1, 1}, // down
|
||||
{1, 1, 1, 0, 0, 0, 0, 1}, // up
|
||||
{0, 1, 1, 1, 1, 0, 0, 0}, // north
|
||||
{0, 1, 0, 0, 1, 0, 1, 1}, // south
|
||||
{1, 1, 1, 0, 0, 0, 0, 1}, // west
|
||||
{0, 1, 0, 0, 1, 0, 1, 1}, // east
|
||||
};
|
||||
|
||||
/** The two in-plane axes of each direction's face, as x = 0, y = 1, z = 2. */
|
||||
private static final int[][] PLANE_AXES = {{0, 2}, {0, 2}, {0, 1}, {0, 1}, {1, 2}, {1, 2}};
|
||||
|
||||
static void derive(MeshTables t) {
|
||||
float[] positions = t.quadPositions;
|
||||
for (int q = 0; q < t.quadInfo.length; q++) {
|
||||
// The quad's bounding box, axis by axis: the lower corner, then the upper.
|
||||
float[] bounds = t.quadBounds;
|
||||
for (int axis = 0; axis < 3; axis++) {
|
||||
float low = positions[q * 12 + axis];
|
||||
float high = low;
|
||||
for (int v = 1; v < 4; v++) {
|
||||
float value = positions[q * 12 + v * 3 + axis];
|
||||
low = Math.min(low, value);
|
||||
high = Math.max(high, value);
|
||||
}
|
||||
bounds[q * 6 + axis] = low;
|
||||
bounds[q * 6 + 3 + axis] = high;
|
||||
}
|
||||
float minX = bounds[q * 6];
|
||||
float minY = bounds[q * 6 + 1];
|
||||
float minZ = bounds[q * 6 + 2];
|
||||
float maxX = bounds[q * 6 + 3];
|
||||
float maxY = bounds[q * 6 + 4];
|
||||
float maxZ = bounds[q * 6 + 5];
|
||||
|
||||
int info = t.quadInfo[q];
|
||||
int direction = direction(info);
|
||||
boolean partial;
|
||||
boolean flat;
|
||||
boolean onEdge;
|
||||
switch (direction) {
|
||||
case Dirs.DOWN, Dirs.UP -> {
|
||||
partial = minX >= EDGE_LOW || minZ >= EDGE_LOW || maxX <= EDGE_HIGH || maxZ <= EDGE_HIGH;
|
||||
flat = minY == maxY;
|
||||
onEdge = direction == Dirs.DOWN ? minY < EDGE_LOW : maxY > EDGE_HIGH;
|
||||
}
|
||||
case Dirs.NORTH, Dirs.SOUTH -> {
|
||||
partial = minX >= EDGE_LOW || minY >= EDGE_LOW || maxX <= EDGE_HIGH || maxY <= EDGE_HIGH;
|
||||
flat = minZ == maxZ;
|
||||
onEdge = direction == Dirs.NORTH ? minZ < EDGE_LOW : maxZ > EDGE_HIGH;
|
||||
}
|
||||
default -> {
|
||||
partial = minY >= EDGE_LOW || minZ >= EDGE_LOW || maxY <= EDGE_HIGH || maxZ <= EDGE_HIGH;
|
||||
flat = minX == maxX;
|
||||
onEdge = direction == Dirs.WEST ? minX < EDGE_LOW : maxX > EDGE_HIGH;
|
||||
}
|
||||
}
|
||||
info &= ~(FLAT | ON_EDGE | PARTIAL);
|
||||
t.quadInfo[q] = info | (flat ? FLAT : 0) | (onEdge ? ON_EDGE : 0) | (partial ? PARTIAL : 0);
|
||||
|
||||
// Smooth lighting's weights: for each corner of the face, how much of each of the four
|
||||
// blended corner samples it takes, by where the corner sits between the samples.
|
||||
int[] corners = AmbientOcclusion.CORNERS[direction];
|
||||
for (int vertex = 0; vertex < 4; vertex++) {
|
||||
for (int sample = 0; sample < 4; sample++) {
|
||||
int towardA = corners[AmbientOcclusion.SAMPLE_CORNERS[sample][0]];
|
||||
int towardB = corners[AmbientOcclusion.SAMPLE_CORNERS[sample][1]];
|
||||
float weight = towards(towardA, direction, vertex, bounds, q)
|
||||
* towards(towardB, direction, vertex, bounds, q);
|
||||
t.quadAoWeights[q * 16 + vertex * 4 + sample] = weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How far corner {@code vertex} of the face sits toward {@code toward}: its coordinate on that
|
||||
* axis, measured from the far side (1 - coordinate) for the negative directions.
|
||||
*/
|
||||
private static float towards(int toward, int faceDirection, int vertex, float[] bounds, int q) {
|
||||
int axis = Dirs.axisXyz(toward);
|
||||
int[] plane = PLANE_AXES[faceDirection];
|
||||
int planeIndex = plane[0] == axis ? 0 : 1;
|
||||
boolean atMax = CORNER_AT_MAX[faceDirection][vertex * 2 + planeIndex] == 1;
|
||||
float coordinate = bounds[q * 6 + (atMax ? 3 : 0) + axis];
|
||||
return Dirs.positive(toward) ? coordinate : 1.0F - coordinate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Meshes one section from a {@link Snapshot}: every block's model quads, culled against its
|
||||
* neighbors and lit (smoothly or flat, as the game would), its fluid's surfaces, the section's
|
||||
* visibility across its faces, and the translucent layer sorted back to front. What it writes is
|
||||
* what the game's own section compiler writes for the same blocks, vertex for vertex, in the same
|
||||
* order ({@code incari.client.render.mesher.MeshVerifier} checks that on the desktop).
|
||||
*
|
||||
* <p>Worker-side, no game objects. One instance per thread; it keeps its scratch space between
|
||||
* meshes, so after the first few a mesh allocates nothing. Hot path throughout.
|
||||
*/
|
||||
public final class SectionMesher {
|
||||
|
||||
private final MeshTables t;
|
||||
private final GameMath.Random random = new GameMath.Random();
|
||||
private final FluidMesher fluids;
|
||||
private final Visibility visibility = new Visibility();
|
||||
private final QuadSorter sorter = new QuadSorter();
|
||||
|
||||
private int[] parts = new int[16];
|
||||
private int partCount;
|
||||
|
||||
/** Per section block: its entry in the snapshot's tint list, or -1. */
|
||||
private final int[] tintEntry = new int[4096];
|
||||
/** Per snapshot position: its entry in the snapshot's dynamic-shape list, or -1. */
|
||||
private final int[] dynamicEntry = new int[Snapshot.VOLUME];
|
||||
|
||||
/** The quad being written to each layer: its corners so far, x y z each (ADR 0030). */
|
||||
private final float[][] corners = new float[MeshTables.LAYER_COUNT][12];
|
||||
/** Per layer, each quad's facing as written ({@link Facings}). */
|
||||
private final byte[][] quadFacings = {new byte[1024], new byte[256], new byte[256]};
|
||||
/** Each translucent quad's plane across its facing's axis, for a {@link FixedOrder}. */
|
||||
private float[] translucentPlanes = new float[256];
|
||||
/** A layer's vertices while they're regrouped by facing. */
|
||||
private byte[] regroup = new byte[16 * 1024];
|
||||
|
||||
private final int[] runStart = new int[Facings.COUNT];
|
||||
|
||||
private final int[] vertexColor = new int[4];
|
||||
private final int[] vertexLight = new int[4];
|
||||
private final int[] step = new int[6];
|
||||
|
||||
private Snapshot s = new Snapshot();
|
||||
private MeshResult out = new MeshResult();
|
||||
private int format;
|
||||
private float firstX;
|
||||
private float firstY;
|
||||
private float firstZ;
|
||||
|
||||
public SectionMesher(MeshTables tables) {
|
||||
t = tables;
|
||||
fluids = new FluidMesher(tables, this);
|
||||
Arrays.fill(tintEntry, -1);
|
||||
Arrays.fill(dynamicEntry, -1);
|
||||
for (int d = 0; d < 6; d++) {
|
||||
step[d] = Dirs.STEP_X[d] * Snapshot.STEP_X
|
||||
+ Dirs.STEP_Y[d] * Snapshot.STEP_Y
|
||||
+ Dirs.STEP_Z[d] * Snapshot.STEP_Z;
|
||||
}
|
||||
}
|
||||
|
||||
public MeshTables tables() {
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* Meshes {@code snapshot} into {@code result} (cleared first).
|
||||
*
|
||||
* @return false if the section holds a state the tables couldn't describe; the result is then
|
||||
* incomplete and the game should mesh the section itself
|
||||
*/
|
||||
public boolean mesh(Snapshot snapshot, MeshResult result) {
|
||||
s = snapshot;
|
||||
out = result;
|
||||
format = snapshot.vertexFormat;
|
||||
result.clear();
|
||||
result.vertexSize = VertexFormats.size(format);
|
||||
boolean supported = true;
|
||||
prepareLookups();
|
||||
try {
|
||||
char[] states = s.states;
|
||||
int[] flags = t.stateFlags;
|
||||
visibility.clear();
|
||||
for (int z = 0; z < 16; z++) {
|
||||
for (int y = 0; y < 16; y++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
int index = Snapshot.index(x, y, z);
|
||||
int state = states[index];
|
||||
int f = flags[state];
|
||||
if ((f & StateFlags.AIR) != 0) {
|
||||
continue;
|
||||
}
|
||||
if ((f & StateFlags.UNSUPPORTED) != 0) {
|
||||
supported = false;
|
||||
}
|
||||
if ((f & StateFlags.SOLID_RENDER) != 0) {
|
||||
visibility.setOpaque(Snapshot.blockIndex(x, y, z));
|
||||
}
|
||||
if (t.fluidGroup[state] != 0) {
|
||||
fluids.mesh(x, y, z, index, state);
|
||||
}
|
||||
if ((f & StateFlags.MODEL) != 0) {
|
||||
model(x, y, z, index, state, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.visibility = visibility.resolve();
|
||||
bakedQuads();
|
||||
groupByFacing(MeshTables.LAYER_SOLID);
|
||||
groupByFacing(MeshTables.LAYER_CUTOUT);
|
||||
result.facingRuns[MeshTables.LAYER_TRANSLUCENT * Facings.COUNT] =
|
||||
result.vertexCounts[MeshTables.LAYER_TRANSLUCENT] / 4;
|
||||
if (result.translucentQuads > 0) {
|
||||
byte[] facings = quadFacings[MeshTables.LAYER_TRANSLUCENT];
|
||||
if (s.fixedOrder && FixedOrder.holds(facings, result.translucentQuads)) {
|
||||
sorter.fixedInto(result, facings, translucentPlanes);
|
||||
result.fixedOrder = true;
|
||||
} else {
|
||||
sorter.sortInto(result, s.cameraX, s.cameraY, s.cameraZ);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearLookups();
|
||||
}
|
||||
return supported;
|
||||
}
|
||||
|
||||
private void prepareLookups() {
|
||||
for (int i = 0; i < s.tintCount; i++) {
|
||||
tintEntry[s.tintBlock[i] & 0xFFFF] = i;
|
||||
}
|
||||
for (int i = 0; i < s.dynamicCount; i++) {
|
||||
dynamicEntry[s.dynamicIndex[i] & 0xFFFF] = i;
|
||||
}
|
||||
}
|
||||
|
||||
private void clearLookups() {
|
||||
for (int i = 0; i < s.tintCount; i++) {
|
||||
tintEntry[s.tintBlock[i] & 0xFFFF] = -1;
|
||||
}
|
||||
for (int i = 0; i < s.dynamicCount; i++) {
|
||||
dynamicEntry[s.dynamicIndex[i] & 0xFFFF] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- What the snapshot says about a position ---------------------------------------------
|
||||
|
||||
/**
|
||||
* The game's light coordinates for {@code state} standing at {@code index}: full brightness if
|
||||
* it's emissive, else the position's light with block light raised to the state's emission.
|
||||
*/
|
||||
int lightCoords(int state, int index) {
|
||||
if ((t.stateFlags[state] & StateFlags.EMISSIVE) != 0) {
|
||||
return 0xF000F0;
|
||||
}
|
||||
int light = s.light[index];
|
||||
int block = light & 15;
|
||||
int packed = block << 4 | ((light >> 4) & 15) << 20;
|
||||
int emission = t.lightEmission[state];
|
||||
return block < emission ? (packed & 0xFF0000) | emission << 4 : packed;
|
||||
}
|
||||
|
||||
float shade(int state, int index) {
|
||||
if ((t.stateFlags[state] & StateFlags.DYNAMIC_SHAPE) != 0) {
|
||||
int entry = dynamicEntry[index];
|
||||
if (entry >= 0) {
|
||||
return s.dynamicShade[entry];
|
||||
}
|
||||
}
|
||||
return t.shade[state];
|
||||
}
|
||||
|
||||
boolean collisionFull(int state, int index) {
|
||||
if ((t.stateFlags[state] & StateFlags.DYNAMIC_SHAPE) != 0) {
|
||||
int entry = dynamicEntry[index];
|
||||
if (entry >= 0) {
|
||||
return (s.dynamicBits[entry] & Snapshot.DYNAMIC_COLLISION_FULL) != 0;
|
||||
}
|
||||
}
|
||||
return (t.stateFlags[state] & StateFlags.COLLISION_FULL) != 0;
|
||||
}
|
||||
|
||||
boolean sturdy(int state, int index, int direction) {
|
||||
if ((t.stateFlags[state] & StateFlags.DYNAMIC_SHAPE) != 0) {
|
||||
int entry = dynamicEntry[index];
|
||||
if (entry >= 0) {
|
||||
return (s.dynamicBits[entry] >> Snapshot.DYNAMIC_STURDY_SHIFT & 1 << direction) != 0;
|
||||
}
|
||||
}
|
||||
return (t.stateFlags[state] >> StateFlags.STURDY_SHIFT & 1 << direction) != 0;
|
||||
}
|
||||
|
||||
/** A tinted block's color for a tint source (-1 for none); see {@link Snapshot#addTint}. */
|
||||
int modelTint(int blockIndex, int tintIndex) {
|
||||
int entry = tintEntry[blockIndex];
|
||||
if (entry < 0 || tintIndex >= s.tintModelCount[entry]) {
|
||||
return -1;
|
||||
}
|
||||
return s.tintValues[s.tintStart[entry] + tintIndex];
|
||||
}
|
||||
|
||||
int fluidTint(int blockIndex) {
|
||||
int entry = tintEntry[blockIndex];
|
||||
if (entry < 0 || !s.tintHasFluid[entry]) {
|
||||
return -1;
|
||||
}
|
||||
return s.tintValues[s.tintStart[entry] + s.tintModelCount[entry]];
|
||||
}
|
||||
|
||||
Snapshot snapshot() {
|
||||
return s;
|
||||
}
|
||||
|
||||
int step(int direction) {
|
||||
return step[direction];
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a vertex; quads are four in a row. Notes each quad's facing from its corners (for
|
||||
* {@link #groupByFacing} and {@link FixedOrder}), and a translucent quad's center as the game
|
||||
* does: halfway between its first and third vertex.
|
||||
*/
|
||||
void vertex(int layer, float x, float y, float z, int color, float u, float v, int light) {
|
||||
VertexFormats.put(format, out.vertices[layer], x, y, z, color, u, v, light);
|
||||
int count = out.vertexCounts[layer]++;
|
||||
float[] quad = corners[layer];
|
||||
int corner = (count & 3) * 3;
|
||||
quad[corner] = x;
|
||||
quad[corner + 1] = y;
|
||||
quad[corner + 2] = z;
|
||||
if ((count & 3) == 3) {
|
||||
int index = count >> 2;
|
||||
byte[] facings = quadFacings[layer];
|
||||
if (index == facings.length) {
|
||||
facings = Arrays.copyOf(facings, facings.length * 2);
|
||||
quadFacings[layer] = facings;
|
||||
}
|
||||
int facing = Facings.of(
|
||||
quad[0], quad[1], quad[2], quad[3], quad[4], quad[5], quad[6], quad[7], quad[8], quad[9], quad[10],
|
||||
quad[11]);
|
||||
facings[index] = (byte) facing;
|
||||
if (layer == MeshTables.LAYER_TRANSLUCENT) {
|
||||
if (index == translucentPlanes.length) {
|
||||
translucentPlanes = Arrays.copyOf(translucentPlanes, translucentPlanes.length * 2);
|
||||
}
|
||||
// Down and up lie across y, north and south across z, west and east across x.
|
||||
int axis = facing >> 1;
|
||||
translucentPlanes[index] = axis == 0 ? quad[1] : axis == 1 ? quad[2] : quad[0];
|
||||
}
|
||||
}
|
||||
if (layer == MeshTables.LAYER_TRANSLUCENT) {
|
||||
if ((count & 3) == 0) {
|
||||
firstX = x;
|
||||
firstY = y;
|
||||
firstZ = z;
|
||||
} else if ((count & 3) == 2) {
|
||||
out.addCentroid((firstX + x) / 2.0F, (firstY + y) / 2.0F, (firstZ + z) / 2.0F);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the snapshot's finished quads (block entities drawn as part of it) as they are. */
|
||||
private void bakedQuads() {
|
||||
for (int q = 0; q < s.bakedCount; q++) {
|
||||
int light = s.bakedLight[q];
|
||||
for (int v = 0; v < 4; v++) {
|
||||
int p = q * 12 + v * 3;
|
||||
vertex(
|
||||
MeshTables.LAYER_CUTOUT,
|
||||
s.bakedPositions[p],
|
||||
s.bakedPositions[p + 1],
|
||||
s.bakedPositions[p + 2],
|
||||
s.bakedColors[q * 4 + v],
|
||||
s.bakedUvs[q * 8 + v * 2],
|
||||
s.bakedUvs[q * 8 + v * 2 + 1],
|
||||
light);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Notes that the section draws animated sprite {@code id} of the tables. */
|
||||
void markAnimated(int id) {
|
||||
out.markAnimated(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a layer's quads grouped by facing, in {@link Facings#runOf}'s order, each group in the
|
||||
* order its quads were written, and counts each run (ADR 0030).
|
||||
*/
|
||||
private void groupByFacing(int layer) {
|
||||
int quads = out.vertexCounts[layer] >> 2;
|
||||
if (quads == 0) {
|
||||
return;
|
||||
}
|
||||
byte[] facings = quadFacings[layer];
|
||||
int[] runs = out.facingRuns;
|
||||
int base = layer * Facings.COUNT;
|
||||
boolean ordered = true;
|
||||
int previous = 0;
|
||||
for (int q = 0; q < quads; q++) {
|
||||
int run = Facings.runOf(facings[q]);
|
||||
runs[base + run]++;
|
||||
ordered &= run >= previous;
|
||||
previous = run;
|
||||
}
|
||||
if (ordered) {
|
||||
return;
|
||||
}
|
||||
int quadBytes = out.vertexSize * 4;
|
||||
int total = quads * quadBytes;
|
||||
if (regroup.length < total) {
|
||||
regroup = new byte[Math.max(total, regroup.length * 2)];
|
||||
}
|
||||
byte[] data = out.vertices[layer].array();
|
||||
System.arraycopy(data, 0, regroup, 0, total);
|
||||
int start = 0;
|
||||
for (int run = 0; run < Facings.COUNT; run++) {
|
||||
runStart[run] = start;
|
||||
start += runs[base + run];
|
||||
}
|
||||
for (int q = 0; q < quads; q++) {
|
||||
int run = Facings.runOf(facings[q]);
|
||||
System.arraycopy(regroup, q * quadBytes, data, runStart[run]++ * quadBytes, quadBytes);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Models ---------------------------------------------------------------------------------
|
||||
|
||||
private void model(int x, int y, int z, int index, int state, int f) {
|
||||
int node = t.modelNode[state];
|
||||
if (node < 0) {
|
||||
return;
|
||||
}
|
||||
int packedSeedOffset = t.seedOffset[state];
|
||||
int wx = s.originX + x;
|
||||
int wy = s.originY + y;
|
||||
int wz = s.originZ + z;
|
||||
random.setSeed(GameMath.positionSeed(
|
||||
wx + (packedSeedOffset & 3) - 1,
|
||||
wy + (packedSeedOffset >> 2 & 3) - 1,
|
||||
wz + (packedSeedOffset >> 4 & 3) - 1));
|
||||
partCount = 0;
|
||||
collect(node);
|
||||
if (partCount == 0) {
|
||||
return;
|
||||
}
|
||||
float offsetX = 0.0F;
|
||||
float offsetY = 0.0F;
|
||||
float offsetZ = 0.0F;
|
||||
int table = t.offsetTable[state];
|
||||
if (table >= 0) {
|
||||
long offsetSeed = GameMath.positionSeed(wx, 0, wz);
|
||||
offsetX = t.offsets[table * 48 + (int) (offsetSeed & 15L)];
|
||||
offsetY = t.offsets[table * 48 + 16 + (int) (offsetSeed >> 4 & 15L)];
|
||||
offsetZ = t.offsets[table * 48 + 32 + (int) (offsetSeed >> 8 & 15L)];
|
||||
}
|
||||
float bx = x + offsetX;
|
||||
float by = y + offsetY;
|
||||
float bz = z + offsetZ;
|
||||
boolean solidLayer = (f & StateFlags.FORCE_SOLID_LAYER) != 0;
|
||||
boolean smooth = t.ambientOcclusion && t.lightEmission[state] == 0 && t.partAmbientOcclusion[parts[0]] != 0;
|
||||
int blockIndex = Snapshot.blockIndex(x, y, z);
|
||||
|
||||
// Which faces show, decided once per direction for all of the block's parts.
|
||||
int decided = 0;
|
||||
int shown = 0;
|
||||
for (int p = 0; p < partCount; p++) {
|
||||
int part = parts[p];
|
||||
for (int d = 0; d < 6; d++) {
|
||||
int bit = 1 << d;
|
||||
if ((decided & bit) != 0 && (shown & bit) == 0) {
|
||||
continue;
|
||||
}
|
||||
int from = t.partFaces[part * 8 + d];
|
||||
int to = t.partFaces[part * 8 + d + 1];
|
||||
if (from == to) {
|
||||
continue;
|
||||
}
|
||||
if ((decided & bit) == 0) {
|
||||
decided |= bit;
|
||||
if (faceShows(state, index, d)) {
|
||||
shown |= bit;
|
||||
}
|
||||
}
|
||||
if ((shown & bit) != 0) {
|
||||
int flatLight = smooth ? 0 : lightCoords(state, index + step[d]);
|
||||
for (int i = from; i < to; i++) {
|
||||
quad(t.partQuads[i], state, index, blockIndex, bx, by, bz, smooth, flatLight, solidLayer);
|
||||
}
|
||||
}
|
||||
}
|
||||
int from = t.partFaces[part * 8 + 6];
|
||||
int to = t.partFaces[part * 8 + 7];
|
||||
for (int i = from; i < to; i++) {
|
||||
quad(t.partQuads[i], state, index, blockIndex, bx, by, bz, smooth, -1, solidLayer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Walks a model node the way the game collects a block's parts from its random. */
|
||||
private void collect(int node) {
|
||||
int[] nodes = t.nodes;
|
||||
switch (nodes[node]) {
|
||||
case MeshTables.NODE_SINGLE -> {
|
||||
if (partCount == parts.length) {
|
||||
parts = Arrays.copyOf(parts, partCount * 2);
|
||||
}
|
||||
parts[partCount++] = nodes[node + 1];
|
||||
}
|
||||
case MeshTables.NODE_WEIGHTED -> {
|
||||
int selection = random.nextInt(nodes[node + 1]);
|
||||
int count = nodes[node + 2];
|
||||
for (int i = 0; i < count; i++) {
|
||||
selection -= nodes[node + 3 + 2 * i];
|
||||
if (selection < 0) {
|
||||
collect(nodes[node + 4 + 2 * i]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Weighted model selection past its total");
|
||||
}
|
||||
case MeshTables.NODE_LIST -> {
|
||||
int count = nodes[node + 1];
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (partCount == parts.length) {
|
||||
parts = Arrays.copyOf(parts, partCount * 2);
|
||||
}
|
||||
parts[partCount++] = nodes[node + 2 + i];
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
long seed = random.nextLong();
|
||||
int count = nodes[node + 1];
|
||||
for (int i = 0; i < count; i++) {
|
||||
random.setSeed(seed);
|
||||
collect(nodes[node + 2 + i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a block's face toward {@code direction} shows past its neighbor there. */
|
||||
private boolean faceShows(int state, int index, int direction) {
|
||||
int neighbor = s.states[index + step[direction]];
|
||||
int occluder = t.faceShape[neighbor * 6 + Dirs.opposite(direction)];
|
||||
if (occluder == MeshTables.SHAPE_FULL) {
|
||||
return false;
|
||||
}
|
||||
if ((t.stateFlags[state] & StateFlags.SKIP_RULE) != 0 && skips(state, neighbor, direction)) {
|
||||
return false;
|
||||
}
|
||||
if (occluder == MeshTables.SHAPE_EMPTY) {
|
||||
return true;
|
||||
}
|
||||
int shape = t.faceShape[state * 6 + direction];
|
||||
if (shape == MeshTables.SHAPE_EMPTY) {
|
||||
return true;
|
||||
}
|
||||
int bit = shape * t.shapeCount + occluder;
|
||||
return (t.shapeCovered[bit >> 6] & 1L << bit) == 0;
|
||||
}
|
||||
|
||||
private boolean skips(int state, int neighbor, int direction) {
|
||||
int a = t.skipClass[state];
|
||||
int b = t.skipClass[neighbor];
|
||||
if (a < 0 || b < 0) {
|
||||
return false;
|
||||
}
|
||||
int bit = (a * t.skipClassCount + b) * 6 + direction;
|
||||
return (t.skipTable[bit >> 6] & 1L << bit) != 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lights, tints and writes one quad.
|
||||
*
|
||||
* @param flatLight the face's light for a culled face lit flat, or -1 for an unculled face,
|
||||
* whose light depends on its shape
|
||||
*/
|
||||
private void quad(
|
||||
int q,
|
||||
int state,
|
||||
int index,
|
||||
int blockIndex,
|
||||
float bx,
|
||||
float by,
|
||||
float bz,
|
||||
boolean smooth,
|
||||
int flatLight,
|
||||
boolean solidLayer) {
|
||||
int info = t.quadInfo[q];
|
||||
int animated = t.quadAnimated[q];
|
||||
if (animated != 0) {
|
||||
out.markAnimated(animated - 1);
|
||||
}
|
||||
float brightness = s.cardinalLighting[Quads.shadeDirection(info)];
|
||||
if (smooth) {
|
||||
smoothLight(q, info, state, index, brightness);
|
||||
} else {
|
||||
int light = flatLight;
|
||||
if (light == -1) {
|
||||
int direction = Quads.direction(info);
|
||||
boolean cubic =
|
||||
(info & Quads.FLAT) != 0 && ((info & Quads.ON_EDGE) != 0 || collisionFull(state, index));
|
||||
light = lightCoords(state, cubic ? index + step[direction] : index);
|
||||
}
|
||||
int gray = gray(brightness);
|
||||
for (int v = 0; v < 4; v++) {
|
||||
vertexLight[v] = light;
|
||||
vertexColor[v] = gray;
|
||||
}
|
||||
}
|
||||
int tintIndex = Quads.tintIndex(info);
|
||||
if (tintIndex != -1) {
|
||||
int tint = modelTint(blockIndex, tintIndex);
|
||||
for (int v = 0; v < 4; v++) {
|
||||
vertexColor[v] = multiply(vertexColor[v], tint);
|
||||
}
|
||||
}
|
||||
int layer = solidLayer ? MeshTables.LAYER_SOLID : Quads.layer(info);
|
||||
int emission = Quads.lightEmission(info);
|
||||
float[] positions = t.quadPositions;
|
||||
float[] uvs = t.quadUvs;
|
||||
for (int v = 0; v < 4; v++) {
|
||||
vertex(
|
||||
layer,
|
||||
positions[q * 12 + v * 3] + bx,
|
||||
positions[q * 12 + v * 3 + 1] + by,
|
||||
positions[q * 12 + v * 3 + 2] + bz,
|
||||
vertexColor[v],
|
||||
uvs[q * 8 + v * 2],
|
||||
uvs[q * 8 + v * 2 + 1],
|
||||
AmbientOcclusion.withEmission(vertexLight[v], emission));
|
||||
}
|
||||
}
|
||||
|
||||
/** The game's smooth lighting of one quad: {@link #vertexColor} and {@link #vertexLight}. */
|
||||
private void smoothLight(int q, int info, int state, int index, float brightness) {
|
||||
int direction = Quads.direction(info);
|
||||
char[] states = s.states;
|
||||
int[] flags = t.stateFlags;
|
||||
boolean cubic = (info & Quads.FLAT) != 0 && ((info & Quads.ON_EDGE) != 0 || collisionFull(state, index));
|
||||
int base = cubic ? index + step[direction] : index;
|
||||
int[] corners = AmbientOcclusion.CORNERS[direction];
|
||||
int forward = step[direction];
|
||||
|
||||
int p0 = base + step[corners[0]];
|
||||
int p1 = base + step[corners[1]];
|
||||
int p2 = base + step[corners[2]];
|
||||
int p3 = base + step[corners[3]];
|
||||
int s0 = states[p0];
|
||||
int s1 = states[p1];
|
||||
int s2 = states[p2];
|
||||
int s3 = states[p3];
|
||||
int light0 = lightCoords(s0, p0);
|
||||
int light1 = lightCoords(s1, p1);
|
||||
int light2 = lightCoords(s2, p2);
|
||||
int light3 = lightCoords(s3, p3);
|
||||
float shade0 = shade(s0, p0);
|
||||
float shade1 = shade(s1, p1);
|
||||
float shade2 = shade(s2, p2);
|
||||
float shade3 = shade(s3, p3);
|
||||
boolean open0 = (flags[states[p0 + forward]] & StateFlags.LIGHT_PERMEABLE) != 0;
|
||||
boolean open1 = (flags[states[p1 + forward]] & StateFlags.LIGHT_PERMEABLE) != 0;
|
||||
boolean open2 = (flags[states[p2 + forward]] & StateFlags.LIGHT_PERMEABLE) != 0;
|
||||
boolean open3 = (flags[states[p3 + forward]] & StateFlags.LIGHT_PERMEABLE) != 0;
|
||||
|
||||
// The diagonals, read only where light could reach them; else the first corner stands in
|
||||
// (for all four: the game's choice, kept).
|
||||
float shade02 = shade0;
|
||||
int light02 = light0;
|
||||
if (open2 || open0) {
|
||||
int p = p0 + step[corners[2]];
|
||||
shade02 = shade(states[p], p);
|
||||
light02 = lightCoords(states[p], p);
|
||||
}
|
||||
float shade03 = shade0;
|
||||
int light03 = light0;
|
||||
if (open3 || open0) {
|
||||
int p = p0 + step[corners[3]];
|
||||
shade03 = shade(states[p], p);
|
||||
light03 = lightCoords(states[p], p);
|
||||
}
|
||||
float shade12 = shade0;
|
||||
int light12 = light0;
|
||||
if (open2 || open1) {
|
||||
int p = p1 + step[corners[2]];
|
||||
shade12 = shade(states[p], p);
|
||||
light12 = lightCoords(states[p], p);
|
||||
}
|
||||
float shade13 = shade0;
|
||||
int light13 = light0;
|
||||
if (open3 || open1) {
|
||||
int p = p1 + step[corners[3]];
|
||||
shade13 = shade(states[p], p);
|
||||
light13 = lightCoords(states[p], p);
|
||||
}
|
||||
|
||||
int lightCenter = lightCoords(state, index);
|
||||
int next = index + forward;
|
||||
int nextState = states[next];
|
||||
if (cubic || (flags[nextState] & StateFlags.SOLID_RENDER) == 0) {
|
||||
lightCenter = lightCoords(nextState, next);
|
||||
}
|
||||
float shadeCenter = cubic ? shade(states[base], base) : shade(state, index);
|
||||
|
||||
float sample1 = (shade3 + shade0 + shade03 + shadeCenter) * 0.25F;
|
||||
float sample2 = (shade2 + shade0 + shade02 + shadeCenter) * 0.25F;
|
||||
float sample3 = (shade2 + shade1 + shade12 + shadeCenter) * 0.25F;
|
||||
float sample4 = (shade3 + shade1 + shade13 + shadeCenter) * 0.25F;
|
||||
int blend1 = AmbientOcclusion.blend(light3, light0, light03, lightCenter);
|
||||
int blend2 = AmbientOcclusion.blend(light2, light0, light02, lightCenter);
|
||||
int blend3 = AmbientOcclusion.blend(light2, light1, light12, lightCenter);
|
||||
int blend4 = AmbientOcclusion.blend(light3, light1, light13, lightCenter);
|
||||
int[] vertexOf = AmbientOcclusion.VERTEX_OF_CORNER[direction];
|
||||
if ((info & Quads.PARTIAL) != 0) {
|
||||
float[] weights = t.quadAoWeights;
|
||||
for (int corner = 0; corner < 4; corner++) {
|
||||
int w = q * 16 + corner * 4;
|
||||
float w1 = weights[w];
|
||||
float w2 = weights[w + 1];
|
||||
float w3 = weights[w + 2];
|
||||
float w4 = weights[w + 3];
|
||||
int vertex = vertexOf[corner];
|
||||
vertexColor[vertex] = gray(clampUnit(sample1 * w1 + sample2 * w2 + sample3 * w3 + sample4 * w4));
|
||||
vertexLight[vertex] = AmbientOcclusion.weightedBlend(blend1, blend2, blend3, blend4, w1, w2, w3, w4);
|
||||
}
|
||||
} else {
|
||||
vertexLight[vertexOf[0]] = blend1;
|
||||
vertexLight[vertexOf[1]] = blend2;
|
||||
vertexLight[vertexOf[2]] = blend3;
|
||||
vertexLight[vertexOf[3]] = blend4;
|
||||
vertexColor[vertexOf[0]] = gray(sample1);
|
||||
vertexColor[vertexOf[1]] = gray(sample2);
|
||||
vertexColor[vertexOf[2]] = gray(sample3);
|
||||
vertexColor[vertexOf[3]] = gray(sample4);
|
||||
}
|
||||
for (int v = 0; v < 4; v++) {
|
||||
vertexColor[v] = scale(vertexColor[v], brightness);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- The game's color arithmetic ----------------------------------------------------------
|
||||
|
||||
/** Clamps to 0..1, letting NaN through as the game's clamp does. */
|
||||
private static float clampUnit(float value) {
|
||||
return value < 0.0F ? 0.0F : value > 1.0F ? 1.0F : value;
|
||||
}
|
||||
|
||||
/** An opaque gray of {@code brightness}: the 8-bit channel rounded down. */
|
||||
static int gray(float brightness) {
|
||||
int channel = floor(brightness * 255.0F);
|
||||
return 0xFF000000 | (channel & 0xFF) << 16 | (channel & 0xFF) << 8 | (channel & 0xFF);
|
||||
}
|
||||
|
||||
static int floor(float value) {
|
||||
int truncated = (int) value;
|
||||
return value < truncated ? truncated - 1 : truncated;
|
||||
}
|
||||
|
||||
/** Scales the color channels (not alpha), each truncated and clamped to 0..255. */
|
||||
static int scale(int color, float factor) {
|
||||
int r = clampChannel((int) ((color >> 16 & 0xFF) * factor));
|
||||
int g = clampChannel((int) ((color >> 8 & 0xFF) * factor));
|
||||
int b = clampChannel((int) ((color & 0xFF) * factor));
|
||||
return (color & 0xFF000000) | r << 16 | g << 8 | b;
|
||||
}
|
||||
|
||||
private static int clampChannel(int value) {
|
||||
return value < 0 ? 0 : Math.min(value, 255);
|
||||
}
|
||||
|
||||
/** Multiplies two ARGB colors channel by channel; -1 (opaque white) leaves the other as it is. */
|
||||
static int multiply(int a, int b) {
|
||||
if (a == -1) {
|
||||
return b;
|
||||
}
|
||||
if (b == -1) {
|
||||
return a;
|
||||
}
|
||||
int alpha = (a >>> 24) * (b >>> 24) / 255;
|
||||
int red = (a >> 16 & 0xFF) * (b >> 16 & 0xFF) / 255;
|
||||
int green = (a >> 8 & 0xFF) * (b >> 8 & 0xFF) / 255;
|
||||
int blue = (a & 0xFF) * (b & 0xFF) / 255;
|
||||
return (alpha & 0xFF) << 24 | (red & 0xFF) << 16 | (green & 0xFF) << 8 | (blue & 0xFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package incari.mesher;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* One section to mesh, flattened: the block states and light of the section and two blocks around
|
||||
* it (smooth lighting looks that far), the colors its tinted blocks take where they stand, and the
|
||||
* few per-position facts that don't follow from a state. The game's side fills it from its copy of
|
||||
* the section's surroundings; the mesher reads nothing else of the world.
|
||||
*
|
||||
* <p>Positions are section-relative, from -2 to 17 on each axis: {@link #index}.
|
||||
*/
|
||||
public final class Snapshot {
|
||||
|
||||
/** The border around the section, in blocks. */
|
||||
public static final int BORDER = 2;
|
||||
/** The snapshot's edge: the section's 16 blocks and the border on both sides. */
|
||||
public static final int SIZE = 16 + 2 * BORDER;
|
||||
|
||||
public static final int VOLUME = SIZE * SIZE * SIZE;
|
||||
static final int STEP_X = 1;
|
||||
static final int STEP_Z = SIZE;
|
||||
static final int STEP_Y = SIZE * SIZE;
|
||||
|
||||
/** Vertex formats: the game's own block format (28 bytes), or Incari's compact one (16). */
|
||||
public static final int FORMAT_VANILLA = 0;
|
||||
|
||||
public static final int FORMAT_COMPACT = 1;
|
||||
|
||||
/** Where a section-relative position is in {@link #states} and {@link #light}. */
|
||||
public static int index(int x, int y, int z) {
|
||||
return ((y + BORDER) * SIZE + (z + BORDER)) * SIZE + (x + BORDER);
|
||||
}
|
||||
|
||||
/** A position in the section itself, as the mesher numbers its blocks: y, then z, then x. */
|
||||
public static int blockIndex(int x, int y, int z) {
|
||||
return y << 8 | z << 4 | x;
|
||||
}
|
||||
|
||||
/** The section's lowest corner, in block coordinates. */
|
||||
public int originX;
|
||||
|
||||
public int originY;
|
||||
public int originZ;
|
||||
/** The level's shading of each face direction ({@code CardinalLighting}). */
|
||||
public final float[] cardinalLighting = new float[6];
|
||||
|
||||
/** Block state ids. */
|
||||
public final char[] states = new char[VOLUME];
|
||||
/** Sky light in the high nibble, block light in the low one. */
|
||||
public final byte[] light = new byte[VOLUME];
|
||||
|
||||
/** The camera relative to the section's origin, for sorting translucent quads back to front. */
|
||||
public float cameraX;
|
||||
|
||||
public float cameraY;
|
||||
public float cameraZ;
|
||||
/** {@link #FORMAT_VANILLA} or {@link #FORMAT_COMPACT}. */
|
||||
public int vertexFormat;
|
||||
/**
|
||||
* Whether a translucent layer may use its {@link FixedOrder} instead of being sorted from
|
||||
* {@link #cameraX}.
|
||||
*/
|
||||
public boolean fixedOrder;
|
||||
|
||||
// Tints: for each tinted block in the section, its model's colors (one per tint source) and,
|
||||
// for a fluid, the fluid's color.
|
||||
int tintCount;
|
||||
short[] tintBlock = new short[256];
|
||||
byte[] tintModelCount = new byte[256];
|
||||
boolean[] tintHasFluid = new boolean[256];
|
||||
int[] tintStart = new int[256];
|
||||
int[] tintValues = new int[512];
|
||||
int tintValueCount;
|
||||
|
||||
// Positions whose state has a shape that depends on where it is (StateFlags.DYNAMIC_SHAPE).
|
||||
int dynamicCount;
|
||||
short[] dynamicIndex = new short[16];
|
||||
byte[] dynamicBits = new byte[16];
|
||||
float[] dynamicShade = new float[16];
|
||||
|
||||
static final int DYNAMIC_COLLISION_FULL = 1;
|
||||
static final int DYNAMIC_STURDY_SHIFT = 1;
|
||||
|
||||
// Quads the game's side made already, lit and textured, written into the cutout layer as they
|
||||
// are: block entities drawn as part of the section (ADR 0030).
|
||||
int bakedCount;
|
||||
float[] bakedPositions = new float[12 * 16];
|
||||
float[] bakedUvs = new float[8 * 16];
|
||||
int[] bakedColors = new int[4 * 16];
|
||||
int[] bakedLight = new int[16];
|
||||
private final float[] scratchPositions = new float[12];
|
||||
private final float[] scratchUvs = new float[8];
|
||||
private final int[] scratchColors = new int[4];
|
||||
|
||||
/** Empties the per-block lists before the snapshot is filled again. */
|
||||
public void clearLists() {
|
||||
tintCount = 0;
|
||||
tintValueCount = 0;
|
||||
dynamicCount = 0;
|
||||
bakedCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a finished quad to the cutout layer: four corners' section-relative positions (x y z each)
|
||||
* and texture coordinates (u v each), their ARGB colors, and the packed light of all four.
|
||||
*/
|
||||
public void addBakedQuad(float[] positions, float[] uvs, int[] colors, int light) {
|
||||
if (bakedCount == bakedLight.length) {
|
||||
int grown = bakedCount * 2;
|
||||
bakedPositions = Arrays.copyOf(bakedPositions, grown * 12);
|
||||
bakedUvs = Arrays.copyOf(bakedUvs, grown * 8);
|
||||
bakedColors = Arrays.copyOf(bakedColors, grown * 4);
|
||||
bakedLight = Arrays.copyOf(bakedLight, grown);
|
||||
}
|
||||
System.arraycopy(positions, 0, bakedPositions, bakedCount * 12, 12);
|
||||
System.arraycopy(uvs, 0, bakedUvs, bakedCount * 8, 8);
|
||||
System.arraycopy(colors, 0, bakedColors, bakedCount * 4, 4);
|
||||
bakedLight[bakedCount] = light;
|
||||
bakedCount++;
|
||||
}
|
||||
|
||||
public int bakedCount() {
|
||||
return bakedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* The colors a tinted block takes: {@code modelTints[0..modelCount)} by tint index, and the
|
||||
* fluid's color if it has a fluid ({@code fluidTint} is ignored otherwise). Blocks are added in
|
||||
* any order, each once.
|
||||
*/
|
||||
public void addTint(int blockIndex, int[] modelTints, int modelCount, boolean hasFluid, int fluidTint) {
|
||||
if (tintCount == tintBlock.length) {
|
||||
int grown = tintCount * 2;
|
||||
tintBlock = Arrays.copyOf(tintBlock, grown);
|
||||
tintModelCount = Arrays.copyOf(tintModelCount, grown);
|
||||
tintHasFluid = Arrays.copyOf(tintHasFluid, grown);
|
||||
tintStart = Arrays.copyOf(tintStart, grown);
|
||||
}
|
||||
int needed = modelCount + 1;
|
||||
if (tintValueCount + needed > tintValues.length) {
|
||||
tintValues = Arrays.copyOf(tintValues, Math.max(tintValueCount + needed, tintValues.length * 2));
|
||||
}
|
||||
tintBlock[tintCount] = (short) blockIndex;
|
||||
tintModelCount[tintCount] = (byte) modelCount;
|
||||
tintHasFluid[tintCount] = hasFluid;
|
||||
tintStart[tintCount] = tintValueCount;
|
||||
System.arraycopy(modelTints, 0, tintValues, tintValueCount, modelCount);
|
||||
tintValues[tintValueCount + modelCount] = fluidTint;
|
||||
tintValueCount += needed;
|
||||
tintCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a dynamic-shape state is at {@code index}: whether its collision shape is the full block,
|
||||
* which faces are sturdy (bit per direction), and its shade.
|
||||
*/
|
||||
public void addDynamic(int index, boolean collisionFull, int sturdyFaces, float shade) {
|
||||
if (dynamicCount == dynamicIndex.length) {
|
||||
int grown = dynamicCount * 2;
|
||||
dynamicIndex = Arrays.copyOf(dynamicIndex, grown);
|
||||
dynamicBits = Arrays.copyOf(dynamicBits, grown);
|
||||
dynamicShade = Arrays.copyOf(dynamicShade, grown);
|
||||
}
|
||||
dynamicIndex[dynamicCount] = (short) index;
|
||||
dynamicBits[dynamicCount] =
|
||||
(byte) ((collisionFull ? DYNAMIC_COLLISION_FULL : 0) | sturdyFaces << DYNAMIC_STURDY_SHIFT);
|
||||
dynamicShade[dynamicCount] = shade;
|
||||
dynamicCount++;
|
||||
}
|
||||
|
||||
public int dynamicCount() {
|
||||
return dynamicCount;
|
||||
}
|
||||
|
||||
public void encode(Bytes.Out out) {
|
||||
out.putInt(originX);
|
||||
out.putInt(originY);
|
||||
out.putInt(originZ);
|
||||
for (float f : cardinalLighting) {
|
||||
out.putFloat(f);
|
||||
}
|
||||
out.putFloat(cameraX);
|
||||
out.putFloat(cameraY);
|
||||
out.putFloat(cameraZ);
|
||||
out.putByte(vertexFormat);
|
||||
out.putByte(fixedOrder ? 1 : 0);
|
||||
out.putChars(states, VOLUME);
|
||||
out.putByteArray(light, VOLUME);
|
||||
out.putInt(tintCount);
|
||||
for (int i = 0; i < tintCount; i++) {
|
||||
out.putShort(tintBlock[i]);
|
||||
out.putByte(tintModelCount[i]);
|
||||
out.putByte(tintHasFluid[i] ? 1 : 0);
|
||||
int start = tintStart[i];
|
||||
for (int k = 0; k <= tintModelCount[i]; k++) {
|
||||
out.putInt(tintValues[start + k]);
|
||||
}
|
||||
}
|
||||
out.putInt(dynamicCount);
|
||||
for (int i = 0; i < dynamicCount; i++) {
|
||||
out.putShort(dynamicIndex[i]);
|
||||
out.putByte(dynamicBits[i]);
|
||||
out.putFloat(dynamicShade[i]);
|
||||
}
|
||||
out.putInt(bakedCount);
|
||||
out.putFloats(bakedPositions, bakedCount * 12);
|
||||
out.putFloats(bakedUvs, bakedCount * 8);
|
||||
out.putInts(bakedColors, bakedCount * 4);
|
||||
out.putInts(bakedLight, bakedCount);
|
||||
}
|
||||
|
||||
/** Fills this snapshot from what {@link #encode} wrote. */
|
||||
public void decode(Bytes.In in) {
|
||||
clearLists();
|
||||
originX = in.getInt();
|
||||
originY = in.getInt();
|
||||
originZ = in.getInt();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
cardinalLighting[i] = in.getFloat();
|
||||
}
|
||||
cameraX = in.getFloat();
|
||||
cameraY = in.getFloat();
|
||||
cameraZ = in.getFloat();
|
||||
vertexFormat = in.getByte();
|
||||
fixedOrder = in.getByte() != 0;
|
||||
in.getChars(states);
|
||||
in.getByteArray(light);
|
||||
int tints = in.getInt();
|
||||
int[] scratch = new int[8];
|
||||
for (int i = 0; i < tints; i++) {
|
||||
int block = in.getShort() & 0xFFFF;
|
||||
int modelCount = in.getUnsignedByte();
|
||||
boolean hasFluid = in.getByte() != 0;
|
||||
if (scratch.length < modelCount + 1) {
|
||||
scratch = new int[modelCount + 1];
|
||||
}
|
||||
for (int k = 0; k <= modelCount; k++) {
|
||||
scratch[k] = in.getInt();
|
||||
}
|
||||
addTint(block, scratch, modelCount, hasFluid, scratch[modelCount]);
|
||||
}
|
||||
int dynamics = in.getInt();
|
||||
for (int i = 0; i < dynamics; i++) {
|
||||
int index = in.getShort() & 0xFFFF;
|
||||
int bits = in.getUnsignedByte();
|
||||
float shade = in.getFloat();
|
||||
addDynamic(index, (bits & DYNAMIC_COLLISION_FULL) != 0, bits >> DYNAMIC_STURDY_SHIFT & 0x3F, shade);
|
||||
}
|
||||
int baked = in.getInt();
|
||||
float[] positions = in.getFloats();
|
||||
float[] uvs = in.getFloats();
|
||||
int[] colors = in.getInts();
|
||||
int[] light = in.getInts();
|
||||
bakedCount = 0;
|
||||
for (int q = 0; q < baked; q++) {
|
||||
System.arraycopy(positions, q * 12, scratchPositions, 0, 12);
|
||||
System.arraycopy(uvs, q * 8, scratchUvs, 0, 8);
|
||||
System.arraycopy(colors, q * 4, scratchColors, 0, 4);
|
||||
addBakedQuad(scratchPositions, scratchUvs, scratchColors, light[q]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* What the mesher knows about a block state, one bit each ({@link MeshTables#stateFlags}). The
|
||||
* table builder reads every one of them from the game.
|
||||
*/
|
||||
public final class StateFlags {
|
||||
|
||||
private StateFlags() {}
|
||||
|
||||
public static final int AIR = 1;
|
||||
/** Drawn from its block model (the game's {@code RenderShape.MODEL}). */
|
||||
public static final int MODEL = 1 << 1;
|
||||
/** Fills its block and hides what's behind it ({@code isSolidRender}). */
|
||||
public static final int SOLID_RENDER = 1 << 2;
|
||||
/** Lets light through at corners ({@code isLightPermeable}): ambient occlusion reads it. */
|
||||
public static final int LIGHT_PERMEABLE = 1 << 3;
|
||||
/** Always drawn at full brightness ({@code emissiveRendering}). */
|
||||
public static final int EMISSIVE = 1 << 4;
|
||||
/** The legacy "solid" material flag fluids use for their height at a neighbor. */
|
||||
public static final int LEGACY_SOLID = 1 << 5;
|
||||
/** In the {@code blocks_fluid_flow} tag. */
|
||||
public static final int BLOCKS_FLUID_FLOW = 1 << 6;
|
||||
/** An ice block: never a solid face for flowing fluids. */
|
||||
public static final int ICE = 1 << 7;
|
||||
/**
|
||||
* Its collision shape, and so its shade, full-block test and sturdy faces, depend on where it
|
||||
* is: the snapshot carries them for each position ({@link Snapshot#dynamicCount}).
|
||||
*/
|
||||
public static final int DYNAMIC_SHAPE = 1 << 8;
|
||||
/** Leaves drawn opaque (the "cutout leaves" option off): every quad goes in the solid layer. */
|
||||
public static final int FORCE_SOLID_LAYER = 1 << 9;
|
||||
/** Its collision shape is the full block ({@code isCollisionShapeFullBlock}). */
|
||||
public static final int COLLISION_FULL = 1 << 10;
|
||||
/** A falling fluid ({@code FlowingFluid.FALLING}). */
|
||||
public static final int FLUID_FALLING = 1 << 11;
|
||||
/** Its model is tinted by where it is: the snapshot carries the colors. */
|
||||
public static final int TINTED = 1 << 12;
|
||||
/** Its model couldn't be put in the tables: a section with it is meshed by the game instead. */
|
||||
public static final int UNSUPPORTED = 1 << 13;
|
||||
/** Its faces hide from some neighbors by a rule of its block ({@code skipRendering}). */
|
||||
public static final int SKIP_RULE = 1 << 14;
|
||||
/** Glass-like or leaves: a fluid's side against it shows the fluid's overlay texture. */
|
||||
public static final int FLUID_OVERLAY = 1 << 15;
|
||||
|
||||
/** Six bits from here: {@code isFaceSturdy} (full support) toward each direction. */
|
||||
public static final int STURDY_SHIFT = 16;
|
||||
/** Six bits from here: its own shape hides a fluid face toward each direction. */
|
||||
public static final int HIDES_OWN_FLUID_SHIFT = 22;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* The two vertex formats the mesher writes. Hot path: one call per vertex, nothing allocated.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link Snapshot#FORMAT_VANILLA}, the game's block format, 28 bytes: position as three
|
||||
* floats, color as RGBA bytes, texture coordinates as two floats, light as two shorts (block,
|
||||
* then sky). Byte for byte what the game's own section compiler writes.
|
||||
* <li>{@link Snapshot#FORMAT_COMPACT}, 16 bytes: position as three unsigned shorts (section
|
||||
* relative, 1/2048 of a block from -8), block and sky light as a byte each, color as RGBA
|
||||
* bytes, texture coordinates as two unsigned shorts (1/32768 of the atlas). The WebGL2
|
||||
* backend decodes it in the terrain shaders (ADR 0023).
|
||||
* </ul>
|
||||
*/
|
||||
public final class VertexFormats {
|
||||
|
||||
private VertexFormats() {}
|
||||
|
||||
public static final int VANILLA_SIZE = 28;
|
||||
public static final int COMPACT_SIZE = 16;
|
||||
|
||||
/** Compact positions: steps a block, and the offset that makes -8 the first. */
|
||||
public static final float COMPACT_POSITION_SCALE = 2048.0F;
|
||||
|
||||
public static final float COMPACT_POSITION_OFFSET = 8.0F;
|
||||
/** Compact texture coordinates: steps across the atlas. */
|
||||
public static final float COMPACT_UV_SCALE = 32768.0F;
|
||||
|
||||
public static int size(int format) {
|
||||
return format == Snapshot.FORMAT_COMPACT ? COMPACT_SIZE : VANILLA_SIZE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes one vertex.
|
||||
*
|
||||
* @param color ARGB
|
||||
* @param light packed light coordinates: block in the low 16 bits, sky in the high 16
|
||||
*/
|
||||
static void put(int format, Bytes.Out out, float x, float y, float z, int color, float u, float v, int light) {
|
||||
int abgr = (color & 0xFF00FF00) | (color & 0xFF0000) >> 16 | (color & 0xFF) << 16;
|
||||
byte[] data;
|
||||
if (format == Snapshot.FORMAT_COMPACT) {
|
||||
int at = out.reserve(COMPACT_SIZE);
|
||||
data = out.array();
|
||||
Bytes.putShortAt(data, at, quantize((x + COMPACT_POSITION_OFFSET) * COMPACT_POSITION_SCALE));
|
||||
Bytes.putShortAt(data, at + 2, quantize((y + COMPACT_POSITION_OFFSET) * COMPACT_POSITION_SCALE));
|
||||
Bytes.putShortAt(data, at + 4, quantize((z + COMPACT_POSITION_OFFSET) * COMPACT_POSITION_SCALE));
|
||||
data[at + 6] = (byte) Math.min(light & 0xFFFF, 255);
|
||||
data[at + 7] = (byte) Math.min(light >>> 16, 255);
|
||||
Bytes.putIntAt(data, at + 8, abgr);
|
||||
Bytes.putShortAt(data, at + 12, quantize(u * COMPACT_UV_SCALE));
|
||||
Bytes.putShortAt(data, at + 14, quantize(v * COMPACT_UV_SCALE));
|
||||
} else {
|
||||
int at = out.reserve(VANILLA_SIZE);
|
||||
data = out.array();
|
||||
Bytes.putFloatAt(data, at, x);
|
||||
Bytes.putFloatAt(data, at + 4, y);
|
||||
Bytes.putFloatAt(data, at + 8, z);
|
||||
Bytes.putIntAt(data, at + 12, abgr);
|
||||
Bytes.putFloatAt(data, at + 16, u);
|
||||
Bytes.putFloatAt(data, at + 20, v);
|
||||
Bytes.putIntAt(data, at + 24, light);
|
||||
}
|
||||
}
|
||||
|
||||
/** Rounds to the nearest unsigned short, clamped to its range. */
|
||||
private static int quantize(float value) {
|
||||
int rounded = Math.round(value);
|
||||
return rounded < 0 ? 0 : Math.min(rounded, 0xFFFF);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package incari.mesher;
|
||||
|
||||
/**
|
||||
* Which faces of a section can see each other through it, for the game's occlusion graph: a flood
|
||||
* fill of the section's open blocks from its edges, each connected region joining the faces it
|
||||
* touches. A section with little in it counts as open everywhere; a full one as closed.
|
||||
*
|
||||
* <p>Blocks are numbered as the game's visibility graph numbers them: x, then z, then y.
|
||||
*/
|
||||
final class Visibility {
|
||||
|
||||
private final boolean[] closed = new boolean[4096];
|
||||
private final int[] queue = new int[4096];
|
||||
private int opaque;
|
||||
|
||||
void clear() {
|
||||
java.util.Arrays.fill(closed, false);
|
||||
opaque = 0;
|
||||
}
|
||||
|
||||
void setOpaque(int blockIndex) {
|
||||
closed[blockIndex] = true;
|
||||
opaque++;
|
||||
}
|
||||
|
||||
/** The visibility bits: bit {@code a + 6 * b} for faces a and b, both ways. */
|
||||
long resolve() {
|
||||
if (opaque < 256) {
|
||||
return (1L << 36) - 1;
|
||||
}
|
||||
if (opaque == 4096) {
|
||||
return 0L;
|
||||
}
|
||||
long visible = 0L;
|
||||
for (int y = 0; y < 16; y++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
if (x != 0 && x != 15 && y != 0 && y != 15 && z != 0 && z != 15) {
|
||||
continue;
|
||||
}
|
||||
int start = Snapshot.blockIndex(x, y, z);
|
||||
if (!closed[start]) {
|
||||
int faces = fill(start);
|
||||
for (int a = 0; a < 6; a++) {
|
||||
if ((faces & 1 << a) != 0) {
|
||||
for (int b = 0; b < 6; b++) {
|
||||
if ((faces & 1 << b) != 0) {
|
||||
visible |= 1L << (a + 6 * b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return visible;
|
||||
}
|
||||
|
||||
/** Fills the open region from {@code start}; returns the faces it touches, a bit per direction. */
|
||||
private int fill(int start) {
|
||||
int head = 0;
|
||||
int tail = 0;
|
||||
queue[tail++] = start;
|
||||
closed[start] = true;
|
||||
int faces = 0;
|
||||
while (head < tail) {
|
||||
int index = queue[head++];
|
||||
int x = index & 15;
|
||||
int z = index >> 4 & 15;
|
||||
int y = index >> 8 & 15;
|
||||
if (x == 0) {
|
||||
faces |= 1 << Dirs.WEST;
|
||||
} else if (x == 15) {
|
||||
faces |= 1 << Dirs.EAST;
|
||||
}
|
||||
if (y == 0) {
|
||||
faces |= 1 << Dirs.DOWN;
|
||||
} else if (y == 15) {
|
||||
faces |= 1 << Dirs.UP;
|
||||
}
|
||||
if (z == 0) {
|
||||
faces |= 1 << Dirs.NORTH;
|
||||
} else if (z == 15) {
|
||||
faces |= 1 << Dirs.SOUTH;
|
||||
}
|
||||
if (y > 0) {
|
||||
tail = visit(index - 256, tail);
|
||||
}
|
||||
if (y < 15) {
|
||||
tail = visit(index + 256, tail);
|
||||
}
|
||||
if (z > 0) {
|
||||
tail = visit(index - 16, tail);
|
||||
}
|
||||
if (z < 15) {
|
||||
tail = visit(index + 16, tail);
|
||||
}
|
||||
if (x > 0) {
|
||||
tail = visit(index - 1, tail);
|
||||
}
|
||||
if (x < 15) {
|
||||
tail = visit(index + 1, tail);
|
||||
}
|
||||
}
|
||||
return faces;
|
||||
}
|
||||
|
||||
private int visit(int index, int tail) {
|
||||
if (!closed[index]) {
|
||||
closed[index] = true;
|
||||
queue[tail++] = index;
|
||||
}
|
||||
return tail;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* The terrain mesher (ADR 0023). Worker-side: no game objects, only the flat formats defined
|
||||
* here ({@link incari.mesher.MeshTables}, {@link incari.mesher.Snapshot}, {@link
|
||||
* incari.mesher.MeshResult}).
|
||||
*/
|
||||
@NullMarked
|
||||
package incari.mesher;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -0,0 +1,23 @@
|
||||
package incari.mesher;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
|
||||
import com.tngtech.archunit.core.importer.ImportOption;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
|
||||
/**
|
||||
* The mesher is compiled alone into the page's worker module: it may use only the JDK's basics and
|
||||
* JSpecify. No game, library or platform types.
|
||||
*/
|
||||
@AnalyzeClasses(packages = "incari.mesher", importOptions = ImportOption.DoNotIncludeTests.class)
|
||||
class BoundaryTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule onlyJdkAndJspecify = classes()
|
||||
.should()
|
||||
.onlyDependOnClassesThat()
|
||||
.resideInAnyPackage("java.lang..", "java.util", "org.jspecify..", "incari.mesher..")
|
||||
.allowEmptyShould(true);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package incari.mesher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The mesher's copies of the game's arithmetic. The game itself checks them against its own
|
||||
* before meshing; here, what can be checked without it.
|
||||
*/
|
||||
class GameMathTest {
|
||||
|
||||
@Test
|
||||
void theRandomIsJavasGenerator() {
|
||||
java.util.Random reference = new java.util.Random();
|
||||
GameMath.Random ours = new GameMath.Random();
|
||||
for (long seed = -500; seed < 500; seed += 7) {
|
||||
reference.setSeed(seed * 0x9E3779B97F4A7C15L);
|
||||
ours.setSeed(seed * 0x9E3779B97F4A7C15L);
|
||||
for (int bound : new int[] {1, 2, 3, 7, 16, 64, 100, 1 << 20, 1_000_003}) {
|
||||
assertThat(ours.nextInt(bound)).isEqualTo(reference.nextInt(bound));
|
||||
}
|
||||
assertThat(ours.nextLong()).isEqualTo(reference.nextLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSineIsATableOfSixtyFiveThousandSteps() {
|
||||
assertThat(GameMath.sin(0.0)).isEqualTo(0.0F);
|
||||
assertThat(GameMath.cos(0.0)).isEqualTo(1.0F);
|
||||
assertThat(GameMath.sin(Math.PI / 2)).isEqualTo(1.0F);
|
||||
// Within a step of the true value everywhere.
|
||||
for (double a = -10.0; a < 10.0; a += 0.01) {
|
||||
assertThat((double) GameMath.sin(a)).isCloseTo(Math.sin(a), org.assertj.core.data.Offset.offset(2e-4));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theArctangentIsCloseToTheTrueOne() {
|
||||
for (double y = -1.0; y <= 1.0; y += 0.05) {
|
||||
for (double x = -1.0; x <= 1.0; x += 0.05) {
|
||||
if (Math.abs(x) + Math.abs(y) > 1e-6) {
|
||||
assertThat(GameMath.atan2(y, x))
|
||||
.isCloseTo(Math.atan2(y, x), org.assertj.core.data.Offset.offset(1e-5));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void positionSeedsDifferByPosition() {
|
||||
assertThat(GameMath.positionSeed(0, 0, 0)).isZero();
|
||||
assertThat(GameMath.positionSeed(1, 0, 0)).isNotEqualTo(GameMath.positionSeed(0, 0, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
package incari.mesher;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The mesher on hand-made tables: what it writes for a lone cube, how faces between cubes are
|
||||
* culled, and that its formats survive the trip to a worker and back. Its agreement with the game's
|
||||
* own compiler is checked against the game itself ({@code ./gradlew :app-desktop:smokeMesher}).
|
||||
*/
|
||||
class SectionMesherTest {
|
||||
|
||||
private static final int AIR = 0;
|
||||
private static final int STONE = 1;
|
||||
private static final int GLASS = 2;
|
||||
private static final int SHEET = 3;
|
||||
|
||||
/**
|
||||
* Four states: air, a stone cube (culls against anything full), a glass cube (translucent), and
|
||||
* a translucent sheet: only a cube's top and bottom, as a still water surface seen both ways.
|
||||
*/
|
||||
private static MeshTables tables(boolean ambientOcclusion) {
|
||||
MeshTables.Builder b = new MeshTables.Builder(4, ambientOcclusion);
|
||||
b.state(AIR, StateFlags.AIR | StateFlags.LIGHT_PERMEABLE, 0, 1.0F);
|
||||
int[][] stoneFaces = new int[7][];
|
||||
int[][] glassFaces = new int[7][];
|
||||
int[][] sheetFaces = new int[7][];
|
||||
for (int d = 0; d < 6; d++) {
|
||||
stoneFaces[d] = new int[] {b.quad(face(d), uvs(), d, MeshTables.LAYER_SOLID, -1, -1, 0)};
|
||||
glassFaces[d] = new int[] {b.quad(face(d), uvs(), d, MeshTables.LAYER_TRANSLUCENT, -1, -1, 0)};
|
||||
sheetFaces[d] = d == Dirs.DOWN || d == Dirs.UP
|
||||
? new int[] {b.quad(face(d), uvs(), d, MeshTables.LAYER_TRANSLUCENT, -1, -1, 0)}
|
||||
: new int[0];
|
||||
}
|
||||
stoneFaces[6] = new int[0];
|
||||
glassFaces[6] = new int[0];
|
||||
sheetFaces[6] = new int[0];
|
||||
int stoneNode = b.singleNode(b.part(stoneFaces, true));
|
||||
int glassNode = b.singleNode(b.part(glassFaces, true));
|
||||
int sheetNode = b.singleNode(b.part(sheetFaces, true));
|
||||
b.state(STONE, StateFlags.MODEL | StateFlags.SOLID_RENDER | StateFlags.COLLISION_FULL, 0, 0.2F);
|
||||
b.model(STONE, stoneNode);
|
||||
b.state(GLASS, StateFlags.MODEL | StateFlags.LIGHT_PERMEABLE | StateFlags.COLLISION_FULL, 0, 1.0F);
|
||||
b.model(GLASS, glassNode);
|
||||
b.state(SHEET, StateFlags.MODEL | StateFlags.LIGHT_PERMEABLE, 0, 1.0F);
|
||||
b.model(SHEET, sheetNode);
|
||||
for (int d = 0; d < 6; d++) {
|
||||
b.faceShape(STONE, d, MeshTables.SHAPE_FULL);
|
||||
}
|
||||
b.faceShapes(2, (x, y) -> y == MeshTables.SHAPE_FULL);
|
||||
return b.build();
|
||||
}
|
||||
|
||||
/** A unit cube's face toward direction d, corners in the order the game's model baker uses. */
|
||||
private static float[] face(int d) {
|
||||
float[][] corners =
|
||||
switch (d) {
|
||||
case Dirs.DOWN -> new float[][] {{0, 0, 1}, {0, 0, 0}, {1, 0, 0}, {1, 0, 1}};
|
||||
case Dirs.UP -> new float[][] {{0, 1, 0}, {0, 1, 1}, {1, 1, 1}, {1, 1, 0}};
|
||||
case Dirs.NORTH -> new float[][] {{1, 1, 0}, {1, 0, 0}, {0, 0, 0}, {0, 1, 0}};
|
||||
case Dirs.SOUTH -> new float[][] {{0, 1, 1}, {0, 0, 1}, {1, 0, 1}, {1, 1, 1}};
|
||||
case Dirs.WEST -> new float[][] {{0, 1, 0}, {0, 0, 0}, {0, 0, 1}, {0, 1, 1}};
|
||||
default -> new float[][] {{1, 1, 1}, {1, 0, 1}, {1, 0, 0}, {1, 1, 0}};
|
||||
};
|
||||
float[] positions = new float[12];
|
||||
for (int v = 0; v < 4; v++) {
|
||||
System.arraycopy(corners[v], 0, positions, v * 3, 3);
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
|
||||
private static float[] uvs() {
|
||||
return new float[] {0, 0, 0, 0.0625F, 0.0625F, 0.0625F, 0.0625F, 0};
|
||||
}
|
||||
|
||||
private static Snapshot snapshot(int... blocks) {
|
||||
Snapshot s = new Snapshot();
|
||||
for (int i = 0; i < 6; i++) {
|
||||
s.cardinalLighting[i] = new float[] {0.5F, 1.0F, 0.8F, 0.8F, 0.6F, 0.6F}[i];
|
||||
}
|
||||
// Full sky light everywhere.
|
||||
java.util.Arrays.fill(s.light, (byte) 0xF0);
|
||||
for (int i = 0; i < blocks.length; i += 4) {
|
||||
s.states[Snapshot.index(blocks[i], blocks[i + 1], blocks[i + 2])] = (char) blocks[i + 3];
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoneCubeHasSixLitFaces() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
MeshResult result = new MeshResult();
|
||||
assertThat(mesher.mesh(snapshot(5, 5, 5, STONE), result)).isTrue();
|
||||
|
||||
assertThat(result.vertexCount(MeshTables.LAYER_SOLID)).isEqualTo(24);
|
||||
ByteBuffer vertices =
|
||||
ByteBuffer.wrap(result.vertexBytes(MeshTables.LAYER_SOLID)).order(ByteOrder.LITTLE_ENDIAN);
|
||||
// The down face first: its first corner at (5, 5, 6), shaded half, lit by the sky.
|
||||
assertThat(vertices.getFloat(0)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(4)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(8)).isEqualTo(6.0F);
|
||||
assertThat(vertices.getInt(12)).isEqualTo(0xFF7F7F7F);
|
||||
assertThat(vertices.getShort(26) & 0xFFFF).isEqualTo(240);
|
||||
// Then up, at full brightness.
|
||||
assertThat(vertices.getInt(4 * 28 + 12)).isEqualTo(0xFFFFFFFF);
|
||||
}
|
||||
|
||||
@Test
|
||||
void facesBetweenCubesAreCulled() {
|
||||
SectionMesher mesher = new SectionMesher(tables(true));
|
||||
MeshResult result = new MeshResult();
|
||||
mesher.mesh(snapshot(5, 5, 5, STONE, 6, 5, 5, STONE), result);
|
||||
assertThat(result.vertexCount(MeshTables.LAYER_SOLID)).isEqualTo(4 * 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
void translucentQuadsAreSortedFarthestFirst() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
MeshResult result = new MeshResult();
|
||||
Snapshot s = snapshot(1, 1, 1, GLASS, 10, 1, 1, GLASS);
|
||||
s.cameraX = 0.0F;
|
||||
s.cameraY = 1.5F;
|
||||
s.cameraZ = 1.5F;
|
||||
mesher.mesh(s, result);
|
||||
assertThat(result.translucentQuadCount()).isEqualTo(12);
|
||||
ByteBuffer indices = ByteBuffer.wrap(result.sortedIndexBytes()).order(ByteOrder.LITTLE_ENDIAN);
|
||||
// The first quad drawn belongs to the far cube (its vertices come after the near one's 24).
|
||||
assertThat(indices.getShort(0) & 0xFFFF).isGreaterThanOrEqualTo(24);
|
||||
assertThat(indices.getShort((12 - 1) * 12) & 0xFFFF).isLessThan(24);
|
||||
}
|
||||
|
||||
@Test
|
||||
void quadsAcrossOneAxisKeepAnOrderThatHoldsFromEveryCamera() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
MeshResult result = new MeshResult();
|
||||
// Two sheets in a column: tops at y 2 and 4, bottoms at y 1 and 3.
|
||||
Snapshot s = snapshot(1, 1, 1, SHEET, 1, 3, 1, SHEET);
|
||||
s.fixedOrder = true;
|
||||
s.cameraX = 8.0F;
|
||||
s.cameraY = 2.5F;
|
||||
s.cameraZ = 8.0F;
|
||||
mesher.mesh(s, result);
|
||||
assertThat(result.fixedOrder()).isTrue();
|
||||
// Quads facing down by their plane falling, quads facing up by their plane rising, wherever
|
||||
// the camera is: from y 2.5 it sees the bottom at 3 and the top at 2, drawn farthest first.
|
||||
assertThat(quadPlanesY(result)).containsExactly(3.0F, 1.0F, 2.0F, 4.0F);
|
||||
|
||||
s.cameraY = 30.0F;
|
||||
mesher.mesh(s, result);
|
||||
assertThat(quadPlanesY(result)).containsExactly(3.0F, 1.0F, 2.0F, 4.0F);
|
||||
}
|
||||
|
||||
@Test
|
||||
void quadsAcrossSeveralAxesOrWithoutTheSwitchAreSortedFromTheCamera() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
MeshResult result = new MeshResult();
|
||||
Snapshot s = snapshot(1, 1, 1, SHEET, 5, 1, 1, GLASS);
|
||||
s.fixedOrder = true;
|
||||
mesher.mesh(s, result);
|
||||
assertThat(result.fixedOrder()).isFalse();
|
||||
|
||||
s = snapshot(1, 1, 1, SHEET, 1, 3, 1, SHEET);
|
||||
s.cameraY = 30.0F;
|
||||
mesher.mesh(s, result);
|
||||
assertThat(result.fixedOrder()).isFalse();
|
||||
// Sorted by centers from above: the lowest first.
|
||||
assertThat(quadPlanesY(result)).containsExactly(1.0F, 2.0F, 3.0F, 4.0F);
|
||||
}
|
||||
|
||||
/** Each translucent quad's y, in the order the sorted indices draw them (the vanilla format). */
|
||||
private static float[] quadPlanesY(MeshResult result) {
|
||||
ByteBuffer indices = ByteBuffer.wrap(result.sortedIndexBytes()).order(ByteOrder.LITTLE_ENDIAN);
|
||||
ByteBuffer vertices = ByteBuffer.wrap(result.vertexBytes(MeshTables.LAYER_TRANSLUCENT))
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
int vertexSize =
|
||||
result.vertexByteCount(MeshTables.LAYER_TRANSLUCENT) / result.vertexCount(MeshTables.LAYER_TRANSLUCENT);
|
||||
float[] planes = new float[result.translucentQuadCount()];
|
||||
for (int q = 0; q < planes.length; q++) {
|
||||
int first = indices.getShort(q * 12) & 0xFFFF;
|
||||
planes[q] = vertices.getFloat(first * vertexSize + 4);
|
||||
}
|
||||
return planes;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptySectionIsOpenEverywhere() {
|
||||
SectionMesher mesher = new SectionMesher(tables(true));
|
||||
MeshResult result = new MeshResult();
|
||||
mesher.mesh(snapshot(), result);
|
||||
assertThat(result.isEmpty()).isTrue();
|
||||
assertThat(result.visibility).isEqualTo((1L << 36) - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFullSectionIsClosed() {
|
||||
int[] blocks = new int[4096 * 4];
|
||||
int i = 0;
|
||||
for (int y = 0; y < 16; y++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
blocks[i++] = x;
|
||||
blocks[i++] = y;
|
||||
blocks[i++] = z;
|
||||
blocks[i++] = STONE;
|
||||
}
|
||||
}
|
||||
}
|
||||
MeshResult result = new MeshResult();
|
||||
new SectionMesher(tables(true)).mesh(snapshot(blocks), result);
|
||||
assertThat(result.visibility).isZero();
|
||||
// Only the faces toward the air around the section show.
|
||||
assertThat(result.vertexCount(MeshTables.LAYER_SOLID)).isEqualTo(6 * 256 * 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFormatsSurviveTheTripToAWorker() {
|
||||
MeshTables tables = tables(true);
|
||||
Bytes.Out encodedTables = new Bytes.Out(1024);
|
||||
tables.encode(encodedTables);
|
||||
Snapshot s = snapshot(3, 4, 5, STONE, 3, 5, 5, GLASS);
|
||||
s.addTint(Snapshot.blockIndex(3, 4, 5), new int[] {0xFF123456}, 1, false, -1);
|
||||
s.addDynamic(Snapshot.index(0, 0, 0), true, 0b101, 0.2F);
|
||||
Bytes.Out encodedSnapshot = new Bytes.Out(1024);
|
||||
encodedSnapshot.putInt(MeshJobs.MESH);
|
||||
s.encode(encodedSnapshot);
|
||||
|
||||
MeshJobs worker = new MeshJobs();
|
||||
Bytes.Out tablesMessage = new Bytes.Out(1024);
|
||||
tablesMessage.putInt(MeshJobs.TABLES);
|
||||
tablesMessage.putBytes(encodedTables.array(), 0, encodedTables.size());
|
||||
assertThat(worker.handle(tablesMessage.array(), 0, tablesMessage.size()))
|
||||
.isNull();
|
||||
Bytes.Out reply = worker.handle(encodedSnapshot.array(), 0, encodedSnapshot.size());
|
||||
assertThat(reply).isNotNull();
|
||||
Bytes.In in = new Bytes.In(reply.array(), 0, reply.size());
|
||||
assertThat(in.getInt()).isEqualTo(MeshJobs.OK);
|
||||
MeshResult remote = new MeshResult();
|
||||
remote.decode(in);
|
||||
|
||||
MeshResult local = new MeshResult();
|
||||
new SectionMesher(MeshTables.decode(new Bytes.In(encodedTables.array(), 0, encodedTables.size())))
|
||||
.mesh(s, local);
|
||||
for (int layer = 0; layer < MeshTables.LAYER_COUNT; layer++) {
|
||||
assertThat(remote.vertexCount(layer)).isEqualTo(local.vertexCount(layer));
|
||||
assertThat(java.util.Arrays.copyOf(remote.vertexBytes(layer), remote.vertexByteCount(layer)))
|
||||
.isEqualTo(java.util.Arrays.copyOf(local.vertexBytes(layer), local.vertexByteCount(layer)));
|
||||
}
|
||||
assertThat(remote.visibility).isEqualTo(local.visibility);
|
||||
assertThat(remote.translucentQuadCount()).isEqualTo(local.translucentQuadCount());
|
||||
for (int layer = 0; layer < MeshTables.LAYER_COUNT; layer++) {
|
||||
for (int run = 0; run < Facings.COUNT; run++) {
|
||||
assertThat(remote.facingRun(layer, run)).isEqualTo(local.facingRun(layer, run));
|
||||
}
|
||||
}
|
||||
assertThat(remote.animatedSprites()).isEqualTo(local.animatedSprites());
|
||||
}
|
||||
|
||||
@Test
|
||||
void solidQuadsAreGroupedByFacingInTheOrderWritten() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
MeshResult result = new MeshResult();
|
||||
// Two cubes side by side along x: each writes its faces down, up, north, south, then its
|
||||
// free side, so the first cube's faces come before the second's within each facing.
|
||||
mesher.mesh(snapshot(5, 5, 5, STONE, 6, 5, 5, STONE), result);
|
||||
|
||||
int[] runs = new int[Facings.COUNT];
|
||||
for (int run = 0; run < Facings.COUNT; run++) {
|
||||
runs[run] = result.facingRun(MeshTables.LAYER_SOLID, run);
|
||||
}
|
||||
assertThat(runs).containsExactly(0, 2, 2, 2, 2, 1, 1);
|
||||
ByteBuffer vertices =
|
||||
ByteBuffer.wrap(result.vertexBytes(MeshTables.LAYER_SOLID)).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int quad = 4 * 28;
|
||||
// Both down faces first (at y 5, the first cube's at x 5 to 6, then the second's)...
|
||||
assertThat(vertices.getFloat(4)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(quad + 4)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(0)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(quad)).isEqualTo(6.0F);
|
||||
// ...and the west face (the first cube's, at x 5) just before the east one (at x 7).
|
||||
assertThat(vertices.getFloat(8 * quad)).isEqualTo(5.0F);
|
||||
assertThat(vertices.getFloat(9 * quad)).isEqualTo(7.0F);
|
||||
// The translucent layer is never regrouped: it's sorted.
|
||||
assertThat(result.facingRun(MeshTables.LAYER_TRANSLUCENT, 0)).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sectionsNoteTheAnimatedSpritesTheyDraw() {
|
||||
MeshTables.Builder b = new MeshTables.Builder(2, false);
|
||||
b.state(AIR, StateFlags.AIR | StateFlags.LIGHT_PERMEABLE, 0, 1.0F);
|
||||
int[][] faces = new int[7][];
|
||||
for (int d = 0; d < 6; d++) {
|
||||
int quad = b.quad(face(d), uvs(), d, MeshTables.LAYER_SOLID, -1, -1, 0);
|
||||
b.animatedQuad(quad, 70);
|
||||
faces[d] = new int[] {quad};
|
||||
}
|
||||
faces[6] = new int[0];
|
||||
b.state(STONE, StateFlags.MODEL | StateFlags.SOLID_RENDER | StateFlags.COLLISION_FULL, 0, 1.0F);
|
||||
b.model(STONE, b.singleNode(b.part(faces, false)));
|
||||
MeshTables tables = b.build();
|
||||
MeshResult result = new MeshResult();
|
||||
|
||||
new SectionMesher(tables).mesh(snapshot(), result);
|
||||
assertThat(result.animatedSprites()[1]).isZero();
|
||||
new SectionMesher(tables).mesh(snapshot(1, 2, 3, STONE), result);
|
||||
assertThat(result.animatedSprites()[1]).isEqualTo(1L << 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void facingsComeFromTheCornersAndTheirWinding() {
|
||||
int[] expected = {Dirs.DOWN, Dirs.UP, Dirs.NORTH, Dirs.SOUTH, Dirs.WEST, Dirs.EAST};
|
||||
for (int d = 0; d < 6; d++) {
|
||||
float[] p = face(d);
|
||||
assertThat(facing(p)).as("direction %d", d).isEqualTo(expected[d]);
|
||||
// Wound the other way, the same quad faces the other way (as fluids' back faces are).
|
||||
float[] reversed = {p[0], p[1], p[2], p[9], p[10], p[11], p[6], p[7], p[8], p[3], p[4], p[5]};
|
||||
assertThat(facing(reversed)).isEqualTo(Dirs.opposite(expected[d]));
|
||||
}
|
||||
// A crossed plant's diagonal quad, a degenerate one, and a face far outside the section.
|
||||
assertThat(facing(new float[] {0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0})).isEqualTo(Facings.UNASSIGNED);
|
||||
assertThat(facing(new float[] {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0})).isEqualTo(Facings.UNASSIGNED);
|
||||
float[] far = face(Dirs.UP);
|
||||
for (int v = 0; v < 4; v++) {
|
||||
far[v * 3 + 1] = 20.0F;
|
||||
}
|
||||
assertThat(facing(far)).isEqualTo(Facings.UNASSIGNED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCameraSeesFacesTowardItAndNoneFacingAwayFromAFarSection() {
|
||||
// Well above and east of the section: the up and east faces, not down or west.
|
||||
int bits = Facings.visible(30.0F, 40.0F, 8.0F);
|
||||
assertThat(bits & 1 << Dirs.UP).isNotZero();
|
||||
assertThat(bits & 1 << Dirs.DOWN).isZero();
|
||||
assertThat(bits & 1 << Dirs.EAST).isNotZero();
|
||||
assertThat(bits & 1 << Dirs.WEST).isZero();
|
||||
assertThat(bits & 1 << Dirs.NORTH).isNotZero();
|
||||
assertThat(bits & 1 << Dirs.SOUTH).isNotZero();
|
||||
assertThat(bits & 1 << Facings.UNASSIGNED).isNotZero();
|
||||
// Close to the section's top: a face just above it could still be seen from below.
|
||||
assertThat(Facings.visible(8.0F, 18.5F, 8.0F) & 1 << Dirs.DOWN).isNotZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void visibleRunsNextToEachOtherAreOneRange() {
|
||||
// Runs: 3 unassigned, 2 down, 4 up, none north, 5 south, 1 west, 6 east.
|
||||
int[] runs = {9, 9, 3, 2, 4, 0, 5, 1, 6};
|
||||
int[] ranges = new int[2 * Facings.COUNT];
|
||||
// From above, north-east of the section: unassigned, up, south (none north... so up and
|
||||
// south touch), east; not down or west.
|
||||
int seen = 1 << Facings.UNASSIGNED | 1 << Dirs.UP | 1 << Dirs.SOUTH | 1 << Dirs.EAST;
|
||||
int count = Facings.visibleRanges(runs, 2, seen, ranges);
|
||||
assertThat(java.util.Arrays.copyOf(ranges, count * 2)).containsExactly(0, 3, 5, 9, 15, 6);
|
||||
// Everything seen: one range of all of them.
|
||||
assertThat(Facings.visibleRanges(runs, 2, 0x7F, ranges)).isEqualTo(1);
|
||||
assertThat(ranges[0]).isZero();
|
||||
assertThat(ranges[1]).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bakedQuadsGoIntoTheCutoutLayerAsTheyAre() {
|
||||
Snapshot s = snapshot(1, 1, 1, STONE);
|
||||
float[] positions = face(Dirs.UP);
|
||||
for (int v = 0; v < 4; v++) {
|
||||
positions[v * 3] += 4.0F;
|
||||
}
|
||||
s.addBakedQuad(positions, uvs(), new int[] {0xFF666666, 0xFF666666, 0xFF999999, 0xFF999999}, 0xF000A0);
|
||||
Bytes.Out encoded = new Bytes.Out(1024);
|
||||
s.encode(encoded);
|
||||
Snapshot decoded = new Snapshot();
|
||||
decoded.decode(new Bytes.In(encoded.array(), 0, encoded.size()));
|
||||
assertThat(decoded.bakedCount()).isEqualTo(1);
|
||||
|
||||
MeshResult result = new MeshResult();
|
||||
new SectionMesher(tables(false)).mesh(decoded, result);
|
||||
assertThat(result.vertexCount(MeshTables.LAYER_CUTOUT)).isEqualTo(4);
|
||||
ByteBuffer vertices =
|
||||
ByteBuffer.wrap(result.vertexBytes(MeshTables.LAYER_CUTOUT)).order(ByteOrder.LITTLE_ENDIAN);
|
||||
assertThat(vertices.getFloat(0)).isEqualTo(4.0F);
|
||||
assertThat(vertices.getFloat(4)).isEqualTo(1.0F);
|
||||
// Colors as given (ARGB in, ABGR bytes out), the light as given.
|
||||
assertThat(vertices.getInt(12)).isEqualTo(0xFF666666);
|
||||
assertThat(vertices.getInt(2 * 28 + 12)).isEqualTo(0xFF999999);
|
||||
assertThat(vertices.getInt(24)).isEqualTo(0xF000A0);
|
||||
// It's an up face: its run is the up run.
|
||||
assertThat(result.facingRun(MeshTables.LAYER_CUTOUT, Facings.runOf(Dirs.UP)))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
private static int facing(float[] p) {
|
||||
return Facings.of(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void compactVerticesQuantizeWithinHalfAStep() {
|
||||
SectionMesher mesher = new SectionMesher(tables(false));
|
||||
Snapshot s = snapshot(15, 0, 7, STONE);
|
||||
s.vertexFormat = Snapshot.FORMAT_COMPACT;
|
||||
MeshResult result = new MeshResult();
|
||||
mesher.mesh(s, result);
|
||||
ByteBuffer vertices =
|
||||
ByteBuffer.wrap(result.vertexBytes(MeshTables.LAYER_SOLID)).order(ByteOrder.LITTLE_ENDIAN);
|
||||
assertThat(result.vertexByteCount(MeshTables.LAYER_SOLID)).isEqualTo(24 * 16);
|
||||
// The down face's first corner: (15, 0, 8).
|
||||
assertThat((vertices.getShort(0) & 0xFFFF) / 2048.0F - 8.0F).isEqualTo(15.0F);
|
||||
assertThat((vertices.getShort(2) & 0xFFFF) / 2048.0F - 8.0F).isEqualTo(0.0F);
|
||||
assertThat((vertices.getShort(4) & 0xFFFF) / 2048.0F - 8.0F).isEqualTo(8.0F);
|
||||
assertThat(vertices.get(7) & 0xFF).isEqualTo(240);
|
||||
assertThat((vertices.getShort(14) & 0xFFFF) / 32768.0F).isEqualTo(0.0F);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user