<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple 3D Voxel Editor</title>
<style>
body, html {
margin: 0; overflow: hidden; height: 100%;
font-family: Arial, sans-serif;
background: #222;
color: #ddd;
display: flex; flex-direction: column;
}
#container {
flex-grow: 1;
position: relative;
}
#colorPick {
position: fixed;
top: 10px; left: 10px;
z-index: 10;
}
#instructions {
position: fixed;
bottom: 10px; left:50%;
transform: translateX(-50%);
color: #aaa;
font-size: 14px;
background: rgba(0,0,0,0.4);
padding: 6px 12px;
border-radius: 6px;
}
#shareLink {
position: fixed;
top: 10px; right: 10px;
background: #333;
color: #eee;
padding: 4px 10px;
border-radius: 4px;
user-select: all;
max-width: 300px;
font-size: 12px;
}
</style>
</head>
<body>
<input type="color" id="colorPick" title="Pick color" value="#ff0000" />
<div id="container"></div>
<div id="instructions">Click grid to add/remove voxels. Pick color. Share via URL below.</div>
<div id="shareLink" title="Copy & Share URL"></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.152.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.152.2/examples/js/controls/OrbitControls.js"></script>
<script>
(() => {
const container = document.getElementById('container');
const colorPicker = document.getElementById('colorPick');
const shareLinkElem = document.getElementById('shareLink');
// Basic settings
const gridSize = 16; // 16x16x16 grid for voxels
const voxelSize = 1;
const colors = []; // store unique colors to limit palette
// Scene Setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
const camera = new THREE.PerspectiveCamera(60, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(gridSize/2, gridSize, gridSize * 1.5);
const renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(gridSize/2, 0, gridSize/2);
controls.update();
// Ambient + directional light
const ambient = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambient);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(50, 100, 50);
scene.add(dirLight);
// Grid Helper on floor
const gridHelper = new THREE.GridHelper(gridSize*voxelSize, gridSize, 0x888888, 0x444444);
gridHelper.position.y = 0;
scene.add(gridHelper);
// Data structure for voxels: key -> THREE.Mesh for easy removal
// key = 'x,y,z'
const voxels = new Map();
// Geometry for voxel cube (unit cube)
const cubeGeo = new THREE.BoxGeometry(voxelSize, voxelSize, voxelSize);
// Raycaster for mouse picking
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Plane for raycasting click on ground (y=0)
const groundPlane = new THREE.Plane(new THREE.Vector3(0,1,0), 0);
// Current selected color as hex string
let currentColor = colorPicker.value.toLowerCase();
// ----------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------
// Round coords to integer voxel grid coordinates
function roundVoxelPos(pos) {
return {
x: Math.floor(pos.x),
y: Math.floor(pos.y),
z: Math.floor(pos.z)
};
}
// Create or remove voxel at position
function toggleVoxel(x,y,z){
const key = `${x},${y},${z}`;
if(voxels.has(key)){
// Remove voxel
const mesh = voxels.get(key);
scene.remove(mesh);
voxels.delete(key);
} else {
if(y < 0 || y >= gridSize) return; // limit y height
// Create new voxel mesh
let colorIndex = colors.indexOf(currentColor);
if(colorIndex === -1){
colors.push(currentColor);
colorIndex = colors.length - 1;
}
const cubeMat = new THREE.MeshLambertMaterial({color: currentColor});
const cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.position.set(x + voxelSize/2, y + voxelSize/2, z + voxelSize/2);
scene.add(cube);
voxels.set(key, cube);
}
updateURLHash();
}
// Raycast mouse to grid plane and return voxel coordinate
function getVoxelPosFromMouse(event){
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersectPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(groundPlane, intersectPoint);
if(!intersectPoint) return null;
// Snap to voxel grid:
const voxelPos = roundVoxelPos(intersectPoint);
if(voxelPos.x < 0 || voxelPos.x >= gridSize ||
voxelPos.z < 0 || voxelPos.z >= gridSize) return null;
return {x: voxelPos.x, y:0, z: voxelPos.z};
}
// For clicking on existing voxels or adjacent face, we can improve:
// For simplicity, we just toggle voxel at ground level y=0.
// Extension: raycast cubes and add/remove above face, etc.
// ----------------------------------------------------------------
// URL hash encoding: save voxels as x,y,z,colorIndex joined by _ for each voxel, separated by -
// Example: x:y:z:c - x:y:z:c - ...
// x,y,z in decimal, c = color index (number)
// Colors are saved in order of appearance in colors[]
// ----------------------------------------------------------------
function updateURLHash(){
const parts = [];
voxels.forEach((mesh,key)=>{
// key = x,y,z
const [x,y,z] = key.split(',').map(s=>parseInt(s));
// find color index
const color = mesh.material.color.getHexString();
// color stored as #rrggbb, convert to #rrggbb format
let hex = '#' + color;
// find color index in colors array
const colorIndex = colors.indexOf(hex.toLowerCase());
if(colorIndex === -1) return; // skip if missing (unlikely)
parts.push(`${x}:${y}:${z}:${colorIndex}`);
});
const dataStr = parts.join('-');
// Save colors palette as well: comma separated hex values without #
// We'll append colors after a | separator. e.g. hash = data|colors
const colorStr = colors.map(c=>c.replace('#','')).join(',');
if(dataStr.length > 0){
location.hash = `#${dataStr}|${colorStr}`;
} else {
location.hash = '';
}
shareLinkElem.textContent = location.href;
}
// Load voxel data from URL hash
function loadFromHash(){
const hash = location.hash.slice(1);
if(!hash) return;
const [dataStr, colorStr] = hash.split('|');
if(!dataStr) return;
// Parse colors
if(colorStr){
colors.length = 0;
colorStr.split(',').forEach(c=>{
colors.push('#'+c);
});
}
// Clear existing voxels
voxels.forEach(mesh=>{
scene.remove(mesh);
});
voxels.clear();
// Parse voxels
const voxelData = dataStr.split('-');
voxelData.forEach(v=>{
const [x,y,z,cIndex] = v.split(':');
const xi = parseInt(x), yi=parseInt(y), zi=parseInt(z), ci=parseInt(cIndex);
const color = colors[ci];
if(color === undefined) return;
// Create voxel
const cubeMat = new THREE.MeshLambertMaterial({color});
const cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.position.set(xi + voxelSize/2, yi + voxelSize/2, zi + voxelSize/2);
scene.add(cube);
voxels.set(`${xi},${yi},${zi}`, cube);
});
}
// ----------------------------------------------------------------
// Event listeners
// ----------------------------------------------------------------
container.addEventListener('click', (ev) => {
ev.preventDefault();
// Get voxel under mouse
// For simplicity add/remove voxel on ground y=0 grid cell
const pos = getVoxelPosFromMouse(ev);
if(!pos) return;
toggleVoxel(pos.x, pos.y, pos.z);
});
colorPicker.addEventListener('input', e => {
currentColor = e.target.value.toLowerCase();
});
// Window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// On load from hash
loadFromHash();
updateURLHash();
// Simple render loop
function animate(){
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
})();
</script>
</body>
</html>