voxel

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package voxel provides chunked 3D voxel worlds with greedy meshing, cross-chunk face culling, incremental per-voxel sky and block light propagation, incremental dirty-chunk remeshing, DDA voxel raycasting, and deterministic versioned YAML persistence.

Coordinates follow github.com/nsgo-dev/game/pkg/math3d and github.com/nsgo-dev/game/pkg/render3d: right-handed Y-up space (+X right, +Y up, -Z forward), with counter-clockwise front-facing triangles. Voxel (x, y, z) occupies the world-space cube from (x, y, z)*VoxelSize to (x+1, y+1, z+1)*VoxelSize.

Editing a block with World.SetBlock updates sky and block light (0..15 each) incrementally across chunk boundaries, marks the edited chunk dirty, and marks adjacent existing chunks dirty only when face visibility, ambient occlusion, or lighting changes across their boundaries. Call Mesher.RemeshDirty (or World.RemeshDirty) each frame to rebuild only affected chunks into render3d.Mesh (or ChunkMesh.ColoredMesh for vertex-shaded render3d.ColoredMesh) buffers.

Index

Examples

Constants

View Source
const (
	// DefaultChunkSize is the default cubic chunk edge length (16x16x16 = 4096 voxels).
	DefaultChunkSize = 16
	// MinChunkSize is the smallest supported power-of-two chunk edge length.
	MinChunkSize = 4
	// MaxChunkSize is the largest supported power-of-two chunk edge length.
	MaxChunkSize = 64
	// DefaultVoxelSize is the default world-space size of one voxel edge.
	DefaultVoxelSize float32 = 1
)
View Source
const FormatVersion = 1

FormatVersion is the current voxel world YAML schema version.

View Source
const MaxLightLevel uint8 = 15

MaxLightLevel is the maximum per-voxel sky or block light level (0..15).

View Source
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL

SchemaComment is the first line Encode writes so YAML language servers validate and complete voxel world files automatically.

View Source
const SchemaURL = "https://game.nsgo.dev/schemas/voxel.v1.json"

SchemaURL is where the JSON Schema of version 1 voxel world documents is published.

Variables

View Source
var (
	ErrInvalidBlock   = errors.New("voxel: invalid block definition")
	ErrDuplicateBlock = errors.New("voxel: duplicate block definition")
	ErrRegistryFull   = errors.New("voxel: block registry is full")
)

Sentinel errors returned by Registry operations.

Functions

func AOFactor

func AOFactor(level uint8) float32

AOFactor converts a discrete ambient occlusion level (0..3) into a linear brightness multiplier in [0.25, 1.0].

func CombineLightColor

func CombineLightColor(sky, block uint8, aoScale float32, style LightStyle) math3d.Vec4

CombineLightColor evaluates the linear RGBA vertex color for a vertex with sky light (0..15), block light (0..15), and optional ambient occlusion scale (pass 1 when AO is disabled, or AOFactor(ao) when enabled).

func CompareChunkCoords

func CompareChunkCoords(a, b ChunkCoord) int

CompareChunkCoords orders two chunk coordinates lexicographically by X, Y, Z.

func Encode

func Encode(doc *WorldDoc) ([]byte, error)

Encode validates doc and serializes it as deterministic 2-space YAML prefixed with SchemaComment.

func LightFactor

func LightFactor(level uint8) float32

LightFactor converts a discrete sky or block light level (0..15) into a linear-space brightness multiplier in [0, 1]. Using a quadratic curve in linear space produces a perceptually even gradient after sRGB encoding in render3d.

func NewCollider

func NewCollider(w *World) *physics3d.VoxelCollider

NewCollider returns a *physics3d.VoxelCollider backed directly by w.

Overlap, raycast, and sweep queries read solid blocks directly from w without building a triangle mesh, so World.SetBlock edits take effect immediately with zero rebuild. When added to a *physics3d.World via physics3d.World.AddVoxelCollider, solid-block edits automatically wake sleeping dynamic bodies near the edited voxel.

func SaveYAML

func SaveYAML(w *World, name string) ([]byte, error)

SaveYAML encodes w as deterministic versioned YAML text.

func ValidChunkSize

func ValidChunkSize(n int) bool

ValidChunkSize reports whether n is a supported power-of-two chunk size.

func Validate

func Validate(doc *WorldDoc) error

Validate checks that doc conforms to the version 1 voxel world schema.

Types

type AABBMoveResult

