Skip to main content

A Voxelize world handles the chunk loading and rendering, as well as any 3D objects. This class extends the ThreeJS Scene class. This means that you can add any ThreeJS objects to the world, and they will be rendered. The world also implements NetIntercept, which means it intercepts chunk-related packets from the server and constructs chunk meshes from them.

There are a couple components that are by default created by the world that holds data:

  • World.registry: A block registry that handles block textures and block instances.
  • World.chunks: A chunk manager that stores all the chunks in the world.
  • World.physics: A physics engine that handles voxel AABB physics simulation of client-side physics.
  • World.loader: An asset loader that handles loading textures and other assets.
  • World.sky: A sky that can render the sky and the sun.
  • World.clouds: A clouds that renders the cubical clouds.

One thing to keep in mind that there are no specific setters like setVoxelByVoxel or setVoxelRotationByVoxel. This is because, instead, you should use updateVoxel and updateVoxels to update voxels.

Example

const world = new VOXELIZE.World();

// Update the voxel at `(0, 0, 0)` to a voxel type `12` in the world across the network.
world.updateVoxel(0, 0, 0, 12)

// Register the interceptor with the network.
network.register(world);

// Register an image to block sides.
world.applyBlockTexture("Test", VOXELIZE.ALL_FACES, "https://example.com/test.png");

// Update the world every frame.
world.update(controls.position);

World

Type parameters​

NameType
Tany

Hierarchy​

  • Scene

    ↳ World

Implements​

Constructors​

constructor​

• new World<T>(options?): World<T>

Create a new Voxelize world.

Type parameters​

NameType
Tany

Parameters​

NameTypeDescription
optionsPartial<WorldOptions>The options to create the world.

Returns​

World<T>

Overrides​

Scene.constructor

Properties​

blockAnimations​

• blockAnimations: BlockAnimations

How animated blocks (Block.isAnimated: doors, and whatever else moves between its states) swing from one state's geometry into the next. The game registers a BlockAnimation per block name; the engine tracks each such voxel's mesh across remeshes and drives the motion.


blockTextureGeneration​

• blockTextureGeneration: number = 0

How many times a block texture has been written, bumped by every texture API. Every atlas slot starts life as the magenta-and-black unknown checker, and painting is spread over the load (image loads resolve whenever they resolve), so anything that samples the atlas into its own table has to be able to tell that its table predates the paint. Compare this against the value read when the table was built; unequal means rebuild.


chunkPipeline​

• chunkPipeline: ChunkPipeline

Pipeline for chunk lifecycle state machine (request -> processing -> loaded).


chunkRenderer​

• chunkRenderer: ChunkRenderer

Chunk rendering state (materials, uniforms).


clouds​

• clouds: Clouds

The clouds that renders the cubical clouds.


csmRenderer​

• csmRenderer: CSMRenderer = null

The CSM (Cascaded Shadow Map) renderer for shader-based lighting.


extraInitData​

• extraInitData: Record<string, unknown> = {}


farTerrain​

• farTerrain: FarTerrain

Coarse terrain past the loaded chunks, drawn from server-sampled tiles when the world serves them (farTerrain in the INIT options) and farTerrainDistance is above 0. See FarTerrain.


isInitialized​

• isInitialized: boolean = false

Whether or not this world is connected to the server and initialized with data from the server.


items​

• items: ItemRegistry

The item registry that holds all item definitions and provides utility methods for item operations.


lightCones​

• lightCones: LightCones

Shared dynamic spot-cone lighting (flashlights, vehicle headlights). The game rebuilds the cone list every frame; chunk materials bind these uniforms at creation.


loader​

• loader: Loader

An asset loader to load in things like textures, images, GIFs and audio buffers.


localLights​

• localLights: LocalLights

Local light emitters: block-anchored sources scanned out of chunks plus game-registered dynamic sources, clustered into the chunk shaders. The game declares semantic block profiles and dynamic lights; the engine owns scanning, selection, culling, and GPU representation.


meshApplyStats​

• meshApplyStats: MeshApplyStats

Running cost of applying mesh results on the main thread; see MeshApplyStats.


meshPipeline​

• meshPipeline: MeshPipeline

Pipeline for mesh generation with ordering guarantees.


meshTransfer​

• Readonly meshTransfer: Object

Configure and inspect mesh worker buffer transfer (transfer vs SharedArrayBuffer).

Type declaration​

NameType
benchmark(options: MeshTransferBenchmarkOptions) => Promise<MeshTransferBenchmarkResult>
configure(config: { mode?: WorkerTransferMode }) => void
getMode() => WorkerTransferMode
getStats() => MeshWorkerTransferStats | Record<WorkerTransferStrategy, MeshWorkerTransferStats>
getStatus() => { isCrossOriginIsolated: boolean ; isSharedArrayBufferAvailable: boolean ; mode: WorkerTransferMode ; pool: ChunkSharedPoolStats ; stats: MeshWorkerTransferStats | Record<WorkerTransferStrategy, MeshWorkerTransferStats> ; strategy: WorkerTransferStrategy }
getStrategy() => WorkerTransferStrategy
isSharedArrayBufferAvailable() => boolean
resetStats() => void
setStrategy(strategy: "transfer" | "shared") => void

options​

• options: WorldOptions

The options to create the world.


orderIndependent​

