mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 16:25:36 +00:00
Draw trees in the studio's 3D world as whole blocks
Each column carried only its highest solid block, so a tree's leaves stood as a pillar down to the ground. The ground is now the terrain's top, and the solid blocks above it go to the studio as a list per column. The 3D world draws them as cubes and leaves out the faces that touch the ground or each other. The 2D map still colours and shades a column by its highest block.
This commit is contained in:
1 parent
55f6a06f9f
commit
4e46eb4a6a
17 files changed
+457
-57
No files matched your search
@@ -36,8 +36,10 @@ import java.util.function.Function;
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
|
||||
* i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4
|
||||
* f32 heights[grid²], when the header says so | f32 pickNoise[grid²], when the header says so
|
||||
* i16 ground[grid²] | padding to 4 | i16 cover[grid²], when the header names blocks
|
||||
* 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
|
||||
* </pre>
|
||||
* {@code raised} is the sum of the raised counts, which the header also holds.
|
||||
* 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.
|
||||
@@ -56,15 +58,16 @@ final class MapTileEncoding {
|
||||
boolean hasHeights = tile.heights() != null;
|
||||
boolean hasPickNoise = tile.pickNoise() != null;
|
||||
MapTile.Blocks blocks = tile.blocks();
|
||||
int raised = blocks == null ? 0 : blocks.raised().length;
|
||||
byte[] header = gson.toJson(new Header(tile.size(), tile.blocksPerPixel(), tile.subjectKind(), tile.labels(),
|
||||
hasHeights, hasPickNoise, blocks == null ? null : statesPlayersSee(blocks.names(), pluginLooks)))
|
||||
hasHeights, hasPickNoise, blocks == null ? null : statesPlayersSee(blocks.names(), pluginLooks), raised))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
int cells = tile.gridSize() * tile.gridSize();
|
||||
int length = aligned(Integer.BYTES + header.length)
|
||||
+ aligned(cells * Short.BYTES) * 2
|
||||
+ (hasHeights ? cells * Float.BYTES : 0)
|
||||
+ (hasPickNoise ? cells * Float.BYTES : 0)
|
||||
+ (blocks == null ? 0 : aligned(cells * Short.BYTES) * 2);
|
||||
+ (blocks == null ? 0 : aligned(cells * Short.BYTES) * 3 + aligned(raised * Short.BYTES) * 2);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header);
|
||||
align(buffer);
|
||||
@@ -81,6 +84,9 @@ final class MapTileEncoding {
|
||||
if (blocks != null) {
|
||||
putShorts(buffer, blocks.ground());
|
||||
putShorts(buffer, blocks.cover());
|
||||
putShorts(buffer, blocks.raisedCounts());
|
||||
putShorts(buffer, blocks.raisedY());
|
||||
putShorts(buffer, blocks.raised());
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
@@ -105,6 +111,6 @@ final class MapTileEncoding {
|
||||
}
|
||||
|
||||
private record Header(int size, double blocksPerPixel, MapLabel.Kind subjectKind, List<MapLabel> labels,
|
||||
boolean heights, boolean pickNoise, List<String> blocks) {
|
||||
boolean heights, boolean pickNoise, List<String> blocks, int raised) {
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
package art.arcane.iris.core.studio.map;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/** What lies on top of the world's columns, from one {@link BlockSource}. */
|
||||
@FunctionalInterface
|
||||
interface ColumnTops {
|
||||
@@ -26,11 +28,47 @@ interface ColumnTops {
|
||||
/**
|
||||
* The top of one column.
|
||||
*
|
||||
* @param groundY the height of its ground block above the dimension's bottom
|
||||
* @param groundY the height of its ground block above the dimension's bottom: the terrain's top, under what stands
|
||||
* on it
|
||||
* @param ground the ground block's key, or null where the column holds no ground
|
||||
* @param cover the key of the block standing on the ground, such as grass or a layer of snow, or null for none
|
||||
* @param raised the solid blocks above the ground, such as a tree's wood and leaves
|
||||
*/
|
||||
record ColumnTop(int groundY, String ground, String cover) {
|
||||
static final ColumnTop NOTHING = new ColumnTop(0, null, null);
|
||||
record ColumnTop(int groundY, String ground, String cover, Raised raised) {
|
||||
static final ColumnTop NOTHING = new ColumnTop(0, null, null, Raised.NONE);
|
||||
|
||||
ColumnTop(int groundY, String ground, String cover) {
|
||||
this(groundY, ground, cover, Raised.NONE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The solid blocks above a column's ground, highest first, with the gaps between them left out. Kept as two arrays,
|
||||
* as a forest's chunk holds over a thousand of them.
|
||||
*
|
||||
* @param ys each block's height above the dimension's bottom
|
||||
* @param blocks each block's key
|
||||
*/
|
||||
record Raised(short[] ys, String[] blocks) {
|
||||
static final Raised NONE = new Raised(new short[0], new String[0]);
|
||||
|
||||
int count() {
|
||||
return ys.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof Raised raised && Arrays.equals(ys, raised.ys) && Arrays.equals(blocks, raised.blocks);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return 31 * Arrays.hashCode(ys) + Arrays.hashCode(blocks);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Raised" + Arrays.toString(ys) + Arrays.toString(blocks);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,14 @@ import art.arcane.iris.util.project.context.IrisContext;
|
||||
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.shorts.ShortArrayList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
/**
|
||||
@@ -45,8 +49,10 @@ final class GeneratedChunks implements ColumnTops {
|
||||
private static final int CHUNK_SHIFT = 4;
|
||||
private static final int BLOCKS_ACROSS = 1 << CHUNK_SHIFT;
|
||||
private static final int CHUNK_MASK = BLOCKS_ACROSS - 1;
|
||||
// A chunk's top is about 5 KB, so this many stay under 50 MB.
|
||||
private static final int MOST_CHUNKS_KEPT = 8192;
|
||||
// A chunk's top is about 5 KB, and each block raised over its ground adds a height and a shared key.
|
||||
private static final int CHUNK_TOP_BYTES = 5 * 1024;
|
||||
private static final int RAISED_BLOCK_BYTES = Short.BYTES + Integer.BYTES;
|
||||
private static final long MOST_BYTES_KEPT = 64L * 1024 * 1024;
|
||||
private static final String LEASE_NAME = "studio_block_preview";
|
||||
|
||||
private final Engine engine;
|
||||
@@ -55,7 +61,10 @@ final class GeneratedChunks implements ColumnTops {
|
||||
|
||||
GeneratedChunks(Engine engine) {
|
||||
this.engine = engine;
|
||||
this.tops = Caffeine.newBuilder().maximumSize(MOST_CHUNKS_KEPT).build(this::generate);
|
||||
this.tops = Caffeine.newBuilder()
|
||||
.maximumWeight(MOST_BYTES_KEPT)
|
||||
.weigher((Long key, ChunkTop top) -> top.bytes())
|
||||
.build(this::generate);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -74,7 +83,8 @@ final class GeneratedChunks implements ColumnTops {
|
||||
IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) {
|
||||
engine.getGeneration().generate(chunkX << CHUNK_SHIFT, chunkZ << CHUNK_SHIFT, blocks, biomes, false, lease.sessionId());
|
||||
}
|
||||
return new ChunkTop(topsOf(blocks, this::seenByPlayers));
|
||||
IntBinaryOperator terrainY = (x, z) -> engine.getHeight((chunkX << CHUNK_SHIFT) + x, (chunkZ << CHUNK_SHIFT) + z, true);
|
||||
return new ChunkTop(topsOf(blocks, terrainY, this::seenByPlayers));
|
||||
}
|
||||
|
||||
// A plugin's block can be solid on the server where players see grass they walk through.
|
||||
@@ -93,43 +103,77 @@ final class GeneratedChunks implements ColumnTops {
|
||||
}
|
||||
|
||||
private record ChunkTop(ColumnTop[] columns) {
|
||||
int bytes() {
|
||||
int raisedBlocks = 0;
|
||||
for (ColumnTop column : columns) {
|
||||
raisedBlocks += column.raised().count();
|
||||
}
|
||||
return CHUNK_TOP_BYTES + raisedBlocks * RAISED_BLOCK_BYTES;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The top of each column of a chunk's blocks, row by row from the north west.
|
||||
*
|
||||
* @param seenByPlayers the state players see in place of a block, which decides whether it is ground; the block
|
||||
* @param terrainY the height of the terrain's top block in each column, by its x and z in the chunk, which
|
||||
* the blocks above stand on
|
||||
* @param seenByPlayers the state players see in place of a block, which decides whether it is solid; the block
|
||||
* itself for all but a plugin's
|
||||
*/
|
||||
static ColumnTop[] topsOf(Hunk<PlatformBlockState> blocks, UnaryOperator<PlatformBlockState> seenByPlayers) {
|
||||
static ColumnTop[] topsOf(Hunk<PlatformBlockState> blocks, IntBinaryOperator terrainY, UnaryOperator<PlatformBlockState> seenByPlayers) {
|
||||
ColumnTop[] columns = new ColumnTop[BLOCKS_ACROSS * BLOCKS_ACROSS];
|
||||
for (int z = 0; z < BLOCKS_ACROSS; z++) {
|
||||
for (int x = 0; x < BLOCKS_ACROSS; x++) {
|
||||
columns[z * BLOCKS_ACROSS + x] = topOf(blocks, x, z, seenByPlayers);
|
||||
columns[z * BLOCKS_ACROSS + x] = topOf(blocks, x, z, terrainY.applyAsInt(x, z), seenByPlayers);
|
||||
}
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
// The ground is the highest block something can stand on, so a tree's leaves and a roof count; what stands on it
|
||||
// without being ground, such as grass or a layer of snow, is its cover.
|
||||
private static ColumnTop topOf(Hunk<PlatformBlockState> blocks, int x, int z, UnaryOperator<PlatformBlockState> seenByPlayers) {
|
||||
// The ground is the highest solid block at or under the terrain's top, so a cave open to the sky lowers it. Solid
|
||||
// blocks above it, such as a tree, are raised; what stands on the ground without being solid, such as grass or a
|
||||
// layer of snow, is its cover. A column with nothing solid under its raised blocks takes the highest as its ground.
|
||||
private static ColumnTop topOf(Hunk<PlatformBlockState> blocks, int x, int z, int terrainY, UnaryOperator<PlatformBlockState> seenByPlayers) {
|
||||
RaisedBlocks raised = new RaisedBlocks();
|
||||
for (int y = blocks.getHeight() - 1; y >= 0; y--) {
|
||||
PlatformBlockState block = blocks.get(x, y, z);
|
||||
if (block == null || !isGround(seenByPlayers.apply(block))) {
|
||||
if (block == null || !isSolid(seenByPlayers.apply(block))) {
|
||||
continue;
|
||||
}
|
||||
PlatformBlockState above = y + 1 < blocks.getHeight() ? blocks.get(x, y + 1, z) : null;
|
||||
return new ColumnTop(y, block.key(), isCover(above) ? above.key() : null);
|
||||
if (y > terrainY) {
|
||||
raised.add(y, block.key());
|
||||
continue;
|
||||
}
|
||||
return new ColumnTop(y, block.key(), coverOn(blocks, x, y, z, seenByPlayers), raised.toRaised());
|
||||
}
|
||||
return ColumnTop.NOTHING;
|
||||
return raised.isEmpty() ? ColumnTop.NOTHING : topOf(blocks, x, z, blocks.getHeight(), seenByPlayers);
|
||||
}
|
||||
|
||||
private static boolean isGround(PlatformBlockState block) {
|
||||
private static String coverOn(Hunk<PlatformBlockState> blocks, int x, int groundY, int z, UnaryOperator<PlatformBlockState> seenByPlayers) {
|
||||
PlatformBlockState above = groundY + 1 < blocks.getHeight() ? blocks.get(x, groundY + 1, z) : null;
|
||||
boolean isCover = above != null && !above.isAir() && !above.isFluid() && !isSolid(seenByPlayers.apply(above));
|
||||
return isCover ? above.key() : null;
|
||||
}
|
||||
|
||||
private static boolean isSolid(PlatformBlockState block) {
|
||||
return !block.isAir() && !block.isFluid() && block.isSolid();
|
||||
}
|
||||
|
||||
private static boolean isCover(PlatformBlockState block) {
|
||||
return block != null && !block.isAir() && !block.isFluid();
|
||||
private static final class RaisedBlocks {
|
||||
private final ShortArrayList ys = new ShortArrayList();
|
||||
private final List<String> blocks = new ArrayList<>();
|
||||
|
||||
void add(int y, String block) {
|
||||
ys.add((short) y);
|
||||
blocks.add(block);
|
||||
}
|
||||
|
||||
boolean isEmpty() {
|
||||
return blocks.isEmpty();
|
||||
}
|
||||
|
||||
Raised toRaised() {
|
||||
return isEmpty() ? Raised.NONE : new Raised(ys.toShortArray(), blocks.toArray(String[]::new));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,11 +40,14 @@ public record MapTile(int size, double blocksPerPixel, MapLabel.Kind subjectKind
|
||||
/**
|
||||
* The top of each cell's column.
|
||||
*
|
||||
* @param names the block keys the grids index
|
||||
* @param ground each cell's ground block, or {@link #NO_BLOCK} where the column holds none
|
||||
* @param cover the block standing on each cell's ground, such as grass, or {@link #NO_BLOCK}
|
||||
* @param names the block keys the grids index
|
||||
* @param ground each cell's ground block, the terrain's top, or {@link #NO_BLOCK} where the column holds none
|
||||
* @param cover the block standing on each cell's ground, such as grass, or {@link #NO_BLOCK}
|
||||
* @param raisedCounts how many solid blocks stand above each cell's ground, such as a tree's wood and leaves
|
||||
* @param raisedY the height of each raised block, cell after cell and each cell's highest first
|
||||
* @param raised each raised block, in the order of {@code raisedY}
|
||||
*/
|
||||
public record Blocks(List<String> names, short[] ground, short[] cover) {
|
||||
public record Blocks(List<String> names, short[] ground, short[] cover, short[] raisedCounts, short[] raisedY, short[] raised) {
|
||||
public static final short NO_BLOCK = -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import art.arcane.iris.engine.framework.render.RenderType;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.util.project.stream.ProceduralStream;
|
||||
import it.unimi.dsi.fastutil.shorts.ShortArrayList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -73,8 +74,8 @@ public final class MapTileRenderer {
|
||||
|
||||
/**
|
||||
* {@code tile}, drawn from ({@code startX}, {@code startZ}), with the block on top of each of its columns from
|
||||
* {@code source}. Where the tile carries heights they become the heights of that ground, which is the terrain's
|
||||
* with what generation put on it.
|
||||
* {@code source}, and the solid blocks raised above it. Where the tile carries heights they become the heights of
|
||||
* that ground: the terrain's top as generated, under what stands on it.
|
||||
*
|
||||
* @throws IllegalArgumentException when the tile is coarser than the source is drawn at
|
||||
* @throws CancellationException as soon as {@code cancelled} answers true
|
||||
@@ -90,6 +91,9 @@ public final class MapTileRenderer {
|
||||
int cells = grid.size() * grid.size();
|
||||
short[] ground = new short[cells];
|
||||
short[] cover = new short[cells];
|
||||
short[] raisedCounts = new short[cells];
|
||||
ShortArrayList raisedY = new ShortArrayList();
|
||||
ShortArrayList raised = new ShortArrayList();
|
||||
float[] heights = tile.heights() == null ? null : new float[cells];
|
||||
BlockNames names = new BlockNames();
|
||||
for (int gridZ = 0; gridZ < grid.size(); gridZ++) {
|
||||
@@ -100,12 +104,19 @@ public final class MapTileRenderer {
|
||||
ColumnTops.ColumnTop top = tops.at((int) Math.floor(grid.worldX(gridX)), worldZ);
|
||||
ground[cell] = names.indexOf(top.ground());
|
||||
cover[cell] = names.indexOf(top.cover());
|
||||
ColumnTops.Raised raisedHere = top.raised();
|
||||
raisedCounts[cell] = (short) raisedHere.count();
|
||||
raisedY.addElements(raisedY.size(), raisedHere.ys());
|
||||
for (String block : raisedHere.blocks()) {
|
||||
raised.add(names.indexOf(block));
|
||||
}
|
||||
if (heights != null) {
|
||||
heights[cell] = top.groundY();
|
||||
}
|
||||
}
|
||||
}
|
||||
return tile.withBlocks(new MapTile.Blocks(names.names(), ground, cover), heights);
|
||||
MapTile.Blocks blocks = new MapTile.Blocks(names.names(), ground, cover, raisedCounts, raisedY.toShortArray(), raised.toShortArray());
|
||||
return tile.withBlocks(blocks, heights);
|
||||
}
|
||||
|
||||
private ColumnTops topsOf(BlockSource source) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.project.hunk.Hunk;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.function.IntBinaryOperator;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@@ -11,38 +12,84 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class GeneratedChunksTest {
|
||||
private static final int HEIGHT = 8;
|
||||
private static final int HEIGHT = 12;
|
||||
private static final PlatformBlockState STONE = block("minecraft:stone", true);
|
||||
private static final PlatformBlockState POPPY = block("minecraft:poppy", false);
|
||||
private static final PlatformBlockState LOG = block("minecraft:oak_log", true);
|
||||
private static final PlatformBlockState LEAVES = block("minecraft:oak_leaves", true);
|
||||
private static final PlatformBlockState TRIPWIRE = block("minecraft:tripwire", false);
|
||||
// A plugin's grass: solid on the server, a tripwire to players.
|
||||
private static final PlatformBlockState PLUGIN_GRASS = block("craftengine:custom_7", true);
|
||||
|
||||
@Test
|
||||
public void theGroundIsTheHighestSolidBlockAndWhatStandsOnItItsCover() {
|
||||
public void theGroundIsTheTerrainsTopAndWhatStandsOnItItsCover() {
|
||||
Hunk<PlatformBlockState> blocks = Hunk.newArrayHunk(16, HEIGHT, 16);
|
||||
blocks.set(0, 3, 0, STONE);
|
||||
blocks.set(0, 4, 0, POPPY);
|
||||
blocks.set(1, 2, 0, STONE);
|
||||
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, UnaryOperator.identity());
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, terrainAt(3), UnaryOperator.identity());
|
||||
|
||||
assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", "minecraft:poppy"), tops[0]);
|
||||
assertEquals(new ColumnTops.ColumnTop(2, "minecraft:stone", null), tops[1]);
|
||||
assertEquals(ColumnTops.ColumnTop.NOTHING, tops[2]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aTreeIsRaisedOverTheGroundItStandsOnInsteadOfBeingTheGround() {
|
||||
Hunk<PlatformBlockState> blocks = Hunk.newArrayHunk(16, HEIGHT, 16);
|
||||
blocks.set(0, 3, 0, STONE);
|
||||
blocks.set(0, 4, 0, LOG);
|
||||
blocks.set(0, 5, 0, LOG);
|
||||
blocks.set(0, 6, 0, LEAVES);
|
||||
blocks.set(1, 3, 0, STONE);
|
||||
blocks.set(1, 4, 0, POPPY);
|
||||
blocks.set(1, 6, 0, LEAVES);
|
||||
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, terrainAt(3), UnaryOperator.identity());
|
||||
|
||||
ColumnTops.Raised trunk = new ColumnTops.Raised(new short[]{6, 5, 4}, new String[]{"minecraft:oak_leaves", "minecraft:oak_log", "minecraft:oak_log"});
|
||||
assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", null, trunk), tops[0]);
|
||||
ColumnTops.Raised canopy = new ColumnTops.Raised(new short[]{6}, new String[]{"minecraft:oak_leaves"});
|
||||
assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", "minecraft:poppy", canopy), tops[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aCaveOpenToTheSkyLowersTheGround() {
|
||||
Hunk<PlatformBlockState> blocks = Hunk.newArrayHunk(16, HEIGHT, 16);
|
||||
blocks.set(0, 1, 0, STONE);
|
||||
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, terrainAt(3), UnaryOperator.identity());
|
||||
|
||||
assertEquals(new ColumnTops.ColumnTop(1, "minecraft:stone", null), tops[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void blocksWithNothingSolidUnderThemAreTheGround() {
|
||||
Hunk<PlatformBlockState> blocks = Hunk.newArrayHunk(16, HEIGHT, 16);
|
||||
blocks.set(0, 8, 0, STONE);
|
||||
blocks.set(0, 9, 0, STONE);
|
||||
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, terrainAt(3), UnaryOperator.identity());
|
||||
|
||||
assertEquals(new ColumnTops.ColumnTop(9, "minecraft:stone", null), tops[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPluginBlockPlayersWalkThroughIsCoverThoughTheServerHoldsItSolid() {
|
||||
Hunk<PlatformBlockState> blocks = Hunk.newArrayHunk(16, HEIGHT, 16);
|
||||
blocks.set(0, 3, 0, STONE);
|
||||
blocks.set(0, 4, 0, PLUGIN_GRASS);
|
||||
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, block -> block == PLUGIN_GRASS ? TRIPWIRE : block);
|
||||
ColumnTops.ColumnTop[] tops = GeneratedChunks.topsOf(blocks, terrainAt(3), block -> block == PLUGIN_GRASS ? TRIPWIRE : block);
|
||||
|
||||
assertEquals(new ColumnTops.ColumnTop(3, "minecraft:stone", "craftengine:custom_7"), tops[0]);
|
||||
}
|
||||
|
||||
private static IntBinaryOperator terrainAt(int y) {
|
||||
return (x, z) -> y;
|
||||
}
|
||||
|
||||
private static PlatformBlockState block(String key, boolean solid) {
|
||||
PlatformBlockState block = mock(PlatformBlockState.class);
|
||||
when(block.key()).thenReturn(key);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LabelKind, MapLabel, MapTile } from './types'
|
||||
import type { LabelKind, MapLabel, MapTile, TileBlocks } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
@@ -11,6 +11,8 @@ interface TileHeader {
|
||||
pickNoise: boolean
|
||||
/** The blocks the ground and cover grids index; absent or null on a tile without them. */
|
||||
blocks?: string[] | null
|
||||
/** How many blocks are raised over the ground of all cells together. */
|
||||
raised?: number
|
||||
}
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
@@ -19,8 +21,8 @@ function aligned(bytes: number): number {
|
||||
|
||||
/**
|
||||
* Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject,
|
||||
* region, height, pick noise, ground and cover grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
|
||||
* not copies.
|
||||
* region, height, pick noise, ground, cover and raised block grids, each starting on a multiple of 4 bytes. The grids
|
||||
* are views into the buffer, not copies.
|
||||
*/
|
||||
export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const view = new DataView(buffer)
|
||||
@@ -33,7 +35,6 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT)
|
||||
const pickNoiseAt = heightsAt + (header.heights ? cells * Float32Array.BYTES_PER_ELEMENT : 0)
|
||||
const groundAt = pickNoiseAt + (header.pickNoise ? cells * Float32Array.BYTES_PER_ELEMENT : 0)
|
||||
const coverAt = aligned(groundAt + cells * Int16Array.BYTES_PER_ELEMENT)
|
||||
return {
|
||||
size: header.size,
|
||||
blocksPerPixel: header.blocksPerPixel,
|
||||
@@ -43,13 +44,37 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
regions: new Int16Array(buffer, regionsAt, cells),
|
||||
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null,
|
||||
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null,
|
||||
blocks:
|
||||
header.blocks == null
|
||||
? null
|
||||
: { names: header.blocks, ground: new Int16Array(buffer, groundAt, cells), cover: new Int16Array(buffer, coverAt, cells), colors: [], looks: [], covers: [] }
|
||||
blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number): TileBlocks {
|
||||
const gridBytes = aligned(cells * Int16Array.BYTES_PER_ELEMENT)
|
||||
const coverAt = groundAt + gridBytes
|
||||
const raisedCountsAt = coverAt + gridBytes
|
||||
const raisedYAt = raisedCountsAt + gridBytes
|
||||
const raisedAt = aligned(raisedYAt + raisedCount * Int16Array.BYTES_PER_ELEMENT)
|
||||
return {
|
||||
names,
|
||||
ground: new Int16Array(buffer, groundAt, cells),
|
||||
cover: new Int16Array(buffer, coverAt, cells),
|
||||
raisedStart: startsOf(new Int16Array(buffer, raisedCountsAt, cells)),
|
||||
raisedY: new Int16Array(buffer, raisedYAt, raisedCount),
|
||||
raised: new Int16Array(buffer, raisedAt, raisedCount),
|
||||
colors: [],
|
||||
looks: [],
|
||||
covers: []
|
||||
}
|
||||
}
|
||||
|
||||
function startsOf(counts: Int16Array): Int32Array {
|
||||
const starts = new Int32Array(counts.length + 1)
|
||||
for (let cell = 0; cell < counts.length; cell++) {
|
||||
starts[cell + 1] = starts[cell] + counts[cell]
|
||||
}
|
||||
return starts
|
||||
}
|
||||
|
||||
/** The grid index of a pixel; pixel coordinates run from -1 to size, the ring being the neighbours'. */
|
||||
export function gridIndex(tile: MapTile, pixelX: number, pixelZ: number): number {
|
||||
return (pixelZ + 1) * (tile.size + 2) + pixelX + 1
|
||||
|
||||
@@ -344,7 +344,10 @@ export interface MapTile {
|
||||
/** Where a tile's blocks come from: the chunks the server generates in memory. */
|
||||
export type BlockSource = 'generated'
|
||||
|
||||
/** The top of each cell's column: its ground block, and the block standing on it, such as grass. */
|
||||
/**
|
||||
* The top of each cell's column: its ground block, the terrain's top; the block standing on it, such as grass; and the
|
||||
* solid blocks raised above it, such as a tree's wood and leaves.
|
||||
*/
|
||||
export interface TileBlocks {
|
||||
/** The block states the grids index, as BlockState keys. */
|
||||
names: string[]
|
||||
@@ -352,6 +355,12 @@ export interface TileBlocks {
|
||||
ground: Int16Array
|
||||
/** {@link NO_BLOCK} where nothing stands on the ground. */
|
||||
cover: Int16Array
|
||||
/** Where each cell's raised blocks start in {@link raisedY} and {@link raised}, with one more entry for where the last cell's end. */
|
||||
raisedStart: Int32Array
|
||||
/** The Y of each raised block, cell after cell and each cell's highest first. */
|
||||
raisedY: Int16Array
|
||||
/** Each raised block, in the order of {@link raisedY}. */
|
||||
raised: Int16Array
|
||||
/** The colour of each named block from above, as 0xRRGGBB; the tile source fills it in. */
|
||||
colors: number[]
|
||||
/** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeTile, gridIndex } from '../bridge/tileDecoding'
|
||||
import type { MapLabel, MapTile } from '../bridge/types'
|
||||
import type { MapLabel, MapTile, TileBlocks } from '../bridge/types'
|
||||
import { countShares, heightBandShares } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors'
|
||||
import { arrowCorners } from './playerArrow'
|
||||
@@ -57,7 +57,42 @@ function encode(size: number, withHeights: boolean, withPickNoise = false): Arra
|
||||
return buffer
|
||||
}
|
||||
|
||||
function nothingRaised(cells: number): Pick<TileBlocks, 'raisedStart' | 'raisedY' | 'raised'> {
|
||||
return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0) }
|
||||
}
|
||||
|
||||
/** A tile of one pixel with its blocks as the bridge sends them: ground, cover and the raised blocks' counts, heights and blocks. */
|
||||
function encodeBlocks(raisedCounts: number[], raisedY: number[], raised: number[]): ArrayBuffer {
|
||||
const size = 1
|
||||
const cells = (size + 2) ** 2
|
||||
const header = new TextEncoder().encode(
|
||||
JSON.stringify({ size, blocksPerPixel: 1, subjectKind: 'BIOME', labels: [PLAINS], heights: false, pickNoise: false, blocks: ['stone', 'leaves', 'log'], raised: raised.length })
|
||||
)
|
||||
const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
|
||||
const grid = align(cells * 2)
|
||||
const groundAt = align(4 + header.length) + grid * 2
|
||||
const raisedYAt = groundAt + grid * 3
|
||||
const raisedAt = align(raisedYAt + raised.length * 2)
|
||||
const buffer = new ArrayBuffer(raisedAt + align(raised.length * 2))
|
||||
new DataView(buffer).setUint32(0, header.length, true)
|
||||
new Uint8Array(buffer, 4).set(header)
|
||||
new Int16Array(buffer, groundAt + grid, cells).fill(-1)
|
||||
new Int16Array(buffer, groundAt + grid * 2, cells).set(raisedCounts)
|
||||
new Int16Array(buffer, raisedYAt, raised.length).set(raisedY)
|
||||
new Int16Array(buffer, raisedAt, raised.length).set(raised)
|
||||
return buffer
|
||||
}
|
||||
|
||||
describe('tile decoding', () => {
|
||||
it('reads the raised blocks of each cell after the cover grid', () => {
|
||||
const blocks = decodeTile(encodeBlocks([0, 0, 0, 0, 2, 0, 0, 1, 0], [70, 69, 66], [1, 2, 1])).blocks!
|
||||
|
||||
expect([...blocks.raisedStart]).toEqual([0, 0, 0, 0, 0, 2, 2, 2, 3, 3])
|
||||
expect([...blocks.raisedY]).toEqual([70, 69, 66])
|
||||
expect([...blocks.raised]).toEqual([1, 2, 1])
|
||||
expect(blocks.cover[4]).toBe(-1)
|
||||
})
|
||||
|
||||
it('reads the header and views each grid where the bridge put it', () => {
|
||||
const tile = decodeTile(encode(3, true))
|
||||
|
||||
@@ -138,13 +173,35 @@ describe('tile style', () => {
|
||||
const cells = tile.subjects.length
|
||||
const cover = new Int16Array(cells).fill(-1)
|
||||
cover[gridIndex(tile, 3, 3)] = 1
|
||||
const blocks = { names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [], covers: [] }
|
||||
const blocks = { ...nothingRaised(cells), names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [], covers: [] }
|
||||
const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
|
||||
|
||||
expect(pixel(pixels, 4, 0, 0)).toBe(0x808080)
|
||||
expect(pixel(pixels, 4, 3, 3)).toBe(0xff0000)
|
||||
})
|
||||
|
||||
it('paints a column with blocks raised over its ground in the colour of the highest', () => {
|
||||
const tile = splitTile()
|
||||
const cells = tile.subjects.length
|
||||
const raisedStart = new Int32Array(cells + 1)
|
||||
raisedStart.fill(2, gridIndex(tile, 3, 3) + 1)
|
||||
const blocks = {
|
||||
names: ['stone', 'leaves', 'log'],
|
||||
ground: new Int16Array(cells).fill(0),
|
||||
cover: new Int16Array(cells).fill(-1),
|
||||
raisedStart,
|
||||
raisedY: Int16Array.of(70, 69),
|
||||
raised: Int16Array.of(1, 2),
|
||||
colors: [0x808080, 0x00ff00, 0x654321],
|
||||
looks: [],
|
||||
covers: []
|
||||
}
|
||||
const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
|
||||
|
||||
expect(pixel(pixels, 4, 0, 0)).toBe(0x808080)
|
||||
expect(pixel(pixels, 4, 3, 3)).toBe(0x00ff00)
|
||||
})
|
||||
|
||||
it('keeps the label colours of a tile without blocks', () => {
|
||||
expect(pixel(stylePixels(splitTile(), { ...FLAT, byBlock: true }), 4, 0, 0)).toBe(PLAINS.color)
|
||||
})
|
||||
|
||||
@@ -39,7 +39,7 @@ export function mapTileSource(client: BridgeClient, tileSize: number, art: Block
|
||||
return tile
|
||||
},
|
||||
bytesOf: (tile) =>
|
||||
tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + tile.size * tile.size * 4,
|
||||
tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + (tile.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.byteLength ?? 0) * 2 + tile.size * tile.size * 4,
|
||||
styleKey,
|
||||
pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size)
|
||||
}
|
||||
|
||||
@@ -55,10 +55,11 @@ const DARKEST_PICK_SHADE = 0.3
|
||||
|
||||
/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
|
||||
export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> {
|
||||
const { size, heights } = tile
|
||||
const { size } = tile
|
||||
const pixels = new Uint8ClampedArray(size * size * 4)
|
||||
const colors = tile.labels.map((label) => label.color)
|
||||
const blocks = style.byBlock ? tile.blocks : null
|
||||
const heights = blocks === null || tile.heights === null ? tile.heights : heightsSeenFromAbove(tile.heights, blocks)
|
||||
const pickNoise = style.pickDisplay === 'picks' || blocks !== null ? null : tile.pickNoise
|
||||
// The bare noise is read by its brightness, which relief shading would mix up.
|
||||
const shading = style.shading && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise')
|
||||
@@ -93,13 +94,34 @@ function labelColor(colors: number[], index: number): number {
|
||||
return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
|
||||
}
|
||||
|
||||
// What stands on the ground is what is seen from above; ground under the sea shows through its water.
|
||||
// Seen from above, the highest block raised over the ground hides it, and what stands on the ground hides the ground;
|
||||
// what lies under the sea shows through its water.
|
||||
function blockColor(blocks: TileBlocks, cell: number, heights: Float32Array | null, seaLevel: number): number {
|
||||
const top = blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell]
|
||||
const top = blockSeenFromAbove(blocks, cell)
|
||||
const color = top === NO_BLOCK ? UNKNOWN_SUBJECT : blocks.colors[top]
|
||||
return heights !== null && heights[cell] < seaLevel ? blend(color, WATER_SURFACE_COLOR, WATER_OVER_GROUND) : color
|
||||
}
|
||||
|
||||
function blockSeenFromAbove(blocks: TileBlocks, cell: number): number {
|
||||
const highestRaised = blocks.raisedStart[cell]
|
||||
if (highestRaised < blocks.raisedStart[cell + 1]) {
|
||||
return blocks.raised[highestRaised]
|
||||
}
|
||||
return blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell]
|
||||
}
|
||||
|
||||
// The ground's heights with each column's highest raised block in place of its ground, so trees stand out in relief.
|
||||
function heightsSeenFromAbove(groundHeights: Float32Array, blocks: TileBlocks): Float32Array {
|
||||
const heights = Float32Array.from(groundHeights)
|
||||
for (let cell = 0; cell < heights.length; cell++) {
|
||||
const highestRaised = blocks.raisedStart[cell]
|
||||
if (highestRaised < blocks.raisedStart[cell + 1]) {
|
||||
heights[cell] = blocks.raisedY[highestRaised]
|
||||
}
|
||||
}
|
||||
return heights
|
||||
}
|
||||
|
||||
// Where nothing picked the spot, as on an image map, it keeps its colour.
|
||||
function byNoise(color: number, noise: number, display: PickDisplay): number {
|
||||
if (Number.isNaN(noise)) {
|
||||
|
||||
@@ -208,6 +208,7 @@ function sameSpan(span: Span, other: Span | null): boolean {
|
||||
return span.look === null && other !== null && other.look === null && other.top === span.top && other.bottom === span.bottom && other.color === span.color && other.water === span.water
|
||||
}
|
||||
|
||||
function shaded(color: number, light: number): Vec3 {
|
||||
/** A 0xRRGGBB colour in a light, as red, green and blue from 0 to 1. */
|
||||
export function shaded(color: number, light: number): Vec3 {
|
||||
return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light]
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { BlockLook } from './blockLooks'
|
||||
import type { CoverLook } from './coverLooks'
|
||||
import type { TerrainPictures } from './terrainAtlas'
|
||||
import type { TerrainSurface } from './terrainMesh'
|
||||
import type { RaisedBlock, TerrainSurface } from './terrainMesh'
|
||||
import type { ColumnArea } from './terrainTiles'
|
||||
|
||||
const NO_VALUE = Number.NaN
|
||||
const NOTHING_RAISED: readonly RaisedBlock[] = []
|
||||
|
||||
/**
|
||||
* The surface read once into columns: where each column's ground and water faces stand, and its colour. A top face
|
||||
@@ -24,6 +25,8 @@ export class ColumnField {
|
||||
readonly looks: (BlockLook | null)[]
|
||||
/** What stands on each column's ground, or null for nothing that is drawn. */
|
||||
readonly covers: (CoverLook | null)[]
|
||||
/** The solid blocks above each column's ground, highest first, each without a look where the field has no atlas. */
|
||||
readonly raised: (readonly RaisedBlock[])[]
|
||||
/** The atlas of the looks, or null where no column has one. */
|
||||
readonly pictures: TerrainPictures | null
|
||||
/** How low and high the top faces stand, ground and water alike; null where no column has ground. */
|
||||
@@ -41,6 +44,7 @@ export class ColumnField {
|
||||
this.color = new Int32Array(count)
|
||||
this.looks = new Array<BlockLook | null>(count).fill(null)
|
||||
this.covers = new Array<CoverLook | null>(count).fill(null)
|
||||
this.raised = new Array<readonly RaisedBlock[]>(count).fill(NOTHING_RAISED)
|
||||
const hasPictures = surface.pictures !== undefined
|
||||
let anyLook = false
|
||||
let [lowestTop, highestTop] = [Infinity, -Infinity]
|
||||
@@ -59,7 +63,9 @@ export class ColumnField {
|
||||
const look = hasPictures ? (surface.lookAt?.(column, row) ?? null) : null
|
||||
this.looks[index] = look
|
||||
this.covers[index] = hasPictures ? (surface.coverAt?.(column, row) ?? null) : null
|
||||
anyLook ||= look !== null
|
||||
const raised = surface.raisedAt?.(column, row) ?? NOTHING_RAISED
|
||||
this.raised[index] = hasPictures ? raised : raised.map((block) => ({ ...block, look: null }))
|
||||
anyLook ||= look !== null || this.raised[index].some((block) => block.look !== null)
|
||||
lowestTop = Math.min(lowestTop, ground + 1)
|
||||
highestTop = Math.max(highestTop, ground + 1, water === null ? ground : water + 1)
|
||||
}
|
||||
@@ -80,6 +86,15 @@ export class ColumnField {
|
||||
return this.contains(column, row) && !Number.isNaN(this.groundTop[this.indexOf(column, row)])
|
||||
}
|
||||
|
||||
/** Whether the block at {@code y} in the column is the column's ground or a block raised over it; false outside the field. */
|
||||
isSolidAt(column: number, row: number, y: number): boolean {
|
||||
if (!this.hasGround(column, row)) {
|
||||
return false
|
||||
}
|
||||
const index = this.indexOf(column, row)
|
||||
return y < this.groundTop[index] || this.raised[index].some((block) => block.y === y)
|
||||
}
|
||||
|
||||
/** Whether any column has ground. */
|
||||
hasAnyGround(): boolean {
|
||||
return this.groundTop.some((top) => !Number.isNaN(top))
|
||||
|
||||
@@ -3,7 +3,7 @@ import { heightColor } from '../map/heightColors'
|
||||
import type { BlockLook } from './blockLooks'
|
||||
import type { CoverLook } from './coverLooks'
|
||||
import type { TerrainPictures } from './terrainAtlas'
|
||||
import type { TerrainSurface } from './terrainMesh'
|
||||
import type { RaisedBlock, TerrainSurface } from './terrainMesh'
|
||||
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles'
|
||||
|
||||
export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks'
|
||||
@@ -57,6 +57,20 @@ export class MapTerrain implements TerrainSurface {
|
||||
return cover === NO_BLOCK ? null : (this.tile.blocks!.covers[cover] ?? null)
|
||||
}
|
||||
|
||||
raisedAt(column: number, row: number): readonly RaisedBlock[] {
|
||||
const blocks = this.coloring === 'blocks' ? this.tile.blocks : null
|
||||
if (blocks === null) {
|
||||
return []
|
||||
}
|
||||
const cell = this.cellAt(column, row)
|
||||
const raised: RaisedBlock[] = []
|
||||
for (let at = blocks.raisedStart[cell]; at < blocks.raisedStart[cell + 1]; at++) {
|
||||
const block = blocks.raised[at]
|
||||
raised.push({ y: blocks.raisedY[at], color: blocks.colors[block], look: blocks.looks[block] ?? null })
|
||||
}
|
||||
return raised
|
||||
}
|
||||
|
||||
colorAt(column: number, row: number): number {
|
||||
if (this.coloring === 'height') {
|
||||
return heightColor(this.heightAt(column, row), this.fluidHeight)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { FaceLook } from './blockLooks'
|
||||
import type { ColumnField } from './columnField'
|
||||
import { shaded } from './columnFaces'
|
||||
import { FACE_LIGHT } from './coverLooks'
|
||||
import type { Picture, QuadBatch, Vec3 } from './quadBatch'
|
||||
import type { RaisedBlock } from './terrainMesh'
|
||||
import { sunk, tintAt } from './waterTint'
|
||||
|
||||
/** One face of a whole block: the step to the block it touches, and its quad on a block of {@code step} wide. */
|
||||
interface BlockFace {
|
||||
columnStep: number
|
||||
yStep: number
|
||||
rowStep: number
|
||||
light: number
|
||||
/** Which of the block's pictures the face shows, and whether that picture stands upright. */
|
||||
picture: (look: NonNullable<RaisedBlock['look']>) => FaceLook
|
||||
standing: boolean
|
||||
/** The quad's corner, along and up from the block's lowest north west corner; it faces the way up crosses along. */
|
||||
quad: (step: number) => [Vec3, Vec3, Vec3]
|
||||
}
|
||||
|
||||
// A block's bottom shows the picture of its top, as the end of a log does.
|
||||
const BLOCK_FACES: readonly BlockFace[] = [
|
||||
{ columnStep: 0, yStep: 1, rowStep: 0, light: FACE_LIGHT.up, picture: (look) => look.top, standing: false, quad: (step) => [[0, 1, 0], [step, 0, 0], [0, 0, step]] },
|
||||
{ columnStep: 0, yStep: -1, rowStep: 0, light: FACE_LIGHT.down, picture: (look) => look.top, standing: false, quad: (step) => [[0, 0, 0], [0, 0, step], [step, 0, 0]] },
|
||||
{ columnStep: 0, yStep: 0, rowStep: -1, light: FACE_LIGHT.north, picture: (look) => look.side, standing: true, quad: (step) => [[0, 0, 0], [step, 0, 0], [0, 1, 0]] },
|
||||
{ columnStep: 0, yStep: 0, rowStep: 1, light: FACE_LIGHT.south, picture: (look) => look.side, standing: true, quad: (step) => [[step, 0, step], [-step, 0, 0], [0, 1, 0]] },
|
||||
{ columnStep: -1, yStep: 0, rowStep: 0, light: FACE_LIGHT.west, picture: (look) => look.side, standing: true, quad: (step) => [[0, 0, step], [0, 0, -step], [0, 1, 0]] },
|
||||
{ columnStep: 1, yStep: 0, rowStep: 0, light: FACE_LIGHT.east, picture: (look) => look.side, standing: true, quad: (step) => [[step, 0, 0], [0, 0, step], [0, 1, 0]] }
|
||||
]
|
||||
|
||||
/**
|
||||
* The blocks raised above the ground, such as trees, as whole blocks: each face that touches neither the ground nor
|
||||
* another raised block. A face at the field's edge is drawn, as the field next to it is not known here. Blocks under
|
||||
* water sink toward its deep colour as the ground does.
|
||||
*/
|
||||
export function addRaisedFaces(field: ColumnField, batch: QuadBatch): void {
|
||||
const step = field.blocksPerColumn
|
||||
for (let row = 0; row < field.rows; row++) {
|
||||
for (let column = 0; column < field.columns; column++) {
|
||||
const index = field.indexOf(column, row)
|
||||
const water = field.waterTopAt(column, row)
|
||||
for (const block of field.raised[index]) {
|
||||
const corner: Vec3 = [field.originX + column * step, block.y, field.originZ + row * step]
|
||||
for (const face of BLOCK_FACES) {
|
||||
if (field.isSolidAt(column + face.columnStep, row + face.rowStep, block.y + face.yStep)) {
|
||||
continue
|
||||
}
|
||||
addFace(batch, face, corner, step, block, water)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addFace(batch: QuadBatch, face: BlockFace, corner: Vec3, step: number, block: RaisedBlock, water: number | null): void {
|
||||
const [start, along, up] = face.quad(step)
|
||||
const origin: Vec3 = [corner[0] + start[0], corner[1] + start[1], corner[2] + start[2]]
|
||||
const look = block.look === null ? null : face.picture(block.look)
|
||||
const light = shaded(look === null ? block.color : look.tint, face.light)
|
||||
const color = water === null ? light : sunk(light, tintAt(water - (block.y + start[1])))
|
||||
const picture: Picture | null = look === null ? null : { cell: look.cell, standing: face.standing }
|
||||
batch.add(origin, along, up, color, color, picture)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Vector3, type BufferGeometry, type Mesh } from 'three'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildTerrainMesh, type TerrainSurface } from './terrainMesh'
|
||||
import { buildTerrainMesh, type RaisedBlock, type TerrainSurface } from './terrainMesh'
|
||||
import { submergedTint, tintAt } from './waterTint'
|
||||
|
||||
const GROUND = 10
|
||||
@@ -184,3 +184,33 @@ describe('terrain mesh', () => {
|
||||
expect(nothing.object.children).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('raised blocks', () => {
|
||||
const raisedAt = (y: number): RaisedBlock => ({ y, color: RED, look: null })
|
||||
// The faces drawn for the raised blocks, which come after the ground's.
|
||||
const raisedFaces = (raised: TerrainSurface['raisedAt']): ReturnType<typeof faces> =>
|
||||
faces(meshes({ ...dry, raisedAt: raised }).ground.geometry).slice(quads(meshes(dry).ground))
|
||||
|
||||
it('stands a raised block as a whole block, each face looking away from it', () => {
|
||||
const leaf = raisedFaces((column, row) => (column === 2 && row === 2 ? [raisedAt(GROUND + 4)] : []))
|
||||
const middle = new Vector3(102.5, GROUND + 4.5, 202.5)
|
||||
|
||||
expect(leaf).toHaveLength(6)
|
||||
for (const face of leaf) {
|
||||
expect(face.middle.clone().sub(middle).normalize().dot(face.normal)).toBeCloseTo(1)
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves out the faces that touch the ground or another raised block', () => {
|
||||
const tree = raisedFaces((column, row) => {
|
||||
if (column === 2 && row === 1) {
|
||||
return [raisedAt(GROUND + 2), raisedAt(GROUND + 1)]
|
||||
}
|
||||
return column === 2 && row === 2 ? [raisedAt(GROUND + 2)] : []
|
||||
})
|
||||
|
||||
// The trunk's lower block shows four sides, its upper one three and its top, the leaf all but the side on the trunk.
|
||||
expect(tree).toHaveLength(13)
|
||||
expect(tree.some((face) => face.normal.y === -1 && face.middle.y === GROUND + 1)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { groundFaces, waterFaces } from './columnFaces'
|
||||
import { ColumnField } from './columnField'
|
||||
import { coverGeometry } from './coverFaces'
|
||||
import type { CoverLook } from './coverLooks'
|
||||
import { addRaisedFaces } from './raisedFaces'
|
||||
import type { TerrainPictures } from './terrainAtlas'
|
||||
import type { ColumnArea } from './terrainTiles'
|
||||
import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint'
|
||||
@@ -31,6 +32,16 @@ export interface TerrainSurface {
|
||||
lookAt?(column: number, row: number): BlockLook | null
|
||||
/** What stands on the column's ground, such as grass or a flower, or null for nothing that is drawn. */
|
||||
coverAt?(column: number, row: number): CoverLook | null
|
||||
/** The solid blocks above the column's ground, such as a tree's wood and leaves, highest first. */
|
||||
raisedAt?(column: number, row: number): readonly RaisedBlock[]
|
||||
}
|
||||
|
||||
/** A solid block above a column's ground, drawn as a whole block. */
|
||||
export interface RaisedBlock {
|
||||
y: number
|
||||
color: number
|
||||
/** What the block looks like, or null to show its colour. */
|
||||
look: BlockLook | null
|
||||
}
|
||||
|
||||
const CUTOUT_ALPHA = 0.5
|
||||
@@ -45,7 +56,8 @@ export interface TerrainMesh {
|
||||
* The surface as columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft shades
|
||||
* blocks, with the ground under water sunk toward a deep colour and a light sheet of water over it. Sides on the edge reach down to {@code base}, so tiles of ground next to
|
||||
* each other leave no cracks. The columns in {@code holes} are left out, for finer ground to fill. Columns with a look
|
||||
* show their block's textures, one picture to a block face.
|
||||
* show their block's textures, one picture to a block face. Blocks raised above the ground, such as trees, stand as
|
||||
* whole blocks.
|
||||
*/
|
||||
export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainMesh {
|
||||
const field = new ColumnField(surface, holes)
|
||||
@@ -53,7 +65,9 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r
|
||||
if (!field.hasAnyGround()) {
|
||||
return { object: group, field, dispose: () => {} }
|
||||
}
|
||||
const ground = groundFaces(field, base).geometry()
|
||||
const groundBatch = groundFaces(field, base)
|
||||
addRaisedFaces(field, groundBatch)
|
||||
const ground = groundBatch.geometry()
|
||||
const water = waterFaces(field).geometry()
|
||||
const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: field.pictures?.texture ?? null })
|
||||
const waterMaterial = new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide })
|
||||
|
||||
Reference in new issue
Block a user