type AABBMoveResult struct {
	// Box is the resolved world-space AABB after axis-separated collision and
	// optional ledge step-up.
	Box math3d.AABB
	// Moved is the actual displacement applied to Box (Box.Min - initial.Min).
	Moved math3d.Vec3
	// Grounded reports whether the resolved box rests on a solid block underneath.
	Grounded bool
	// OnWall reports whether horizontal movement was blocked on X or Z.
	OnWall bool
	// OnCeiling reports whether upward movement was blocked by a solid block above.
	OnCeiling bool
	// SteppedUp reports whether the box automatically climbed a ledge up to stepHeight.
	SteppedUp bool
	// WallNormal is the horizontal unit normal of the last blocking wall face,
	// or the zero vector when OnWall is false.
	WallNormal math3d.Vec3
}

AABBMoveResult reports the outcome of MoveAndSlideAABB.

func MoveAndSlideAABB

func MoveAndSlideAABB(w *World, box math3d.AABB, delta math3d.Vec3, stepHeight float32) AABBMoveResult

MoveAndSlideAABB moves an axis-aligned box through solid blocks in w by delta using axis-separated swept AABB resolution (Y, then X, then Z).

Because each axis sweeps strictly against faces perpendicular to that axis, flat floors and walls never snag on internal seams between adjacent blocks. When blocked horizontally while grounded and stepHeight > 0 (with delta.Y <= 0), MoveAndSlideAABB attempts an automatic step-up up to stepHeight (checking ceiling headroom and greater horizontal progress) so characters walk cleanly onto single-block ledges.

type BlockCoord

type BlockCoord struct {
	X, Y, Z int
}

BlockCoord is an integer voxel coordinate in world space.

func (BlockCoord) Add

func (c BlockCoord) Add(d BlockCoord) BlockCoord

Add returns c + d.

func (BlockCoord) Sub

func (c BlockCoord) Sub(d BlockCoord) BlockCoord

Sub returns c - d.

type BlockDef

type BlockDef struct {
	// ID is the numeric block ID. Pass 0 to Register to assign the next free ID.
	ID BlockID
	// Name is the unique human-readable block name used in YAML saves.
	Name string
	// Transparent marks blocks that do not hide opaque neighbors behind them
	// (such as glass or water). Faces between two identical transparent blocks
	// are culled.
	Transparent bool
	// NonSolid marks blocks skipped by default solid raycasts (such as water or tall grass).
	NonSolid bool
	// MaterialID groups emitted faces into SubMesh ranges during meshing.
	MaterialID uint32
	// Emissive is the block light level (0..15) emitted by this block into the
	// block-light channel (for example 14 for a torch or 15 for lava/glowstone).
	// Zero means the block emits no light.
	Emissive uint8
	// LightOpacity is the light attenuation (0..15) applied to light passing
	// through a Transparent block (for example 1 for leaves or 2 for water).
	// Zero lets direct sky light pass unattenuated and attenuates propagated
	// light by 1 per voxel step. Opaque blocks (Transparent == false) always
	// block incoming light completely (effective opacity 15).
	LightOpacity uint8
}

BlockDef describes a registered voxel block type.

Zero values represent an opaque, solid block with MaterialID 0, so BlockDef{Name: "stone"} works with minimal configuration.

type BlockDoc

type BlockDoc struct {
	// ID is the non-zero numeric block ID referenced by chunk runs.
	ID BlockID `yaml:"id" schema:"required,minimum=1"`
	// Name is the unique human-readable name of the block type.
	Name string `yaml:"name" schema:"required,minLength=1"`
	// Transparent marks blocks whose neighbors remain visible behind them (such as glass or water).
	Transparent bool `yaml:"transparent,omitempty"`
	// NonSolid marks blocks excluded from solid collision and default raycasts.
	NonSolid bool `yaml:"nonSolid,omitempty"`
	// MaterialID groups emitted faces into SubMesh ranges when meshing.
	MaterialID uint32 `yaml:"materialId,omitempty"`
	// Emissive is the block light level (0..15) emitted into the block-light channel.
	Emissive uint8 `yaml:"emissive,omitempty" schema:"minimum=0,maximum=15"`
	// LightOpacity is the light attenuation (0..15) for transparent blocks; 0 lets direct sky light pass and attenuates propagated light by 1.
	LightOpacity uint8 `yaml:"lightOpacity,omitempty" schema:"minimum=0,maximum=15"`
}

BlockDoc describes one non-air block type in a WorldDoc palette.

type BlockID

type BlockID uint16

BlockID identifies a block type stored in a voxel chunk. ID 0 is always Air.

const Air BlockID = 0

Air is the reserved empty block ID (0).

type CharacterMoveResult

type CharacterMoveResult struct {
	Pos        math3d.Vec3
	Grounded   bool
	OnWall     bool
	OnCeiling  bool
	SteppedUp  bool
	WallNormal math3d.Vec3
}

CharacterMoveResult summarizes the outcome of CharacterMover.Move.

type CharacterMover