• orderIndependent: OrderIndependentTransparency = null

The blended layers' accumulation, when WorldClientOptions.orderIndependentTransparency is set; null draws the sorted pipeline.


physics​

• physics: Engine

The voxel physics engine using @voxelize/physics-engine.


regionArenas​

• regionArenas: ChunkRegionArenas = null

Region buffer arenas batching the shared-opaque bucket, one BatchedMesh per region; null until the first opaque section lands or when WorldClientOptions.regionArenas disables batching.


registry​

• registry: Registry

The block registry that holds all block data, such as texture and block properties.


shaderClock​

• Readonly shaderClock: ShaderClock

The clock chunk shaders animate on (waves, sway, flicker, animated atlas frames): the shared clock, slewed and wrapped for the GPU, so every player sees the same wave at the same moment.


sky​

• sky: Sky

The sky that renders the sky and the sun.


swayProfileTable​

• Readonly swayProfileTable: Uniform<any>

Flat vec4-pair table behind the shared cutout buckets' sway shader; see createSwayTableShader. Slot 0 stays zeroed as the "no sway" profile.


waterOptics​

• waterOptics: WaterOptics

The camera-driven underwater optics state, updated via World.updateWaterOptics.


waterOpticsFluidFilter​

• waterOpticsFluidFilter: (block: Block) => boolean = null

Which fluid blocks count as water for the camera's underwater optics. null (the default) treats every fluid as water. A game with other fluids (lava) returns false for them, so a camera inside one does not get water fog, sky fade and the backside water surface.

Type declaration​

▸ (block): boolean

Parameters​
NameType
blockBlock
Returns​

boolean

Accessors​

day​

• get day(): number

Days the world clock has completed. With World.time it forms World.sharedClock; on its own it is what a moon phase or a "day N" readout would count.

Returns​

number


deleteRadius​

• get deleteRadius(): number

Returns​

number


disposed​

• get disposed(): boolean

Whether dispose has run. A disposed world is a corpse: its workers are gone and its chunks released, and anything still holding it is holding the whole scene graph in memory for nothing.

Returns​

boolean


farTerrainDistance​

• get farTerrainDistance(): number

How far the far-terrain layer reaches past the viewer, in blocks; 0 turns it off. Takes effect only in a world that serves far terrain. The fog range follows it. See WorldOptions.farTerrainDistance.

Returns​

number

• set farTerrainDistance(distance): void

Parameters​

NameType
distancenumber

Returns​

void


fogDistance​

• get fogDistance(): number

A fixed fog distance in blocks, independent of renderRadius; null when fog is still derived from the radius. See WorldOptions.fogDistance.

Returns​

number

• set fogDistance(distance): void

Parameters​

NameType
distancenumber

Returns​

void


renderRadius​

• get renderRadius(): number

Returns​

number

• set renderRadius(radius): void

Parameters​

NameType
radiusnumber

Returns​

void


sectionVisibilityStats​

• get sectionVisibilityStats(): Object

Returns​

Object

NameType
constrainednumber
isCompleteboolean
reachednumber
sectionsnumber
visiblenumber

sharedClock​

• get sharedClock(): number

Seconds since the world's clock began: day * timePerDay + time. Unlike World.time it never wraps at midnight, and every client of a world agrees on it to within the STATS sync threshold, which makes it the clock for cosmetic motion all players must see alike — cloud drift, the shooting-star schedule. A /time jump moves it within the current day, so those effects jump with the sky rather than diverging from it.

A world whose clock is frozen (doesTickTime false) has no shared game clock at all, so the wall clock stands in: clients agree to within their NTP skew, which is all a cosmetic schedule needs.

Returns​

number


time​

• get time(): number

Returns​

number

• set time(time): void

Parameters​

NameType
timenumber

Returns​

void

Methods​

addBlockEntityUpdateListener​

▸ addBlockEntityUpdateListener(listener): () => void

Parameters​

NameType
listenerBlockEntityUpdateListener<T>

Returns​

fn

▸ (): void

Returns​

void


addBlockUpdateListener​

▸ addBlockUpdateListener(listener): () => void

Parameters​

NameType
listenerBlockUpdateListener

Returns​

fn

▸ (): void

Returns​

void


addChunkInitListener​

▸ addChunkInitListener(coords, listener): () => void

Parameters​

NameType
coordsCoords2
listener(chunk: Chunk) => void

Returns​

fn

▸ (): void

Returns​

void


adoptOrderIndependentMaterials​

▸ adoptOrderIndependentMaterials(materials): Material[]

Adopts every material in materials that can accumulate, and makes the texel forks of the see-through chunk materials among them, so a warmup compiles the programs play draws with (a material adopted after it compiled compiles again). Returns the forks: no scene holds them until a mesh's textures call for one, so a warmup has to draw them itself.

Parameters​

NameType
materialsIterable<Material, any, any>

Returns​

Material[]


applyBlockFrames​

▸ applyBlockFrames(idOrName, faceNames, keyframes, fadeFrames?): Promise<void>

Apply a set of keyframes to a block. This will load the keyframes from the sources and start the animation to play the keyframes on the block's texture atlas.

Parameters​

