diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java index 72b3730bb..83570373a 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/MapTileEncoding.java @@ -39,13 +39,15 @@ import java.util.function.Function; * i16 ground[grid²] | padding to 4 | i16 cover[grid²] | padding to 4 | i16 raisedCounts[grid²] | padding to 4 * | i16 raisedY[raised] | padding to 4 | i16 raised[raised] | padding to 4, when the header names blocks * u8 voxelX[voxels] | padding to 4 | u8 voxelZ[voxels] | padding to 4 | i16 voxelY[voxels] | padding to 4 - * | i16 voxelBlock[voxels] | padding to 4 | u8 voxelFaces[voxels] | padding to 4, when the header counts voxels + * | i16 voxelBlock[voxels] | padding to 4 | u8 voxelFaces[voxels] | padding to 4 | u8 voxelLights[voxels] | padding to 4 + * | u16 voxelShades[shades] | padding to 4, when the header counts voxels * i16 runCounts[grid²] | padding to 4 | i16 runBottoms[runs] | padding to 4 | i16 runTops[runs] | padding to 4 - * | i16 runBlocks[runs] | padding to 4 | i16 runCovers[runs] | padding to 4 | u8 runCoverShares[runs] | padding to 4, - * when the header counts runs + * | i16 runBlocks[runs] | padding to 4 | i16 runCovers[runs] | padding to 4 | u8 runCoverShares[runs] | padding to 4 + * | u8 runLights[runs] | padding to 4 | u8 runOcclusions[runs] | padding to 4, when the header counts runs * * {@code raised} is the sum of the raised counts, which the header also holds, as it holds {@code voxels}, the count of * blocks seen from the open air, and {@code runs}, the sum of the run counts, each -1 for a tile without them. + * {@code shades} is the count of faces the voxel faces name, one a set bit. * The header holds the size, the scale, the subject kind, the labels the grids index, and the blocks the ground and * cover grids index when the tile carries the tops of its columns, each as the state players see. Every array starts on a * multiple of 4 bytes, so the studio views them in place. @@ -79,8 +81,8 @@ final class MapTileEncoding { + (hasHeights ? cells * Float.BYTES : 0) + (hasPickNoise ? cells * Float.BYTES : 0) + (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2) - + (voxels == null ? 0 : aligned(voxelCount) * 3 + aligned(voxelCount * Short.BYTES) * 2) - + (runs == null ? 0 : aligned(cells * Short.BYTES) + aligned(runCount * Short.BYTES) * 4 + aligned(runCount)); + + (voxels == null ? 0 : aligned(voxelCount) * 4 + aligned(voxelCount * Short.BYTES) * 2 + aligned(voxels.shades().length * Short.BYTES)) + + (runs == null ? 0 : aligned(cells * Short.BYTES) + aligned(runCount * Short.BYTES) * 4 + aligned(runCount) * 3); ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(header.length).put(header); align(buffer); @@ -107,6 +109,8 @@ final class MapTileEncoding { putShorts(buffer, voxels.y()); putShorts(buffer, voxels.blocks()); putBytes(buffer, voxels.faces()); + putBytes(buffer, voxels.lights()); + putShorts(buffer, voxels.shades()); } if (runs != null) { putShorts(buffer, runs.counts()); @@ -115,6 +119,8 @@ final class MapTileEncoding { putShorts(buffer, runs.blocks()); putShorts(buffer, runs.covers()); putBytes(buffer, runs.coverShares()); + putBytes(buffer, runs.lights()); + putBytes(buffer, runs.occlusions()); } return buffer.array(); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ChunkBorders.java b/core/src/main/java/art/arcane/iris/core/studio/map/ChunkBorders.java index 64c0e9127..f886ec534 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ChunkBorders.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ChunkBorders.java @@ -19,8 +19,9 @@ package art.arcane.iris.core.studio.map; import it.unimi.dsi.fastutil.booleans.BooleanArrayList; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; +import it.unimi.dsi.fastutil.bytes.ByteArrayList; +import it.unimi.dsi.fastutil.ints.Int2ByteMap; +import it.unimi.dsi.fastutil.ints.Int2ByteOpenHashMap; import it.unimi.dsi.fastutil.shorts.ShortArrayList; import java.util.ArrayList; @@ -43,9 +44,9 @@ record ChunkBorders(Wall[] walls) { private static final int ACROSS = 16; private static final int LAST = ACROSS - 1; - /** Takes a face a chunk shows on {@code side}, at its x, y and z in the chunk. */ + /** Takes a face a chunk shows on {@code side}, at its x, y and z in the chunk, lit by the cell it faces. */ interface FaceSink { - void add(int x, int y, int z, String block, int side); + void add(int x, int y, int z, String block, int side, int light); } /** @@ -69,10 +70,11 @@ record ChunkBorders(Wall[] walls) { * @param tops the cell above each run's highest * @param blocks each run's block, or null for runs of open air * @param fluid whether each run holds water + * @param light the sky's light in each run of open air, 0 to 15; 0 for others */ - record Runs(int[] firstOfPlace, short[] bottoms, short[] tops, String[] blocks, boolean[] fluid) { - // A bottom, a top, a shared key and the fluid flag. - private static final int RUN_BYTES = Short.BYTES + Short.BYTES + Integer.BYTES + 1; + record Runs(int[] firstOfPlace, short[] bottoms, short[] tops, String[] blocks, boolean[] fluid, byte[] light) { + // A bottom, a top, a shared key, the fluid flag and the light. + private static final int RUN_BYTES = Short.BYTES + Short.BYTES + Integer.BYTES + 2; int bytes() { return firstOfPlace.length * Integer.BYTES + tops.length * RUN_BYTES; @@ -102,7 +104,7 @@ record ChunkBorders(Wall[] walls) { } int top = Math.min(hidden.tops()[run], open.tops()[air]); for (int y = Math.max(hidden.bottoms()[run], open.bottoms()[air]); y < top; y++) { - faces.add(xOf(side, place), y, zOf(side, place), hidden.blocks()[run], side); + faces.add(xOf(side, place), y, zOf(side, place), hidden.blocks()[run], side, open.light()[air]); } } } @@ -112,18 +114,18 @@ record ChunkBorders(Wall[] walls) { /** * The cells along {@code side} the chunk took for closed off from the sky that touch the open air of {@code beside}, * the chunk on that side: a hollow whose only way out is across the edge, such as a pit dug under an overhang. Each - * is a place in the chunk as {@link VisibleBlocks#positions()} gives it. + * is a place in the chunk as {@link VisibleBlocks#positions()} gives it, with the light of the cell beside it. */ - IntList reachedFrom(ChunkBorders beside, int side) { + Int2ByteMap reachedFrom(ChunkBorders beside, int side) { Runs sealed = walls[side - NORTH].sealed(); Runs open = beside.walls[opposite(side) - NORTH].open(); - IntList reached = new IntArrayList(); + Int2ByteMap reached = new Int2ByteOpenHashMap(); for (int place = 0; place < ACROSS; place++) { for (int run = sealed.firstOfPlace()[place]; run < sealed.firstOfPlace()[place + 1]; run++) { for (int air = open.firstOfPlace()[place]; air < open.firstOfPlace()[place + 1]; air++) { int top = Math.min(sealed.tops()[run], open.tops()[air]); for (int y = Math.max(sealed.bottoms()[run], open.bottoms()[air]); y < top; y++) { - reached.add(VisibleBlocks.positionOf(xOf(side, place), y, zOf(side, place))); + reached.put(VisibleBlocks.positionOf(xOf(side, place), y, zOf(side, place)), open.light()[air]); } } } @@ -158,6 +160,7 @@ record ChunkBorders(Wall[] walls) { private final ShortArrayList tops = new ShortArrayList(); private final List blocks = new ArrayList<>(); private final BooleanArrayList fluid = new BooleanArrayList(); + private final ByteArrayList light = new ByteArrayList(); private int place; /** Starts the runs of the next place along the side. */ @@ -166,10 +169,10 @@ record ChunkBorders(Wall[] walls) { } /** Adds the cell at {@code y} of the current place, joining the run below where it is of the same. */ - void add(int y, String block, boolean holdsFluid) { + void add(int y, String block, boolean holdsFluid, int cellLight) { int last = tops.size() - 1; boolean joins = last >= firstOfPlace[place] && tops.getShort(last) == y && fluid.getBoolean(last) == holdsFluid - && (block == null ? blocks.get(last) == null : block.equals(blocks.get(last))); + && light.getByte(last) == cellLight && (block == null ? blocks.get(last) == null : block.equals(blocks.get(last))); if (joins) { tops.set(last, (short) (y + 1)); return; @@ -178,11 +181,13 @@ record ChunkBorders(Wall[] walls) { tops.add((short) (y + 1)); blocks.add(block); fluid.add(holdsFluid); + light.add((byte) cellLight); } Runs build() { firstOfPlace[ACROSS] = tops.size(); - return new Runs(firstOfPlace, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new), fluid.toBooleanArray()); + return new Runs(firstOfPlace, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new), fluid.toBooleanArray(), + light.toByteArray()); } } } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ChunkCells.java b/core/src/main/java/art/arcane/iris/core/studio/map/ChunkCells.java new file mode 100644 index 000000000..502e3b4d4 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ChunkCells.java @@ -0,0 +1,330 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import it.unimi.dsi.fastutil.ints.Int2ByteMap; +import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue; + +import java.util.Set; +import java.util.function.IntBinaryOperator; +import java.util.function.UnaryOperator; + +/** + * A chunk's cells as players see them, with the sky's light in each, as Minecraft lights a world: full under the open + * sky, through air without loss, one level less through each leaf or block of water and one less with each step aside. + * Beside the chunk, the terrain's height alone tells what lies there: open air above it, the sea below the fluid's height. + *

+ * A block face is shaded by the light of the cell it faces and by how many of the blocks around each of its corners are + * opaque, as Minecraft's smooth lighting darkens the corners where blocks meet. + */ +final class ChunkCells { + static final int FULL_LIGHT = 15; + /** Where a face's light lies in its shade; each corner's opaque neighbours follow in two bits each. */ + static final int LIGHT_BITS = 4; + static final int CORNER_BITS = 2; + static final int MOST_OPAQUE_AROUND_CORNER = 3; + private static final int LIGHT_MASK = (1 << LIGHT_BITS) - 1; + private static final int CORNERS = 4; + private static final int ACROSS = 16; + private static final int UP = 1; + private static final Set ALWAYS_IN_WATER = Set.of("minecraft:kelp", "minecraft:kelp_plant", "minecraft:seagrass", + "minecraft:tall_seagrass", "minecraft:bubble_column"); + private static final String LEAVES_SUFFIX = "_leaves"; + /** + * Each side's face corners as the studio draws them, a cube's corner each, in {@link VisibleBlocks#SIDES}' order: + * top left, bottom left, bottom right and top right as seen from outside. + */ + private static final int[][][] FACE_CORNERS = { + {{0, 0, 1}, {0, 0, 0}, {1, 0, 0}, {1, 0, 1}}, + {{0, 1, 0}, {0, 1, 1}, {1, 1, 1}, {1, 1, 0}}, + {{1, 1, 0}, {1, 0, 0}, {0, 0, 0}, {0, 1, 0}}, + {{0, 1, 1}, {0, 0, 1}, {1, 0, 1}, {1, 1, 1}}, + {{0, 1, 0}, {0, 0, 0}, {0, 0, 1}, {0, 1, 1}}, + {{1, 1, 1}, {1, 0, 1}, {1, 0, 0}, {1, 1, 0}} + }; + + private final Hunk chunk; + private final IntBinaryOperator terrainY; + private final int fluidHeight; + private final int height; + private final PlatformBlockState[] seen; + private final boolean[] open; + private final boolean[] fluid; + private final byte[] dimming; + private final byte[] light; + + private ChunkCells(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers) { + this.chunk = chunk; + this.terrainY = terrainY; + this.fluidHeight = fluidHeight; + this.height = chunk.getHeight(); + int cells = ACROSS * height * ACROSS; + this.seen = new PlatformBlockState[cells]; + this.open = new boolean[cells]; + this.fluid = new boolean[cells]; + this.dimming = new byte[cells]; + this.light = new byte[cells]; + for (int y = 0; y < height; y++) { + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + PlatformBlockState block = chunk.get(x, y, z); + int cell = cellOf(x, y, z); + seen[cell] = block == null || block.isAir() ? null : seenByPlayers.apply(block); + open[cell] = seen[cell] == null || !seen[cell].isOccluding(); + fluid[cell] = seen[cell] != null && holdsFluid(seen[cell]); + dimming[cell] = (byte) (fluid[cell] || (seen[cell] != null && materialOf(seen[cell].key()).endsWith(LEAVES_SUFFIX)) ? 1 : 0); + } + } + } + } + + /** + * @param terrainY the terrain's top in a column by its x and z from the chunk's corner, which reaches into the + * chunks around it + * @param fluidHeight the height the sea fills to + * @param seenByPlayers the state players see in place of a block, which decides what hides what + * @param litBeside cells along the chunk's sides, as {@link VisibleBlocks#positionOf} places them, that the open + * air of the chunks beside it reaches, each with the light of the cell beside it there + */ + static ChunkCells of(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers, + Int2ByteMap litBeside) { + ChunkCells cells = new ChunkCells(chunk, terrainY, fluidHeight, seenByPlayers); + cells.spreadSkyLight(litBeside); + return cells; + } + + int height() { + return height; + } + + Hunk chunk() { + return chunk; + } + + /** The block players see in a cell of the chunk, or null for air. */ + PlatformBlockState seenAt(int x, int y, int z) { + return seen[cellOf(x, y, z)]; + } + + boolean isOpen(int x, int y, int z) { + return open[cellOf(x, y, z)]; + } + + boolean holdsFluid(int x, int y, int z) { + return fluid[cellOf(x, y, z)]; + } + + /** What lies beside the chunk, judged by the terrain's height there alone. */ + Outside outsideAt(int x, int y, int z) { + if (y >= height) { + return Outside.AIR; + } + if (y < 0 || y <= terrainY.applyAsInt(x, z)) { + return Outside.SOLID; + } + return y <= fluidHeight ? Outside.FLUID : Outside.AIR; + } + + /** The sky's light in a cell, 0 to {@link #FULL_LIGHT}, in the chunk or beside it. */ + int lightAt(int x, int y, int z) { + if (isInside(x, y, z)) { + return light[cellOf(x, y, z)]; + } + return switch (outsideAt(x, y, z)) { + case AIR -> FULL_LIGHT; + case FLUID -> Math.max(0, FULL_LIGHT - (fluidHeight - y)); + case SOLID -> 0; + }; + } + + /** The light a block shows on faces that stand inside it, such as a plant's: its own cell's, or the brightest beside a solid one. */ + int blockLightAt(int x, int y, int z) { + if (open[cellOf(x, y, z)]) { + return light[cellOf(x, y, z)]; + } + int brightest = 0; + for (int[] side : VisibleBlocks.SIDES) { + brightest = Math.max(brightest, lightAt(x + side[0], y + side[1], z + side[2])); + } + return brightest; + } + + /** + * The shade of a block's face on a side: the light of the cell it faces, then for each of its corners, in + * {@link #FACE_CORNERS}' order, how many of the three cells around the corner in front of the face are opaque, as + * Minecraft counts them; two opaque sides hide the corner between them too. + */ + short faceShade(int x, int y, int z, int side) { + int[] normal = VisibleBlocks.SIDES[side]; + int frontX = x + normal[0]; + int frontY = y + normal[1]; + int frontZ = z + normal[2]; + int shade = lightAt(frontX, frontY, frontZ); + for (int corner = 0; corner < CORNERS; corner++) { + shade |= opaqueAround(frontX, frontY, frontZ, normal, FACE_CORNERS[side][corner]) << (LIGHT_BITS + corner * CORNER_BITS); + } + return (short) shade; + } + + /** A face's shade lit by {@code light} with no corner darkened, for a face whose surroundings lie in another chunk. */ + static short plainShade(int light) { + return (short) light; + } + + static int lightOf(short shade) { + return shade & LIGHT_MASK; + } + + /** How many opaque cells the corners of a face shaded {@code shade} have together, 0 to 12. */ + static int opaqueAroundCorners(short shade) { + int opaque = 0; + for (int corner = 0; corner < CORNERS; corner++) { + opaque += (shade >> (LIGHT_BITS + corner * CORNER_BITS)) & MOST_OPAQUE_AROUND_CORNER; + } + return opaque; + } + + /** The shade of the top of the block at a cell. */ + short topShade(int x, int y, int z) { + return faceShade(x, y, z, UP); + } + + private int opaqueAround(int frontX, int frontY, int frontZ, int[] normal, int[] corner) { + int[] first = new int[3]; + int[] second = new int[3]; + int found = 0; + for (int axis = 0; axis < 3; axis++) { + if (normal[axis] != 0) { + continue; + } + int[] along = found++ == 0 ? first : second; + along[axis] = corner[axis] == 1 ? 1 : -1; + } + boolean firstOpaque = isOpaque(frontX + first[0], frontY + first[1], frontZ + first[2]); + boolean secondOpaque = isOpaque(frontX + second[0], frontY + second[1], frontZ + second[2]); + if (firstOpaque && secondOpaque) { + return MOST_OPAQUE_AROUND_CORNER; + } + boolean between = isOpaque(frontX + first[0] + second[0], frontY + first[1] + second[1], frontZ + first[2] + second[2]); + return (firstOpaque ? 1 : 0) + (secondOpaque ? 1 : 0) + (between ? 1 : 0); + } + + private boolean isOpaque(int x, int y, int z) { + return isInside(x, y, z) ? !open[cellOf(x, y, z)] : outsideAt(x, y, z) == Outside.SOLID; + } + + // Straight down from the sky in each column, then aside and on, a level less a step, as far as the light reaches. + private void spreadSkyLight(Int2ByteMap litBeside) { + IntArrayFIFOQueue lit = new IntArrayFIFOQueue(); + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + int level = FULL_LIGHT; + for (int y = height - 1; y >= 0 && open[cellOf(x, y, z)]; y--) { + level -= dimming[cellOf(x, y, z)]; + if (level <= 0) { + break; + } + light(cellOf(x, y, z), level, lit); + } + } + } + for (int y = 0; y < height; y++) { + for (int z = 0; z < ACROSS; z++) { + for (int x = 0; x < ACROSS; x++) { + if (isOnSide(x, z)) { + lightFromBeside(x, y, z, lit); + } + } + } + } + for (Int2ByteMap.Entry beside : litBeside.int2ByteEntrySet()) { + int position = beside.getIntKey(); + int cell = cellOf(position & (ACROSS - 1), position >> VisibleBlocks.POSITION_Y_SHIFT, (position >> 4) & (ACROSS - 1)); + if (open[cell]) { + light(cell, beside.getByteValue() - 1 - dimming[cell], lit); + } + } + while (!lit.isEmpty()) { + int cell = lit.dequeueInt(); + int x = cell % ACROSS; + int z = (cell / ACROSS) % ACROSS; + int y = cell / (ACROSS * ACROSS); + for (int[] side : VisibleBlocks.SIDES) { + int nx = x + side[0]; + int ny = y + side[1]; + int nz = z + side[2]; + if (isInside(nx, ny, nz) && open[cellOf(nx, ny, nz)]) { + int neighbour = cellOf(nx, ny, nz); + light(neighbour, light[cell] - 1 - dimming[neighbour], lit); + } + } + } + } + + private void lightFromBeside(int x, int y, int z, IntArrayFIFOQueue lit) { + int cell = cellOf(x, y, z); + if (!open[cell]) { + return; + } + for (int side = 2; side < VisibleBlocks.SIDES.length; side++) { + int[] step = VisibleBlocks.SIDES[side]; + if (!isInside(x + step[0], y, z + step[2])) { + light(cell, lightAt(x + step[0], y, z + step[2]) - 1 - dimming[cell], lit); + } + } + } + + private void light(int cell, int level, IntArrayFIFOQueue lit) { + if (level > light[cell]) { + light[cell] = (byte) level; + lit.enqueue(cell); + } + } + + private static boolean isOnSide(int x, int z) { + return x == 0 || z == 0 || x == ACROSS - 1 || z == ACROSS - 1; + } + + // Water around a waterlogged block, or one that only grows in water, has no side against it. + private static boolean holdsFluid(PlatformBlockState block) { + return block.isFluid() || block.isWaterLogged() || ALWAYS_IN_WATER.contains(materialOf(block.key())); + } + + private static String materialOf(String key) { + int properties = key.indexOf('['); + return properties < 0 ? key : key.substring(0, properties); + } + + boolean isInside(int x, int y, int z) { + return x >= 0 && x < ACROSS && z >= 0 && z < ACROSS && y >= 0 && y < height; + } + + static int cellOf(int x, int y, int z) { + return (y * ACROSS + z) * ACROSS + x; + } + + /** What lies beside the chunk, judged by the terrain's height there alone. */ + enum Outside { + SOLID, + FLUID, + AIR + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java index 0a3ed8d74..f9fff1f20 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnRuns.java @@ -44,10 +44,17 @@ import java.util.function.UnaryOperator; * @param blocks the key of the block most of each run's top shows * @param covers the key of the plant most often standing on each run's top, or null where none does * @param coverShares how much of each run's top its plants stand on, 0 for none to {@link #WHOLE_SHARE} for all of it + * @param lights the sky's light on each run's top, the mean of its blocks' tops in {@link #LIGHT_STEPS} of a level + * @param occlusions how many opaque cells stand around each corner of each run's top, the mean of its blocks' tops in + * {@link #OCCLUSION_STEPS} of a cell, so far ground is as dark as the near ground it stands for */ -record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares) { +record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares, byte[] lights, + byte[] occlusions) { static final int MOST_LEVEL = 4; static final int WHOLE_SHARE = 255; + static final int LIGHT_STEPS = 16; + static final int OCCLUSION_STEPS = 64; + private static final int CORNERS = 4; private static final int ACROSS = 16; private static final int SOLID_SHARE_DIVISOR = 4; @@ -64,8 +71,10 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks * @param level the areas are {@code 2^level} blocks across, 1 to {@link #MOST_LEVEL} * @param terrainY the terrain's top in a column by its x and z in the chunk * @param seenByPlayers the state players see in place of a block, which decides whether it is solid + * @param cells the chunk's cells with their light, which shade the runs' tops */ - static ColumnRuns of(Hunk chunk, int level, IntBinaryOperator terrainY, UnaryOperator seenByPlayers) { + static ColumnRuns of(Hunk chunk, int level, IntBinaryOperator terrainY, UnaryOperator seenByPlayers, + ChunkCells cells) { int areaBlocks = 1 << level; int areasAcross = ACROSS / areaBlocks; int fewestSolid = Math.max(1, areaBlocks * areaBlocks / SOLID_SHARE_DIVISOR); @@ -73,7 +82,7 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks Runs runs = new Runs(); for (int areaZ = 0; areaZ < areasAcross; areaZ++) { for (int areaX = 0; areaX < areasAcross; areaX++) { - Area area = new Area(chunk, areaX * areaBlocks, areaZ * areaBlocks, areaBlocks, seenByPlayers); + Area area = new Area(chunk, areaX * areaBlocks, areaZ * areaBlocks, areaBlocks, seenByPlayers, cells); int before = runs.found; area.addRuns(fewestSolid, area.lowestOf(terrainY), runs); counts[areaZ * areasAcross + areaX] = (short) (runs.found - before); @@ -86,7 +95,7 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks public boolean equals(Object other) { return other instanceof ColumnRuns runs && Arrays.equals(counts, runs.counts) && Arrays.equals(bottoms, runs.bottoms) && Arrays.equals(tops, runs.tops) && Arrays.equals(blocks, runs.blocks) && Arrays.equals(covers, runs.covers) - && Arrays.equals(coverShares, runs.coverShares); + && Arrays.equals(coverShares, runs.coverShares) && Arrays.equals(lights, runs.lights) && Arrays.equals(occlusions, runs.occlusions); } @Override @@ -105,6 +114,10 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks static final Cover NONE = new Cover(null, 0); } + /** How a run's top is lit, in {@link #LIGHT_STEPS} and {@link #OCCLUSION_STEPS}. */ + private record Shade(int light, int occlusion) { + } + /** The runs of every area as they are found, area after area and each area's from the top down. */ private static final class Runs { private static final int NONE = -1; @@ -113,10 +126,13 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks private final List blocks = new ArrayList<>(); private final List covers = new ArrayList<>(); private final ByteArrayList coverShares = new ByteArrayList(); + private final ByteArrayList lights = new ByteArrayList(); + private final ByteArrayList occlusions = new ByteArrayList(); private int top = NONE; private int bottom; private String block; private Cover cover; + private Shade shade; private int found; boolean isOpen() { @@ -127,11 +143,12 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks return isOpen() && shown.equals(block); } - void start(int y, String shown, Cover onTop) { + void start(int y, String shown, Cover onTop, Shade topShade) { top = y; bottom = y; block = shown; cover = onTop; + shade = topShade; } void extendTo(int y) { @@ -157,18 +174,21 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks blocks.add(block); covers.add(cover.block()); coverShares.add((byte) cover.share()); + lights.add((byte) shade.light()); + occlusions.add((byte) shade.occlusion()); found++; top = NONE; } ColumnRuns toColumnRuns(short[] counts) { return new ColumnRuns(counts, bottoms.toShortArray(), tops.toShortArray(), blocks.toArray(String[]::new), - covers.toArray(String[]::new), coverShares.toByteArray()); + covers.toArray(String[]::new), coverShares.toByteArray(), lights.toByteArray(), occlusions.toByteArray()); } } /** One square area of a chunk, read a height at a time. */ - private record Area(Hunk chunk, int minX, int minZ, int across, UnaryOperator seenByPlayers) { + private record Area(Hunk chunk, int minX, int minZ, int across, UnaryOperator seenByPlayers, + ChunkCells cells) { int lowestOf(IntBinaryOperator terrainY) { int lowest = Integer.MAX_VALUE; for (int z = minZ; z < minZ + across; z++) { @@ -192,7 +212,7 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks runs.extendTo(y); } else { runs.end(); - runs.start(y, shown, coverOn(y)); + runs.start(y, shown, coverOn(y), shadeOfTopsAt(y)); } if (y <= groundY) { runs.endAsGround(); @@ -246,6 +266,38 @@ record ColumnRuns(short[] counts, short[] bottoms, short[] tops, String[] blocks return standing == 0 ? Cover.NONE : new Cover(mostOf(plants), standing * WHOLE_SHARE / (across * across)); } + // The mean shade of the tops of the area's blocks at the height that are open above, as the near ground shows + // them; where none is, the light above the area, unshaded. + private Shade shadeOfTopsAt(int y) { + int light = 0; + int occlusion = 0; + int tops = 0; + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + if (isSolid(chunk.get(x, y, z)) && (y + 1 >= chunk.getHeight() || cells.isOpen(x, y + 1, z))) { + short shade = cells.topShade(x, y, z); + light += ChunkCells.lightOf(shade); + occlusion += ChunkCells.opaqueAroundCorners(shade); + tops++; + } + } + } + if (tops == 0) { + return new Shade(lightAbove(y) * LIGHT_STEPS, 0); + } + return new Shade(Math.round((float) light * LIGHT_STEPS / tops), Math.round((float) occlusion * OCCLUSION_STEPS / (tops * CORNERS))); + } + + private int lightAbove(int y) { + int brightest = 0; + for (int z = minZ; z < minZ + across; z++) { + for (int x = minX; x < minX + across; x++) { + brightest = Math.max(brightest, cells.lightAt(x, y + 1, z)); + } + } + return brightest; + } + private static String mostOf(Map counts) { return counts.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElseThrow(); } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java index df7a21c3b..b8f3e72b3 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/ColumnTops.java @@ -53,21 +53,25 @@ interface ColumnTops { /** * One area's runs of solid blocks, highest first, the last being the ground, with the plant most often standing on - * each run's top, or null, and how much of the top plants stand on, out of {@link ColumnRuns#WHOLE_SHARE}. + * each run's top, or null, how much of the top plants stand on, out of {@link ColumnRuns#WHOLE_SHARE}, and how the + * top is lit, as {@link ColumnRuns#lights} and {@link ColumnRuns#occlusions} give it. */ - record AreaRuns(short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares) { + record AreaRuns(short[] bottoms, short[] tops, String[] blocks, String[] covers, byte[] coverShares, byte[] lights, byte[] occlusions) { } /** - * Blocks seen in a square of columns, each with the sides that face the open air. + * Blocks seen in a square of columns, each with the sides that face the open air and how they are lit. * * @param x each block's column from the square's west edge * @param z each block's column from the square's north edge * @param y each block's height above the dimension's bottom * @param blocks each block's key * @param faces the sides of each block that face the open air, in {@link VisibleBlocks#SIDES}' order + * @param lights the light each block shows on faces that stand inside it, as {@link VisibleBlocks#lights} gives it + * @param shades the shade of each face {@link #faces} names, block after block and side after side, as + * {@link ChunkCells#faceShade} gives it */ - record TileVoxels(byte[] x, byte[] z, short[] y, String[] blocks, byte[] faces) { + record TileVoxels(byte[] x, byte[] z, short[] y, String[] blocks, byte[] faces, byte[] lights, short[] shades) { } /** diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java index f438786bb..f822fe3f2 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/GeneratedChunks.java @@ -30,9 +30,9 @@ import art.arcane.iris.util.project.hunk.Hunk; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import it.unimi.dsi.fastutil.bytes.ByteArrayList; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.ints.IntSets; +import it.unimi.dsi.fastutil.ints.Int2ByteMap; +import it.unimi.dsi.fastutil.ints.Int2ByteMaps; +import it.unimi.dsi.fastutil.ints.Int2ByteOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; @@ -78,10 +78,10 @@ final class GeneratedChunks implements ColumnTops { // blocks out to the horizon holds tens of thousands of chunks. private static final int CHUNK_TOP_BYTES = 5 * 1024; private static final int RAISED_BLOCK_BYTES = Short.BYTES + Integer.BYTES; - // Its place, a shared key and the sides it shows. - private static final int VISIBLE_BLOCK_BYTES = Integer.BYTES + Integer.BYTES + Byte.BYTES; - // Its bottom, its top and a shared key. - private static final int RUN_BYTES = Short.BYTES + Short.BYTES + Integer.BYTES; + // Its place, a shared key, the sides it shows and its light. + private static final int VISIBLE_BLOCK_BYTES = Integer.BYTES + Integer.BYTES + Byte.BYTES + Byte.BYTES; + // Its bottom, its top, a shared key and its top's light and occlusion. + private static final int RUN_BYTES = Short.BYTES + Short.BYTES + Integer.BYTES + Byte.BYTES + Byte.BYTES; private static final long MOST_BYTES_KEPT = 512L * 1024 * 1024; private static final String LEASE_NAME = "studio_block_preview"; // Half the cores, as the bridge does, so a studio filling its view leaves the server room to run. @@ -261,23 +261,30 @@ final class GeneratedChunks implements ColumnTops { if (chunk == null) { return false; } - IntSet reached = new IntOpenHashSet(); + Int2ByteMap reached = new Int2ByteOpenHashMap(); for (int side = ChunkBorders.NORTH; side <= ChunkBorders.EAST; side++) { ChunkTop beside = knownChunk(keyOf(chunkX + VisibleBlocks.SIDES[side][0], chunkZ + VisibleBlocks.SIDES[side][2])); if (beside != null) { - reached.addAll(chunk.visible().borders().reachedFrom(beside.visible().borders(), side)); + keepBrightest(reached, chunk.visible().borders().reachedFrom(beside.visible().borders(), side)); } } if (reached.isEmpty()) { return false; } - reached.addAll(chunk.reachedBeside()); + keepBrightest(reached, chunk.reachedBeside()); ChunkTop retraced = generateUnchecked(key, reached); chunks.put(key, retraced); tops.put(key, retraced); return true; } + // A cell on a chunk's corner touches two chunks beside it, and takes the brighter light. + private static void keepBrightest(Int2ByteMap into, Int2ByteMap lights) { + for (Int2ByteMap.Entry light : lights.int2ByteEntrySet()) { + into.mergeByte(light.getIntKey(), light.getByteValue(), (known, found) -> (byte) Math.max(known, found)); + } + } + // A neighbour neither the tile nor the cache holds was never generated, and the chunk's own judgement stands. private ChunkTop knownChunk(long key) { ChunkTop chunk = chunks.get(key); @@ -292,7 +299,7 @@ final class GeneratedChunks implements ColumnTops { int chunkMinX = chunkX << CHUNK_SHIFT; int chunkMinZ = chunkZ << CHUNK_SHIFT; chunk.visible().borders().facesAgainst(beside.visible().borders(), side, - (x, y, z, block, faceSide) -> voxels.add(chunkMinX + x, y, chunkMinZ + z, block, 1 << faceSide)); + (x, y, z, block, faceSide, light) -> voxels.addFace(chunkMinX + x, y, chunkMinZ + z, block, faceSide, light)); } } } @@ -316,6 +323,10 @@ final class GeneratedChunks implements ColumnTops { private final ShortArrayList y = new ShortArrayList(); private final List blocks = new ArrayList<>(); private final ByteArrayList faces = new ByteArrayList(); + private final ByteArrayList lights = new ByteArrayList(); + // Each block's face shades by side, SIDES of them a block, as a face shown later can come between. + private final ShortArrayList shadesBySide = new ShortArrayList(); + private int shownFaces; TileVoxelsBuilder(int minX, int minZ, int size) { this.minX = minX; @@ -324,36 +335,76 @@ final class GeneratedChunks implements ColumnTops { } void addVisible(VisibleBlocks visible, int chunkMinX, int chunkMinZ) { + int shade = 0; for (int at = 0; at < visible.count(); at++) { int position = visible.positions()[at]; - add(chunkMinX + (position & CHUNK_MASK), position >> VisibleBlocks.POSITION_Y_SHIFT, - chunkMinZ + ((position >> CHUNK_SHIFT) & CHUNK_MASK), visible.blocks()[at], visible.faces()[at]); + int index = indexOf(chunkMinX + (position & CHUNK_MASK), position >> VisibleBlocks.POSITION_Y_SHIFT, + chunkMinZ + ((position >> CHUNK_SHIFT) & CHUNK_MASK), visible.blocks()[at], visible.lights()[at]); + for (int side = 0; side < VisibleBlocks.SIDES.length; side++) { + if ((visible.faces()[at] & 1 << side) == 0) { + continue; + } + short faceShade = visible.shades()[shade++]; + if (index != NOT_ADDED) { + show(index, side, faceShade); + } + } } } - /** Adds a block at its place in the world with the sides it shows, or those sides to the block already there. */ - void add(int worldX, int blockY, int worldZ, String block, int sides) { + /** Adds a block's face on a side at its place in the world, lit by {@code light} with no corner darkened. */ + void addFace(int worldX, int blockY, int worldZ, String block, int side, int light) { + int at = indexOf(worldX, blockY, worldZ, block, (byte) 0); + if (at != NOT_ADDED) { + show(at, side, ChunkCells.plainShade(light)); + } + } + + // The block's index, added at its place in the world unless already there; none outside the square. + private int indexOf(int worldX, int blockY, int worldZ, String block, byte light) { int squareX = worldX - minX; int squareZ = worldZ - minZ; if (squareX < 0 || squareZ < 0 || squareX >= size || squareZ >= size) { - return; + return NOT_ADDED; } long place = ((long) blockY << Integer.SIZE) | ((long) squareZ << Short.SIZE) | squareX; int known = indexByPlace.getOrDefault(place, NOT_ADDED); if (known != NOT_ADDED) { - faces.set(known, (byte) (faces.getByte(known) | sides)); - return; + return known; } - indexByPlace.put(place, faces.size()); + int added = faces.size(); + indexByPlace.put(place, added); x.add((byte) squareX); z.add((byte) squareZ); y.add((short) blockY); blocks.add(block); - faces.add((byte) sides); + faces.add((byte) 0); + lights.add(light); + shadesBySide.size(shadesBySide.size() + VisibleBlocks.SIDES.length); + return added; + } + + private void show(int at, int side, short shade) { + byte shown = faces.getByte(at); + if ((shown & 1 << side) == 0) { + faces.set(at, (byte) (shown | 1 << side)); + shownFaces++; + } + shadesBySide.set(at * VisibleBlocks.SIDES.length + side, shade); } TileVoxels build() { - return new TileVoxels(x.toByteArray(), z.toByteArray(), y.toShortArray(), blocks.toArray(String[]::new), faces.toByteArray()); + short[] shades = new short[shownFaces]; + int shade = 0; + for (int at = 0; at < faces.size(); at++) { + for (int side = 0; side < VisibleBlocks.SIDES.length; side++) { + if ((faces.getByte(at) & 1 << side) != 0) { + shades[shade++] = shadesBySide.getShort(at * VisibleBlocks.SIDES.length + side); + } + } + } + return new TileVoxels(x.toByteArray(), z.toByteArray(), y.toShortArray(), blocks.toArray(String[]::new), faces.toByteArray(), + lights.toByteArray(), shades); } } @@ -407,7 +458,8 @@ final class GeneratedChunks implements ColumnTops { int last = first + runs.counts()[area]; return new AreaRuns(Arrays.copyOfRange(runs.bottoms(), first, last), Arrays.copyOfRange(runs.tops(), first, last), Arrays.copyOfRange(runs.blocks(), first, last), Arrays.copyOfRange(runs.covers(), first, last), - Arrays.copyOfRange(runs.coverShares(), first, last)); + Arrays.copyOfRange(runs.coverShares(), first, last), Arrays.copyOfRange(runs.lights(), first, last), + Arrays.copyOfRange(runs.occlusions(), first, last)); } private static void awaitUnlessCancelled(Future chunk, BooleanSupplier cancelled) { @@ -460,10 +512,10 @@ final class GeneratedChunks implements ColumnTops { } private ChunkTop generate(long key) throws Exception { - return generate(key, IntSets.EMPTY_SET); + return generate(key, Int2ByteMaps.EMPTY_MAP); } - private ChunkTop generateUnchecked(long key, IntSet reachedBeside) { + private ChunkTop generateUnchecked(long key, Int2ByteMap reachedBeside) { try { return generate(key, reachedBeside); } catch (Exception failed) { @@ -471,8 +523,8 @@ final class GeneratedChunks implements ColumnTops { } } - /** @param reachedBeside the cells along the chunk's sides the open air of the chunks beside it reaches */ - private ChunkTop generate(long key, IntSet reachedBeside) throws Exception { + /** @param reachedBeside the cells along the chunk's sides the open air of the chunks beside it reaches, with its light */ + private ChunkTop generate(long key, Int2ByteMap reachedBeside) throws Exception { int chunkX = (int) (key >> Integer.SIZE); int chunkZ = (int) key; int height = engine.getHeight(); @@ -484,12 +536,12 @@ final class GeneratedChunks implements ColumnTops { } IntBinaryOperator terrainY = (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true); int fluidHeight = engine.getDimension().getFluidHeight(); + ChunkCells cells = ChunkCells.of(blocks, terrainY, fluidHeight, this::seenByPlayers, reachedBeside); ColumnRuns[] runs = new ColumnRuns[ColumnRuns.MOST_LEVEL]; for (int level = 1; level <= ColumnRuns.MOST_LEVEL; level++) { - runs[level - 1] = ColumnRuns.of(blocks, level, terrainY, this::seenByPlayers); + runs[level - 1] = ColumnRuns.of(blocks, level, terrainY, this::seenByPlayers, cells); } - return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(blocks, terrainY, fluidHeight, this::seenByPlayers, reachedBeside), - runs, reachedBeside); + return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers), VisibleBlocks.of(cells, reachedBeside), runs, reachedBeside); } // A plugin's block can be solid on the server where players see grass they walk through. @@ -509,9 +561,10 @@ final class GeneratedChunks implements ColumnTops { /** * @param runs the chunk's runs of solid blocks in areas 2, 4, 8 and 16 blocks across, for coarser tiles - * @param reachedBeside the cells along its sides found reached through the chunks beside it, which it was traced from + * @param reachedBeside the cells along its sides found reached through the chunks beside it, which it was traced from, + * with the light there */ - private record ChunkTop(ColumnTop[] columns, VisibleBlocks visible, ColumnRuns[] runs, IntSet reachedBeside) { + private record ChunkTop(ColumnTop[] columns, VisibleBlocks visible, ColumnRuns[] runs, Int2ByteMap reachedBeside) { int bytes() { int raisedBlocks = 0; for (ColumnTop column : columns) { @@ -522,7 +575,7 @@ final class GeneratedChunks implements ColumnTops { runs += level.tops().length; } return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES + visible.count() * VISIBLE_BLOCK_BYTES + runs * RUN_BYTES - + visible.borders().bytes() + reachedBeside.size() * Integer.BYTES; + + visible.shades().length * Short.BYTES + visible.borders().bytes() + reachedBeside.size() * (Integer.BYTES + Byte.BYTES); } } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java index 43a2d3d21..c6a49b9d0 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTile.java @@ -64,8 +64,11 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind * @param blocks the index in the tile's block names of the block most of each run's top shows * @param covers the index of the plant most often standing on each run's top, or {@link Blocks#NO_BLOCK} * @param coverShares how much of each run's top plants stand on, 0 to 255 for all of it + * @param lights the sky's light on each run's top, in sixteenths of a level, 0 to 240 + * @param occlusions how many opaque cells stand around each corner of each run's top, in sixty-fourths, 0 to 192 */ - public record Runs(short[] counts, short[] bottoms, short[] tops, short[] blocks, short[] covers, byte[] coverShares) { + public record Runs(short[] counts, short[] bottoms, short[] tops, short[] blocks, short[] covers, byte[] coverShares, byte[] lights, + byte[] occlusions) { public int count() { return tops.length; } @@ -79,8 +82,12 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind * @param y each block's height above the dimension's bottom * @param blocks the index of each block in the tile's block names * @param faces the sides of each block that face the open air, a bit each: down, up, north, south, west, east + * @param lights the sky's light each block shows on faces that stand inside it, such as a plant's, 0 to 15 + * @param shades the shade of each face {@code faces} names, block after block and side after side: the light of the + * cell it faces in the lowest 4 bits, then for each corner, 2 bits each, how many of the 3 cells around + * it are opaque */ - public record Voxels(byte[] x, byte[] z, short[] y, short[] blocks, byte[] faces) { + public record Voxels(byte[] x, byte[] z, short[] y, short[] blocks, byte[] faces, byte[] lights, short[] shades) { public int count() { return x.length; } diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java index 554f43035..7cba4ea89 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/MapTileRenderer.java @@ -133,6 +133,8 @@ public final class MapTileRenderer { ShortArrayList blocks = new ShortArrayList(); ShortArrayList covers = new ShortArrayList(); ByteArrayList coverShares = new ByteArrayList(); + ByteArrayList lights = new ByteArrayList(); + ByteArrayList occlusions = new ByteArrayList(); for (int gridZ = 0; gridZ < grid.size(); gridZ++) { int worldZ = (int) Math.floor(grid.worldZ(gridZ)); for (int gridX = 0; gridX < grid.size(); gridX++) { @@ -148,10 +150,12 @@ public final class MapTileRenderer { covers.add(names.indexOf(area.covers()[run])); } coverShares.addElements(coverShares.size(), area.coverShares()); + lights.addElements(lights.size(), area.lights()); + occlusions.addElements(occlusions.size(), area.occlusions()); } } return new MapTile.Runs(counts, bottoms.toShortArray(), runTops.toShortArray(), blocks.toShortArray(), covers.toShortArray(), - coverShares.toByteArray()); + coverShares.toByteArray(), lights.toByteArray(), occlusions.toByteArray()); } // Only a tile of a block a pixel shows its blocks one by one; coarser ones show the tops of their columns. @@ -164,7 +168,7 @@ public final class MapTileRenderer { for (int at = 0; at < blocks.length; at++) { blocks[at] = names.indexOf(found.blocks()[at]); } - return new MapTile.Voxels(found.x(), found.z(), found.y(), blocks, found.faces()); + return new MapTile.Voxels(found.x(), found.z(), found.y(), blocks, found.faces(), found.lights(), found.shades()); } private ColumnTops topsOf(BlockSource source) { diff --git a/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java b/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java index ada62e8d8..b5c23b60c 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java +++ b/core/src/main/java/art/arcane/iris/core/studio/map/VisibleBlocks.java @@ -21,36 +21,38 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.hunk.Hunk; import it.unimi.dsi.fastutil.bytes.ByteArrayList; +import it.unimi.dsi.fastutil.ints.Int2ByteMap; +import it.unimi.dsi.fastutil.ints.Int2ByteMaps; import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.ints.IntSets; +import it.unimi.dsi.fastutil.shorts.ShortArrayList; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Set; import java.util.function.IntBinaryOperator; import java.util.function.UnaryOperator; /** - * The blocks of a chunk that can be seen from the open air above it, each with the sides that face that air. The open - * air is every cell no opaque block fills that the sky reaches, through water and leaves too, so the ground, cliffs, - * overhangs, the wood inside a tree and the floor of a lake are seen, and a cave closed to the sky is not. + * The blocks of a chunk that can be seen from the open air above it, each with the sides that face that air and how + * they are lit. The open air is every cell no opaque block fills that the sky reaches, through water and leaves too, + * so the ground, cliffs, overhangs, the wood inside a tree and the floor of a lake are seen, and a cave closed to the + * sky is not. * * @param positions each block's place in the chunk: x in the lowest 4 bits, z in the next 4, then its height above the * dimension's bottom * @param blocks each block's key * @param faces the sides of each block that face the open air, a bit each in {@link #SIDES}' order + * @param lights the sky's light each block shows on faces that stand inside it, such as a plant's, 0 to 15 + * @param shades the shade of each face {@link #faces} names, block after block and side after side, as + * {@link ChunkCells#faceShade} gives it * @param borders the cells along the chunk's sides, for the faces it shows once the chunks beside it are known; two * visible blocks are equal by the faces they show without them */ -record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorders borders) { +record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, byte[] lights, short[] shades, ChunkBorders borders) { /** The order of the sides in {@link #faces}: down, up, north, south, west, east. */ static final int[][] SIDES = {{0, -1, 0}, {0, 1, 0}, {0, 0, -1}, {0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}; static final int POSITION_Y_SHIFT = 8; private static final int ACROSS = 16; - private static final Set ALWAYS_IN_WATER = Set.of("minecraft:kelp", "minecraft:kelp_plant", "minecraft:seagrass", - "minecraft:tall_seagrass", "minecraft:bubble_column"); private static final int Z_SHIFT = 4; int count() { @@ -65,16 +67,15 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder * @param seenByPlayers the state players see in place of a block, which decides what hides what */ static VisibleBlocks of(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers) { - return of(chunk, terrainY, fluidHeight, seenByPlayers, IntSets.EMPTY_SET); + return of(ChunkCells.of(chunk, terrainY, fluidHeight, seenByPlayers, Int2ByteMaps.EMPTY_MAP), Int2ByteMaps.EMPTY_MAP); } /** * @param reachedBeside cells along the chunk's sides, as {@link #positionOf} places them, that the open air of the * chunks beside it reaches, which the terrain's height there does not tell */ - static VisibleBlocks of(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers, - IntSet reachedBeside) { - return new Finder(chunk, terrainY, fluidHeight, seenByPlayers, reachedBeside).find(); + static VisibleBlocks of(ChunkCells cells, Int2ByteMap reachedBeside) { + return new Finder(cells, reachedBeside).find(); } /** A block's place in its chunk, as {@link #positions} holds it. */ @@ -84,8 +85,8 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder @Override public boolean equals(Object other) { - return other instanceof VisibleBlocks visible && Arrays.equals(positions, visible.positions) - && Arrays.equals(blocks, visible.blocks) && Arrays.equals(faces, visible.faces); + return other instanceof VisibleBlocks visible && Arrays.equals(positions, visible.positions) && Arrays.equals(blocks, visible.blocks) + && Arrays.equals(faces, visible.faces) && Arrays.equals(lights, visible.lights) && Arrays.equals(shades, visible.shades); } @Override @@ -99,49 +100,18 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder } private static final class Finder { + private final ChunkCells cells; private final Hunk chunk; - private final IntBinaryOperator terrainY; - private final int fluidHeight; private final int height; - private final PlatformBlockState[] seen; - private final boolean[] open; - private final boolean[] fluid; private final boolean[] skyReaches; - private final IntSet reachedBeside; + private final Int2ByteMap reachedBeside; - Finder(Hunk chunk, IntBinaryOperator terrainY, int fluidHeight, UnaryOperator seenByPlayers, - IntSet reachedBeside) { - this.chunk = chunk; - this.terrainY = terrainY; - this.fluidHeight = fluidHeight; + Finder(ChunkCells cells, Int2ByteMap reachedBeside) { + this.cells = cells; + this.chunk = cells.chunk(); + this.height = cells.height(); this.reachedBeside = reachedBeside; - this.height = chunk.getHeight(); - int cells = ACROSS * height * ACROSS; - this.seen = new PlatformBlockState[cells]; - this.open = new boolean[cells]; - this.fluid = new boolean[cells]; - this.skyReaches = new boolean[cells]; - for (int y = 0; y < height; y++) { - for (int z = 0; z < ACROSS; z++) { - for (int x = 0; x < ACROSS; x++) { - PlatformBlockState block = chunk.get(x, y, z); - int cell = cellOf(x, y, z); - seen[cell] = block == null || block.isAir() ? null : seenByPlayers.apply(block); - open[cell] = seen[cell] == null || !seen[cell].isOccluding(); - fluid[cell] = seen[cell] != null && holdsFluid(seen[cell]); - } - } - } - } - - // Water around a waterlogged block, or one that only grows in water, has no side against it. - private static boolean holdsFluid(PlatformBlockState block) { - return block.isFluid() || block.isWaterLogged() || ALWAYS_IN_WATER.contains(materialOf(block.key())); - } - - private static String materialOf(String key) { - int properties = key.indexOf('['); - return properties < 0 ? key : key.substring(0, properties); + this.skyReaches = new boolean[ACROSS * height * ACROSS]; } VisibleBlocks find() { @@ -149,25 +119,33 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder IntArrayList positions = new IntArrayList(); List blocks = new ArrayList<>(); ByteArrayList faces = new ByteArrayList(); + ByteArrayList lights = new ByteArrayList(); + ShortArrayList shades = new ShortArrayList(); for (int y = 0; y < height; y++) { for (int z = 0; z < ACROSS; z++) { for (int x = 0; x < ACROSS; x++) { - int cell = cellOf(x, y, z); - if (seen[cell] == null) { + if (cells.seenAt(x, y, z) == null) { continue; } int sides = sidesFacingTheSky(x, y, z); // A plant or a leaf the sky reaches shows whatever it touches; its model may have faces no side hides. - if (sides == 0 && !(open[cell] && skyReaches[cell])) { + if (sides == 0 && !(cells.isOpen(x, y, z) && skyReaches[ChunkCells.cellOf(x, y, z)])) { continue; } positions.add(positionOf(x, y, z)); blocks.add(chunk.get(x, y, z).key()); faces.add((byte) sides); + lights.add((byte) cells.blockLightAt(x, y, z)); + for (int side = 0; side < SIDES.length; side++) { + if ((sides & 1 << side) != 0) { + shades.add(cells.faceShade(x, y, z, side)); + } + } } } } - return new VisibleBlocks(positions.toIntArray(), blocks.toArray(String[]::new), faces.toByteArray(), borders()); + return new VisibleBlocks(positions.toIntArray(), blocks.toArray(String[]::new), faces.toByteArray(), lights.toByteArray(), + shades.toShortArray(), borders()); } private ChunkBorders borders() { @@ -186,14 +164,14 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder int x = ChunkBorders.xOf(side, place); int z = ChunkBorders.zOf(side, place); for (int y = 0; y < height; y++) { - int cell = cellOf(x, y, z); - if (skyReaches[cell]) { - reached.add(y, null, fluid[cell]); - } else if (open[cell]) { - sealed.add(y, null, fluid[cell]); + boolean holdsFluid = cells.holdsFluid(x, y, z); + if (skyReaches[ChunkCells.cellOf(x, y, z)]) { + reached.add(y, null, holdsFluid, cells.lightAt(x, y, z)); + } else if (cells.isOpen(x, y, z)) { + sealed.add(y, null, holdsFluid, 0); } - if (seen[cell] != null && !facesOutside(x, y, z, side)) { - hidden.add(y, chunk.get(x, y, z).key(), fluid[cell]); + if (cells.seenAt(x, y, z) != null && !facesOutside(x, y, z, side)) { + hidden.add(y, chunk.get(x, y, z).key(), holdsFluid, 0); } } reached.nextPlace(); @@ -204,15 +182,15 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder } // Fills every open cell the sky reaches, from the top of the chunk and from beside it where the ground around - // lies lower. + // lies lower or the chunk beside it is known to be open. private void spreadTheSky() { int[] queue = new int[skyReaches.length]; int queued = 0; for (int y = 0; y < height; y++) { for (int z = 0; z < ACROSS; z++) { for (int x = 0; x < ACROSS; x++) { - int cell = cellOf(x, y, z); - if (open[cell] && (touchesOpenOutside(x, y, z) || reachedBeside.contains(positionOf(x, y, z)))) { + if (cells.isOpen(x, y, z) && (touchesOpenOutside(x, y, z) || reachedBeside.containsKey(positionOf(x, y, z)))) { + int cell = ChunkCells.cellOf(x, y, z); skyReaches[cell] = true; queue[queued++] = cell; } @@ -228,11 +206,11 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder int nx = x + side[0]; int ny = y + side[1]; int nz = z + side[2]; - if (!isInside(nx, ny, nz)) { + if (!cells.isInside(nx, ny, nz)) { continue; } - int neighbour = cellOf(nx, ny, nz); - if (open[neighbour] && !skyReaches[neighbour]) { + int neighbour = ChunkCells.cellOf(nx, ny, nz); + if (cells.isOpen(nx, ny, nz) && !skyReaches[neighbour]) { skyReaches[neighbour] = true; queue[queued++] = neighbour; } @@ -245,7 +223,7 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder int nx = x + side[0]; int ny = y + side[1]; int nz = z + side[2]; - if (!isInside(nx, ny, nz) && outsideAt(nx, ny, nz) != Outside.SOLID) { + if (!cells.isInside(nx, ny, nz) && cells.outsideAt(nx, ny, nz) != ChunkCells.Outside.SOLID) { return true; } } @@ -254,16 +232,15 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder // A side faces the sky where the cell beside it is open air the sky reaches; water hides the sides of water. private int sidesFacingTheSky(int x, int y, int z) { - boolean isFluid = fluid[cellOf(x, y, z)]; + boolean isFluid = cells.holdsFluid(x, y, z); int sides = 0; for (int side = 0; side < SIDES.length; side++) { int nx = x + SIDES[side][0]; int ny = y + SIDES[side][1]; int nz = z + SIDES[side][2]; boolean faces; - if (isInside(nx, ny, nz)) { - int neighbour = cellOf(nx, ny, nz); - faces = skyReaches[neighbour] && !(isFluid && fluid[neighbour]); + if (cells.isInside(nx, ny, nz)) { + faces = skyReaches[ChunkCells.cellOf(nx, ny, nz)] && !(isFluid && cells.holdsFluid(nx, ny, nz)); } else { faces = facesOutside(x, y, z, side); } @@ -276,33 +253,8 @@ record VisibleBlocks(int[] positions, String[] blocks, byte[] faces, ChunkBorder // Whether a side facing out of the chunk faces open air there, by the terrain's height beside the chunk. private boolean facesOutside(int x, int y, int z, int side) { - Outside outside = outsideAt(x + SIDES[side][0], y + SIDES[side][1], z + SIDES[side][2]); - return outside == Outside.AIR || (outside == Outside.FLUID && !fluid[cellOf(x, y, z)]); + ChunkCells.Outside outside = cells.outsideAt(x + SIDES[side][0], y + SIDES[side][1], z + SIDES[side][2]); + return outside == ChunkCells.Outside.AIR || (outside == ChunkCells.Outside.FLUID && !cells.holdsFluid(x, y, z)); } - - private Outside outsideAt(int x, int y, int z) { - if (y >= height) { - return Outside.AIR; - } - if (y < 0 || y <= terrainY.applyAsInt(x, z)) { - return Outside.SOLID; - } - return y <= fluidHeight ? Outside.FLUID : Outside.AIR; - } - - private boolean isInside(int x, int y, int z) { - return x >= 0 && x < ACROSS && z >= 0 && z < ACROSS && y >= 0 && y < height; - } - - private static int cellOf(int x, int y, int z) { - return (y * ACROSS + z) * ACROSS + x; - } - } - - /** What lies beside the chunk, judged by the terrain's height there alone. */ - private enum Outside { - SOLID, - FLUID, - AIR } } diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/ChunkBordersTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/ChunkBordersTest.java index b80e304a3..84c003c72 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/ChunkBordersTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/ChunkBordersTest.java @@ -2,7 +2,7 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.hunk.Hunk; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.Int2ByteMap; import it.unimi.dsi.fastutil.ints.IntSet; import org.junit.Test; @@ -77,10 +77,10 @@ public class ChunkBordersTest { ChunkBorders shaftBorders = VisibleBlocks.of(shaft, (x, z) -> top, NO_FLUID, UnaryOperator.identity()).borders(); VisibleBlocks closed = VisibleBlocks.of(overhang, (x, z) -> top, NO_FLUID, UnaryOperator.identity()); - IntSet reached = new IntOpenHashSet(closed.borders().reachedFrom(shaftBorders, ChunkBorders.WEST)); - VisibleBlocks opened = VisibleBlocks.of(overhang, (x, z) -> top, NO_FLUID, UnaryOperator.identity(), reached); + Int2ByteMap reached = closed.borders().reachedFrom(shaftBorders, ChunkBorders.WEST); + VisibleBlocks opened = VisibleBlocks.of(ChunkCells.of(overhang, (x, z) -> top, NO_FLUID, UnaryOperator.identity(), reached), reached); - assertEquals(IntSet.of(VisibleBlocks.positionOf(0, 4, 7), VisibleBlocks.positionOf(0, 5, 7)), reached); + assertEquals(IntSet.of(VisibleBlocks.positionOf(0, 4, 7), VisibleBlocks.positionOf(0, 5, 7)), reached.keySet()); assertFalse(shows(closed, VisibleBlocks.positionOf(2, 4, 7))); assertTrue(shows(opened, VisibleBlocks.positionOf(2, 4, 7))); assertTrue(shows(opened, VisibleBlocks.positionOf(1, 3, 7))); @@ -102,7 +102,7 @@ public class ChunkBordersTest { ChunkBorders borders = VisibleBlocks.of(chunk, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity()).borders(); ChunkBorders besideBorders = VisibleBlocks.of(beside, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity()).borders(); List faces = new ArrayList<>(); - borders.facesAgainst(besideBorders, side, (x, y, z, block, faceSide) -> { + borders.facesAgainst(besideBorders, side, (x, y, z, block, faceSide, light) -> { assertEquals(side, faceSide); faces.add(x + "," + y + "," + z + " " + block); }); diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/ChunkCellsTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/ChunkCellsTest.java new file mode 100644 index 000000000..65d9c3630 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/map/ChunkCellsTest.java @@ -0,0 +1,113 @@ +package art.arcane.iris.core.studio.map; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import it.unimi.dsi.fastutil.ints.Int2ByteMaps; +import org.junit.Test; + +import java.util.function.UnaryOperator; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ChunkCellsTest { + private static final int HEIGHT = 12; + private static final int GROUND_Y = 3; + private static final int NO_FLUID = -1; + private static final int DOWN = 0; + private static final int UP = 1; + private static final PlatformBlockState STONE = block("minecraft:stone", true); + private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves", false); + + @Test + public void openGroundIsFullyLitWithNoCornerDarkened() { + short shade = cellsOf(groundUpTo(GROUND_Y)).topShade(7, GROUND_Y, 7); + + assertEquals(ChunkCells.FULL_LIGHT, ChunkCells.lightOf(shade)); + assertEquals(0, ChunkCells.opaqueAroundCorners(shade)); + } + + @Test + public void eachLeafAboveDimsTheSkyByALevel() { + Hunk chunk = groundUpTo(GROUND_Y); + fillLayer(chunk, GROUND_Y + 3, LEAVES); + fillLayer(chunk, GROUND_Y + 4, LEAVES); + + assertEquals(ChunkCells.FULL_LIGHT - 2, ChunkCells.lightOf(cellsOf(chunk).topShade(7, GROUND_Y, 7))); + } + + @Test + public void groundUnderARoofIsLitFromTheSideLessAStepAtATime() { + Hunk chunk = groundUpTo(GROUND_Y); + fillLayer(chunk, GROUND_Y + 3, STONE); + for (int z = 0; z < 16; z++) { + chunk.set(15, GROUND_Y + 3, z, null); + } + + ChunkCells cells = cellsOf(chunk); + + assertEquals(ChunkCells.FULL_LIGHT, cells.lightAt(15, GROUND_Y + 1, 7)); + assertEquals(ChunkCells.FULL_LIGHT - 3, cells.lightAt(12, GROUND_Y + 1, 7)); + } + + @Test + public void groundAtTheFootOfAWallDarkensTheCornersAgainstIt() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 0; z < 16; z++) { + chunk.set(8, GROUND_Y + 1, z, STONE); + } + + short shade = cellsOf(chunk).topShade(7, GROUND_Y, 7); + + // The up face's corners run from the north west: two lie against the wall to the east, each beside it and past it. + assertEquals(4, ChunkCells.opaqueAroundCorners(shade)); + assertEquals(ChunkCells.FULL_LIGHT, ChunkCells.lightOf(shade)); + } + + @Test + public void aFaceAgainstOpaqueSidesOnBothHandsHidesTheCornerBetweenThem() { + Hunk chunk = groundUpTo(GROUND_Y); + chunk.set(8, GROUND_Y + 1, 7, STONE); + chunk.set(7, GROUND_Y + 1, 8, STONE); + + short shade = cellsOf(chunk).topShade(7, GROUND_Y, 7); + + // The south east corner has both sides opaque, so counts as all three; the corners on one side count one each. + assertEquals(ChunkCells.MOST_OPAQUE_AROUND_CORNER + 2, ChunkCells.opaqueAroundCorners(shade)); + } + + @Test + public void theUndersideOfBuriedGroundIsDark() { + assertEquals(0, ChunkCells.lightOf(cellsOf(groundUpTo(GROUND_Y)).faceShade(7, 1, 7, DOWN))); + assertEquals(ChunkCells.FULL_LIGHT, ChunkCells.lightOf(cellsOf(groundUpTo(GROUND_Y)).faceShade(7, GROUND_Y, 7, UP))); + } + + private static ChunkCells cellsOf(Hunk chunk) { + return ChunkCells.of(chunk, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity(), Int2ByteMaps.EMPTY_MAP); + } + + private static void fillLayer(Hunk chunk, int y, PlatformBlockState block) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + chunk.set(x, y, z, block); + } + } + } + + private static Hunk groundUpTo(int topY) { + Hunk chunk = Hunk.newArrayHunk(16, HEIGHT, 16); + for (int y = 0; y <= topY; y++) { + fillLayer(chunk, y, STONE); + } + return chunk; + } + + private static PlatformBlockState block(String key, boolean occluding) { + PlatformBlockState block = mock(PlatformBlockState.class); + when(block.key()).thenReturn(key); + when(block.isOccluding()).thenReturn(occluding); + when(block.isSolid()).thenReturn(true); + return block; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java index bd515770c..6045cddfd 100644 --- a/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java +++ b/core/src/test/java/art/arcane/iris/core/studio/map/ColumnRunsTest.java @@ -2,26 +2,29 @@ package art.arcane.iris.core.studio.map; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.project.hunk.Hunk; +import it.unimi.dsi.fastutil.ints.Int2ByteMaps; import org.junit.Test; import java.util.function.UnaryOperator; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ColumnRunsTest { private static final int HEIGHT = 16; private static final int GROUND_Y = 3; - private static final PlatformBlockState GRASS = block("minecraft:grass_block"); - private static final PlatformBlockState LOG = block("minecraft:oak_log"); - private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves"); + private static final int NO_FLUID = -1; + private static final PlatformBlockState GRASS = block("minecraft:grass_block", true); + private static final PlatformBlockState LOG = block("minecraft:oak_log", true); + private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves", false); private static final PlatformBlockState GRASS_PLANT = plant("minecraft:short_grass"); @Test public void flatGroundIsOneRunPerArea() { - ColumnRuns runs = ColumnRuns.of(groundUpTo(GROUND_Y), 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + ColumnRuns runs = runsOf(groundUpTo(GROUND_Y)); assertEquals(64, runs.counts().length); assertEquals(1, runs.counts()[0]); @@ -42,7 +45,7 @@ public class ColumnRunsTest { } } - ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + ColumnRuns runs = runsOf(chunk); assertEquals(3, runs.counts()[0]); assertArrayEquals(new short[]{GROUND_Y + 6, GROUND_Y + 4, GROUND_Y}, new short[]{runs.tops()[0], runs.tops()[1], runs.tops()[2]}); @@ -59,7 +62,7 @@ public class ColumnRunsTest { } } - ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + ColumnRuns runs = runsOf(chunk); int area = 1 * 8 + 1; int first = runs.firstRunOf(area); @@ -73,13 +76,51 @@ public class ColumnRunsTest { Hunk chunk = groundUpTo(GROUND_Y); chunk.set(0, GROUND_Y + 1, 0, GRASS_PLANT); - ColumnRuns runs = ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity()); + ColumnRuns runs = runsOf(chunk); assertEquals("minecraft:short_grass", runs.covers()[0]); assertEquals(ColumnRuns.WHOLE_SHARE / 4, runs.coverShares()[0] & 0xFF); assertEquals(null, runs.covers()[1]); } + @Test + public void openGroundIsLitFullyAndGroundUnderACanopyIsDarker() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 0; z < 8; z++) { + for (int x = 0; x < 8; x++) { + chunk.set(x, GROUND_Y + 3, z, LEAVES); + chunk.set(x, GROUND_Y + 4, z, LEAVES); + } + } + + ColumnRuns runs = runsOf(chunk); + int shadedArea = 1 * 8 + 1; + int openArea = 7 * 8 + 7; + int ground = runs.firstRunOf(shadedArea) + runs.counts()[shadedArea] - 1; + + assertEquals(ChunkCells.FULL_LIGHT * ColumnRuns.LIGHT_STEPS, runs.lights()[runs.firstRunOf(openArea)] & 0xFF); + assertEquals(0, runs.occlusions()[runs.firstRunOf(openArea)]); + assertTrue((runs.lights()[ground] & 0xFF) < ChunkCells.FULL_LIGHT * ColumnRuns.LIGHT_STEPS); + } + + @Test + public void groundAtTheFootOfAWallHasItsCornersDarkened() { + Hunk chunk = groundUpTo(GROUND_Y); + for (int z = 0; z < 16; z++) { + chunk.set(4, GROUND_Y + 1, z, LOG); + } + + ColumnRuns runs = runsOf(chunk); + int besideWall = 4 * 8 + 1; + + assertTrue(runs.occlusions()[runs.firstRunOf(besideWall) + runs.counts()[besideWall] - 1] > 0); + } + + private static ColumnRuns runsOf(Hunk chunk) { + ChunkCells cells = ChunkCells.of(chunk, (x, z) -> GROUND_Y, NO_FLUID, UnaryOperator.identity(), Int2ByteMaps.EMPTY_MAP); + return ColumnRuns.of(chunk, 1, (x, z) -> GROUND_Y, UnaryOperator.identity(), cells); + } + private static Hunk groundUpTo(int topY) { Hunk chunk = Hunk.newArrayHunk(16, HEIGHT, 16); for (int y = 0; y <= topY; y++) { @@ -92,10 +133,11 @@ public class ColumnRunsTest { return chunk; } - private static PlatformBlockState block(String key) { + private static PlatformBlockState block(String key, boolean occluding) { PlatformBlockState block = mock(PlatformBlockState.class); when(block.key()).thenReturn(key); when(block.isSolid()).thenReturn(true); + when(block.isOccluding()).thenReturn(occluding); return block; } diff --git a/studio/src/renderer/src/bridge/tileDecoding.ts b/studio/src/renderer/src/bridge/tileDecoding.ts index e7ca7ac95..c7685e5ea 100644 --- a/studio/src/renderer/src/bridge/tileDecoding.ts +++ b/studio/src/renderer/src/bridge/tileDecoding.ts @@ -88,13 +88,17 @@ function decodeRuns(buffer: ArrayBuffer, countsAt: number, cells: number, count: const blocksAt = topsAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) const coversAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) const coverSharesAt = coversAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const lightsAt = coverSharesAt + aligned(count) + const occlusionsAt = lightsAt + aligned(count) return { starts: startsOf(new Int16Array(buffer, countsAt, cells)), bottoms: new Int16Array(buffer, bottomsAt, count), tops: new Int16Array(buffer, topsAt, count), blocks: new Int16Array(buffer, blocksAt, count), covers: new Int16Array(buffer, coversAt, count), - coverShares: new Uint8Array(buffer, coverSharesAt, count) + coverShares: new Uint8Array(buffer, coverSharesAt, count), + lights: new Uint8Array(buffer, lightsAt, count), + occlusions: new Uint8Array(buffer, occlusionsAt, count) } } @@ -103,15 +107,30 @@ function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxe const yAt = zAt + aligned(count) const blocksAt = yAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) const facesAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT) + const lightsAt = facesAt + aligned(count) + const shadesAt = lightsAt + aligned(count) + const faces = new Uint8Array(buffer, facesAt, count) return { x: new Uint8Array(buffer, xAt, count), z: new Uint8Array(buffer, zAt, count), y: new Int16Array(buffer, yAt, count), blocks: new Int16Array(buffer, blocksAt, count), - faces: new Uint8Array(buffer, facesAt, count) + faces, + lights: new Uint8Array(buffer, lightsAt, count), + shades: new Uint16Array(buffer, shadesAt, facesShown(faces)) } } +function facesShown(faces: Uint8Array): number { + let shown = 0 + for (const sides of faces) { + for (let rest = sides; rest !== 0; rest &= rest - 1) { + shown++ + } + } + return shown +} + function startsOf(counts: Int16Array): Int32Array { const starts = new Int32Array(counts.length + 1) for (let cell = 0; cell < counts.length; cell++) { diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index f90d04891..e3f133226 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -389,6 +389,10 @@ export interface TileVoxels { blocks: Int16Array /** The sides of each block that face the open air, a bit each in {@link VOXEL_SIDES}' order. */ faces: Uint8Array + /** The sky's light each block shows on faces that stand inside it, such as a plant's, 0 to 15. */ + lights: Uint8Array + /** The shade of each face {@link faces} names, block after block and side after side, as skyLight reads it. */ + shades: Uint16Array } /** @@ -406,8 +410,17 @@ export interface TileRuns { covers: Int16Array /** How much of each run's top plants stand on, 0 to 255 for all of it. */ coverShares: Uint8Array + /** The sky's light on each run's top, the mean of its blocks' tops, in sixteenths of a level. */ + lights: Uint8Array + /** How many opaque cells stand around each corner of each run's top, the mean of its blocks' tops, in sixty-fourths. */ + occlusions: Uint8Array } +/** {@link TileRuns.lights} to a light level. */ +export const RUN_LIGHT_STEPS = 16 +/** {@link TileRuns.occlusions} to a count of opaque cells. */ +export const RUN_OCCLUSION_STEPS = 64 + /** The order of the sides in {@link TileVoxels.faces}. */ export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const diff --git a/studio/src/renderer/src/scene/runFaces.test.ts b/studio/src/renderer/src/scene/runFaces.test.ts index 7bec40384..065299a1f 100644 --- a/studio/src/renderer/src/scene/runFaces.test.ts +++ b/studio/src/renderer/src/scene/runFaces.test.ts @@ -8,6 +8,21 @@ const GROUND = 10 const BASE = 0 const CANOPY_BOTTOM = 14 const CANOPY_TOP = 15 +const FULLY_LIT = 15 * 16 + +// Two columns of plain ground side by side, their tops lit and darkened as given. +function flatRuns(lights: Uint8Array, occlusions: Uint8Array): SurfaceRuns['runs'] { + return { + starts: Int32Array.of(0, 1, 2), + bottoms: Int16Array.of(0, 0), + tops: Int16Array.of(GROUND, GROUND), + blocks: Int16Array.of(0, 0), + covers: Int16Array.of(-1, -1), + coverShares: new Uint8Array(2), + lights, + occlusions + } +} // Two columns side by side, a block each: plain ground on the west, ground with a canopy floating over it on the east. const surface: TerrainSurface = { @@ -28,7 +43,9 @@ const runs: SurfaceRuns = { tops: Int16Array.of(GROUND, CANOPY_TOP, GROUND), blocks: Int16Array.of(0, 1, 0), covers: Int16Array.of(-1, -1, -1), - coverShares: new Uint8Array(3) + coverShares: new Uint8Array(3), + lights: new Uint8Array(3).fill(FULLY_LIT), + occlusions: new Uint8Array(3) }, cellAt: (column) => column, looks: [null, null], @@ -54,7 +71,7 @@ describe('run faces', () => { }) it('draws the tops of neighbouring columns at one height in one block as one face', () => { - const flat: SurfaceRuns = { ...runs, runs: { starts: Int32Array.of(0, 1, 2), bottoms: Int16Array.of(0, 0), tops: Int16Array.of(GROUND, GROUND), blocks: Int16Array.of(0, 0), covers: Int16Array.of(-1, -1), coverShares: new Uint8Array(2) } } + const flat: SurfaceRuns = { ...runs, runs: flatRuns(new Uint8Array(2).fill(FULLY_LIT), new Uint8Array(2)) } const geometry = runFaces(new ColumnField(surface), flat, BASE).geometry() const positions = geometry.getAttribute('position') const tops = [] @@ -67,6 +84,23 @@ describe('run faces', () => { expect(tops).toEqual([2]) }) + it('darkens a top by the mean light and corner shade of the blocks it stands for', () => { + const shaded: SurfaceRuns = { ...runs, runs: flatRuns(Uint8Array.of(FULLY_LIT, 10 * 16), Uint8Array.of(0, 32)) } + const geometry = runFaces(new ColumnField(surface), shaded, BASE).geometry() + const positions = geometry.getAttribute('position') + const colors = geometry.getAttribute('color') + const topColorAt = (x: number): number => { + for (let first = 0; first < positions.count; first += 4) { + if (positions.getY(first) === GROUND + 1 && positions.getY(first + 3) === GROUND + 1 && Math.min(positions.getX(first), positions.getX(first + 3)) === x) { + return colors.getX(first) + } + } + return NaN + } + + expect(topColorAt(1)).toBeLessThan(topColorAt(0) * 0.7) + }) + it('floats a canopy over the ground with its underside showing', () => { const drawn = faces() diff --git a/studio/src/renderer/src/scene/runFaces.ts b/studio/src/renderer/src/scene/runFaces.ts index 4e5e58674..6576756eb 100644 --- a/studio/src/renderer/src/scene/runFaces.ts +++ b/studio/src/renderer/src/scene/runFaces.ts @@ -1,4 +1,5 @@ -import { NO_BLOCK, type TileRuns } from '../bridge/types' +import { NO_BLOCK, RUN_LIGHT_STEPS, RUN_OCCLUSION_STEPS, type TileRuns } from '../bridge/types' +import { brightnessOfCorner, brightnessOfLight } from './skyLight' import type { Direction } from './blockModels' import type { BlockLook } from './blockLooks' import type { ColumnField } from './columnField' @@ -66,12 +67,14 @@ function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns, const top = runs.tops[run] const bottom = runs.bottoms[run] const block = runs.blocks[run] + const light = brightnessOfLight(runs.lights[run] / RUN_LIGHT_STEPS) if (run === first || runs.bottoms[run - 1] !== top + 1) { - const color = underWater(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), top + 1, water) + const topLight = light * brightnessOfCorner(runs.occlusions[run] / RUN_OCCLUSION_STEPS) + const color = underWater(lit(withPlants(surface, run, colorOf(surface, block, 'top', FACE_LIGHT.up)), topLight), top + 1, water) faces.add('up', row, column, top + 1, top + 1, color, color) } if (!isGround && (run === last || runs.tops[run + 1] !== bottom - 1)) { - const color = underWater(colorOf(surface, block, 'top', FACE_LIGHT.down), bottom, water) + const color = underWater(lit(colorOf(surface, block, 'top', FACE_LIGHT.down), light), bottom, water) faces.add('down', row, column, bottom, bottom, color, color) } for (const side of SIDES) { @@ -80,7 +83,7 @@ function addColumn(faces: MergedFaces, field: ColumnField, surface: SurfaceRuns, const lowest = isGround ? (known ? -Infinity : base) : bottom const covered = known ? spansOf(surface, surface.cellAt(...neighbour)) : [] for (const open of uncovered({ bottom: lowest, top }, covered)) { - addSide(faces, surface, column, row, side, open, top, block, water) + addSide(faces, surface, column, row, side, open, top, block, water, light) } } } @@ -123,19 +126,35 @@ export function uncovered(span: Span, covered: readonly Span[]): Span[] { } // The top block of a run shows its side picture; the blocks under it, the picture of the blocks under a column's top. -function addSide(faces: MergedFaces, surface: SurfaceRuns, column: number, row: number, side: Side, open: Span, runTop: number, block: number, water: number | null): void { +// Sides take the light of the run's top, as the open air beside it mostly holds. +function addSide( + faces: MergedFaces, + surface: SurfaceRuns, + column: number, + row: number, + side: Side, + open: Span, + runTop: number, + block: number, + water: number | null, + skyLight: number +): void { const light = side.direction === 'north' || side.direction === 'south' ? FACE_LIGHT.north : FACE_LIGHT.west if (open.top === runTop) { - const color = colorOf(surface, block, 'side', light) + const color = lit(colorOf(surface, block, 'side', light), skyLight) faces.add(side.direction, row, column, runTop, runTop + 1, underWater(color, runTop, water), underWater(color, runTop + 1, water)) } const belowTop = open.top === runTop ? runTop - 1 : open.top if (belowTop >= open.bottom) { - const color = colorOf(surface, block, 'below', light) + const color = lit(colorOf(surface, block, 'below', light), skyLight) faces.add(side.direction, row, column, open.bottom, belowTop + 1, underWater(color, open.bottom, water), underWater(color, belowTop + 1, water)) } } +function lit(color: Vec3, brightness: number): Vec3 { + return [color[0] * brightness, color[1] * brightness, color[2] * brightness] +} + function colorOf(surface: SurfaceRuns, block: number, face: 'top' | 'side' | 'below', light: number): Vec3 { const look = surface.looks[block] return shaded(look === null || look === undefined ? surface.colors[block] : look[face].color, light) diff --git a/studio/src/renderer/src/scene/skyLight.ts b/studio/src/renderer/src/scene/skyLight.ts new file mode 100644 index 000000000..e4c921121 --- /dev/null +++ b/studio/src/renderer/src/scene/skyLight.ts @@ -0,0 +1,39 @@ +/** + * How bright the server's sky light and corner darkening make a face, as Minecraft's smooth lighting shows them. A + * face's shade holds the sky's light in the cell it faces, 0 to {@link FULL_LIGHT}, in its lowest bits, then for each of + * its corners how many of the three cells around it are opaque. + */ + +export const FULL_LIGHT = 15 +const LIGHT_BITS = 4 +const CORNER_BITS = 2 +const LIGHT_MASK = (1 << LIGHT_BITS) - 1 +const CORNER_MASK = (1 << CORNER_BITS) - 1 +// Between Minecraft's Moody and Bright, so shade under trees reads without the forest floor going black. +const LIFT = 0.5 +// What a cell the sky never reaches still shows, so a cave mouth is dark but not a hole. +const DARKEST = 0.12 +// Each opaque cell around a corner takes this off its brightness; linear, so a far area's mean darkens as its blocks do. +const DARKENING_PER_OPAQUE_CELL = 0.2 + +/** The brightness of a cell lit at {@code light}, which may lie between levels, from {@link DARKEST} to 1. */ +export function brightnessOfLight(light: number): number { + const level = Math.min(FULL_LIGHT, Math.max(0, light)) / FULL_LIGHT + const moody = level / (4 - 3 * level) + const bright = 1 - (1 - moody) ** 4 + return DARKEST + (1 - DARKEST) * (moody + (bright - moody) * LIFT) +} + +/** How much a corner keeps of its brightness with {@code opaque} cells around it, which may be a mean. */ +export function brightnessOfCorner(opaque: number): number { + return 1 - DARKENING_PER_OPAQUE_CELL * opaque +} + +export function lightOf(shade: number): number { + return shade & LIGHT_MASK +} + +/** How many cells around a face's corner are opaque, the corners in the order the face's corners are drawn. */ +export function opaqueAround(shade: number, corner: number): number { + return (shade >> (LIGHT_BITS + corner * CORNER_BITS)) & CORNER_MASK +} diff --git a/studio/src/renderer/src/scene/voxelMesh.test.ts b/studio/src/renderer/src/scene/voxelMesh.test.ts index 0f1cb98a0..569ca21cc 100644 --- a/studio/src/renderer/src/scene/voxelMesh.test.ts +++ b/studio/src/renderer/src/scene/voxelMesh.test.ts @@ -42,13 +42,19 @@ const surface: TerrainSurface = { colorAt: () => 0x808080 } -function voxelsOf(blocks: number[], faces: number[]): SurfaceVoxels { +const FULL_LIGHT = 15 + +// Every face lit fully with no corner darkened, unless shades are given. +function voxelsOf(blocks: number[], faces: number[], shades?: number[]): SurfaceVoxels { + const shown = faces.reduce((count, sides) => count + sides.toString(2).split('1').length - 1, 0) const voxels: TileVoxels = { x: Uint8Array.from(blocks.map((_, at) => at)), z: new Uint8Array(blocks.length), y: new Int16Array(blocks.length).fill(GROUND), blocks: Int16Array.from(blocks), - faces: Uint8Array.from(faces) + faces: Uint8Array.from(faces), + lights: new Uint8Array(blocks.length).fill(FULL_LIGHT), + shades: Uint16Array.from(shades ?? new Array(shown).fill(FULL_LIGHT)) } return { voxels, models: [null, leaves, grass, null], looks: [stoneLook, null, null, null], colors: [0x808080, 0, 0, 0], isWater: [false, false, false, true] } } @@ -78,6 +84,23 @@ describe('voxel mesh', () => { expect(faceCount(cutOut)).toBe(2) }) + it('darkens a corner of a face where opaque blocks stand around it, and splits the face away from it', () => { + const cornerHidden = FULL_LIGHT | (3 << 4) + const { opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [cornerHidden]), plain) + const colors = opaque!.getAttribute('color') + + expect(colors.getY(0)).toBeLessThan(colors.getY(2) * 0.5) + expect(colors.getY(1)).toBeCloseTo(colors.getY(2)) + expect(Array.from(opaque!.getIndex()!.array)).toEqual([1, 2, 3, 1, 3, 0]) + }) + + it('darkens a face lit by less of the sky', () => { + const lit = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [FULL_LIGHT]), plain).opaque! + const shaded = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP], [8]), plain).opaque! + + expect(shaded.getAttribute('color').getY(0)).toBeLessThan(lit.getAttribute('color').getY(0) * 0.7) + }) + it('draws water as the sides of its sheet that face the air', () => { const { water, opaque } = voxelGeometries(new ColumnField(surface), voxelsOf([WATER], [UP | DOWN]), plain) diff --git a/studio/src/renderer/src/scene/voxelMesh.ts b/studio/src/renderer/src/scene/voxelMesh.ts index ace7585fa..24f8987e1 100644 --- a/studio/src/renderer/src/scene/voxelMesh.ts +++ b/studio/src/renderer/src/scene/voxelMesh.ts @@ -5,6 +5,7 @@ import type { BlockLook, FaceLook } from './blockLooks' import type { ColumnField } from './columnField' import { shaded } from './columnFaces' import { FACE_LIGHT, type CoverFace, type CoverLook } from './coverLooks' +import { brightnessOfCorner, brightnessOfLight, lightOf, opaqueAround } from './skyLight' import type { UvCell } from './terrainAtlas' import { sunk, tintAt } from './waterTint' @@ -41,6 +42,8 @@ const CUBE_FACES: Record = { west: [[0, 1, 0], [0, 0, 0], [0, 0, 1], [0, 1, 1]], east: [[1, 1, 1], [1, 0, 1], [1, 0, 0], [1, 1, 0]] } +// The axis a side's faces look along: x, y or z. +const NORMAL_AXIS: Record = { down: 1, up: 1, north: 2, south: 2, west: 0, east: 0 } /** * Each block seen from the open air drawn as Minecraft draws it: the faces of its model, leaving out a face its model @@ -52,12 +55,15 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai const cutOut = new FaceSoup(true) const water = new FaceSoup(false) const { voxels } = surface + let firstShade = 0 for (let at = 0; at < voxels.x.length; at++) { const column = voxels.x[at] const row = voxels.z[at] const corner: Color = [field.originX + column, voxels.y[at], field.originZ + row] const block = voxels.blocks[at] const sides = voxels.faces[at] + const shades = new FaceShades(voxels.shades, firstShade, sides, voxels.lights[at]) + firstShade += shades.count const waterTop = field.waterTopAt(column, row) if (surface.isWater[block]) { addCubeFaces(sides, (_side, corners) => water.add(corner, corners, null, null)) @@ -70,7 +76,8 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai continue } const color = underWater(face.color, corner[1] + middleY(face.corners), waterTop) - ;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), color) + const brightness = face.cullFace === null ? shades.inside() : shades.across(face.cullFace, face.corners) + ;(face.cell.hasGaps ? cutOut : opaque).add(corner, face.corners, pictureUvs(face.cell, face.uvs), litCorners(color, brightness)) } continue } @@ -80,12 +87,84 @@ export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plai const light = shaded(face === null ? surface.colors[block] : face.tint, FACE_LIGHT[side]) const color = underWater(light, corner[1] + middleY(corners), waterTop) const cell = face === null ? plain : face.cell - ;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), color) + ;(cell.hasGaps ? cutOut : opaque).add(corner, corners, pictureUvs(cell, WHOLE_PICTURE), litCorners(color, shades.ofCube(side))) }) } return { opaque: opaque.geometry(), cutOut: cutOut.geometry(), water: water.geometry() } } +type CornerBrightness = readonly [number, number, number, number] + +/** One block's face shades, as the server sent them for the sides it shows, read as each corner's brightness. */ +class FaceShades { + readonly count: number + + constructor( + private readonly shades: Uint16Array, + private readonly first: number, + private readonly sides: number, + private readonly ownLight: number + ) { + let count = 0 + for (let rest = sides; rest !== 0; rest &= rest - 1) { + count++ + } + this.count = count + } + + /** A whole face on a side, its corners in {@link CUBE_FACES}' order. */ + ofCube(side: Direction): CornerBrightness { + const shade = this.shadeOf(side) + const light = brightnessOfLight(lightOf(shade)) + return [0, 1, 2, 3].map((corner) => light * brightnessOfCorner(opaqueAround(shade, corner))) as unknown as CornerBrightness + } + + /** A model's face against a side, smaller than the block's, each corner as bright as that place of the whole face. */ + across(side: Direction, corners: Corners): CornerBrightness { + const whole = this.ofCube(side) + const cube = CUBE_FACES[side] + return corners.map((place) => { + let brightness = 0 + for (let corner = 0; corner < CORNERS; corner++) { + brightness += whole[corner] * weightAt(place, cube[corner], side) + } + return brightness + }) as unknown as CornerBrightness + } + + /** A face that stands inside the block, such as a plant's, lit as the block's own cell, with no corner darkened. */ + inside(): CornerBrightness { + const light = brightnessOfLight(this.ownLight) + return [light, light, light, light] + } + + private shadeOf(side: Direction): number { + const bit = SIDE_BITS[side] + let before = 0 + for (let rest = this.sides & (bit - 1); rest !== 0; rest &= rest - 1) { + before++ + } + return this.shades[this.first + before] + } +} + +// How much a corner of a whole face counts at a place on it: the product, along the face's two axes, of how near the +// place lies to the corner's edge. +function weightAt(place: Corners[number], corner: Corners[number], side: Direction): number { + const across = NORMAL_AXIS[side] + let weight = 1 + for (let axis = 0; axis < 3; axis++) { + if (axis !== across) { + weight *= corner[axis] === 1 ? place[axis] : 1 - place[axis] + } + } + return weight +} + +function litCorners(color: Color, brightness: CornerBrightness): Color[] { + return brightness.map((amount) => [color[0] * amount, color[1] * amount, color[2] * amount] as const) +} + function addCubeFaces(sides: number, add: (side: Direction, corners: Corners) => void): void { for (const side of VOXEL_SIDES) { if ((sides & SIDE_BITS[side]) !== 0) { @@ -109,11 +188,14 @@ function pictureUvs(cell: UvCell, uvs: Uvs): Uvs { const CORNERS = 4 const FIRST_CAPACITY_FACES = 4096 -/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colour. */ +/** Faces gathered for one geometry, each with its own corners, so every face keeps its own colours. */ class FaceSoup { private positions: Float32Array = new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) private uvs: Float32Array | null private colors: Float32Array | null + // Whether each face is split along its other diagonal, as Minecraft splits one whose darker corners lie on the first, + // so the shading runs along the face and not across a crease. + private flipped: Uint8Array = new Uint8Array(FIRST_CAPACITY_FACES) private faces = 0 constructor(textured: boolean) { @@ -121,7 +203,8 @@ class FaceSoup { this.colors = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) : null } - add(origin: Color, corners: Corners, uvs: Uvs | null, color: Color | null): void { + /** Adds a face, with a colour for each corner, or none. */ + add(origin: Color, corners: Corners, uvs: Uvs | null, colors: readonly Color[] | null): void { this.reserveOne() const first = this.faces * CORNERS for (let corner = 0; corner < CORNERS; corner++) { @@ -133,10 +216,11 @@ class FaceSoup { this.uvs[vertex * 2] = uvs[corner][0] this.uvs[vertex * 2 + 1] = uvs[corner][1] } - if (this.colors !== null && color !== null) { - this.colors.set(color, vertex * 3) + if (this.colors !== null && colors !== null) { + this.colors.set(colors[corner], vertex * 3) } } + this.flipped[this.faces] = colors !== null && sum(colors[0]) + sum(colors[2]) < sum(colors[1]) + sum(colors[3]) ? 1 : 0 this.faces++ } @@ -155,7 +239,9 @@ class FaceSoup { const indices = new Uint32Array(this.faces * 6) for (let face = 0; face < this.faces; face++) { const first = face * CORNERS - indices.set([first, first + 1, first + 2, first, first + 2, first + 3], face * 6) + const split = + this.flipped[face] === 1 ? [first + 1, first + 2, first + 3, first + 1, first + 3, first] : [first, first + 1, first + 2, first, first + 2, first + 3] + indices.set(split, face * 6) } geometry.setIndex(new BufferAttribute(indices, 1)) return geometry @@ -168,9 +254,16 @@ class FaceSoup { this.positions = grown(this.positions) this.uvs = this.uvs === null ? null : grown(this.uvs) this.colors = this.colors === null ? null : grown(this.colors) + const flipped = new Uint8Array(this.flipped.length * 2) + flipped.set(this.flipped) + this.flipped = flipped } } +function sum(color: Color): number { + return color[0] + color[1] + color[2] +} + function grown(values: Float32Array): Float32Array { const bigger = new Float32Array(values.length * 2) bigger.set(values)