type CharacterMover struct {
	// Pos is the world-space bottom-center of the character's AABB (feet).
	Pos math3d.Vec3
	// HalfWidth is the half-extent along X.
	HalfWidth float32
	// HalfDepth is the half-extent along Z.
	HalfDepth float32
	// Height is the full vertical height of the AABB along +Y.
	Height float32
	// StepHeight is the maximum vertical ledge height climbed automatically while
	// grounded. NewCharacterMover defaults this to 1.0 (one default voxel); set
	// to 0 to disable automatic step-up.
	StepHeight float32
	// Gravity is the vertical acceleration in units/s^2 (negative for -Y).
	// NewCharacterMover defaults this to -9.81.
	Gravity float32
	// Vel is the character's current velocity in units per second.
	Vel math3d.Vec3
	// Grounded reports whether the character ended the last Move on solid blocks.
	Grounded bool
	// OnWall reports whether the last Move was blocked horizontally.
	OnWall bool
	// OnCeiling reports whether the last Move hit a ceiling block above.
	OnCeiling bool
	// WallNormal is the horizontal unit normal of the last blocking wall hit.
	WallNormal math3d.Vec3
}

CharacterMover drives a simple axis-aligned box character directly against a voxel World using axis-separated AABB move-and-slide with gravity, jumping, and automatic single-block ledge step-up, without needing a physics3d.World.

Pos is the world-space bottom-center of the character's box (the feet).

func NewCharacterMover

func NewCharacterMover(pos math3d.Vec3, halfWidth, height float32) *CharacterMover

NewCharacterMover returns a CharacterMover centered horizontally at pos (feet at pos.Y) with square horizontal footprint [-halfWidth, +halfWidth], vertical height, default StepHeight of 1.0, and Gravity of -9.81.

func (*CharacterMover) Bounds

func (c *CharacterMover) Bounds() math3d.AABB

Bounds returns the character's current world-space AABB.

func (*CharacterMover) Move

func (c *CharacterMover) Move(w *World, wishMove math3d.Vec3, dt time.Duration) CharacterMoveResult

Move advances the character through w for dt using axis-separated AABB move-and-slide. wishMove.X and wishMove.Z set horizontal velocity directly; a non-zero wishMove.Y sets Vel.Y (such as for a jump) while wishMove.Y == 0 lets Gravity govern vertical motion.

type Chunk

type Chunk struct {
	// contains filtered or unexported fields
}

Chunk stores a dense cubic N x N x N grid of BlockID values in (y, z, x) order (index = (y*N + z)*N + x), alongside per-voxel sky and block light levels packed into one byte per voxel (high nibble: sky 0..15, low nibble: block 0..15).

func (*Chunk) BlockLight

func (c *Chunk) BlockLight(lx, ly, lz int) uint8

BlockLight returns the stored block light level (0..15) at chunk-local coordinates (lx, ly, lz), or 0 if out of bounds. Use World.BlockLight for cross-chunk world-coordinate queries.

func (*Chunk) Blocks

func (c *Chunk) Blocks() []BlockID

Blocks returns the chunk's underlying block slice in (y, z, x) order (index = (y*N + z)*N + x). Callers should treat it as read-only; edit blocks via World.SetBlock so dirty tracking stays accurate.

func (*Chunk) Bounds

func (c *Chunk) Bounds(voxelSize float32) math3d.AABB

Bounds returns the world-space axis-aligned bounding box of c.

func (*Chunk) Coord

func (c *Chunk) Coord() ChunkCoord

Coord returns the chunk's integer coordinate in chunk space.

func (*Chunk) Dirty

func (c *Chunk) Dirty() bool

Dirty reports whether c has unmeshed edits.

func (*Chunk) Empty

func (c *Chunk) Empty() bool

Empty reports whether every voxel in c is Air.

func (*Chunk) Get

func (c *Chunk) Get(lx, ly, lz int) BlockID

Get returns the block at chunk-local coordinates (lx, ly, lz), or Air if out of bounds.

func (*Chunk) Light

func (c *Chunk) Light(lx, ly, lz int) (sky, block uint8)

Light returns both the stored sky light and block light levels (0..15 each) at chunk-local coordinates (lx, ly, lz), or (0, 0) if out of bounds.

func (*Chunk) NonAirCount

func (c *Chunk) NonAirCount() int

NonAirCount returns the number of non-air voxels in c.

func (*Chunk) Revision

func (c *Chunk) Revision() uint64

Revision returns a monotonically increasing edit counter for c.

func (*Chunk) Size

func (c *Chunk) Size() int

Size returns the chunk's edge length N.

func (*Chunk) SkyLight

func (c *Chunk) SkyLight(lx, ly, lz int) uint8

SkyLight returns the stored sky light level (0..15) at chunk-local coordinates (lx, ly, lz), or 0 if out of bounds. Use World.SkyLight for cross-chunk world-coordinate queries.

type ChunkCoord