NameTypeDefault valueDescription
idOrNamestring | numberundefinedThe ID or name of the block.
faceNamesstring | string[]undefinedThe face name or names to apply the texture to.
keyframes[number, string | Color | HTMLImageElement][]undefinedThe keyframes to apply to the texture.
fadeFramesnumber0The number of frames to fade between each keyframe.

Returns​

Promise<void>


applyBlockGif​

▸ applyBlockGif(idOrName, faceNames, source, interval?): Promise<void>

Apply a GIF animation to a block. This will load the GIF from the source and start the animation using applyBlockFrames internally.

Parameters​

NameTypeDefault valueDescription
idOrNamestringundefinedThe ID or name of the block.
faceNamesstring | string[]undefinedThe face name or names to apply the texture to.
sourcestringundefinedThe source of the GIF. Note that this must be a GIF file ending with .gif.
intervalnumber66.666667The interval between each frame of the GIF in milliseconds. Defaults to 66.666667ms.

Returns​

Promise<void>


applyBlockTexture​

▸ applyBlockTexture(idOrName, faceNames, source): void

Apply a texture to a face or faces of a block. This will automatically load the image from the source and draw it onto the block's texture atlas.

An isolated face, whose pixels belong to a voxel, takes this as its default — what the face looks like where there is no voxel to ask, which is every display mesh: a held block, a drop, an inventory thumbnail. applyBlockTextureAt still overrides it per voxel.

Parameters​

NameTypeDescription
idOrNamestring | numberThe ID or name of the block.
faceNamesstring | string[]The face names to apply the texture to.
sourcestring | Color | Texture<unknown> | HTMLImageElementThe source of the texture.

Returns​

void

Deprecated

When applying the same texture to multiple faces, use texture groups instead for better atlas efficiency. Define texture_group on the server-side block faces and use applyTextureGroup or applyTextureGroups on the client.


applyBlockTextureAt​

▸ applyBlockTextureAt(idOrName, faceName, source, voxel): CustomChunkShaderMaterial

Parameters​

NameType
idOrNamestring | number
faceNamestring
sourcestring | Color | Texture<unknown> | HTMLImageElement
voxelCoords3

Returns​

CustomChunkShaderMaterial


applyBlockTextures​

▸ applyBlockTextures(data): Promise<void[]>

Apply multiple block textures at once. See applyBlockTexture for more information.

Parameters​

NameTypeDescription
data{ faceNames: string | string[] ; idOrName: string | number ; source: string | Color }[]The data to apply the block textures.

Returns​

Promise<void[]>

A promise that resolves when all the textures are applied.

Deprecated

When applying the same texture to multiple faces, use texture groups instead for better atlas efficiency. Define texture_group on the server-side block faces and use applyTextureGroup or applyTextureGroups on the client.


applyTextureGroup​

▸ applyTextureGroup(groupName, source): any

Parameters​

NameType
groupNamestring
sourcestring | Color | Texture<unknown> | HTMLImageElement

Returns​

any


applyTextureGroups​

▸ applyTextureGroups(data): Promise<any[]>

Parameters​

NameType
data{ groupName: string ; source: string | Color | Texture<unknown> | HTMLImageElement }[]

Returns​

Promise<any[]>


benchmarkMeshTransfer​

▸ benchmarkMeshTransfer(options): Promise<MeshTransferBenchmarkResult>

Parameters​

NameType
optionsMeshTransferBenchmarkOptions

Returns​

Promise<MeshTransferBenchmarkResult>


customizeBlockDynamic​

▸ customizeBlockDynamic(idOrName, fn): void

Parameters​

NameType
idOrNamestring | number
fn(pos: Coords3) => { aabbs: AABB[] ; faces: { corners: { pos: [number, number, number] ; uv: number[] }[] ; dir: [number, number, number] ; emissive?: number ; independent: boolean ; isolated: boolean ; name: string ; pigmentMask?: number ; range: UV ; regionalTint?: boolean ; stageTintMask?: number ; textureGroup: string }[] ; isTransparent: [boolean, boolean, boolean, boolean, boolean, boolean] }

Returns​

void


customizeMaterialShaders​

▸ customizeMaterialShaders(idOrName, faceName?, data?): CustomChunkShaderMaterial

Parameters​

NameTypeDefault value
idOrNamestring | numberundefined
faceNamestringnull
dataObjectundefined
data.fragmentShaderstringundefined
data.uniforms?Objectundefined
data.vertexShaderstringundefined

Returns​

CustomChunkShaderMaterial


dispose​

▸ dispose(): void

Returns​

void


expandCoupledUpdates​

▸ expandCoupledUpdates(updates): BlockUpdate[]

Expand a batch of updates so every coupled unit it touches changes whole — the mirror of the server's update intake, run on every batch updateVoxels receives. Exposed so a caller can learn the outcome of a placement before committing to it (an anchor whose partner voxel is occupied expands to nothing); the result is idempotent, so it can be handed straight back to World.updateVoxels. See expandCoupledUpdates.

Parameters​

NameType
updatesBlockUpdate[]

Returns​

BlockUpdate[]


fillUnpaintedSurfaces​

▸ fillUnpaintedSurfaces(options?): TextureFillResult

Dress every surface still on the unknown checker: an isolated face in its default if that has landed, everything else in options.unpaintedFallbackColor. The census keeps reporting them as fallback, so a stage made presentable this way does not pass for a finished one.

Parameters​

NameType
optionsObject
options.color?string

Returns​

