diff --git a/experiments/tests/voxel-world.test.mjs b/experiments/tests/voxel-world.test.mjs new file mode 100644 index 0000000..e508e17 --- /dev/null +++ b/experiments/tests/voxel-world.test.mjs @@ -0,0 +1,139 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { VoxelWorld, groundHeight, chunkIndex, blockKey } from '../voxel-frontier/world-core.mjs'; +import { canOccupy, spawnPlayer, stepPlayer, EYE_HEIGHT } from '../voxel-frontier/player-physics.mjs'; +import { ChunkRenderer } from '../voxel-frontier/world-render.mjs'; + +test('terrain is deterministic and has continuous bedrock', () => { + const a = new VoxelWorld({ radius: 4 }), b = new VoxelWorld({ radius: 4 }); + assert.deepEqual([...a.blocks], [...b.blocks]); + for (let x = -4; x <= 4; x++) for (let z = -4; z <= 4; z++) { + assert.equal(a.get(x, -1, z), 'stone'); + assert.equal(a.get(x, groundHeight(x, z), z), 'grass'); + } +}); + +test('block edits can be persisted, replayed, and deleted', () => { + const changes = []; + const world = new VoxelWorld({ radius: 4, onChange: c => changes.push(c) }); + assert.equal(world.set(0, 10, 0, 'wood'), true); + assert.equal(world.get(0, 10, 0), 'wood'); + assert.equal(world.set(0, 10, 0, 'wood'), false); + assert.equal(world.set(0, 10, 0, null), true); + assert.equal(world.get(0, 10, 0), null); + assert.equal(changes.length, 2); + const reloaded = new VoxelWorld({ radius: 4, edits: world.exportEdits() }); + assert.equal(reloaded.get(0, 10, 0), null); + assert.equal(reloaded.get(0, -1, 0), 'stone'); +}); + +test('invalid coordinates and bedrock edits are rejected', () => { + const world = new VoxelWorld({ radius: 4 }); + assert.equal(world.set(0, -1, 0, null), false); + assert.equal(world.set(10, 2, 0, 'wood'), false); + assert.equal(world.set(0, 100, 0, 'wood'), false); + assert.equal(world.set(0, 8, 0, 'unknown'), false); + assert.equal(world.get(0, -1, 0), 'stone'); +}); + +test('malformed saved edits cannot inject blocks outside the playable world', () => { + const world = new VoxelWorld({ radius: 4, edits: { + '999,2,2': 'stone', '0,-1,0': null, '0,10,0': 'wood', '0,11,0': 'lava', + '__proto__': 'stone' + } }); + assert.equal(world.get(0, 10, 0), 'wood'); + assert.equal(world.get(0, 11, 0), null); + assert.equal(world.get(0, -1, 0), 'stone'); + assert.equal(world.get(999, 2, 2), null); +}); + +test('negative chunk coordinates use mathematical floor', () => { + assert.equal(chunkIndex(-1), -1); + assert.equal(chunkIndex(-8), -1); + assert.equal(chunkIndex(-9), -2); + assert.equal(chunkIndex(8), 1); + assert.equal(blockKey(-1, 2, 3), '-1,2,3'); +}); + +const floorWorld = obstacle => ({ + radius: 20, + solid(x, y, z) { + return y <= 0 || (x === 1 && z === 0 && obstacle.includes(y)); + }, + highestAt() { return 0; } +}); + +test('player spawns above solid ground and has eye height', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + assert.equal(p.y, .5); + assert.equal(p.y + EYE_HEIGHT, 2.1); + assert.equal(canOccupy(world, p.x, p.y, p.z), true); + assert.equal(canOccupy(world, p.x, p.y - .1, p.z), false); +}); + +test('player cannot walk through a two-block wall', () => { + const world = floorWorld([1, 2]); + const p = spawnPlayer(world, 0, 0); + p.yaw = 0; + for (let i = 0; i < 12; i++) stepPlayer(world, p, { strafe: 1 }, .05); + assert.ok(p.x < .23, 'player should stop before wall'); + assert.ok(p.y < .6, 'player should not step up a two-block wall'); +}); + +test('player can climb a one-block step', () => { + const world = floorWorld([1]); + const p = spawnPlayer(world, 0, 0); + p.yaw = 0; + for (let i = 0; i < 4; i++) stepPlayer(world, p, { strafe: 1 }, .05); + assert.ok(p.x > .3, 'player should move across the step'); + assert.ok(p.y >= 1.49, 'player should stand on top of step'); +}); + +test('jump arcs and lands on the ground', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + stepPlayer(world, p, { jump: true }, .016); + assert.ok(p.y > .5); + assert.ok(p.vy > 0); + for (let i = 0; i < 160; i++) stepPlayer(world, p, {}, .016); + assert.ok(Math.abs(p.y - .5) < .001, 'jump should land exactly on ground'); + assert.equal(p.grounded, true); +}); + +test('long falls do not tunnel through solid terrain', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + p.y = 30; p.vy = 0; p.grounded = false; + for (let i = 0; i < 200; i++) stepPlayer(world, p, {}, .05); + assert.ok(Math.abs(p.y - .5) < .001); +}); + +test('chunk meshing culls interior faces and updates after edits', () => { + class BufferGeometry { + constructor() { this.attributes = {}; } + setAttribute(name, attr) { this.attributes[name] = attr; } + computeBoundingSphere() {} + dispose() {} + } + class Float32BufferAttribute { constructor(array) { this.array = array; } } + class Mesh { constructor(geometry, material) { this.geometry = geometry; this.material = material; this.userData = {}; } } + const THREE = { BufferGeometry, Float32BufferAttribute, Mesh }; + const objects = new Set(); + const scene = { add: object => objects.add(object), remove: object => objects.delete(object) }; + const world = new VoxelWorld({ radius: 3 }); + const materials = { grass: {}, stone: {}, wood: {} }; + const renderer = new ChunkRenderer(THREE, scene, world, materials); + const faces = () => [...objects].reduce((sum, mesh) => sum + mesh.geometry.attributes.position.array.length / 18, 0); + const before = faces(); + assert.ok(before > 0 && before < world.blocks.size * 6, 'interior faces must be removed'); + assert.ok(objects.size < world.blocks.size / 5, 'meshing must reduce draw calls'); + assert.equal(world.set(0, 10, 0, 'stone'), true); + renderer.updateAt(0, 0); + assert.equal(faces(), before + 6, 'isolated block adds six visible faces'); + assert.equal(world.set(0, 10, 0, null), true); + renderer.updateAt(0, 0); + assert.equal(faces(), before); + renderer.dispose(); + assert.equal(objects.size, 0); +}); diff --git a/experiments/voxel-frontier/game.js b/experiments/voxel-frontier/game.js index 483e90b..2edb5e3 100644 --- a/experiments/voxel-frontier/game.js +++ b/experiments/voxel-frontier/game.js @@ -1,4 +1,8 @@ import * as THREE from 'three'; +import { VoxelWorld, BLOCK_TYPES } from './world-core.mjs'; +import { spawnPlayer, stepPlayer, canOccupy, PLAYER_RADIUS, PLAYER_HEIGHT, EYE_HEIGHT } from './player-physics.mjs'; +import { ChunkRenderer } from './world-render.mjs'; +import { raycastVoxel } from './voxel-raycast.mjs'; const game = document.querySelector('#game'); const hud = document.querySelector('#stats'); @@ -7,163 +11,155 @@ const start = document.querySelector('#start'); const error = document.querySelector('#error'); const scene = new THREE.Scene(); scene.background = new THREE.Color(0x9bc6cf); -scene.fog = new THREE.Fog(0x9bc6cf, 18, 54); -const camera = new THREE.PerspectiveCamera(77, innerWidth / innerHeight, 0.05, 90); +scene.fog = new THREE.Fog(0x9bc6cf, 18, 57); +const camera = new THREE.PerspectiveCamera(76, innerWidth / innerHeight, .05, 90); +camera.rotation.order = 'YXZ'; const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' }); renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); renderer.setSize(innerWidth, innerHeight); -renderer.shadowMap.enabled = false; game.prepend(renderer.domElement); -scene.add(new THREE.HemisphereLight(0xe5f4ff, 0x4d5b3e, 2.0)); -const sun = new THREE.DirectionalLight(0xfff1c6, 2.2); +scene.add(new THREE.HemisphereLight(0xe6f3ff, 0x56633d, 2)); +const sun = new THREE.DirectionalLight(0xffefc4, 2.3); sun.position.set(-12, 26, 18); scene.add(sun); -const size = 13; const materials = { grass: new THREE.MeshLambertMaterial({ color: 0x729b5d }), stone: new THREE.MeshLambertMaterial({ color: 0x8d9da0 }), wood: new THREE.MeshLambertMaterial({ color: 0x9e704b }) }; -const box = new THREE.BoxGeometry(1, 1, 1); -const map = new Map(); -const meshes = []; -const key = (x, y, z) => x + ',' + y + ',' + z; -const groundHeight = (x, z) => Math.max(0, Math.floor(2.1 + Math.sin(x / 3.5) * 1.2 + Math.cos(z / 4.1) * 1.3)); const editsKey = 'voxel-frontier-world-v1'; -let edits = {}; -try { edits = JSON.parse(localStorage.getItem(editsKey) || '{}') || {}; } catch { edits = {}; } -function notify(message) { - toast.textContent = message; -} -function addBlock(x, y, z, kind, record = false) { - const id = key(x, y, z); - if (map.has(id)) return false; - const m = new THREE.Mesh(box, materials[kind] || materials.stone); - m.position.set(x, y, z); - m.userData = { x, y, z, kind }; - scene.add(m); - map.set(id, m); - meshes.push(m); - if (record) { edits[id] = kind; save(); } - return true; -} -function removeBlock(m, record = false) { - const { x, y, z } = m.userData; - const id = key(x, y, z); - if (!map.delete(id)) return; - scene.remove(m); - const index = meshes.indexOf(m); - if (index !== -1) meshes.splice(index, 1); - if (record) { edits[id] = null; save(); } -} -function save() { - try { localStorage.setItem(editsKey, JSON.stringify(edits)); } catch {} -} -for (let x = -size; x <= size; x++) for (let z = -size; z <= size; z++) { - const h = groundHeight(x, z); - for (let y = -1; y <= h; y++) addBlock(x, y, z, y === h ? 'grass' : 'stone'); -} -for (let x = -size + 3; x < size - 3; x += 6) { - for (let z = -size + 3; z < size - 3; z += 7) { - const h = groundHeight(x, z); - addBlock(x, h + 1, z, 'wood'); - addBlock(x, h + 2, z, 'wood'); +let savedEdits = {}; +try { savedEdits = JSON.parse(localStorage.getItem(editsKey) || '{}'); } catch {} +let chunks; +const world = new VoxelWorld({ + edits: savedEdits, + onChange(change) { + try { localStorage.setItem(editsKey, JSON.stringify(world.exportEdits())); } catch {} + chunks?.updateAt(change.x, change.z); + window.dispatchEvent(new CustomEvent('voxel:block-change', { detail: change })); } -} -for (const [id, kind] of Object.entries(edits)) { - const [x, y, z] = id.split(',').map(Number); - const old = map.get(id); - if (old) removeBlock(old); - if (kind) addBlock(x, y, z, kind); -} -const player = { x: 0, z: 5, yaw: 0, pitch: -0.12, blocks: 0 }; +}); +chunks = new ChunkRenderer(THREE, scene, world, materials); +const player = spawnPlayer(world); const pressed = new Set(); -let selected = 'grass'; -let playing = false; +let selected = 'grass', playing = false, mined = 0; let lastFrame = performance.now(); -player.yaw = -0.2; -function playerHeight() { - const x = Math.max(-size, Math.min(size, Math.round(player.x))); - const z = Math.max(-size, Math.min(size, Math.round(player.z))); - for (let y = 12; y >= -1; y--) if (map.has(key(x, y, z))) return y + 2.18; - return 3; +const lookDirection = new THREE.Vector3(); +const highlight = new THREE.LineSegments( + new THREE.EdgesGeometry(new THREE.BoxGeometry(1.012, 1.012, 1.012)), + new THREE.LineBasicMaterial({ color: 0xfff4d4, transparent: true, opacity: .72 }) +); +highlight.visible = false; +scene.add(highlight); +function notify(message) { toast.textContent = message; } +function selectBlock(kind) { + if (!BLOCK_TYPES.includes(kind)) return false; + selected = kind; + document.querySelectorAll('#hotbar button').forEach(button => + button.classList.toggle('active', button.dataset.block === kind)); + notify('Selected ' + kind); + return true; +} +function target() { + return raycastVoxel(world, camera.position, camera.getWorldDirection(lookDirection), 6.5); +} +function intersectsPlayer(x, y, z) { + return Math.abs(player.x - x) < PLAYER_RADIUS + .5 + && Math.abs(player.z - z) < PLAYER_RADIUS + .5 + && player.y < y + .5 && player.y + PLAYER_HEIGHT > y - .5; } -camera.position.set(player.x, playerHeight(), player.z); -const raycaster = new THREE.Raycaster(); -raycaster.far = 7; function blockAction(place) { - raycaster.setFromCamera({ x: 0, y: 0 }, camera); - const hit = raycaster.intersectObjects(meshes, false)[0]; - if (!hit) return notify('Find a block within reach'); - const m = hit.object; + const hit = target(); + if (!hit) { notify('Move closer to a block'); return false; } if (place) { - const pos = m.position.clone().add(hit.face.normal); - if (Math.abs(pos.x - player.x) < .7 && Math.abs(pos.z - player.z) < .7 && Math.abs(pos.y - camera.position.y + 1) < 1.5) return; - if (addBlock(Math.round(pos.x), Math.round(pos.y), Math.round(pos.z), selected, true)) notify('Placed ' + selected); - } else { - const { y } = m.userData; - if (y <= -1) return notify('Bedrock stays intact'); - removeBlock(m, true); - player.blocks++; - hud.textContent = 'Blocks mined: ' + player.blocks; - notify('Mined ' + m.userData.kind + ' · ' + player.blocks + ' blocks'); + const { x, y, z } = hit.adjacent; + if (intersectsPlayer(x, y, z)) { notify('Cannot build inside yourself'); return false; } + if (!world.set(x, y, z, selected)) { notify('Cannot place a block there'); return false; } + notify('Placed ' + selected); + return true; } + if (hit.y <= -1) { notify('Bedrock stays intact'); return false; } + const kind = world.get(hit.x, hit.y, hit.z); + if (!kind || !world.set(hit.x, hit.y, hit.z, null)) return false; + mined++; + hud.textContent = 'Blocks mined: ' + mined; + notify('Mined ' + kind + ' · ' + mined + ' blocks'); + return true; } -renderer.domElement.addEventListener('click', () => { +renderer.domElement.addEventListener('mousedown', event => { if (!playing) return; - if (document.pointerLockElement !== renderer.domElement) renderer.domElement.requestPointerLock?.(); - else blockAction(false); + if (event.button === 2) { event.preventDefault(); blockAction(true); return; } + if (event.button !== 0) return; + if (document.pointerLockElement !== renderer.domElement) { + renderer.domElement.requestPointerLock?.().catch(() => notify('Mouse lock unavailable. Use keyboard controls.')); + return; + } + blockAction(false); }); -renderer.domElement.addEventListener('contextmenu', e => { e.preventDefault(); if (playing) blockAction(true); }); -document.addEventListener('mousemove', e => { +renderer.domElement.addEventListener('contextmenu', event => event.preventDefault()); +document.addEventListener('mousemove', event => { if (document.pointerLockElement !== renderer.domElement) return; - player.yaw -= e.movementX * 0.002; - player.pitch = THREE.MathUtils.clamp(player.pitch - e.movementY * 0.002, -1.48, 1.48); + player.yaw -= event.movementX * .002; + player.pitch = THREE.MathUtils.clamp(player.pitch - event.movementY * .002, -1.48, 1.48); }); -document.addEventListener('keydown', e => { - if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(e.code)) e.preventDefault(); - pressed.add(e.code); - if (e.code === 'Digit1' || e.code === 'Digit2' || e.code === 'Digit3') { - selected = ['grass', 'stone', 'wood'][Number(e.code.slice(-1)) - 1]; - document.querySelectorAll('#hotbar button').forEach(button => button.classList.toggle('active', button.dataset.block === selected)); - notify('Selected ' + selected); - } +document.addEventListener('pointerlockchange', () => { + if (playing && document.pointerLockElement !== renderer.domElement) notify('Click the world to capture your mouse'); }); -document.addEventListener('keyup', e => pressed.delete(e.code)); -document.querySelectorAll('#hotbar button').forEach(button => button.addEventListener('click', () => { - selected = button.dataset.block; - document.querySelectorAll('#hotbar button').forEach(b => b.classList.toggle('active', b === button)); -})); +document.addEventListener('keydown', event => { + if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space'].includes(event.code)) event.preventDefault(); + pressed.add(event.code); + if (/^Digit[123]$/.test(event.code)) selectBlock(BLOCK_TYPES[Number(event.code.slice(-1)) - 1]); +}); +document.addEventListener('keyup', event => pressed.delete(event.code)); +window.addEventListener('blur', () => pressed.clear()); +document.querySelectorAll('#hotbar button').forEach(button => + button.addEventListener('click', () => selectBlock(button.dataset.block))); document.querySelector('#play').addEventListener('click', () => { playing = true; start.classList.add('hidden'); - renderer.domElement.requestPointerLock?.().catch(() => {}); - notify('Explore. Mine. Build.'); + renderer.domElement.requestPointerLock?.().catch(() => notify('Click the world to capture your mouse')); + notify('WASD move · Space jump · Shift sprint · Mine and build'); }); window.addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); }); +window.addEventListener('error', event => { error.textContent = 'Game error: ' + event.message; }); + +window.voxelFrontier = Object.freeze({ + world, player, camera, scene, + selectBlock, + get selectedBlock() { return selected; }, + get playing() { return playing; }, + get minedBlocks() { return mined; }, + mine: () => blockAction(false), + place: () => blockAction(true), + resetWorld() { try { localStorage.removeItem(editsKey); } catch {} location.reload(); } +}); + function tick(now) { requestAnimationFrame(tick); - const dt = Math.min(.05, (now - lastFrame) / 1000); + const dt = Math.min(.05, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now; if (playing) { - const fwd = Number(pressed.has('KeyW') || pressed.has('ArrowUp')) - Number(pressed.has('KeyS') || pressed.has('ArrowDown')); - const side = Number(pressed.has('KeyD') || pressed.has('ArrowRight')) - Number(pressed.has('KeyA') || pressed.has('ArrowLeft')); - const len = Math.hypot(fwd, side) || 1; - const speed = pressed.has('ShiftLeft') ? 8 : 5; - const dx = (-Math.sin(player.yaw) * fwd + Math.cos(player.yaw) * side) / len * speed * dt; - const dz = (-Math.cos(player.yaw) * fwd - Math.sin(player.yaw) * side) / len * speed * dt; - player.x = THREE.MathUtils.clamp(player.x + dx, -size + .7, size - .7); - player.z = THREE.MathUtils.clamp(player.z + dz, -size + .7, size - .7); - camera.position.set(player.x, THREE.MathUtils.lerp(camera.position.y, playerHeight(), Math.min(1, dt * 9)), player.z); - camera.rotation.order = 'YXZ'; - camera.rotation.y = player.yaw; - camera.rotation.x = player.pitch; + const forward = Number(pressed.has('KeyW') || pressed.has('ArrowUp')) - + Number(pressed.has('KeyS') || pressed.has('ArrowDown')); + const strafe = Number(pressed.has('KeyD') || pressed.has('ArrowRight')) - + Number(pressed.has('KeyA') || pressed.has('ArrowLeft')); + stepPlayer(world, player, { + forward, strafe, sprint: pressed.has('ShiftLeft') || pressed.has('ShiftRight'), + jump: pressed.has('Space') + }, dt); } + camera.position.set(player.x, player.y + EYE_HEIGHT, player.z); + camera.rotation.y = player.yaw; + camera.rotation.x = player.pitch; + if (playing && document.pointerLockElement === renderer.domElement) { + const hit = target(); + highlight.visible = !!hit; + if (hit) highlight.position.set(hit.x, hit.y, hit.z); + } else highlight.visible = false; renderer.render(scene, camera); } -window.addEventListener('error', e => { error.textContent = 'Rendering error: ' + e.message; }); requestAnimationFrame(tick); diff --git a/experiments/voxel-frontier/player-physics.mjs b/experiments/voxel-frontier/player-physics.mjs new file mode 100644 index 0000000..9aeaaaf --- /dev/null +++ b/experiments/voxel-frontier/player-physics.mjs @@ -0,0 +1,42 @@ +export const EYE_HEIGHT=1.60,PLAYER_RADIUS=.28,PLAYER_HEIGHT=1.78; +const EPS=.000001; +export function canOccupy(world,x,y,z){ +for(let bx=Math.ceil(x-PLAYER_RADIUS-.5+EPS);bx<=Math.floor(x+PLAYER_RADIUS+.5-EPS);bx++) +for(let bz=Math.ceil(z-PLAYER_RADIUS-.5+EPS);bz<=Math.floor(z+PLAYER_RADIUS+.5-EPS);bz++) +for(let by=Math.ceil(y-.5+EPS);by<=Math.floor(y+PLAYER_HEIGHT+.5-EPS);by++) +if(world.solid(bx,by,bz))return false; +return true; +} +export function spawnPlayer(world,x=0,z=5){return {x,y:world.highestAt(Math.round(x),Math.round(z))+.5,z,vy:0,yaw:-.2,pitch:-.12,grounded:true};} +function moveHorizontal(world,p,axis,delta){ +if(!delta)return; +const x=axis==='x'?p.x+delta:p.x,z=axis==='z'?p.z+delta:p.z; +if(canOccupy(world,x,p.y,z)){p[axis]+=delta;return;} +if(p.grounded&&canOccupy(world,p.x,p.y+1.001,p.z)&&canOccupy(world,x,p.y+1.001,z)){p.y+=1.001;p.vy=0;p[axis]+=delta;} +} +function moveVertical(world,p,delta){ +if(!delta)return; +const target=p.y+delta; +if(canOccupy(world,p.x,target,p.z)){p.y=target;return;} +let safe=p.y,blocked=target; +for(let i=0;i<17;i++){const middle=(safe+blocked)/2;if(canOccupy(world,p.x,middle,p.z))safe=middle;else blocked=middle;} +p.y=safe;p.vy=0;if(delta<0)p.grounded=true; +} +export function stepPlayer(world,p,input,elapsed){ +const dt=Math.max(0,Math.min(.05,elapsed));if(!dt)return p; +const f=Math.max(-1,Math.min(1,input.forward||0)),s=Math.max(-1,Math.min(1,input.strafe||0)); +const length=Math.hypot(f,s)||1,speed=input.sprint?7.4:4.9; +const dx=(-Math.sin(p.yaw)*f+Math.cos(p.yaw)*s)/length*speed*dt; +const dz=(-Math.cos(p.yaw)*f-Math.sin(p.yaw)*s)/length*speed*dt; +const max=world.radius-PLAYER_RADIUS-.22; +moveHorizontal(world,p,'x',Math.max(-max,Math.min(max,p.x+dx))-p.x); +moveHorizontal(world,p,'z',Math.max(-max,Math.min(max,p.z+dz))-p.z); +p.grounded=!canOccupy(world,p.x,p.y-.035,p.z); +if(input.jump&&p.grounded){p.vy=8;p.grounded=false;} +if(!p.grounded)p.vy=Math.max(-24,p.vy-21*dt); +else if(p.vy<0)p.vy=0; +const vertical=p.vy*dt,steps=Math.max(1,Math.ceil(Math.abs(vertical)/.24)); +for(let i=0;i 0) || !(maxDistance > 0)) return null; + const dir = values.map(v => v / length); + const point = [origin.x, origin.y, origin.z]; + if (!point.every(Number.isFinite)) return null; + const cell = point.map(v => Math.floor(v + .5)); + const step = dir.map(v => Math.sign(v)); + const tDelta = dir.map(v => v === 0 ? Infinity : Math.abs(1 / v)); + const tMax = dir.map((v, axis) => { + if (v === 0) return Infinity; + const boundary = cell[axis] + (v > 0 ? .5 : -.5); + return Math.max(0, (boundary - point[axis]) / v); + }); + let distance = 0; + let enteredAxis = -1; + // Every grid crossing consumes distance; this bound prevents infinite loops. + const maxSteps = Math.ceil(maxDistance * 4) + 8; + for (let i = 0; i < maxSteps && distance <= maxDistance + 1e-9; i++) { + if (world.solid(cell[0], cell[1], cell[2])) { + if (enteredAxis < 0) return null; // camera embedded in a block + const normal = [0, 0, 0]; + normal[enteredAxis] = -step[enteredAxis]; + return { + x: cell[0], y: cell[1], z: cell[2], + adjacent: { + x: cell[0] + normal[0], + y: cell[1] + normal[1], + z: cell[2] + normal[2] + }, + normal: { x: normal[0], y: normal[1], z: normal[2] }, + distance + }; + } + // Prefer deterministic axis order on exact edges/corners. + let axis = 0; + if (tMax[1] < tMax[axis]) axis = 1; + if (tMax[2] < tMax[axis]) axis = 2; + if (!Number.isFinite(tMax[axis]) || tMax[axis] > maxDistance) break; + distance = tMax[axis]; + cell[axis] += step[axis]; + tMax[axis] += tDelta[axis]; + enteredAxis = axis; + } + return null; +} diff --git a/experiments/voxel-frontier/world-core.mjs b/experiments/voxel-frontier/world-core.mjs new file mode 100644 index 0000000..77727ea --- /dev/null +++ b/experiments/voxel-frontier/world-core.mjs @@ -0,0 +1,95 @@ +/** + * Deterministic, renderer-independent voxel world. + * Block centers occupy integer coordinates. A block occupies [c-.5, c+.5]. + * Keep this module free of Three.js/DOM dependencies so it can be unit tested. + */ +export const WORLD_RADIUS = 13; +export const MAX_HEIGHT = 32; +export const CHUNK_SIZE = 8; +export const BLOCK_TYPES = Object.freeze(['grass', 'stone', 'wood']); +export const blockKey = (x, y, z) => `${x},${y},${z}`; +export const chunkIndex = coordinate => Math.floor(coordinate / CHUNK_SIZE); +export const chunkKey = (x, z) => `${chunkIndex(x)},${chunkIndex(z)}`; + +export function groundHeight(x, z) { + return Math.max(0, Math.floor(2.1 + Math.sin(x / 3.5) * 1.2 + Math.cos(z / 4.1) * 1.3)); +} + +export class VoxelWorld { + constructor({ radius = WORLD_RADIUS, edits = {}, onChange = null } = {}) { + this.radius = radius; + this.blocks = new Map(); + this.edits = {}; + this.onChange = onChange; + for (let x = -radius; x <= radius; x++) { + for (let z = -radius; z <= radius; z++) { + const height = groundHeight(x, z); + for (let y = -1; y <= height; y++) { + this.blocks.set(blockKey(x, y, z), y === height ? 'grass' : 'stone'); + } + } + } + for (let x = -radius + 3; x < radius - 3; x += 6) { + for (let z = -radius + 3; z < radius - 3; z += 7) { + const h = groundHeight(x, z); + this.blocks.set(blockKey(x, h + 1, z), 'wood'); + this.blocks.set(blockKey(x, h + 2, z), 'wood'); + } + } + if (edits && typeof edits === 'object' && !Array.isArray(edits)) { + for (const [id, kind] of Object.entries(edits).slice(0, 10000)) { + const match = /^(-?\d+),(-?\d+),(-?\d+)$/.exec(id); + if (!match) continue; + const [x, y, z] = match.slice(1).map(Number); + if (!this.inBounds(x, y, z) || y === -1) continue; + if (kind !== null && !BLOCK_TYPES.includes(kind)) continue; + if (kind === null) this.blocks.delete(id); + else this.blocks.set(id, kind); + this.edits[id] = kind; + } + } + } + + inBounds(x, y, z) { + return Number.isInteger(x) && Number.isInteger(y) && Number.isInteger(z) + && Math.abs(x) <= this.radius && Math.abs(z) <= this.radius + && y >= -1 && y <= MAX_HEIGHT; + } + + get(x, y, z) { + return this.blocks.get(blockKey(x, y, z)) ?? null; + } + + solid(x, y, z) { + return this.blocks.has(blockKey(x, y, z)); + } + + set(x, y, z, kind) { + if (!this.inBounds(x, y, z) || y === -1) return false; + if (kind !== null && !BLOCK_TYPES.includes(kind)) return false; + const id = blockKey(x, y, z); + const previous = this.blocks.get(id) ?? null; + if (previous === kind) return false; + if (kind === null) this.blocks.delete(id); + else this.blocks.set(id, kind); + this.edits[id] = kind; + this.onChange?.({ x, y, z, previous, kind }); + return true; + } + + highestAt(x, z) { + for (let y = MAX_HEIGHT; y >= -1; y--) if (this.solid(x, y, z)) return y; + return -1; + } + + forEach(callback) { + for (const [id, kind] of this.blocks) { + const [x, y, z] = id.split(',').map(Number); + callback(kind, x, y, z); + } + } + + exportEdits() { + return { ...this.edits }; + } +} diff --git a/experiments/voxel-frontier/world-render.mjs b/experiments/voxel-frontier/world-render.mjs new file mode 100644 index 0000000..b95370f --- /dev/null +++ b/experiments/voxel-frontier/world-render.mjs @@ -0,0 +1,175 @@ +import { CHUNK_SIZE, chunkIndex } from './world-core.mjs'; + +// Every visible surface is emitted once; hidden interior faces are discarded. +// One draw call per material per 8x8 terrain chunk instead of one per voxel. +const FACES = [ + { n: [1, 0, 0], axis: 'x', u: 'z', v: 'y' }, + { n: [-1, 0, 0], axis: 'x', u: 'z', v: 'y' }, + { n: [0, 1, 0], axis: 'y', u: 'x', v: 'z' }, + { n: [0, -1, 0], axis: 'y', u: 'x', v: 'z' }, + { n: [0, 0, 1], axis: 'z', u: 'x', v: 'y' }, + { n: [0, 0, -1], axis: 'z', u: 'x', v: 'y' } +]; +const TRIANGLES = [0, 1, 2, 0, 2, 3]; + +// Combine adjacent coplanar faces of the same material into larger rectangles. +// This reduces triangles as well as draw calls while keeping exact voxel boundaries. +function greedyQuads(groups) { + const data = new Map(); + for (const group of groups.values()) { + const { kind, face, plane, cells } = group; + let item = data.get(kind); + if (!item) { + item = { positions: [], normals: [] }; + data.set(kind, item); + } + const visited = new Set(); + for (const key of cells) { + if (visited.has(key)) continue; + const [u, v] = key.split(',').map(Number); + let width = 1; + while (cells.has(`${u + width},${v}`) && !visited.has(`${u + width},${v}`)) width++; + let height = 1; + for (;;) { + let rowComplete = true; + for (let dx = 0; dx < width; dx++) { + const next = `${u + dx},${v + height}`; + if (!cells.has(next) || visited.has(next)) { rowComplete = false; break; } + } + if (!rowComplete) break; + height++; + } + for (let dy = 0; dy < height; dy++) + for (let dx = 0; dx < width; dx++) visited.add(`${u + dx},${v + dy}`); + + const point = (a, b) => { + const xyz = { x: 0, y: 0, z: 0 }; + xyz[face.axis] = plane; + xyz[face.u] = a; + xyz[face.v] = b; + return [xyz.x, xyz.y, xyz.z]; + }; + const quad = [ + point(u - .5, v - .5), point(u + width - .5, v - .5), + point(u + width - .5, v + height - .5), point(u - .5, v + height - .5) + ]; + const ab = quad[1].map((n, i) => n - quad[0][i]); + const ac = quad[2].map((n, i) => n - quad[0][i]); + const cross = [ab[1] * ac[2] - ab[2] * ac[1], + ab[2] * ac[0] - ab[0] * ac[2], + ab[0] * ac[1] - ab[1] * ac[0]]; + if (cross.reduce((sum, n, i) => sum + n * face.n[i], 0) < 0) quad.reverse(); + for (const index of TRIANGLES) { + item.positions.push(...quad[index]); + item.normals.push(...face.n); + } + } + } + return data; +} +const id = (cx, cz) => cx + ',' + cz; + +export class ChunkRenderer { + constructor(THREE, scene, world, materials) { + this.THREE = THREE; + this.scene = scene; + this.world = world; + this.materials = materials; + this.chunks = new Map(); + this.meshes = new Set(); + this.buildAll(); + } + + buildAll() { + const low = chunkIndex(-this.world.radius); + const high = chunkIndex(this.world.radius); + for (let cx = low; cx <= high; cx++) + for (let cz = low; cz <= high; cz++) + this.rebuild(cx, cz); + } + + rebuild(cx, cz) { + const name = id(cx, cz); + const previous = this.chunks.get(name) || []; + for (const mesh of previous) { + this.meshes.delete(mesh); + this.scene.remove(mesh); + mesh.geometry.dispose(); + } + const groups = new Map(); + const world = this.world; + const minX = Math.max(-world.radius, cx * CHUNK_SIZE); + const maxX = Math.min(world.radius, (cx + 1) * CHUNK_SIZE - 1); + const minZ = Math.max(-world.radius, cz * CHUNK_SIZE); + const maxZ = Math.min(world.radius, (cz + 1) * CHUNK_SIZE - 1); + for (let x = minX; x <= maxX; x++) for (let z = minZ; z <= maxZ; z++) { + for (let y = -1; y <= 32; y++) { + const kind = world.get(x, y, z); + if (!kind) continue; + for (let faceIndex = 0; faceIndex < FACES.length; faceIndex++) { + const face = FACES[faceIndex]; + const [nx, ny, nz] = face.n; + if (world.solid(x + nx, y + ny, z + nz)) continue; + const xyz = { x, y, z }; + const plane = xyz[face.axis] + face.n[['x','y','z'].indexOf(face.axis)] * .5; + const groupId = `${kind}|${faceIndex}|${plane}`; + let group = groups.get(groupId); + if (!group) { + group = { kind, face, plane, cells: new Set() }; + groups.set(groupId, group); + } + group.cells.add(`${xyz[face.u]},${xyz[face.v]}`); + } + } + } + const data = greedyQuads(groups); + const fresh = []; + for (const [kind, item] of data) { + if (!item.positions.length) continue; + const geometry = new this.THREE.BufferGeometry(); + geometry.setAttribute('position', new this.THREE.Float32BufferAttribute(item.positions, 3)); + geometry.setAttribute('normal', new this.THREE.Float32BufferAttribute(item.normals, 3)); + geometry.computeBoundingSphere(); + const mesh = new this.THREE.Mesh(geometry, this.materials[kind] || this.materials.stone); + mesh.userData.chunk = name; + mesh.frustumCulled = true; + this.scene.add(mesh); + this.meshes.add(mesh); + fresh.push(mesh); + } + this.chunks.set(name, fresh); + } + + updateAt(x, z) { + const cx = chunkIndex(x), cz = chunkIndex(z); + this.rebuild(cx, cz); + // A changed boundary voxel can expose a face in the adjacent chunk. + if (x % CHUNK_SIZE === 0) this.rebuild(cx - 1, cz); + if ((x + 1) % CHUNK_SIZE === 0) this.rebuild(cx + 1, cz); + if (z % CHUNK_SIZE === 0) this.rebuild(cx, cz - 1); + if ((z + 1) % CHUNK_SIZE === 0) this.rebuild(cx, cz + 1); + } + + pick(raycaster) { + const hit = raycaster.intersectObjects([...this.meshes], false)[0]; + if (!hit) return null; + const normal = hit.face.normal.clone(); + const inside = hit.point.clone().addScaledVector(normal, -0.025); + const outside = hit.point.clone().addScaledVector(normal, 0.025); + const round = value => Math.round(value); + return { + x: round(inside.x), y: round(inside.y), z: round(inside.z), + adjacent: { x: round(outside.x), y: round(outside.y), z: round(outside.z) }, + normal + }; + } + + dispose() { + for (const [cxcz] of this.chunks) { + const meshes = this.chunks.get(cxcz); + for (const mesh of meshes) { this.scene.remove(mesh); mesh.geometry.dispose(); } + } + this.chunks.clear(); + this.meshes.clear(); + } +}