type ChunkCoord struct {
	X, Y, Z int
}

ChunkCoord is an integer chunk index in chunk-grid space.

func (ChunkCoord) Add

func (c ChunkCoord) Add(d ChunkCoord) ChunkCoord

Add returns c + d.

func (ChunkCoord) Sub

func (c ChunkCoord) Sub(d ChunkCoord) ChunkCoord

Sub returns c - d.

type ChunkDoc

type ChunkDoc struct {
	// X is the chunk's X index in chunk-grid coordinates.
	X int `yaml:"x"`
	// Y is the chunk's Y index in chunk-grid coordinates.
	Y int `yaml:"y"`
	// Z is the chunk's Z index in chunk-grid coordinates.
	Z int `yaml:"z"`
	// Runs holds run-length encoded block tokens ("id*count" or "id" for count 1) in (y, z, x) order whose counts sum to chunkSize^3.
	Runs []string `yaml:"runs" schema:"required,minItems=1"`
}

ChunkDoc stores one non-empty chunk using run-length encoded block runs in (y, z, x) order.

type ChunkMesh

type ChunkMesh struct {
	// Coord is the chunk's grid coordinate.
	Coord ChunkCoord
	// Origin is the world-space minimum corner of the chunk.
	Origin math3d.Vec3
	// Bounds is the tight axis-aligned bounding box of Mesh.Positions, or
	// math3d.AABBEmpty when the chunk emitted no faces.
	Bounds math3d.AABB
	// Mesh holds CCW front-facing indexed triangle geometry compatible with
	// render3d.UploadMesh.
	Mesh render3d.Mesh
	// SubMeshes partitions Mesh.Indices by BlockDef.MaterialID in ascending
	// MaterialID order.
	SubMeshes []SubMesh
	// AO holds per-vertex ambient occlusion levels in [0, 3] (3 = unoccluded,
	// 0 = fully occluded) when MeshOptions.AmbientOcclusion is true; nil otherwise.
	AO []uint8
	// SkyLight holds per-vertex sky light levels in [0, 15] when
	// MeshOptions.Lighting is true; nil otherwise.
	SkyLight []uint8
	// BlockLight holds per-vertex block light levels in [0, 15] when
	// MeshOptions.Lighting is true; nil otherwise.
	BlockLight []uint8
	// Colors holds per-vertex linear RGBA shading colors combining sky light,
	// block light, and AO when MeshOptions.Lighting is true; nil otherwise.
	Colors []math3d.Vec4
	// QuadCount is the number of emitted quads (len(Mesh.Indices) / 6).
	QuadCount int
}

ChunkMesh holds the triangulated geometry generated for one chunk, ready to upload with render3d.UploadMesh or (with vertex light/AO colors) render3d.UploadColoredMesh via ChunkMesh.ColoredMesh.

func (ChunkMesh) ColoredMesh

func (cm ChunkMesh) ColoredMesh() render3d.ColoredMesh

ColoredMesh returns a render3d.ColoredMesh ready for render3d.UploadColoredMesh and colored render3d pipelines (such as render3d.NewUnlitPipeline or render3d.NewMaterialPipeline with VertexColors: true).

When ChunkMesh.Colors is populated (from MeshOptions.Lighting), it is used directly. Otherwise, if ChunkMesh.AO is populated, grayscale linear AO colors are generated; if neither is populated, Colors is nil (which render3d uploads as linear white).

func (ChunkMesh) Empty

func (cm ChunkMesh) Empty() bool

Empty reports whether the chunk produced no visible triangles.

type Face

type Face uint8

Face identifies one of the six axis-aligned faces of a voxel cube.

const (
	FacePosX Face = iota // +X (east)
	FaceNegX             // -X (west)
	FacePosY             // +Y (up / top)
	FaceNegY             // -Y (down / bottom)
	FacePosZ             // +Z (south)
	FaceNegZ             // -Z (north)
	// FaceCount is the number of cube face directions.
	FaceCount = 6
)

func (Face) Normal

func (f Face) Normal() math3d.Vec3

Normal returns the outward unit normal of face f.

func (Face) Opposite

func (f Face) Opposite() Face

Opposite returns the face pointing in the opposite direction.

func (Face) Step

func (f Face) Step() BlockCoord

Step returns the integer neighbor offset in the direction of face f.

func (Face) String

func (f Face) String() string

String returns a short human-readable label such as "+Y".

type LightStyle

type LightStyle struct {
	// SkyColor is the linear RGB tint at maximum sky light (level 15).
	// When both SkyColor and BlockColor are zero, [DefaultLightStyle] is used.
	SkyColor math3d.Vec3
	// BlockColor is the linear RGB tint at maximum block light (level 15).
	BlockColor math3d.Vec3
	// Ambient is the minimum linear brightness floor when both sky and block
	// light are 0 (for example 0.03 so unlit caves remain faintly visible).
	Ambient float32
}

