Three.js Voxel Builder Development
Expert guidance for working with a modern Vue 3 + Three.js Voxel Builder application featuring WebGPU support, natural lighting, and urban planning visualization tools.
Project Overview
This skill provides specialized knowledge for developing and maintaining a sophisticated voxel building system with:
Minecraft-style block placement with spatial hash optimizationWebGPU-accelerated rendering for modern browsersCityJSON urban data visualizationTouch and desktop interfaces3D preview system with live thumbnailsDevelopment Commands
When starting work or building the project:
1. **Install dependencies**: `npm install`
2. **Start dev server**: `npm run dev`
3. **Build for production**: `npm run build` (includes TypeScript compilation)
4. **Preview production**: `npm run preview`
Core Architecture Understanding
Three View System
The application uses single-page navigation with three core views:
**VoxelEngine** (PRIMARY): Main voxel building system using WebGL**ThreejsScene**: Interactive demo with WebGPU-accelerated animations ⚡**CityJSONViewer**: Urban data visualization with CityJSON support (WebGL)Navigation is handled in `src/App.vue` with reactive view switching.
WebGPU Support (October 2025)
ThreejsScene uses WebGPU for modern GPU-accelerated rendering:
Automatic browser compatibility detectionReal-time status notificationsGraceful fallback if unavailableRequires Chrome/Edge 113+, Firefox 133+, Safari 18+**When working with WebGPU components:**
```typescript
// Import from three/webgpu
import * as THREE from 'three/webgpu'
// Use NodeMaterial variants
const material = new THREE.MeshStandardNodeMaterial({ color: 0x70f39e });
// Async renderer initialization
const renderer = new THREE.WebGPURenderer({ antialias: true });
await renderer.init();
// Use setAnimationLoop
renderer.setAnimationLoop(animate);
// Check WebGPU support
import { detectWebGPU } from './utils/webgpuDetector';
const support = await detectWebGPU();
```
Voxel Builder System
**Architecture approach**: One mesh per block for simplicity and reliability
**Key features:**
Spatial hash optimization for efficient raycastingNatural lighting with HemisphereLight + DirectionalLight + Fog5 block types with realistic materials (Grass, Stone, Wood, Glass, Water)Precise 1m×1m grid with visual feedbackSmart preview system with color-coded snapping**Tool system:**
**Place Mode**: Green/cyan preview, snapping to surfaces and blocks**Delete Mode**: Red preview, targets existing blocks onlyKeyboard shortcuts: X (delete), 1-5 (block types)Tool state affects raycasting behavior and preview colorsComponent Architecture
**ThreejsScene** (`src/components/ThreejsScene.vue`) - WebGPU ⚡
WebGPU renderer with async initializationOrbitControls, lighting, shadows demonstrationMeshStandardNodeMaterial for WebGPU compatibilityBatchedMesh with instance managementJump animation system with external triggers**CityJSONViewer** (`src/components/CityJSONViewer.vue`)
High-level wrapper for CityJSON urban dataAuto-fitting camera positioningError handling and loading statesProgrammatic loading via CityJSONIntegration class**VoxelEngine** (`src/components/VoxelEngine.vue`)
Block placement with tool system (place/delete)Real-time preview with color-coded feedbackTouch and mouse interface supportStatistics tracking (voxel count, chunks, FPS)Key Utility Classes
**CityJSONIntegration** (`src/utils/cityJsonIntegration.ts`)
```typescript
import { CityJSONIntegration } from './utils/cityJsonIntegration';
const integration = new CityJSONIntegration({
chunkSize: 2000,
onComplete: () => console.log('Loaded!')
});
const scene = await integration.loadCityJSON('/path/to/data.json');
```
**VoxelEngine System** (`src/utils/voxelEngine.ts`)
BlockPlacer: Core placement logic with raycasting and snappingSparseVoxelGrid: Chunk-based voxel storage for large worldsVoxelRenderer: Three.js mesh management and renderingBlockTypeLibrary: Block type definitions and materials**Touch Interface** (`src/utils/touchInterface.ts`)
Hammer.js integration for gesture recognitionMulti-touch support for orbit controlsTouch-specific preview and placement handlingFile Organization
```
src/
├── components/
│ ├── ThreejsScene.vue # Three.js WebGPU demo with animations
│ ├── CityJSONViewer.vue # Urban data visualization
│ └── VoxelEngine.vue # Minecraft-style editor
├── utils/
│ ├── geometryGenerator.ts # Three.js WebGPU geometry utilities
│ ├── webgpuDetector.ts # WebGPU browser compatibility detector
│ ├── cityJsonIntegration.ts # CityJSON wrapper class
│ ├── voxelEngine.ts # Voxel engine core systems
│ └── touchInterface.ts # Mobile gesture handling
├── App.vue # Main router with view switching
└── main.ts # Vue app entry point
```
Development Guidelines
TypeScript Configuration
Strict mode enabled with comprehensive linting rulesES2020 target with bundler module resolutionVue SFC support with proper type checkingThree.js Version Compatibility
**Current version**: Three.js 0.180.0 with WebGPU support
**Key changes from previous versions:**
WebGPU Renderer: ThreejsScene uses `WebGPURenderer` with async initializationNode Materials: Uses `MeshStandardNodeMaterial` instead of `MeshStandardMaterial`Import paths: WebGPU components import from `three/webgpu`Animation loop: Uses `setAnimationLoop()` instead of `requestAnimationFrame()`Texture encoding replaced with `colorSpace` propertyAll peer dependencies aligned to 0.180.0Local Fork Strategy
**cityjson-threejs-loader:**
Uses forked version from GitHub (`github:KonstiDoll/cityjson-threejs-loader`)Ensures compatibility with Three.js r178 and custom patchesMaintains version control over critical urban visualization dependenciesVoxel Engine Development
When working with the voxel system:
Always pass current tool mode to raycasting functionsPreview colors indicate tool state and placement validityUse sparse grid for efficient memory management in large worldsPerformance Considerations
Mouse events throttled using `requestAnimationFrame`Preview updates check position equality before re-renderingVoxel storage uses chunk-based architecture (16³ chunks)BatchedMesh used for rendering multiple instances efficientlyImplemented Features (January 2025)
3D Preview System ⭐
VoxelMiniViewer component - Standalone 3D preview with Three.jsHover-based activation - Live 3D preview on library object mouseoverOrbitControls integration - Interactive camera control in miniature viewIdentical lighting - Same natural lighting as main editorSmooth animations - Smooth camera transitions and fade effectsRobust error handling - Fallback materials and debug loggingComplete Export/Import System
VoxelExporter class - JSON, Binary, Compressed formatsObject library - Modern UI with categories and search3D thumbnail generation - Off-screen Three.js renderingLocalStorage integration - Persistent library storageAutomatic material detection - Block-type-specific renderingAdvanced Voxel Engine
Spatial hash optimization - Performance-optimized raycastingTool system - Place/Delete with visual previewIntelligent block snapping - Automatic dockingTouch interface - Mobile-optimized controlsChunk system - Scales for large structuresTesting Urban Data
The CityJSONViewer includes demo data generation for testing without external files. Use the built-in generator when developing new visualization features.
Migration History
**October 2025**: Migrated ThreejsScene to WebGPU (Three.js 0.180.0)**January 2025**: Added 3D preview system and Voxel Library**Previous**: Migrated from Three.js r165 to r178Updated Vue 3 to latest (3.5.13)Resolved all breaking changes in dependency chainMaintained backward compatibility for existing CityJSON datasetsWhen to Use This Skill
Use this skill when:
Working with Three.js voxel rendering systemsImplementing WebGPU features in Vue 3 applicationsBuilding block-based 3D editorsIntegrating CityJSON urban data visualizationDebugging Three.js raycasting or material issuesOptimizing 3D performance in web applicationsImplementing touch gestures for 3D navigationConstraints
VoxelEngine and CityJSONViewer remain on WebGL for stabilityWebGPU features require modern browser versions (see compatibility notes)Chunk-based architecture required for worlds larger than 1000 blocksTouch interface requires Hammer.js dependencyCityJSON integration requires forked loader dependency