Skip to content

Voxel.Renderer

JollyPixel Voxel Engine and Renderer

๐Ÿ“Œ About โ€‹

Chunked voxel engine and Three.js renderer. Use VoxelEngine directly, or VoxelRenderer to plug it into a JollyPixel engine (ECS) scene. Either way you get multi-layer voxel worlds with tileset textures, face culling, block transforms, JSON save/load, and optional physics via a pluggable collider interface (Rapier3D included).

๐Ÿ’ก Features โ€‹

  • Chunked world (default 16ยณ) - only dirty chunks are rebuilt each frame, the rest are left alone
  • Named layers composited top-down; decorative layers override base terrain without Z-fighting
  • Toggle visibility, reorder, add/remove layers, and move them in world space
  • Face culling between adjacent solid voxels to keep triangle counts low
  • Optional greedy meshing (greedy: true) merging coplanar identical faces - about 3x fewer triangles on terrain
  • Many built-in block shapes (cube, slabs, ramp, corners, pole, stairs) and a BlockShape interface for custom geometry
  • Per-block transforms via a packed byte - 90ยฐ Y rotations and X/Z flips without duplicating definitions
  • Multiple tilesets at different resolutions; tiles referenced by { tilesetId, col, row }
  • Per-face texture overrides on any block definition
  • "lambert" (default) or "standard" (PBR) material modes
  • Configurable alphaTest for foliage and sprite-style cutout blocks
  • save() / load() round-trips the full world state as plain JSON
  • TiledConverter to import Tiled .tmj maps in "stacked" or "flat" layer modes
  • Optional physics through the backend-agnostic VoxelCollider interface, with "box" or "trimesh" colliders rebuilt per dirty chunk and a Rapier3D plugin included; zero extra dependency if omitted
  • Compatible with JollyPixel engine logger
  • Debug mode (engine.debug) exposing live face/triangle counts and a wireframe view of the meshed chunks

NOTE

The implementation and optimization are probably far from perfect. Feel free to open a PR to help us.

๐Ÿ’ƒ Getting Started โ€‹

This package is available in the Node Package Repository and can be easily installed with npm or yarn.

bash
$ npm i @jolly-pixel/voxel.renderer
# or
$ yarn add @jolly-pixel/voxel.renderer

๐Ÿ‘€ Usage example โ€‹

Basic - place voxels manually โ€‹

ts
const blocks: BlockDefinition[] = [
  {
    id: 1,
    name: "Dirt",
    shapeId: "cube",
    collidable: true,
    faceTextures: {
      [Face.PosY]: {
        tilesetId: "default",
        col: 0,
        row: 2
      },
      [Face.NegX]: {
        tilesetId: "default",
        col: 0,
        row: 1
      },
      [Face.NegZ]: {
        tilesetId: "default",
        col: 0,
        row: 1
      },
      [Face.PosX]: {
        tilesetId: "default",
        col: 0,
        row: 1
      },
      [Face.PosZ]: {
        tilesetId: "default",
        col: 0,
        row: 1
      }
    },
    defaultTexture: {
      tilesetId: "default",
      col: 2,
      row: 0
    }
  }
];

const voxelMap = world.createActor("map")
  .addComponentAndGet(VoxelRenderer, {
    chunkSize: 16,
    layers: ["Ground"],
    blocks
  });

voxelMap.engine.loadTileset({
  id: "default",
  src: "tileset/UV_cube.png",
  tileSize: 32
});

// Place a flat 8ร—8 ground plane
for (let x = 0; x < 8; x++) {
  for (let z = 0; z < 8; z++) {
    voxelMap.engine.setVoxel("Ground", {
      position: { x, y: 0, z },
      blockId: 1
    });
  }
}

Tiled import - convert a .tmj map โ€‹

ts
import { loadJSON } from "@jolly-pixel/engine";
import {
  VoxelRenderer,
  TiledConverter,
  type TiledMap
} from "@jolly-pixel/voxel.renderer";

// No blocks or layers needed here - load() restores them from the JSON snapshot
const voxelMap = world.createActor("map")
  .addComponentAndGet(VoxelRenderer, { alphaTest: 0.1, material: "lambert" });

const tiledMap = await loadJSON<TiledMap>("tilemap/map.tmj");

const worldJson = new TiledConverter().convert(tiledMap, {
  // Map Tiled .tsx source references to the PNG files served by your dev server
  resolveTilesetSrc: (src) => "tilemap/" + src.replace(/\.tsx$/, ".png"),
  layerMode: "stacked"
});

voxelMap.engine.load(worldJson);

await loadRuntime(runtime);

Rapier3D physics โ€‹

Physics is plugged in through the backend-agnostic VoxelCollider interface

ts
import Rapier from "@dimforge/rapier3d-compat";
import { RapierVoxelCollider } from "@jolly-pixel/voxel.renderer/plugins/rapier/index.js";

await Rapier.init();
const rapierWorld = new Rapier.World({
  x: 0,
  y: -9.81,
  z: 0
});

// Step physics once per fixed tick, before the scene update
world.on("beforeFixedUpdate", () => rapierWorld.step());

const voxelMap = world.createActor("map")
  .addComponentAndGet(VoxelRenderer, {
    chunkSize: 16,
    layers: ["Ground"],
    blocks,
    collider: (context) => new RapierVoxelCollider({
      api: Rapier,
      world: rapierWorld,
      ...context
    })
  });