LightStyle controls how per-vertex sky light, block light, and ambient occlusion combine into linear RGB vertex colors in ChunkMesh.Colors.

func DefaultLightStyle

func DefaultLightStyle() LightStyle

DefaultLightStyle returns a neutral linear lighting style with white daylight (1, 1, 1), white block light (1, 1, 1), and zero ambient floor.

type MeshOptions

type MeshOptions struct {
	// AmbientOcclusion computes per-vertex Minecraft-style ambient occlusion
	// levels (0..3) in ChunkMesh.AO and flips quad diagonals to avoid
	// interpolation artifacts. Faces merge only when all four AO corners match.
	AmbientOcclusion bool
	// Lighting samples per-voxel sky and block light levels (0..15) across chunk
	// boundaries into ChunkMesh.SkyLight, ChunkMesh.BlockLight, and linear RGBA
	// vertex colors in ChunkMesh.Colors (ready for ChunkMesh.ColoredMesh and
	// render3d). Greedy meshing merges faces only when lighting matches.
	Lighting bool
	// SmoothLighting enables 4-voxel corner light averaging when Lighting is
	// true, eliminating per-block lighting stair-steps across faces and chunk
	// boundaries. Ignored when Lighting is false.
	SmoothLighting bool
	// LightStyle controls how sky light, block light, and ambient occlusion
	// combine into ChunkMesh.Colors when Lighting is true. The zero value uses
	// [DefaultLightStyle].
	LightStyle LightStyle
	// WorldSpace offsets emitted vertex positions by ChunkMesh.Origin so the
	// mesh can be drawn with an identity model transform. When false (default),
	// positions are chunk-local in [0, ChunkSize*VoxelSize].
	WorldSpace bool
	// DisableGreedy emits one quad per visible voxel face without merging
	// coplanar neighbors. Useful for comparison benchmarks and debugging.
	DisableGreedy bool
	// IgnoreNeighbors treats voxels outside the chunk as Air instead of
	// sampling neighboring chunks for face culling, ambient occlusion, and
	// lighting.
	IgnoreNeighbors bool
	// UVMode controls quad UV scaling (default UVWorld).
	UVMode UVMode
}

MeshOptions configures greedy chunk meshing. The zero value enables greedy meshing, cross-chunk neighbor culling, chunk-local vertex positions, and tiling UVWorld coordinates.

type Mesher

type Mesher struct {
	// contains filtered or unexported fields
}

Mesher builds chunk meshes using reusable scratch buffers so incremental per-frame remeshing avoids temporary working-set allocations. A Mesher is not safe for concurrent use by multiple goroutines; give each worker its own Mesher.

func NewMesher

func NewMesher() *Mesher

NewMesher returns a reusable Mesher.

func (*Mesher) MeshChunk

func (m *Mesher) MeshChunk(w *World, cc ChunkCoord, opts MeshOptions) ChunkMesh

MeshChunk builds a ChunkMesh for the chunk at cc in w. If cc does not exist or has no visible faces, MeshChunk returns an empty ChunkMesh with Coord and Origin populated.

func (*Mesher) RemeshDirty

func (m *Mesher) RemeshDirty(w *World, opts MeshOptions) []ChunkMesh

RemeshDirty meshes every chunk currently marked dirty in w in deterministic CompareChunkCoords order, clears their dirty flags, and returns the rebuilt ChunkMesh list. Chunks that became completely empty still appear in the result with Empty()==true so callers can discard stale GPU meshes.

type RaycastHit

type RaycastHit struct {
	// Block is the integer coordinate of the struck voxel.
	Block BlockCoord
	// Adjacent is the empty voxel coordinate immediately outside the struck
	// face (Block.Add(Face.Step())), where a newly placed block belongs.
	Adjacent BlockCoord
	// Face is the face of Block that the ray entered.
	Face Face
	// Normal is the outward unit normal of Face.
	Normal math3d.Vec3
	// Point is the world-space intersection point on the face.
	Point math3d.Vec3
	// Distance is the Euclidean distance from ray.Origin to Point.
	Distance float32
	// BlockID is the block stored at Block.
	BlockID BlockID
}

RaycastHit describes the first voxel struck by a raycast.

type RaycastOptions

type RaycastOptions struct {
	// IncludeNonSolid causes raycasts to stop on any non-air block, including
	// blocks registered with NonSolid=true (such as water or foliage).
	IncludeNonSolid bool
}

RaycastOptions configures World.RaycastWith.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry maps block IDs and names to their BlockDef properties. Block ID 0 is always pre-registered as "air" (transparent and non-solid). Unregistered non-zero block IDs are treated as opaque, solid, MaterialID 0 so worlds can also use raw block IDs without pre-registration.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns a Registry containing only Air (ID 0, name "air").

