mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 08:44:50 +00:00
Draw the 3D world's near ground block by block
The near ground was drawn from the top of each column, with the blocks raised above it, so overhangs, the wood under leaves and anything beside a trunk were lost. The server now finds, for each chunk it generates, every block the open air reaches: from the top of the chunk and from beside it above the terrain around, through leaves and water too, so caves closed to the sky stay out. Each block comes with the sides that face that air. Tiles a block a column carry these blocks when asked, and the studio draws each from its model, leaving out a face its model lets a neighbour hide unless that side faces the air. Blocks without a model are cubes of their look or colour; water shows the sides that face the air, and none against plants that grow in it.
This commit is contained in:
1 parent
93d6ffe70e
commit
dccdd8c09d
22 files changed
+975
-42
No files matched your search
@@ -52,6 +52,8 @@ export interface TileRequest {
|
||||
pickNoise: boolean
|
||||
/** Where the tile's blocks come from, or null for a tile without them. */
|
||||
blocks: BlockSource | null
|
||||
/** Whether a tile of a block a pixel with blocks also carries every block seen from the open air. */
|
||||
voxels?: boolean
|
||||
}
|
||||
|
||||
/** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */
|
||||
@@ -141,6 +143,9 @@ export class BridgeClient {
|
||||
})
|
||||
if (request.blocks !== null) {
|
||||
query.set('blocks', request.blocks)
|
||||
if (request.voxels === true) {
|
||||
query.set('voxels', '1')
|
||||
}
|
||||
this.cancelOnAbort(query, signal)
|
||||
}
|
||||
const response = await this.fetch(`tile?${query}`, { signal })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LabelKind, MapLabel, MapTile, TileBlocks } from './types'
|
||||
import type { LabelKind, MapLabel, MapTile, TileBlocks, TileVoxels } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
@@ -13,8 +13,12 @@ interface TileHeader {
|
||||
blocks?: string[] | null
|
||||
/** How many blocks are raised over the ground of all cells together. */
|
||||
raised?: number
|
||||
/** How many blocks can be seen from the open air, or -1 on a tile without them. */
|
||||
voxels?: number
|
||||
}
|
||||
|
||||
const NO_VOXELS = -1
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
}
|
||||
@@ -44,16 +48,17 @@ 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 : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0)
|
||||
blocks: header.blocks == null ? null : decodeBlocks(buffer, groundAt, cells, header.blocks, header.raised ?? 0, header.voxels ?? NO_VOXELS)
|
||||
}
|
||||
}
|
||||
|
||||
function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number): TileBlocks {
|
||||
function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, names: string[], raisedCount: number, voxelCount: 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)
|
||||
const voxelsAt = aligned(raisedAt + raisedCount * Int16Array.BYTES_PER_ELEMENT)
|
||||
return {
|
||||
names,
|
||||
ground: new Int16Array(buffer, groundAt, cells),
|
||||
@@ -61,9 +66,25 @@ function decodeBlocks(buffer: ArrayBuffer, groundAt: number, cells: number, name
|
||||
raisedStart: startsOf(new Int16Array(buffer, raisedCountsAt, cells)),
|
||||
raisedY: new Int16Array(buffer, raisedYAt, raisedCount),
|
||||
raised: new Int16Array(buffer, raisedAt, raisedCount),
|
||||
voxels: voxelCount === NO_VOXELS ? null : decodeVoxels(buffer, voxelsAt, voxelCount),
|
||||
colors: [],
|
||||
looks: [],
|
||||
covers: []
|
||||
covers: [],
|
||||
models: []
|
||||
}
|
||||
}
|
||||
|
||||
function decodeVoxels(buffer: ArrayBuffer, xAt: number, count: number): TileVoxels {
|
||||
const zAt = xAt + aligned(count)
|
||||
const yAt = zAt + aligned(count)
|
||||
const blocksAt = yAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
|
||||
const facesAt = blocksAt + aligned(count * Int16Array.BYTES_PER_ELEMENT)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -361,6 +361,10 @@ export interface TileBlocks {
|
||||
raisedY: Int16Array
|
||||
/** Each raised block, in the order of {@link raisedY}. */
|
||||
raised: Int16Array
|
||||
/** The blocks seen from the open air, where the tile is a block a column and they were asked for; else null. */
|
||||
voxels: TileVoxels | null
|
||||
/** Each named block's model with its pictures placed, for the blocks {@link voxels} names; the tile source fills it in. */
|
||||
models: (CoverLook | null)[]
|
||||
/** 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. */
|
||||
@@ -369,5 +373,24 @@ export interface TileBlocks {
|
||||
covers: (CoverLook | null)[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The blocks of a tile that can be seen from the open air, as the server found them in the chunks it generated, with
|
||||
* the sides of each that face that air.
|
||||
*/
|
||||
export interface TileVoxels {
|
||||
/** Each block's column from the tile's west edge. */
|
||||
x: Uint8Array
|
||||
/** Each block's column from the tile's north edge. */
|
||||
z: Uint8Array
|
||||
y: Int16Array
|
||||
/** Each block's index in the tile's block names. */
|
||||
blocks: Int16Array
|
||||
/** The sides of each block that face the open air, a bit each in {@link VOXEL_SIDES}' order. */
|
||||
faces: Uint8Array
|
||||
}
|
||||
|
||||
/** The order of the sides in {@link TileVoxels.faces}. */
|
||||
export const VOXEL_SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] as const
|
||||
|
||||
export const NO_BLOCK = -1
|
||||
export const NO_LABEL = -1
|
||||
@@ -57,8 +57,8 @@ 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) }
|
||||
function nothingRaised(cells: number): Pick<TileBlocks, 'raisedStart' | 'raisedY' | 'raised' | 'voxels' | 'models'> {
|
||||
return { raisedStart: new Int32Array(cells + 1), raisedY: new Int16Array(0), raised: new Int16Array(0), voxels: null, models: [] }
|
||||
}
|
||||
|
||||
/** A tile of one pixel with its blocks as the bridge sends them: ground, cover and the raised blocks' counts, heights and blocks. */
|
||||
@@ -192,9 +192,11 @@ describe('tile style', () => {
|
||||
raisedStart,
|
||||
raisedY: Int16Array.of(70, 69),
|
||||
raised: Int16Array.of(1, 2),
|
||||
voxels: null,
|
||||
colors: [0x808080, 0x00ff00, 0x654321],
|
||||
looks: [],
|
||||
covers: []
|
||||
covers: [],
|
||||
models: []
|
||||
}
|
||||
const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface TileLayer {
|
||||
pickNoise: boolean
|
||||
/** Where the tiles' blocks come from, or null for tiles without them. */
|
||||
blocks: BlockSource | null
|
||||
/** Whether tiles of a block a pixel with blocks also carry every block seen from the open air, to draw one by one. */
|
||||
voxels?: boolean
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
@@ -24,6 +26,11 @@ export interface TileLayer {
|
||||
const MAP_MOST_BLOCKS_PER_PIXEL = 1
|
||||
const TEXTURED_BLOCKS_PER_PIXEL = 1
|
||||
|
||||
function voxelBytesOf(tile: MapTile): number {
|
||||
const voxels = tile.blocks?.voxels
|
||||
return voxels === null || voxels === undefined ? 0 : voxels.x.byteLength * 3 + voxels.y.byteLength * 2
|
||||
}
|
||||
|
||||
/** Whether the map's tiles this coarse carry blocks. */
|
||||
export function hasBlocksAt(blocksPerPixel: number): boolean {
|
||||
return blocksPerPixel <= MAP_MOST_BLOCKS_PER_PIXEL
|
||||
@@ -36,7 +43,7 @@ export function hasBlocksAt(blocksPerPixel: number): boolean {
|
||||
*/
|
||||
export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt, mostBlocksPerPixel = MAP_MOST_BLOCKS_PER_PIXEL): TileSource<MapTile, TileLayer, TileStyle> {
|
||||
return {
|
||||
layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? ''].join('/'),
|
||||
layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? '', layer.voxels === true].join('/'),
|
||||
fetch: async (address, layer, signal) => {
|
||||
const blocks = layer.blocks !== null && address.blocksPerPixel <= mostBlocksPerPixel ? layer.blocks : null
|
||||
const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal)
|
||||
@@ -46,7 +53,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.blocks?.raisedStart.byteLength ?? 0) + (tile.blocks?.raised.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 + voxelBytesOf(tile) + tile.size * tile.size * 4,
|
||||
styleKey,
|
||||
pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,14 @@ function namesStandingOnGround(blocks: TileBlocks): string[] {
|
||||
return [...standing].map((index) => blocks.names[index])
|
||||
}
|
||||
|
||||
// A tile drawn block by block places the whole models of the blocks it shows.
|
||||
function namesSeenOneByOne(blocks: TileBlocks): string[] {
|
||||
if (blocks.voxels === null) {
|
||||
return []
|
||||
}
|
||||
return [...new Set(blocks.voxels.blocks)].map((index) => blocks.names[index])
|
||||
}
|
||||
|
||||
/** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */
|
||||
export function blockArt(client: BridgeClient, textured: boolean): BlockArt {
|
||||
const images = new BridgeAssets(client, () => {})
|
||||
@@ -33,14 +41,16 @@ export function blockArt(client: BridgeClient, textured: boolean): BlockArt {
|
||||
atlas,
|
||||
paint: async (blocks, withLooks) => {
|
||||
const shownLooks = withLooks ? looks : null
|
||||
const [colorOf, lookOf, coverOf] = await Promise.all([
|
||||
const [colorOf, lookOf, coverOf, modelOf] = await Promise.all([
|
||||
colors.colorsOf(blocks.names),
|
||||
shownLooks?.looksOf(blocks.names) ?? null,
|
||||
shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null
|
||||
shownLooks?.coversOf(namesStandingOnGround(blocks)) ?? null,
|
||||
shownLooks?.coversOf(namesSeenOneByOne(blocks)) ?? null
|
||||
])
|
||||
blocks.colors = blocks.names.map((name) => colorOf.get(name)!)
|
||||
blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null)
|
||||
blocks.covers = coverOf === null ? [] : blocks.names.map((name) => coverOf.get(name) ?? null)
|
||||
blocks.models = modelOf === null ? [] : blocks.names.map((name) => modelOf.get(name) ?? null)
|
||||
},
|
||||
dispose: () => atlas?.dispose()
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ export interface CoverFace {
|
||||
cell: UvCell
|
||||
/** The face's tint in its light, as red, green and blue from 0 to 1. */
|
||||
color: readonly [number, number, number]
|
||||
/** The side whose neighbour, when it is a solid block, hides the face; null when nothing hides it. */
|
||||
cullFace: Direction | null
|
||||
}
|
||||
|
||||
/** A block standing on a column's ground, such as grass, a flower or a layer of snow, as the faces of its model. */
|
||||
@@ -37,7 +39,7 @@ export async function coverLookOf(block: string, model: BlockModel | null, pictu
|
||||
const tint = blockTint(state.name, state.properties, quad.tintIndex)
|
||||
const light = quad.shade ? FACE_LIGHT[quad.facing] : 1
|
||||
const color = [(((tint >> 16) & 0xff) / 255) * light, (((tint >> 8) & 0xff) / 255) * light, ((tint & 0xff) / 255) * light] as const
|
||||
return { corners: quad.corners, uvs: quad.uvs, cell, color }
|
||||
return { corners: quad.corners, uvs: quad.uvs, cell, color, cullFace: quad.cullFace }
|
||||
})
|
||||
)
|
||||
return faces.includes(null) ? null : { faces: faces as CoverFace[] }
|
||||
|
||||
@@ -22,9 +22,11 @@ function tileWithALeaf(): MapTile {
|
||||
raisedStart,
|
||||
raisedY: Int16Array.of(LEAF_Y),
|
||||
raised: Int16Array.of(1),
|
||||
voxels: null,
|
||||
colors: [STONE, LEAVES],
|
||||
looks: [],
|
||||
covers: []
|
||||
covers: [],
|
||||
models: []
|
||||
}
|
||||
return {
|
||||
size: SIZE,
|
||||
|
||||
@@ -4,11 +4,17 @@ import type { BlockLook } from './blockLooks'
|
||||
import type { CoverLook } from './coverLooks'
|
||||
import type { TerrainPictures } from './terrainAtlas'
|
||||
import type { RaisedBlock, TerrainSurface } from './terrainMesh'
|
||||
import type { SurfaceVoxels } from './voxelMesh'
|
||||
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles'
|
||||
|
||||
export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks'
|
||||
|
||||
const UNLABELLED_COLOR = 0x5a5f6b
|
||||
const WATER_NAME = 'minecraft:water'
|
||||
|
||||
function isWater(block: string): boolean {
|
||||
return block === WATER_NAME || block.startsWith(`${WATER_NAME}[`)
|
||||
}
|
||||
|
||||
/**
|
||||
* One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the
|
||||
@@ -73,6 +79,20 @@ export class MapTerrain implements TerrainSurface {
|
||||
return raised
|
||||
}
|
||||
|
||||
voxels(): SurfaceVoxels | null {
|
||||
const blocks = this.coloring === 'blocks' && this.blocksPerColumn === 1 ? this.tile.blocks : null
|
||||
if (blocks === null || blocks.voxels === null || blocks.models.length === 0) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
voxels: blocks.voxels,
|
||||
models: blocks.models,
|
||||
looks: blocks.looks,
|
||||
colors: blocks.colors,
|
||||
isWater: blocks.names.map(isWater)
|
||||
}
|
||||
}
|
||||
|
||||
colorAt(column: number, row: number): number {
|
||||
if (this.coloring === 'height') {
|
||||
return heightColor(this.heightAt(column, row), this.fluidHeight)
|
||||
|
||||
@@ -6,6 +6,7 @@ import { coverGeometry } from './coverFaces'
|
||||
import type { CoverLook } from './coverLooks'
|
||||
import { QuadBatch } from './quadBatch'
|
||||
import { addRaisedFaces } from './raisedFaces'
|
||||
import { voxelGeometries, type SurfaceVoxels } from './voxelMesh'
|
||||
import type { TerrainPictures } from './terrainAtlas'
|
||||
import type { ColumnArea } from './terrainTiles'
|
||||
import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint'
|
||||
@@ -35,6 +36,11 @@ export interface TerrainSurface {
|
||||
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[]
|
||||
/**
|
||||
* Every block seen from the open air, to draw one by one in place of the columns, which then only answer where the
|
||||
* ground lies; null to draw the columns.
|
||||
*/
|
||||
voxels?(): SurfaceVoxels | null
|
||||
}
|
||||
|
||||
/** A solid block above a column's ground, drawn as a whole block. */
|
||||
@@ -66,17 +72,21 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r
|
||||
if (!field.hasAnyGround()) {
|
||||
return { object: group, field, dispose: () => {} }
|
||||
}
|
||||
const voxels = field.pictures === null ? null : (surface.voxels?.() ?? null)
|
||||
if (voxels !== null && field.pictures !== null) {
|
||||
return voxelMesh(field, voxels, field.pictures)
|
||||
}
|
||||
const groundBatch = groundFaces(field, base)
|
||||
const seeThroughBatch = new QuadBatch(true, field.pictures?.plain ?? null)
|
||||
addRaisedFaces(field, groundBatch, seeThroughBatch)
|
||||
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 })
|
||||
const columnWaterMaterial = waterMaterial()
|
||||
const cutOut = field.pictures === null ? [] : [cutOutMesh(coverGeometry(field), field.pictures), cutOutMesh(seeThroughGeometry(seeThroughBatch), field.pictures)]
|
||||
const shownCutOut = cutOut.filter((mesh) => mesh !== null)
|
||||
// The water is drawn last, over what stands under it.
|
||||
group.add(new Mesh(ground, groundMaterial), ...shownCutOut.map((mesh) => mesh.mesh), new Mesh(water, waterMaterial))
|
||||
group.add(new Mesh(ground, groundMaterial), ...shownCutOut.map((mesh) => mesh.mesh), new Mesh(water, columnWaterMaterial))
|
||||
return {
|
||||
object: group,
|
||||
field,
|
||||
@@ -84,12 +94,45 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r
|
||||
ground.dispose()
|
||||
water.dispose()
|
||||
groundMaterial.dispose()
|
||||
waterMaterial.dispose()
|
||||
columnWaterMaterial.dispose()
|
||||
shownCutOut.forEach((mesh) => mesh.dispose())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function voxelMesh(field: ColumnField, voxels: SurfaceVoxels, pictures: TerrainPictures): TerrainMesh {
|
||||
const { opaque, cutOut, water } = voxelGeometries(field, voxels, pictures.plain)
|
||||
const parts: { mesh: Mesh; dispose(): void }[] = []
|
||||
if (opaque !== null) {
|
||||
parts.push(meshOf(opaque, new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: pictures.texture })))
|
||||
}
|
||||
const cutOutPart = cutOutMesh(cutOut, pictures)
|
||||
if (cutOutPart !== null) {
|
||||
parts.push(cutOutPart)
|
||||
}
|
||||
// The water is drawn last, over what stands under it.
|
||||
if (water !== null) {
|
||||
parts.push(meshOf(water, waterMaterial()))
|
||||
}
|
||||
const group = new Group()
|
||||
group.add(...parts.map((part) => part.mesh))
|
||||
return { object: group, field, dispose: () => parts.forEach((part) => part.dispose()) }
|
||||
}
|
||||
|
||||
function meshOf(geometry: BufferGeometry, material: MeshBasicMaterial): { mesh: Mesh; dispose(): void } {
|
||||
return {
|
||||
mesh: new Mesh(geometry, material),
|
||||
dispose: () => {
|
||||
geometry.dispose()
|
||||
material.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function waterMaterial(): MeshBasicMaterial {
|
||||
return new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide })
|
||||
}
|
||||
|
||||
function seeThroughGeometry(batch: QuadBatch): BufferGeometry | null {
|
||||
return batch.count === 0 ? null : batch.geometry()
|
||||
}
|
||||
|
||||
@@ -155,7 +155,8 @@ describe('textured terrain', () => {
|
||||
corners: [[0, 1, 0], [0, 0, 0], [1, 0, 1], [1, 1, 1]],
|
||||
uvs: [[0, 0], [0, 1], [1, 1], [1, 0]],
|
||||
cell: cellAt(4, WHITE),
|
||||
color: [0.5, 0.75, 0.25]
|
||||
color: [0.5, 0.75, 0.25],
|
||||
cullFace: null
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { BufferGeometry } from 'three'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { TileVoxels } from '../bridge/types'
|
||||
import type { Direction } from './blockModels'
|
||||
import type { BlockLook } from './blockLooks'
|
||||
import { ColumnField } from './columnField'
|
||||
import type { CoverFace, CoverLook } from './coverLooks'
|
||||
import { cellAt } from './terrainAtlas'
|
||||
import type { TerrainSurface } from './terrainMesh'
|
||||
import { voxelGeometries, type SurfaceVoxels } from './voxelMesh'
|
||||
|
||||
const GROUND = 10
|
||||
const DOWN = 1
|
||||
const UP = 1 << 1
|
||||
const NORTH = 1 << 2
|
||||
const STONE = 0
|
||||
const LEAVES = 1
|
||||
const GRASS = 2
|
||||
const WATER = 3
|
||||
const plain = cellAt(0, 0xffffff)
|
||||
const stoneLook: BlockLook = {
|
||||
top: { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 },
|
||||
side: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 },
|
||||
below: { cell: cellAt(2, 0x808080), tint: 0xffffff, color: 0x808080 }
|
||||
}
|
||||
|
||||
function face(cullFace: Direction | null, gappy: boolean): CoverFace {
|
||||
return { corners: [[0, 1, 0], [0, 0, 0], [1, 0, 0], [1, 1, 0]], uvs: [[0, 0], [0, 1], [1, 1], [1, 0]], cell: cellAt(3, 0x00ff00, gappy), color: [0, 1, 0], cullFace }
|
||||
}
|
||||
|
||||
const leaves: CoverLook = { faces: (['down', 'up', 'north', 'south', 'west', 'east'] as const).map((side) => face(side, true)) }
|
||||
const grass: CoverLook = { faces: [face(null, true), face(null, true)] }
|
||||
|
||||
const surface: TerrainSurface = {
|
||||
columns: 4,
|
||||
rows: 4,
|
||||
originX: 100,
|
||||
originZ: 200,
|
||||
blocksPerColumn: 1,
|
||||
groundAt: () => GROUND,
|
||||
waterAt: () => null,
|
||||
colorAt: () => 0x808080
|
||||
}
|
||||
|
||||
function voxelsOf(blocks: number[], faces: number[]): SurfaceVoxels {
|
||||
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)
|
||||
}
|
||||
return { voxels, models: [null, leaves, grass, null], looks: [stoneLook, null, null, null], colors: [0x808080, 0, 0, 0], isWater: [false, false, false, true] }
|
||||
}
|
||||
|
||||
const faceCount = (geometry: BufferGeometry | null): number => (geometry === null ? 0 : geometry.getIndex()!.count / 6)
|
||||
|
||||
describe('voxel mesh', () => {
|
||||
it('draws a block without a model as a cube of its look, on the sides that face the open air', () => {
|
||||
const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([STONE], [UP]), plain)
|
||||
|
||||
expect(faceCount(opaque)).toBe(1)
|
||||
expect(faceCount(cutOut)).toBe(0)
|
||||
expect(opaque!.getAttribute('position').getY(0)).toBe(GROUND + 1)
|
||||
expect(opaque!.getAttribute('position').getX(0)).toBe(100)
|
||||
})
|
||||
|
||||
it('leaves out the faces of a model a neighbour hides, and cuts out the faces of a picture with gaps', () => {
|
||||
const { opaque, cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([LEAVES], [UP | NORTH]), plain)
|
||||
|
||||
expect(faceCount(opaque)).toBe(0)
|
||||
expect(faceCount(cutOut)).toBe(2)
|
||||
})
|
||||
|
||||
it('draws every face of a model that nothing hides, such as a plant, whatever sides face the air', () => {
|
||||
const { cutOut } = voxelGeometries(new ColumnField(surface), voxelsOf([GRASS], [0]), plain)
|
||||
|
||||
expect(faceCount(cutOut)).toBe(2)
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
expect(faceCount(water)).toBe(2)
|
||||
expect(faceCount(opaque)).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
import { BufferAttribute, BufferGeometry } from 'three'
|
||||
import { VOXEL_SIDES, type TileVoxels } from '../bridge/types'
|
||||
import type { Direction } from './blockModels'
|
||||
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 type { UvCell } from './terrainAtlas'
|
||||
import { sunk, tintAt } from './waterTint'
|
||||
|
||||
type Corners = CoverFace['corners']
|
||||
type Uvs = CoverFace['uvs']
|
||||
type Color = readonly [number, number, number]
|
||||
|
||||
/** The blocks of a tile seen from the open air, and how to draw each of the blocks they name. */
|
||||
export interface SurfaceVoxels {
|
||||
voxels: TileVoxels
|
||||
/** Each named block's model with its pictures placed, or null to draw it as a cube of its look or colour. */
|
||||
models: readonly (CoverLook | null)[]
|
||||
looks: readonly (BlockLook | null)[]
|
||||
colors: readonly number[]
|
||||
/** Whether each named block is water, drawn as the water's sheet. */
|
||||
isWater: readonly boolean[]
|
||||
}
|
||||
|
||||
/** The faces of a tile's blocks: opaque ones, ones cut out along their pictures, and the water's. Null where there are none. */
|
||||
export interface VoxelGeometries {
|
||||
opaque: BufferGeometry | null
|
||||
cutOut: BufferGeometry | null
|
||||
water: BufferGeometry | null
|
||||
}
|
||||
|
||||
const SIDE_BITS: Record<Direction, number> = Object.fromEntries(VOXEL_SIDES.map((side, bit) => [side, 1 << bit])) as Record<Direction, number>
|
||||
const WHOLE_PICTURE: Uvs = [[0, 0], [0, 1], [1, 1], [1, 0]]
|
||||
// A whole block's face on each side, top left, bottom left, bottom right and top right as seen from outside.
|
||||
const CUBE_FACES: Record<Direction, Corners> = {
|
||||
down: [[0, 0, 1], [0, 0, 0], [1, 0, 0], [1, 0, 1]],
|
||||
up: [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
|
||||
north: [[1, 1, 0], [1, 0, 0], [0, 0, 0], [0, 1, 0]],
|
||||
south: [[0, 1, 1], [0, 0, 1], [1, 0, 1], [1, 1, 1]],
|
||||
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]]
|
||||
}
|
||||
|
||||
/**
|
||||
* Each block seen from the open air drawn as Minecraft draws it: the faces of its model, leaving out a face its model
|
||||
* lets a neighbour hide unless that side faces the open air. A block without a model is a cube of its look, or of its
|
||||
* colour; water shows the sides that face the air. What lies under water sinks toward its deep colour as the ground does.
|
||||
*/
|
||||
export function voxelGeometries(field: ColumnField, surface: SurfaceVoxels, plain: UvCell): VoxelGeometries {
|
||||
const opaque = new FaceSoup(true)
|
||||
const cutOut = new FaceSoup(true)
|
||||
const water = new FaceSoup(false)
|
||||
const { voxels } = surface
|
||||
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 waterTop = field.waterTopAt(column, row)
|
||||
if (surface.isWater[block]) {
|
||||
addCubeFaces(sides, (_side, corners) => water.add(corner, corners, null, null))
|
||||
continue
|
||||
}
|
||||
const model = surface.models[block]
|
||||
if (model !== null) {
|
||||
for (const face of model.faces) {
|
||||
if (face.cullFace !== null && (sides & SIDE_BITS[face.cullFace]) === 0) {
|
||||
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)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const look = surface.looks[block]
|
||||
addCubeFaces(sides, (side, corners) => {
|
||||
const face: FaceLook | null = look === null ? null : side === 'up' || side === 'down' ? look.top : look.side
|
||||
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)
|
||||
})
|
||||
}
|
||||
return { opaque: opaque.geometry(), cutOut: cutOut.geometry(), water: water.geometry() }
|
||||
}
|
||||
|
||||
function addCubeFaces(sides: number, add: (side: Direction, corners: Corners) => void): void {
|
||||
for (const side of VOXEL_SIDES) {
|
||||
if ((sides & SIDE_BITS[side]) !== 0) {
|
||||
add(side, CUBE_FACES[side])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function middleY(corners: Corners): number {
|
||||
return (corners[0][1] + corners[2][1]) / 2
|
||||
}
|
||||
|
||||
function underWater(color: Color, y: number, waterTop: number | null): Color {
|
||||
return waterTop === null ? color : sunk(color, tintAt(waterTop - y))
|
||||
}
|
||||
|
||||
function pictureUvs(cell: UvCell, uvs: Uvs): Uvs {
|
||||
return uvs.map(([u, v]) => [cell.u + u * cell.width, cell.v + v * cell.height]) as unknown as 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. */
|
||||
class FaceSoup {
|
||||
private positions: Float32Array<ArrayBuffer> = new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3)
|
||||
private uvs: Float32Array<ArrayBuffer> | null
|
||||
private colors: Float32Array<ArrayBuffer> | null
|
||||
private faces = 0
|
||||
|
||||
constructor(textured: boolean) {
|
||||
this.uvs = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 2) : null
|
||||
this.colors = textured ? new Float32Array(FIRST_CAPACITY_FACES * CORNERS * 3) : null
|
||||
}
|
||||
|
||||
add(origin: Color, corners: Corners, uvs: Uvs | null, color: Color | null): void {
|
||||
this.reserveOne()
|
||||
const first = this.faces * CORNERS
|
||||
for (let corner = 0; corner < CORNERS; corner++) {
|
||||
const vertex = first + corner
|
||||
this.positions[vertex * 3] = origin[0] + corners[corner][0]
|
||||
this.positions[vertex * 3 + 1] = origin[1] + corners[corner][1]
|
||||
this.positions[vertex * 3 + 2] = origin[2] + corners[corner][2]
|
||||
if (this.uvs !== null && uvs !== null) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
this.faces++
|
||||
}
|
||||
|
||||
geometry(): BufferGeometry | null {
|
||||
if (this.faces === 0) {
|
||||
return null
|
||||
}
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(this.positions.slice(0, this.faces * CORNERS * 3), 3))
|
||||
if (this.uvs !== null) {
|
||||
geometry.setAttribute('uv', new BufferAttribute(this.uvs.slice(0, this.faces * CORNERS * 2), 2))
|
||||
}
|
||||
if (this.colors !== null) {
|
||||
geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, this.faces * CORNERS * 3), 3))
|
||||
}
|
||||
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)
|
||||
}
|
||||
geometry.setIndex(new BufferAttribute(indices, 1))
|
||||
return geometry
|
||||
}
|
||||
|
||||
private reserveOne(): void {
|
||||
if ((this.faces + 1) * CORNERS * 3 <= this.positions.length) {
|
||||
return
|
||||
}
|
||||
this.positions = grown(this.positions)
|
||||
this.uvs = this.uvs === null ? null : grown(this.uvs)
|
||||
this.colors = this.colors === null ? null : grown(this.colors)
|
||||
}
|
||||
}
|
||||
|
||||
function grown(values: Float32Array): Float32Array<ArrayBuffer> {
|
||||
const bigger = new Float32Array(values.length * 2)
|
||||
bigger.set(values)
|
||||
return bigger
|
||||
}
|
||||
@@ -29,7 +29,7 @@ const MOST_BLOCKS_PER_COLUMN = 2 ** COARSEST_LEVEL
|
||||
// Tiles with generated blocks take seconds to minutes each. The same tiles without them stand in, but only on ground
|
||||
// where no tile with blocks of any level is known yet.
|
||||
function withoutBlocks(layer: TileLayer): TileLayer | null {
|
||||
return layer.blocks === null ? null : { ...layer, blocks: null }
|
||||
return layer.blocks === null ? null : { ...layer, blocks: null, voxels: false }
|
||||
}
|
||||
|
||||
interface WorldStudio3DProps {
|
||||
@@ -59,7 +59,7 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS
|
||||
)
|
||||
const showsBlocks = coloring === 'blocks'
|
||||
const layer = useMemo<TileLayer>(
|
||||
() => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, revision: packRevision }),
|
||||
() => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, voxels: showsBlocks, revision: packRevision }),
|
||||
[packRevision, showsBlocks]
|
||||
)
|
||||
const style = useMemo<TerrainStyle<MapTile>>(
|
||||
|
||||
Reference in new issue
Block a user