TextureFillResult


floodLight​

▸ floodLight(queue, color, min?, max?): void

Propagate light nodes outward through the loaded chunks. The algorithm itself lives in "./lighting" and senses the world through the VoxelLightVolume slice this class satisfies.

Parameters​

NameType
queueLightNode[]
colorLightColor
min?Coords3
max?Coords3

Returns​

void


getAABBOverride​

▸ getAABBOverride(voxel): AABB[]

Parameters​

NameType
voxelCoords3

Returns​

AABB[]


getAABBOverrideOwner​

▸ getAABBOverrideOwner(voxel): Coords3

The block voxel an override cell answers for, when it has one.

Parameters​

NameType
voxelCoords3

Returns​

Coords3


getBarrierTopAt​

▸ getBarrierTopAt(vx, vy, vz): number

World-space height the server's bodies find the voxel at vx, vy, vz standing to (its block's barrierHeight above the voxel's floor), or -Infinity where its block has no barrier or no chunk is loaded. The client's own body collides with getCollisionAABBsAt alone; the physics engine reads this so automatic moves never carry it over.

Parameters​

NameType
vxnumber
vynumber
vznumber

Returns​

number


getBaseFogRange​

▸ getBaseFogRange(): WorldFogRange

Returns​

WorldFogRange


getBlockAABBsAt​

▸ getBlockAABBsAt(vx, vy, vz): AABB[]

Parameters​

NameType
vxnumber
vynumber
vznumber

Returns​

AABB[]


getBlockAABBsByIdAt​

▸ getBlockAABBsByIdAt(id, vx, vy, vz): AABB[]

Parameters​

NameType
idnumber
vxnumber
vynumber
vznumber

Returns​

AABB[]


getBlockAABBsForDynamicPatterns​

▸ getBlockAABBsForDynamicPatterns(vx, vy, vz, dynamicPatterns): { aabb: AABB ; worldSpace: boolean }[]

Parameters​

NameType
vxnumber
vynumber
vznumber
dynamicPatternsBlockDynamicPattern[]

Returns​

{ aabb: AABB ; worldSpace: boolean }[]


getBlockAt​

▸ getBlockAt(px, py, pz): Block

Get the block type data by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

Block

The block at the given position, or null if it does not exist.


getBlockById​

▸ getBlockById(id): Block

Get the block type data by a block id. Unknown ids resolve to air (logged once per id) so a server/client registry gap can never take down meshing, lighting, or the agent bridge.

Parameters​

NameTypeDescription
idnumberThe block id.

Returns​

Block

The block data for the given id, or air if it is unknown.


getBlockByIdSafe​

▸ getBlockByIdSafe(id): Block

Parameters​

NameType
idnumber

Returns​

Block


getBlockByName​

▸ getBlockByName(name): Block

Get the block type data by a block name.

Parameters​

NameTypeDescription
namestringThe block name.

Returns​

Block

The block data for the given name, or null if it does not exist.


getBlockEntityDataAt​

▸ getBlockEntityDataAt(px, py, pz): T

Parameters​

NameType
pxnumber
pynumber
pznumber

Returns​

T


getBlockEntityIdAt​

▸ getBlockEntityIdAt(px, py, pz): string

Parameters​

NameType
pxnumber
pynumber
pznumber

Returns​

string


getBlockFaceMaterial​

▸ getBlockFaceMaterial(idOrName, faceName?, voxel?): CustomChunkShaderMaterial

Parameters​

NameType
idOrNamestring | number
faceName?string
voxel?Coords3

Returns​

CustomChunkShaderMaterial


getBlockFacesByFaceNames​

▸ getBlockFacesByFaceNames(id, faceNames, warnUnknown?): { corners: { pos: [number, number, number] ; uv: number[] }[] ; dir: [number, number, number] ; emissive?: number ; independent: boolean ; isolated: boolean ; name: string ; pigmentMask?: number ; range: UV ; regionalTint?: boolean ; stageTintMask?: number ; textureGroup: string }[]

Parameters​

NameTypeDefault value
idnumberundefined
faceNamesstring | RegExp | string[]undefined
warnUnknownbooleanfalse

Returns​

{ corners: { pos: [number, number, number] ; uv: number[] }[] ; dir: [number, number, number] ; emissive?: number ; independent: boolean ; isolated: boolean ; name: string ; pigmentMask?: number ; range: UV ; regionalTint?: boolean ; stageTintMask?: number ; textureGroup: string }[]


getBlockFacesForDynamicPatterns​

▸ getBlockFacesForDynamicPatterns(blockId, dynamicPatterns): { corners: { pos: [number, number, number] ; uv: number[] }[] ; dir: [number, number, number] ; emissive?: number ; independent: boolean ; isolated: boolean ; name: string ; pigmentMask?: number ; range: UV ; regionalTint?: boolean ; stageTintMask?: number ; textureGroup: string }[]

Parameters​

NameType
blockIdnumber
dynamicPatternsBlockDynamicPattern[]

Returns​

{ corners: { pos: [number, number, number] ; uv: number[] }[] ; dir: [number, number, number] ; emissive?: number ; independent: boolean ; isolated: boolean ; name: string ; pigmentMask?: number ; range: UV ; regionalTint?: boolean ; stageTintMask?: number ; textureGroup: string }[]


getBlockOf​