func (*Registry) All

func (r *Registry) All() []BlockDef

All returns all registered non-air block definitions sorted by BlockID.

func (*Registry) ByName

func (r *Registry) ByName(name string) (BlockDef, bool)

ByName returns the BlockDef registered under name.

func (*Registry) Clone

func (r *Registry) Clone() *Registry

Clone returns an independent copy of r.

func (*Registry) Emissive

func (r *Registry) Emissive(id BlockID) uint8

Emissive returns the block light emission level (0..15) of id, or 0 if Air or unregistered.

func (*Registry) Get

func (r *Registry) Get(id BlockID) (BlockDef, bool)

Get returns the BlockDef for id and whether it was registered.

func (*Registry) IsOpaque

func (r *Registry) IsOpaque(id BlockID) bool

IsOpaque reports whether id blocks visibility of adjacent faces and casts ambient occlusion. Air is never opaque; unregistered non-zero IDs are opaque.

func (*Registry) IsSolid

func (r *Registry) IsSolid(id BlockID) bool

IsSolid reports whether id is solid for collision and default raycasts. Air is never solid; unregistered non-zero IDs are solid.

func (*Registry) IsTransparent

func (r *Registry) IsTransparent(id BlockID) bool

IsTransparent reports whether id is air or registered with Transparent=true.

func (*Registry) LightOpacity

func (r *Registry) LightOpacity(id BlockID) uint8

LightOpacity returns the light attenuation (0..15) of id. Air returns 0; opaque blocks (including unregistered non-zero IDs) return MaxLightLevel (15); transparent blocks return their configured LightOpacity.

func (*Registry) MaterialID

func (r *Registry) MaterialID(id BlockID) uint32

MaterialID returns the material group ID of id, or 0 if unregistered.

func (*Registry) MustRegister

func (r *Registry) MustRegister(def BlockDef) BlockID

MustRegister calls Register and panics on error.

func (*Registry) Register

func (r *Registry) Register(def BlockDef) (BlockID, error)

Register adds def to the registry and returns its assigned non-zero BlockID. When def.ID is 0, the lowest unused ID starting from 1 is assigned.

type SubMesh

type SubMesh struct {
	MaterialID uint32
	FirstIndex uint32
	IndexCount uint32
}

SubMesh describes a contiguous index range in ChunkMesh.Mesh sharing one BlockDef.MaterialID.

type UVMode

type UVMode uint8

UVMode controls how texture coordinates are assigned to merged voxel quads.

const (
	// UVWorld spans UVs from (0, 0) to (width, height) in voxel units so
	// repeating textures tile seamlessly across greedy-merged quads.
	UVWorld UVMode = iota
	// UVUnit assigns [0, 1] x [0, 1] UVs to each quad regardless of size.
	UVUnit
)

type World

type World struct {
	// contains filtered or unexported fields
}

World holds a sparse collection of cubic voxel chunks indexed by ChunkCoord, tracks which chunks need remeshing after edits, maintains incremental per-voxel sky and block light propagation, and provides raycasting, direct collision, and YAML persistence.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/math3d"
	"github.com/nsgo-dev/game/pkg/voxel"
)

func main() {
	reg := voxel.NewRegistry()
	stone := reg.MustRegister(voxel.BlockDef{Name: "stone"})
	glass := reg.MustRegister(voxel.BlockDef{Name: "glass", Transparent: true})

	w, _ := voxel.NewWorld(voxel.WorldConfig{ChunkSize: 16, Registry: reg})
	w.FillBox(voxel.BlockCoord{X: 0, Y: 0, Z: 0}, voxel.BlockCoord{X: 15, Y: 0, Z: 15}, stone)
	w.SetBlock(voxel.BlockCoord{X: 4, Y: 1, Z: 4}, glass)

	mesher := voxel.NewMesher()
	meshes := mesher.RemeshDirty(w, voxel.MeshOptions{AmbientOcclusion: true})
	fmt.Printf("initial chunks meshed: %d\n", len(meshes))

	// Raycast down onto the glass block and place a stone block on top of it.
	hit, ok := w.Raycast(math3d.Ray{
		Origin: math3d.Vec3{X: 4.5, Y: 5, Z: 4.5},
		Dir:    math3d.Vec3{X: 0, Y: -1, Z: 0},
	}, 10)
	if ok {
		w.SetBlock(hit.Adjacent, stone)
		updated := mesher.RemeshDirty(w, voxel.MeshOptions{AmbientOcclusion: true})
		fmt.Printf("hit=%v placed=%v remeshed=%d\n", hit.Block, hit.Adjacent, len(updated))
	}

}
Output:
initial chunks meshed: 1
hit={4 1 4} placed={4 2 4} remeshed=1