๐Ÿš€ Running the examples โ€‹

Seven interactive examples live in the examples/ directory and are served by Vite. Start the dev server from the package root:

bash
npm run dev -w @jolly-pixel/voxel.renderer

Then open one of these URLs in your browser:

URLScriptWhat it shows
http://localhost:5173/demo-physics.tsA 32ร—32 voxel terrain with a raised platform and a Rapier3D physics sphere you can roll around with arrow keys
http://localhost:5173/tileset.htmldemo-tileset.tsEvery tile in Tileset001.png laid out as UV-mapped quads with col/row labels, plus a rotating textured cube
http://localhost:5173/shapes.htmldemo-shapes.tsAll 19 built-in block shapes rendered as coloured meshes with a wireframe overlay and labelled name
http://localhost:5173/tiled.htmldemo-tiled.tsA multi-layer Tiled .tmj map imported via TiledConverter in "stacked" mode with WASD camera navigation
http://localhost:5173/noise-world.htmldemo-noise-world.tsA Minecraft-like world generated from simplex noise, with live renderer and mesh counters - the benchmark example
http://localhost:5173/flat-world.htmldemo-flat-world.tsA server-authoritative flat world edited by several browsers at once, with peer brushes over the room's presence channel
http://localhost:5173/transparency.htmldemo-transparency.tsA diorama for checking transparency and lighting: blended water and glass, cutout leaves/grates/windows with and without transparent: true, an alpha-gradient probe for alphaTest, and live light, material and layer controls

The shapes, tileset and transparency examples use OrbitControls (left drag: rotate, right drag: pan, scroll: zoom); the others use Camera3DControls (WASD + mouse).

๐Ÿ“š API โ€‹

  • VoxelEngine - Engine-agnostic core - options, voxel placement, tileset loading, save/load. Usable standalone or via VoxelRenderer.
  • VoxelRenderer - ActorComponent wrapper around VoxelEngine for JollyPixel scenes.
  • World - VoxelWorld, VoxelLayer, VoxelChunk, and related types.
  • Blocks - BlockDefinition, ResolvedBlockDefinition, BlockShape, BlockRegistry, BlockShapeRegistry, and Face.
  • Tileset - TilesetManager, TilesetDefinition, TileRef, UV regions.
  • Serialization - VoxelSerializer and JSON snapshot types.
  • Collision - The VoxelCollider contract and the bundled RapierVoxelCollider plugin.
  • Debug - engine.debug: live face/triangle statistics and wireframe visualization.
  • Built-In Shapes - All built-in block shapes and custom shape authoring.
  • TiledConverter - Converting Tiled .tmj exports to VoxelWorldJSON.
  • Asset kind - Persisting a voxel map as an event-sourced @jolly-pixel/asset-server asset.

๐Ÿงช Benchmarks โ€‹

Noise-world benchmark โ€‹

Use noise-world.html to measure the renderer under load. It builds a heightmap world from simplex noise and reports two separate costs: voxel writes via setVoxel and chunk meshing for dirty chunks.

It is configurable from the query string:

text
/noise-world.html?size=512&chunk=32&seed=42
ParamDefaultEffect
size256World width/depth in voxels (sizeยฒ columns)
chunk16chunkSize; trades draw calls against rebuild cost
seed1337Terrain seed; the same seed always yields the same world

Controls: WASD / Space / Shift to fly, R to rebuild with the next seed, F3 to hide the HUD.

Headless benchmark โ€‹

The browser HUD is only a sanity check; Vite's checker inflates timings. Run headless instead:

bash
npm run bench
npm run bench -- --greedy
npm run bench:compare

Use the minimum of three runs when comparing numbers, since single runs can drift a lot on a throttled machine.

๐Ÿ”ฅ Troubleshooting โ€‹

If something isn't working as expected, enable verbose logging to get detailed runtime output:

ts
// Enable debug logs for the entire runtime
const { world } = runtime;
world.logger.setLevel("debug");
world.logger.enableNamespace("*");

Alternatively, pass a custom Logger instance to VoxelRenderer:

ts
import { Systems } from "@jolly-pixel/engine";
import { VoxelRenderer } from "@jolly-pixel/voxel.renderer";

const vr = new VoxelRenderer({
  logger: new Systems.Logger({
    level: "trace",
    namespaces: ["*"]
  })
});

Quick tips

  • Tileset missing: verify the src path and ensure the image is being served (check browser Network tab and CORS).
  • Cutout/transparent textures look wrong: increase or decrease alphaTest (for example alphaTest: 0.1) to tune cutout thresholds.
  • Physics not working: make sure Rapier is initialized (await Rapier.init()) and that your collider factory returns a RapierVoxelCollider built with that World.
  • Chunks not updating or faces missing: face culling hides faces between adjacent solid voxels; confirm neighboring voxels are placed correctly.

Reporting issues

  • When opening an issue, include package and runtime versions, reproduction steps, and enable debug logs (see above). A minimal repro or screenshot speeds up investigation.

Contributors guide โ€‹

If you are a developer looking to contribute to the project, you must first read the CONTRIBUTING guide.

Once you have finished your development, check that the tests (and linter) are still good by running the following script:

bash
$ npm run test
$ npm run lint

CAUTION

In case you introduce a new feature or fix a bug, make sure to include tests for it as well.

License โ€‹

MIT