▸ getBlockOf(idOrName): Block

Parameters​

NameType
idOrNamestring | number

Returns​

Block


getBlockPassableForDynamicPatterns​

▸ getBlockPassableForDynamicPatterns(vx, vy, vz, dynamicPatterns, defaultPassable): boolean

Parameters​

NameType
vxnumber
vynumber
vznumber
dynamicPatternsBlockDynamicPattern[]
defaultPassableboolean

Returns​

boolean


getBranchAABBsAt​

▸ getBranchAABBsAt(block, vx, vy, vz): AABB[]

The boxes the branch voxel of block at vx, vy, vz is drawn and collides as, in blocks of the voxel: a one-voxel branch or fin's core and arms, or a wide section cell's slice of its core's tube (see branch.ts). Empty for a block that is not a branch, a cut core and a shell whose core is gone.

Parameters​

NameType
blockBlock
vxnumber
vynumber
vznumber

Returns​

AABB[]


getChunkByCoords​

▸ getChunkByCoords(cx, cz): Chunk

Get a chunk by its 2D coordinates.

Parameters​

NameTypeDescription
cxnumberThe x coordinate of the chunk.
cznumberThe z coordinate of the chunk.

Returns​

Chunk

The chunk at the given coordinates, or undefined if it does not exist.


getChunkByName​

▸ getChunkByName(name): Chunk

Get a chunk by its name.

Parameters​

NameTypeDescription
namestringThe name of the chunk to get.

Returns​

Chunk

The chunk with the given name, or undefined if it does not exist.


getChunkByPosition​

▸ getChunkByPosition(px, py, pz): Chunk

Get a chunk that contains a given position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

Chunk

The chunk that contains the position at the given position, or undefined if it does not exist.


getChunkStatus​

▸ getChunkStatus(cx, cz): "requested" | "processing" | "loaded" | "to request"

Get the status of a chunk.

Parameters​

NameTypeDescription
cxnumberThe x 2D coordinate of the chunk.
cznumberThe z 2D coordinate of the chunk.

Returns​

"requested" | "processing" | "loaded" | "to request"

The status of the chunk.


getCollisionAABBsAt​

▸ getCollisionAABBsAt(vx, vy, vz): AABB[]

The boxes a rigid body collides with in the voxel at vx, vy, vz, in world space: exactly what the physics engine stands bodies on. Empty where no chunk is loaded, and for passable blocks and fluids.

Parameters​

NameType
vxnumber
vynumber
vznumber

Returns​

AABB[]


getIsolatedBlockMaterialAt​

▸ getIsolatedBlockMaterialAt(voxel, faceName, defaultDimension?): CustomChunkShaderMaterial

Parameters​

NameType
voxelCoords3
faceNamestring
defaultDimension?number

Returns​

CustomChunkShaderMaterial


getLightColorAt​

▸ getLightColorAt(vx, vy, vz): Color

Get a color instance that represents what an object would be like if it were rendered at the given 3D voxel coordinate. This is useful to dynamically shade objects based on their position in the world. Also used in LightShined.

Parameters​

NameTypeDescription
vxnumberThe voxel's X position.
vynumberThe voxel's Y position.
vznumberThe voxel's Z position.

Returns​

Color

The voxel's light color at the given coordinate.


getLightValuesAt​

▸ getLightValuesAt(vx, vy, vz): Object

Parameters​

NameType
vxnumber
vynumber
vznumber

Returns​

Object

NameType
bluenumber
greennumber
rednumber
sunlightnumber

getMaxHeightAt​

▸ getMaxHeightAt(px, pz): number

Get the highest block at a x/z position. Highest block means the first block counting downwards that isn't empty (isEmpty).

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

number

The highest block at the given position, or 0 if it does not exist.


getMemoryCounters​

▸ getMemoryCounters(): WorldMemoryCounters

Live sizes of every queue and in-flight set in the voxel update -> relight -> remesh pipeline, plus the bytes of serialized chunk payloads parked in worker queues. This is the memory-pressure dashboard for debugging update-flood OOMs (mass terrain edits): sample it while carving and watch which stage balloons.

Returns​

WorldMemoryCounters


getPreviousValueAt​

▸ getPreviousValueAt(px, py, pz, count?): number

Get the previous value of a voxel by a 3D world position.

Parameters​

NameTypeDefault valueDescription
pxnumberundefinedThe x coordinate of the position.
pynumberundefinedThe y coordinate of the position.
pznumberundefinedThe z coordinate of the position.
countnumber1By how much to look back in the history. Defaults to 1.

Returns​

number


getRawVoxelAt​

▸ getRawVoxelAt(px, py, pz): number

The whole packed voxel word at a 3D world position — id, rotation, stage and waterlogging together — or 0 where no chunk is loaded. For callers that compare voxel states as a unit; getVoxelAt and its siblings unpack one field each.

Parameters​

NameType
pxnumber
pynumber
pznumber

Returns​

number


getSunlightAt​

▸ getSunlightAt(px, py, pz): number

Get a voxel sunlight by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

number

The voxel sunlight at the given position, or 0 if it does not exist.


getTextureInfo​

▸ getTextureInfo(): Object

Returns​

Object

NameType
sharedAtlas{ canvas: HTMLCanvasElement ; countPerSide: number }
sharedAtlas.canvasHTMLCanvasElement
sharedAtlas.countPerSidenumber
texturesTextureInfo[]

getTorchLightAt​

▸ getTorchLightAt(px, py, pz, color): number

Get a voxel torch light by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.
colorLightColorThe color of the torch light.

Returns​

number

The voxel torchlight at the given position, or 0 if it does not exist.


getVoxelAt​

▸ getVoxelAt(px, py, pz): number

Get a voxel by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

number

The voxel at the given position, or 0 if it does not exist.


getVoxelRotationAt​

▸ getVoxelRotationAt(px, py, pz): BlockRotation

Get a voxel rotation by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

BlockRotation

The voxel rotation at the given position, or the default rotation if it does not exist.


getVoxelStageAt​

▸ getVoxelStageAt(px, py, pz): number

Get a voxel stage by a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

number

The voxel stage at the given position, or 0 if it does not exist.


getVoxelWaterlogLevelAt​

▸ getVoxelWaterlogLevelAt(px, py, pz): number

The level of waterlogging fluid held by the voxel at a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

number


getVoxelWaterloggedAt​

▸ getVoxelWaterloggedAt(px, py, pz): boolean

Whether the voxel at a 3D world position holds the world's waterlogging fluid alongside its block.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.

Returns​

boolean


hasCustomBlockMaterial​

▸ hasCustomBlockMaterial(id): boolean

Parameters​

NameType
idnumber

Returns​

boolean


initialize​

▸ initialize(): Promise<void>

Initialize the world with the data received from the server. This includes populating the registry, setting the options, and creating the texture atlas.

Returns​

Promise<void>


isCameraSubmerged​

▸ isCameraSubmerged(): boolean

Whether the camera is under water, by the same smoothed submersion the water shaders read: which side of the water a see-through layer in the camera's medium draws on (TRANSPARENT_SORT).

Returns​

boolean


isChunkInView​

▸ isChunkInView(center, target, direction, threshold): boolean

Parameters​

NameType
centerCoords2
targetCoords2
directionVector3
thresholdnumber

Returns​

boolean


isFluidOrWaterloggedAt​

▸ isFluidOrWaterloggedAt(vx, vy, vz): boolean

Whether the voxel at a world position holds water: either it is a fluid block or a block waterlogged with the world's fluid. Reads the packed voxel word once off the chunk instead of resolving the chunk twice (once for the waterlogging bit, once for the block).

Parameters​

NameType
vxnumber
vynumber
vznumber

Returns​

boolean


isWithinWorld​

▸ isWithinWorld(cx, cz): boolean

Whether or not if this chunk coordinate is within (inclusive) the world's bounds. That is, if this chunk coordinate is within WorldServerOptions.minChunk and WorldServerOptions.maxChunk.

Parameters​

NameTypeDescription
cxnumberThe chunk's X position.
cznumberThe chunk's Z position.

Returns​

boolean

Whether or not this chunk is within the bounds of the world.


makeBlockMesh​

▸ makeBlockMesh(idOrName, options?): Group<Object3DEventMap>

Get a mesh of the model of the given block.

Parameters​

NameTypeDescription
idOrNamestring | number-
optionsPartial<{ cached: boolean ; centered: boolean ; crumbs: boolean ; material: "basic" | "standard" ; separateFaces: boolean }>The options of creating this block mesh.

Returns​

Group<Object3DEventMap>

A 3D mesh (group) of the block model.


measureWaterColumnAt​

▸ measureWaterColumnAt(x, y, z): WaterColumnSample

The water column standing over a point — its depth below the resting surface and where that surface sits — or null when the point is not in water. See measureWaterColumn for the walk itself.

A column is one (x, z), so it lives in exactly one chunk: the chunk resolves once and every block of the walk is a raw read off it. The per-block getBlockAt walk this replaces paid a chunk name lookup and a registry lookup for every block between the point and the surface, so a fish forty blocks down cost forty of each, several times a second.

Parameters​

NameType
xnumber
ynumber
znumber

Returns​

WaterColumnSample


meshChunkLocally​

▸ meshChunkLocally(cx, cz, level, generation?, isPriority?): Promise<void>

Parameters​

NameTypeDefault value
cxnumberundefined
cznumberundefined
levelnumberundefined
generation?numberundefined
isPrioritybooleanfalse

Returns​

Promise<void>


meshVoxelBox​

▸ meshVoxelBox(box): Promise<VoxelBoxMesh>

Parameters​

NameType
boxVoxelBoxInput

Returns​

Promise<VoxelBoxMesh>


off​

▸ off<K>(event, listener): this

Unregister a typed event listener for chunk lifecycle events.

Type parameters​

NameType
Kextends keyof WorldChunkEvents

Parameters​

NameTypeDescription
eventKThe event name to stop listening to.
listenerWorldChunkEvents[K]The callback function to remove.

Returns​

this

The world instance for chaining.


on​

▸ on<K>(event, listener): this

Register a typed event listener for chunk lifecycle events.

Type parameters​

NameType
Kextends keyof WorldChunkEvents

Parameters​

NameTypeDescription
eventKThe event name to listen to.
listenerWorldChunkEvents[K]The callback function to execute when the event is emitted.

Returns​

this

The world instance for chaining.


onContextRestored​

▸ onContextRestored(): void

GPU context restored: every chunk atlas already mirrors its animated patches onto its own backing canvas as they draw (AtlasTexture. commitAnimationPatch), so re-uploading it is just needsUpdate = true on the texture three.js already holds — nothing to rebuild from scratch. Local lights pack their own GPU-resident grids and shadow atlas outside three's texture pipeline, so they get their own hook. Wire this to the canvas's webglcontextrestored event (after calling preventDefault() in a webglcontextlost listener — without it the browser never attempts to restore the context at all).

Returns​

void


onDispose​

▸ onDispose(callback): () => void

Tie a resource to this world's lifetime: callback runs once when the world is disposed (at once, if it already has been). For timers, DOM listeners and other things that close over the world from outside the scene graph -- a texture repainted on an interval, a subscription -- and would otherwise outlive it. A page that mounts a second world (a hot-reload remount) keeps every such closure of the first alive, and the world behind it, until the tab is reloaded.

Parameters​

NameType
callback() => void

Returns​

fn

A function that unregisters the callback.

▸ (): void

Returns​

void


once​

▸ once<K>(event, listener): this

Register a one-time typed event listener for chunk lifecycle events.

Type parameters​

NameType
Kextends keyof WorldChunkEvents

Parameters​

NameTypeDescription
eventKThe event name to listen to once.
listenerWorldChunkEvents[K]The callback function to execute when the event is emitted.

Returns​

this

The world instance for chaining.


orderIndependentBandOf​

▸ orderIndependentBandOf(object, material): number

See TransparentMediumSource.orderIndependentBandOf.

Parameters​

NameType
objectObject3D<Object3DEventMap>
materialMaterial

Returns​

number


prepareTransparency​

▸ prepareTransparency(renderer, camera): void

Call once a frame with the camera the scene is about to render with, before that render. Drawing order-independently, it draws the depth of the water in view (the surface the blended layers are split at, see OrderIndependentSeparator), arms the accumulation for that camera, and re-plans the see-through meshes when a block texture was written since (a texture can gain or lose its translucent texels). Sorted, it draws the depth of the water near the panes in view (WaterDepthPass); a frame without it draws every pane before the water.

Parameters​

NameType
rendererWebGLRenderer
cameraCamera

Returns​

void


raycastVoxels​

▸ raycastVoxels(origin, direction, maxDistance, options?): Object

Raycast through the world of voxels and return the details of the first block intersection.

Parameters​

NameTypeDescription
originCoords3The origin of the ray.
directionCoords3The direction of the ray.
maxDistancenumberThe maximum distance of the ray.
optionsObjectThe options for the ray.
options.ignoreFluids?booleanWhether or not to ignore fluids. Defaults to true.
options.ignoreList?number[]A list of blocks to ignore. Defaults to [].
options.ignorePassables?booleanWhether or not to ignore passable blocks. Defaults to false.
options.ignoreSeeThrough?booleanWhether or not to ignore see through blocks. Defaults to false.

Returns​

Object

NameType
normalnumber[]
pointnumber[]
voxelnumber[]

removeAABBOverride​

▸ removeAABBOverride(voxel): void

Parameters​

NameType
voxelCoords3

Returns​

void


removeLight​

▸ removeLight(voxel, color): void

Parameters​

NameType
voxelCoords3
colorLightColor

Returns​

void


removeLightsBatch​

▸ removeLightsBatch(voxels, color): void

Batch remove light from multiple voxels that previously emitted the same light color. This drastically improves performance when many contiguous light sources are removed at once.

Parameters​

NameType
voxelsCoords3[]
colorLightColor

Returns​

void


renderShadowMaps​

▸ renderShadowMaps(renderer, entities?, instancePools?): void

Parameters​

NameType
rendererWebGLRenderer
entities?Object3D<Object3DEventMap>[]
instancePools?Group<Object3DEventMap>[]

Returns​

void


setAABBOverride​

▸ setAABBOverride(voxel, aabbs, owner?): void

Parameters​

NameType
voxelCoords3
aabbsAABB[]
owner?Coords3

Returns​

void


setBlockEntityDataAt​

▸ setBlockEntityDataAt(px, py, pz, data, options?): void

Parameters​

NameType
pxnumber
pynumber
pznumber
dataT
options?Object
options.replace?boolean

Returns​

void


setBlockSway​

▸ setBlockSway(idOrName, options?): void

Register a sway profile for a cutout block instead of compiling it a bespoke material: the block stays in its shared cutout bucket and its quads carry the profile's index into the table createSwayTableShader reads. Parameter defaults mirror createSwayShader; isCrossShaded selects the flattened cross-quad shading the dedicated cross materials used to bake in.

Parameters​

NameType
idOrNamestring | number
optionsPartial<{ amplitude: number ; isCrossShaded: boolean ; rooted: boolean ; scale: number ; speed: number ; yScale: number }>

Returns​

void


setBlockTextureFiltering​

▸ setBlockTextureFiltering(mode): void

Flips how every chunk atlas samples at glancing angles, live: no world rebuild, no chunk remesh, just the texture's filter/mip state (see AtlasTexture.applyFiltering, WorldOptions.blockTextureFiltering). Meant for an A/B run — flip it, hold a pose, measure, flip it back.

Parameters​

NameType
mode"nearest" | "mip-aniso"

Returns​

void


setResolutionOf​

▸ setResolutionOf(idOrName, faceNames, resolution): Promise<void>

Apply a resolution to a block. This will set the resolution of the block's texture atlas. Keep in mind that this face or faces must be independent.

Parameters​

NameTypeDescription
idOrNamestring | numberThe ID or name of the block.
faceNamesstring | string[]The face name or names to apply the resolution to.
resolutionnumber | { x: number ; y: number }The resolution to apply to the block, in pixels.

Returns​

Promise<void>


setSectionReveal​

▸ setSectionReveal(cx, cz, level, reveal): boolean

Draw a section partway through its own fog color: 0 is pure fog tint (the sky-dome gradient it would vanish into at distance), 1 is the section as itself. The terrain fade-in drives this per frame.

Reaches both render paths of a section. Its shared-opaque geometry lives in a region arena slot, whose per-instance batching color carries the value into vChunkReveal; everything else is a per-section mesh on a shared material, which gets the value through a per-draw uChunkReveal that is reset after each draw so the same material draws every other chunk unrevealed. Returns whether the section had anything to draw.

Parameters​

NameType
cxnumber
cznumber
levelnumber
revealnumber

Returns​

boolean


setShowGreedyDebug​

▸ setShowGreedyDebug(show): void

Parameters​

NameType
showboolean

Returns​

void


setSunlightAt​

▸ setSunlightAt(px, py, pz, level): void

Parameters​

NameType
pxnumber
pynumber
pznumber
levelnumber

Returns​

void


setTorchLightAt​

▸ setTorchLightAt(px, py, pz, level, color): void

Parameters​

NameType
pxnumber
pynumber
pznumber
levelnumber
colorLightColor

Returns​

void


setVoxelAt​

▸ setVoxelAt(px, py, pz, voxel): void

Parameters​

NameType
pxnumber
pynumber
pznumber
voxelnumber

Returns​

void


setVoxelRotationAt​

▸ setVoxelRotationAt(px, py, pz, rotation): void

Set a voxel rotation at a 3D world position.

Parameters​

NameTypeDescription
pxnumberThe x coordinate of the position.
pynumberThe y coordinate of the position.
pznumberThe z coordinate of the position.
rotationBlockRotationThe rotation to set.

Returns​

void


setVoxelStageAt​

▸ setVoxelStageAt(px, py, pz, stage): void

Parameters​

NameType
pxnumber
pynumber
pznumber
stagenumber

Returns​

void


setVoxelWaterlogLevelAt​

▸ setVoxelWaterlogLevelAt(px, py, pz, level): void

Parameters​

NameType
pxnumber
pynumber
pznumber
levelnumber

Returns​

void


setVoxelWaterloggedAt​

▸ setVoxelWaterloggedAt(px, py, pz, isWaterlogged): void

Parameters​

NameType
pxnumber
pynumber
pznumber
isWaterloggedboolean

Returns​

void


textureCensus​

▸ textureCensus(): TextureCensus

What every block surface is wearing right now: atlas slots, own-texture face defaults, and every voxel's isolated face, with the ones not yet in their own art listed worst first. The harness asserts on this after a load; a human would otherwise be hunting the scene for magenta.

Returns​

TextureCensus


transparentMediumAt​

▸ transparentMediumAt(x, y, z): TransparentMedium

The medium at a world position, for TRANSPARENT_SORT.

Parameters​

NameType
xnumber
ynumber
znumber

Returns​

TransparentMedium


update​

▸ update(position?, direction?, camera?, isSpectating?): void

Parameters​

NameTypeDefault value
positionVector3undefined
directionVector3undefined
camera?Cameraundefined
isSpectatingbooleanfalse

Returns​

void


updateShaderLighting​

▸ updateShaderLighting(camera, position): void

Parameters​

NameType
cameraCamera
positionVector3

Returns​

void


updateSkyAndClouds​

▸ updateSkyAndClouds(position): void

Parameters​

NameType
positionVector3

Returns​

void


updateVoxel​

▸ updateVoxel(vx, vy, vz, type, options): void

This sends a block update to the server and updates across the network. Block updates are queued to World.chunks | World.chunks.toUpdate and scaffolded to the server WorldClientOptions.maxUpdatesPerUpdate times per tick. Keep in mind that for rotation and y-rotation, the value should be one of the following:

This ignores blocks that are not defined, and also ignores rotations for blocks that are not Block.rotatable (Same for if block is not Block.yRotatable).

Parameters​

NameTypeDescription
vxnumberThe voxel's X position.
vynumberThe voxel's Y position.
vznumberThe voxel's Z position.
typenumberThe type of the voxel.
optionsObjectThe options for the voxel.
options.rotation?numberThe major axis rotation of the voxel.
options.source?"client" | "server"Whether the update is from the client or server. Defaults to "client".
options.stage?numberThe stage of the voxel.
options.yRotation?numberThe Y rotation on the major axis. Applies to blocks with major axis of PY or NY.

Returns​

void


updateVoxels​

▸ updateVoxels(updates, source?): void

Parameters​

NameTypeDefault value
updatesBlockUpdate[]undefined
source"client" | "server""client"

Returns​

void


updateWaterOptics​

▸ updateWaterOptics(cameraPosition, deltaSeconds): void

Parameters​

NameType
cameraPositionVector3
deltaSecondsnumber

Returns​

void