func FromDoc

func FromDoc(doc *WorldDoc) (*World, error)

FromDoc validates doc and constructs a World populated with its palette and chunks. Every loaded chunk is marked dirty so Mesher.RemeshDirty builds initial meshes for the world.

func LoadYAML

func LoadYAML(data []byte) (*World, string, error)

LoadYAML parses YAML bytes and returns the reconstructed World and document Name.

func LoadYAMLWith

func LoadYAMLWith(data []byte, file string) (*World, string, error)

LoadYAMLWith is LoadYAML with an optional source file name attached to errors.

func NewWorld

func NewWorld(cfg WorldConfig) (*World, error)

NewWorld constructs an empty World with cfg. Invalid ChunkSize or VoxelSize values return an error.

func (*World) Block

func (w *World) Block(pos BlockCoord) BlockID

Block returns the BlockID at world voxel coordinate pos, or Air if the chunk is not allocated.

func (*World) BlockBounds

func (w *World) BlockBounds(pos BlockCoord) math3d.AABB

BlockBounds returns the world-space axis-aligned bounding box of voxel pos.

func (*World) BlockLight

func (w *World) BlockLight(pos BlockCoord) uint8

BlockLight returns the block light level (0..15) at world voxel coordinate pos.

func (*World) BlockToChunk

func (w *World) BlockToChunk(pos BlockCoord) (cc ChunkCoord, lx, ly, lz int)

BlockToChunk splits a world voxel coordinate into its chunk coordinate and chunk-local coordinates (lx, ly, lz) in [0, ChunkSize).

func (*World) Bounds

func (w *World) Bounds() math3d.AABB

Bounds returns the world-space axis-aligned bounding box enclosing all non-empty chunks, or math3d.AABBEmpty when the world has no non-air blocks.

func (*World) Chunk

func (w *World) Chunk(cc ChunkCoord) *Chunk

Chunk returns the allocated chunk at cc, or nil if none exists.

func (*World) ChunkCoords

func (w *World) ChunkCoords() []ChunkCoord

ChunkCoords returns all allocated chunk coordinates sorted by CompareChunkCoords.

func (*World) ChunkCount

func (w *World) ChunkCount() int

ChunkCount returns the number of currently allocated chunks (including empty chunks that have not yet been pruned).

func (*World) ChunkOrigin

func (w *World) ChunkOrigin(cc ChunkCoord) BlockCoord

ChunkOrigin returns the world voxel coordinate of local (0, 0, 0) in cc.

func (*World) ChunkSize

func (w *World) ChunkSize() int

ChunkSize returns the edge length N of each cubic chunk.

func (*World) ChunkWorldOrigin

func (w *World) ChunkWorldOrigin(cc ChunkCoord) math3d.Vec3

ChunkWorldOrigin returns the world-space position of local (0, 0, 0) in cc.

func (*World) Clear

func (w *World) Clear()

Clear removes all chunks, light data, and dirty flags from w while keeping its ChunkSize, VoxelSize, and Registry.

func (*World) ClearDirty

func (w *World) ClearDirty(cc ChunkCoord)

ClearDirty clears the dirty flag on cc.

func (*World) Collider

func (w *World) Collider() *physics3d.VoxelCollider

Collider returns a *physics3d.VoxelCollider backed directly by w. It is equivalent to NewCollider(w).

func (*World) DirtyChunks

func (w *World) DirtyChunks() []ChunkCoord

DirtyChunks returns all dirty chunk coordinates sorted by CompareChunkCoords.

func (*World) DirtyCount

func (w *World) DirtyCount() int

DirtyCount returns the number of chunks currently marked dirty.

func (*World) FillBox

func (w *World) FillBox(a, b BlockCoord, id BlockID) int

FillBox fills every voxel in the inclusive box [minPos, maxPos] with id and returns the number of voxels that changed. Min/max components are ordered automatically per axis.

func (*World) IsDirty

func (w *World) IsDirty(cc ChunkCoord) bool

IsDirty reports whether cc is currently marked dirty.

func (*World) IsSolid

func (w *World) IsSolid(pos BlockCoord) bool

IsSolid reports whether the block at world voxel coordinate pos is solid according to the world's Registry. Unallocated chunks contain Air and are not solid.

func (*World) Light

func (w *World) Light(pos BlockCoord) (sky, block uint8)

Light returns both the sky light and block light levels (0..15 each) at pos.

func (*World) MarkDirty

func (w *World) MarkDirty(cc ChunkCoord)

MarkDirty marks cc dirty if it exists in w.

func (*World) MeshChunk

func (w *World) MeshChunk(cc ChunkCoord, opts MeshOptions) ChunkMesh

MeshChunk is a convenience wrapper around Mesher.MeshChunk for one-off builds. For repeated per-frame remeshing, keep a reusable Mesher.

func (*World) PruneEmptyChunks

func (w *World) PruneEmptyChunks() int

PruneEmptyChunks removes all allocated chunks that contain only Air and are not dirty, returning the number of chunks freed. Any non-default light passing through a pruned air chunk is preserved seamlessly.

func (*World) Raycast

func (w *World) Raycast(ray math3d.Ray, maxDist float32) (RaycastHit, bool)

Raycast walks voxels along ray using 3D DDA (Amanatides & Woo) up to maxDist world-space units (ray.Dir need not be unit-length) and returns the first solid block hit. Use World.RaycastWith to include non-solid blocks.

func (*World) RaycastWith

func (w *World) RaycastWith(ray math3d.Ray, maxDist float32, opts RaycastOptions) (RaycastHit, bool)

RaycastWith is World.Raycast with configurable filtering options.

func (*World) RecomputeLight

func (w *World) RecomputeLight()

RecomputeLight recomputes sky light and block light across the entire world from scratch and marks any existing non-empty chunks whose light (or border neighbor light) changed as dirty.

func (*World) Registry

func (w *World) Registry() *Registry

Registry returns the world's block Registry.

func (*World) RemeshDirty

func (w *World) RemeshDirty(opts MeshOptions) []ChunkMesh

RemeshDirty is a convenience wrapper around Mesher.RemeshDirty.

func (*World) SetBlock

func (w *World) SetBlock(pos BlockCoord, id BlockID) bool

SetBlock sets the voxel at pos to id and returns whether the block changed.

When the block changes, SetBlock updates sky and block light incrementally, marks the edited chunk dirty, and marks adjacent existing chunks dirty only when face visibility, cross-chunk ambient occlusion, or voxel lighting changes across their boundaries.

func (*World) SkyLight

func (w *World) SkyLight(pos BlockCoord) uint8

SkyLight returns the sky light level (0..15) at world voxel coordinate pos. Voxels above the world return MaxLightLevel (15). Voxels below the lowest non-empty chunk return the sky light at the bottom of that column.

func (*World) ToDoc

func (w *World) ToDoc(name string) *WorldDoc

ToDoc exports w as a canonical deterministic WorldDoc: palette entries sorted by ID, non-empty chunks sorted by CompareChunkCoords, and block grids compressed with canonical merged run-length encoding.

func (*World) VoxelSize

func (w *World) VoxelSize() float32

VoxelSize returns the world-space edge length of one voxel.

func (*World) WorldToBlock

func (w *World) WorldToBlock(p math3d.Vec3) BlockCoord

WorldToBlock converts a world-space position to the enclosing integer voxel coordinate.

type WorldConfig

type WorldConfig struct {
	// ChunkSize is the power-of-two cubic edge length of each chunk (4..64).
	// Zero uses DefaultChunkSize (16).
	ChunkSize int
	// VoxelSize is the world-space edge length of each voxel.
	// Zero uses DefaultVoxelSize (1.0).
	VoxelSize float32
	// Registry defines block properties. Nil creates a new empty Registry
	// where Air (0) is empty and any non-zero BlockID is opaque and solid.
	Registry *Registry
}

WorldConfig configures a new World.

type WorldDoc

type WorldDoc struct {
	// Version is the schema version; must be 1.
	Version int `yaml:"version" schema:"required"`
	// Name is an optional human-readable name for the world.
	Name string `yaml:"name,omitempty"`
	// ChunkSize is the power-of-two cubic chunk edge length, from 4 to 64.
	ChunkSize int `yaml:"chunkSize" schema:"required,minimum=4,maximum=64"`
	// VoxelSize is the world-space edge length of one voxel; omitted or 0 defaults to 1.
	VoxelSize float32 `yaml:"voxelSize,omitempty" schema:"exclusiveMinimum=0"`
	// Palette lists the non-air block definitions used by the world, sorted by ID.
	Palette []BlockDoc `yaml:"palette,omitempty"`
	// Chunks lists the non-empty chunks in the world, sorted by (x, y, z).
	Chunks []ChunkDoc `yaml:"chunks,omitempty"`
}

WorldDoc is the root of a versioned YAML voxel world document.

func Parse

func Parse(data []byte) (*WorldDoc, error)

Parse decodes and validates a YAML voxel world document. Unknown fields and trailing YAML documents are rejected. Returned errors are *loaderr.Error values carrying line, column, field path, and a fix hint.

func ParseWith

func ParseWith(data []byte, file string) (*WorldDoc, error)

ParseWith is Parse with an optional source file name attached to errors.

func (*WorldDoc) EffectiveVoxelSize

func (d *WorldDoc) EffectiveVoxelSize() float32

EffectiveVoxelSize returns doc.VoxelSize, defaulting to DefaultVoxelSize (1) when zero.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL