diff --git a/.github/workflows/deploy-pages.yml b/.github/workflows/deploy-pages.yml
index a788959..03951b7 100644
--- a/.github/workflows/deploy-pages.yml
+++ b/.github/workflows/deploy-pages.yml
@@ -29,7 +29,7 @@ jobs:
- name: Prepare site
run: |
mkdir -p dist
- cp -R index.html browser-phone dist/
+ cp -R index.html browser-phone minecraft dist/
cp CNAME dist/CNAME
- name: Setup Pages
diff --git a/README.md b/README.md
index aff9cee..ab63e36 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,10 @@
# Subnautica-Inspired Underwater Slice
+> **Also in this repo:** [`minecraft/`](minecraft/) — BlockCraft, a
+> browser-based Minecraft clone built with three.js (procedural terrain,
+> day/night cycle, block building). It is deployed with the GitHub Pages site
+> at `/minecraft/`.
+
This repository is now a **Unity 6.3 LTS** prototype focused on building the look and feel of a
Subnautica-style underwater scene. The goal is a strong visual vertical slice rather than a full
survival sandbox.
diff --git a/minecraft/README.md b/minecraft/README.md
new file mode 100644
index 0000000..566a793
--- /dev/null
+++ b/minecraft/README.md
@@ -0,0 +1,59 @@
+# BlockCraft
+
+A Minecraft-style voxel sandbox that runs entirely in the browser. No build
+step, no asset files — terrain, textures, sounds and the sky are all generated
+procedurally at runtime.
+
+Open `index.html` through any static file server (it uses ES modules, so the
+`file://` protocol won't work):
+
+```bash
+cd minecraft
+python3 -m http.server 8000
+# then visit http://localhost:8000
+```
+
+## Features
+
+- **Infinite procedural terrain** — chunked world streamed around the player,
+ with rolling hills, mountains, deserts, snow biomes, beaches, lakes and seas
+- **Caves and ores** — 3D-noise carved caverns with coal and iron deposits
+- **Trees** that generate across chunk borders deterministically
+- **Block breaking and placing** with a 9-slot hotbar (keys 1–9, mouse wheel,
+ or middle-click to pick the block you're looking at)
+- **Pixel-art texture atlas** painted onto a canvas at startup — grass, stone,
+ sand, logs, leaves, glass, water and more
+- **Lighting** — baked ambient occlusion, per-face shading and a depth-based
+ darkness heuristic for caves
+- **Day/night cycle** — square sun and moon, stars, drifting blocky clouds,
+ and dawn/dusk fog tinting
+- **Physics** — AABB collision, jumping, swimming with an underwater fog
+ effect, and a creative-style fly mode (`F`)
+- **Persistence** — your block edits are stored in `localStorage` per world
+ seed; use `?seed=...` in the URL to visit a specific world
+- **Procedural audio** — break/place/splash sounds synthesized with WebAudio
+
+## Controls
+
+| Input | Action |
+| ---------------- | --------------------- |
+| `W A S D` | Move |
+| Mouse | Look |
+| Left click | Break block |
+| Right click | Place block |
+| Middle click | Pick block |
+| `Space` | Jump / swim / fly up |
+| `Shift` | Sprint / fly down |
+| `F` | Toggle flying |
+| `1`–`9` / wheel | Select hotbar slot |
+| `Esc` | Pause menu |
+
+## Tech notes
+
+- [three.js](https://threejs.org) r165, vendored in `vendor/` so the game works
+ offline and the version is pinned
+- One mesh per 16×16×96 chunk (plus a translucent mesh for water/glass), built
+ with face culling, per-vertex ambient occlusion and a texture atlas
+- Terrain from seeded 2D simplex noise (continents, hills, mountain mask,
+ biomes) plus 3D value noise for caves
+- Voxel raycasting uses the Amanatides–Woo DDA traversal
diff --git a/minecraft/index.html b/minecraft/index.html
new file mode 100644
index 0000000..2aff2a9
--- /dev/null
+++ b/minecraft/index.html
@@ -0,0 +1,66 @@
+
+
+
+
+
+ BlockCraft — a browser voxel sandbox
+
+
+
+
+
+
+
+
+
+
+
+
BlockCraft
+
An infinite voxel sandbox that runs in your browser.
+
+
+
W A S D move
+
Mouse look around
+
Left click break block
+
Right click place block
+
Middle click pick block
+
Space jump / swim up
+
Shift sprint / fly down
+
F toggle flying
+
1–9 / wheel select block
+
Esc pause
+
+
+
Play
+
+
+ New world
+ Reset changes
+
+
+
+
+
+
+
+
+
+
diff --git a/minecraft/js/audio.js b/minecraft/js/audio.js
new file mode 100644
index 0000000..49549c4
--- /dev/null
+++ b/minecraft/js/audio.js
@@ -0,0 +1,81 @@
+// Tiny procedural sound effects via WebAudio; no audio assets needed.
+
+let ctx = null;
+
+function audioCtx() {
+ if (!ctx) {
+ const AC = window.AudioContext || window.webkitAudioContext;
+ if (!AC) return null;
+ ctx = new AC();
+ }
+ if (ctx.state === 'suspended') ctx.resume();
+ return ctx;
+}
+
+function noiseBuffer(ac, seconds) {
+ const buffer = ac.createBuffer(1, Math.floor(ac.sampleRate * seconds), ac.sampleRate);
+ const data = buffer.getChannelData(0);
+ for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;
+ return buffer;
+}
+
+export function playBreak() {
+ const ac = audioCtx();
+ if (!ac) return;
+ const t = ac.currentTime;
+
+ const src = ac.createBufferSource();
+ src.buffer = noiseBuffer(ac, 0.14);
+
+ const filter = ac.createBiquadFilter();
+ filter.type = 'lowpass';
+ filter.frequency.setValueAtTime(900, t);
+ filter.frequency.exponentialRampToValueAtTime(220, t + 0.13);
+
+ const gain = ac.createGain();
+ gain.gain.setValueAtTime(0.28, t);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + 0.14);
+
+ src.connect(filter).connect(gain).connect(ac.destination);
+ src.start(t);
+}
+
+export function playPlace() {
+ const ac = audioCtx();
+ if (!ac) return;
+ const t = ac.currentTime;
+
+ const osc = ac.createOscillator();
+ osc.type = 'square';
+ osc.frequency.setValueAtTime(210, t);
+ osc.frequency.exponentialRampToValueAtTime(150, t + 0.07);
+
+ const gain = ac.createGain();
+ gain.gain.setValueAtTime(0.09, t);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + 0.08);
+
+ osc.connect(gain).connect(ac.destination);
+ osc.start(t);
+ osc.stop(t + 0.09);
+}
+
+export function playSplash() {
+ const ac = audioCtx();
+ if (!ac) return;
+ const t = ac.currentTime;
+
+ const src = ac.createBufferSource();
+ src.buffer = noiseBuffer(ac, 0.25);
+
+ const filter = ac.createBiquadFilter();
+ filter.type = 'bandpass';
+ filter.frequency.setValueAtTime(700, t);
+ filter.Q.value = 0.8;
+
+ const gain = ac.createGain();
+ gain.gain.setValueAtTime(0.12, t);
+ gain.gain.exponentialRampToValueAtTime(0.001, t + 0.25);
+
+ src.connect(filter).connect(gain).connect(ac.destination);
+ src.start(t);
+}
diff --git a/minecraft/js/blocks.js b/minecraft/js/blocks.js
new file mode 100644
index 0000000..4402c4a
--- /dev/null
+++ b/minecraft/js/blocks.js
@@ -0,0 +1,177 @@
+// Block ids, per-face texture tiles and physical properties.
+
+export const Blocks = {
+ AIR: 0,
+ GRASS: 1,
+ DIRT: 2,
+ STONE: 3,
+ COBBLESTONE: 4,
+ PLANKS: 5,
+ LOG: 6,
+ LEAVES: 7,
+ SAND: 8,
+ GLASS: 9,
+ WATER: 10,
+ BEDROCK: 11,
+ SNOWY_GRASS: 12,
+ COAL_ORE: 13,
+ IRON_ORE: 14,
+};
+
+export const Tiles = {
+ GRASS_TOP: 0,
+ GRASS_SIDE: 1,
+ DIRT: 2,
+ STONE: 3,
+ COBBLESTONE: 4,
+ PLANKS: 5,
+ LOG_SIDE: 6,
+ LOG_TOP: 7,
+ LEAVES: 8,
+ SAND: 9,
+ GLASS: 10,
+ WATER: 11,
+ BEDROCK: 12,
+ SNOW_TOP: 13,
+ SNOW_SIDE: 14,
+ COAL_ORE: 15,
+ IRON_ORE: 16,
+};
+
+// tiles: [top, bottom, side]
+export const BLOCK_DEFS = {
+ [Blocks.GRASS]: {
+ name: 'Grass',
+ tiles: [Tiles.GRASS_TOP, Tiles.DIRT, Tiles.GRASS_SIDE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.DIRT]: {
+ name: 'Dirt',
+ tiles: [Tiles.DIRT, Tiles.DIRT, Tiles.DIRT],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.STONE]: {
+ name: 'Stone',
+ tiles: [Tiles.STONE, Tiles.STONE, Tiles.STONE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.COBBLESTONE]: {
+ name: 'Cobblestone',
+ tiles: [Tiles.COBBLESTONE, Tiles.COBBLESTONE, Tiles.COBBLESTONE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.PLANKS]: {
+ name: 'Planks',
+ tiles: [Tiles.PLANKS, Tiles.PLANKS, Tiles.PLANKS],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.LOG]: {
+ name: 'Log',
+ tiles: [Tiles.LOG_TOP, Tiles.LOG_TOP, Tiles.LOG_SIDE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.LEAVES]: {
+ name: 'Leaves',
+ tiles: [Tiles.LEAVES, Tiles.LEAVES, Tiles.LEAVES],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.SAND]: {
+ name: 'Sand',
+ tiles: [Tiles.SAND, Tiles.SAND, Tiles.SAND],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.GLASS]: {
+ name: 'Glass',
+ tiles: [Tiles.GLASS, Tiles.GLASS, Tiles.GLASS],
+ opaque: false,
+ solid: true,
+ translucent: true,
+ },
+ [Blocks.WATER]: {
+ name: 'Water',
+ tiles: [Tiles.WATER, Tiles.WATER, Tiles.WATER],
+ opaque: false,
+ solid: false,
+ translucent: true,
+ },
+ [Blocks.BEDROCK]: {
+ name: 'Bedrock',
+ tiles: [Tiles.BEDROCK, Tiles.BEDROCK, Tiles.BEDROCK],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.SNOWY_GRASS]: {
+ name: 'Snowy Grass',
+ tiles: [Tiles.SNOW_TOP, Tiles.DIRT, Tiles.SNOW_SIDE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.COAL_ORE]: {
+ name: 'Coal Ore',
+ tiles: [Tiles.COAL_ORE, Tiles.COAL_ORE, Tiles.COAL_ORE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+ [Blocks.IRON_ORE]: {
+ name: 'Iron Ore',
+ tiles: [Tiles.IRON_ORE, Tiles.IRON_ORE, Tiles.IRON_ORE],
+ opaque: true,
+ solid: true,
+ translucent: false,
+ },
+};
+
+export function isOpaque(id) {
+ const def = BLOCK_DEFS[id];
+ return def ? def.opaque : false;
+}
+
+export function isSolid(id) {
+ const def = BLOCK_DEFS[id];
+ return def ? def.solid : false;
+}
+
+export function isTranslucent(id) {
+ const def = BLOCK_DEFS[id];
+ return def ? def.translucent : false;
+}
+
+export function tileForFace(id, dirY) {
+ const def = BLOCK_DEFS[id];
+ if (!def) return 0;
+ if (dirY > 0) return def.tiles[0];
+ if (dirY < 0) return def.tiles[1];
+ return def.tiles[2];
+}
+
+// Blocks the player can put in the hotbar.
+export const HOTBAR_BLOCKS = [
+ Blocks.GRASS,
+ Blocks.DIRT,
+ Blocks.STONE,
+ Blocks.COBBLESTONE,
+ Blocks.PLANKS,
+ Blocks.LOG,
+ Blocks.LEAVES,
+ Blocks.SAND,
+ Blocks.GLASS,
+];
diff --git a/minecraft/js/constants.js b/minecraft/js/constants.js
new file mode 100644
index 0000000..5f5a584
--- /dev/null
+++ b/minecraft/js/constants.js
@@ -0,0 +1,26 @@
+export const CHUNK_SIZE = 16;
+export const WORLD_HEIGHT = 96;
+export const SEA_LEVEL = 30;
+
+// Chunk radius around the player that gets meshed and rendered.
+export const RENDER_DISTANCE = 6;
+export const UNLOAD_DISTANCE = RENDER_DISTANCE + 2;
+// Max milliseconds per frame spent generating/meshing chunks (at least one
+// chunk is always processed so loading can never stall).
+export const MESH_TIME_BUDGET_MS = 6;
+
+export const GRAVITY = 26;
+export const JUMP_SPEED = 8.6;
+export const WALK_SPEED = 4.3;
+export const SPRINT_SPEED = 6.8;
+export const FLY_SPEED = 11;
+export const SWIM_SPEED = 3.0;
+
+export const PLAYER_HALF_WIDTH = 0.3;
+export const PLAYER_HEIGHT = 1.8;
+export const PLAYER_EYE_HEIGHT = 1.62;
+
+export const REACH_DISTANCE = 6.5;
+
+// Length of a full day/night cycle, in seconds.
+export const DAY_LENGTH = 600;
diff --git a/minecraft/js/main.js b/minecraft/js/main.js
new file mode 100644
index 0000000..aa1a5f7
--- /dev/null
+++ b/minecraft/js/main.js
@@ -0,0 +1,419 @@
+import * as THREE from 'three';
+import { REACH_DISTANCE, RENDER_DISTANCE, CHUNK_SIZE, SEA_LEVEL } from './constants.js';
+import { Blocks, BLOCK_DEFS, HOTBAR_BLOCKS, tileForFace } from './blocks.js';
+import { TextureAtlas } from './textures.js';
+import { World } from './world.js';
+import { Player } from './player.js';
+import { raycastVoxel } from './raycast.js';
+import { Particles } from './particles.js';
+import { Sky } from './sky.js';
+import { playBreak, playPlace, playSplash } from './audio.js';
+import { seedFromString } from './rng.js';
+
+// ----------------------------------------------------------------- seed
+
+function resolveSeed() {
+ const params = new URLSearchParams(location.search);
+ let seedStr = params.get('seed');
+ try {
+ if (!seedStr) seedStr = localStorage.getItem('blockcraft:seed');
+ if (!seedStr) seedStr = String(Math.floor(Math.random() * 1e9));
+ localStorage.setItem('blockcraft:seed', seedStr);
+ } catch {
+ if (!seedStr) seedStr = '1337';
+ }
+ const seed = /^\d+$/.test(seedStr) ? parseInt(seedStr, 10) >>> 0 : seedFromString(seedStr);
+ return { seed, seedStr };
+}
+
+const { seed, seedStr } = resolveSeed();
+
+// ----------------------------------------------------------------- three
+
+const canvas = document.getElementById('game');
+const renderer = new THREE.WebGLRenderer({
+ canvas,
+ antialias: true,
+ powerPreference: 'high-performance',
+});
+renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+renderer.setSize(window.innerWidth, window.innerHeight);
+
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(
+ 75,
+ window.innerWidth / window.innerHeight,
+ 0.1,
+ 1000
+);
+
+const atlas = new TextureAtlas();
+const world = new World(scene, atlas, seed);
+const player = new Player(world);
+const sky = new Sky(scene);
+const particles = new Particles(scene);
+
+const defaultFogNear = scene.fog.near;
+const defaultFogFar = scene.fog.far;
+
+// Spawn on land if possible.
+(function spawn() {
+ let sx = 0;
+ let sz = 0;
+ for (let r = 0; r <= 26; r++) {
+ let found = false;
+ for (let a = 0; a < 8; a++) {
+ const x = Math.round(Math.cos((a / 8) * Math.PI * 2) * r * 8);
+ const z = Math.round(Math.sin((a / 8) * Math.PI * 2) * r * 8);
+ if (world.gen.heightAt(x, z) > SEA_LEVEL + 1) {
+ sx = x;
+ sz = z;
+ found = true;
+ break;
+ }
+ }
+ if (found) break;
+ }
+ player.teleportToSurface(sx + 0.5, sz + 0.5);
+})();
+
+// Block highlight outline.
+const highlight = new THREE.LineSegments(
+ new THREE.EdgesGeometry(new THREE.BoxGeometry(1.002, 1.002, 1.002)),
+ new THREE.LineBasicMaterial({ color: 0x111111, transparent: true, opacity: 0.7 })
+);
+highlight.visible = false;
+scene.add(highlight);
+
+// ----------------------------------------------------------------- input
+
+const input = {
+ forward: 0,
+ strafe: 0,
+ sprint: false,
+ jump: false,
+ down: false,
+};
+const keys = new Set();
+let locked = false;
+let selectedSlot = 0;
+
+function refreshAxes() {
+ input.forward = (keys.has('KeyW') ? 1 : 0) - (keys.has('KeyS') ? 1 : 0);
+ input.strafe = (keys.has('KeyD') ? 1 : 0) - (keys.has('KeyA') ? 1 : 0);
+ input.jump = keys.has('Space');
+ input.sprint = keys.has('ShiftLeft') || keys.has('ShiftRight');
+ input.down = input.sprint;
+}
+
+document.addEventListener('keydown', (e) => {
+ if (e.code === 'Space') e.preventDefault();
+ if (e.repeat) return;
+ keys.add(e.code);
+ refreshAxes();
+
+ if (e.code === 'KeyF' && locked) {
+ player.flying = !player.flying;
+ if (player.flying) player.velocity.y = 0;
+ flashStatus(player.flying ? 'Flying enabled' : 'Flying disabled');
+ }
+ if (/^Digit[1-9]$/.test(e.code)) {
+ selectSlot(parseInt(e.code.slice(5), 10) - 1);
+ }
+});
+
+document.addEventListener('keyup', (e) => {
+ keys.delete(e.code);
+ refreshAxes();
+});
+
+window.addEventListener('blur', () => {
+ keys.clear();
+ refreshAxes();
+});
+
+// Some browsers emit a bogus, huge movement delta right after the pointer is
+// locked (and occasionally mid-session); skip the first events and clamp
+// spikes so the camera never jolts.
+let skipMouseEvents = 0;
+document.addEventListener('mousemove', (e) => {
+ if (!locked) return;
+ if (skipMouseEvents > 0) {
+ skipMouseEvents--;
+ return;
+ }
+ const dx = Math.max(-350, Math.min(350, e.movementX));
+ const dy = Math.max(-350, Math.min(350, e.movementY));
+ player.rotate(dx, dy, 0.0022);
+});
+
+// ------------------------------------------------------- block interaction
+
+function currentTarget() {
+ const dir = player.lookDirection();
+ return raycastVoxel(world, player.eyePosition, dir, REACH_DISTANCE);
+}
+
+function breakBlock() {
+ const hit = currentTarget();
+ if (!hit || hit.id === Blocks.BEDROCK) return;
+ const tile = tileForFace(hit.id, 0);
+ world.setBlock(hit.x, hit.y, hit.z, Blocks.AIR);
+ particles.burst(hit.x + 0.5, hit.y + 0.5, hit.z + 0.5, atlas.averageColor(tile), 18);
+ playBreak();
+}
+
+function placeBlock() {
+ const hit = currentTarget();
+ if (!hit) return;
+ const x = hit.x + hit.normal[0];
+ const y = hit.y + hit.normal[1];
+ const z = hit.z + hit.normal[2];
+ const existing = world.getBlock(x, y, z);
+ if (existing !== Blocks.AIR && existing !== Blocks.WATER) return;
+ if (player.overlapsBlock(x, y, z)) return;
+ if (world.setBlock(x, y, z, HOTBAR_BLOCKS[selectedSlot])) playPlace();
+}
+
+function pickBlock() {
+ const hit = currentTarget();
+ if (!hit) return;
+ const remap = {
+ [Blocks.SNOWY_GRASS]: Blocks.GRASS,
+ [Blocks.COAL_ORE]: Blocks.STONE,
+ [Blocks.IRON_ORE]: Blocks.STONE,
+ [Blocks.BEDROCK]: Blocks.STONE,
+ };
+ const id = remap[hit.id] ?? hit.id;
+ const idx = HOTBAR_BLOCKS.indexOf(id);
+ if (idx >= 0) selectSlot(idx);
+}
+
+let actionTimer = null;
+function startAction(fn) {
+ stopAction();
+ fn();
+ actionTimer = setInterval(fn, 240);
+}
+function stopAction() {
+ if (actionTimer) {
+ clearInterval(actionTimer);
+ actionTimer = null;
+ }
+}
+
+canvas.addEventListener('mousedown', (e) => {
+ if (!locked) return;
+ if (e.button === 0) startAction(breakBlock);
+ else if (e.button === 2) startAction(placeBlock);
+ else if (e.button === 1) {
+ e.preventDefault();
+ pickBlock();
+ }
+});
+document.addEventListener('mouseup', stopAction);
+document.addEventListener('contextmenu', (e) => e.preventDefault());
+
+document.addEventListener(
+ 'wheel',
+ (e) => {
+ if (!locked) return;
+ const delta = Math.sign(e.deltaY);
+ selectSlot((selectedSlot + delta + HOTBAR_BLOCKS.length) % HOTBAR_BLOCKS.length);
+ },
+ { passive: true }
+);
+
+// ----------------------------------------------------------------- HUD
+
+const overlay = document.getElementById('overlay');
+const playButton = document.getElementById('play-button');
+const newWorldButton = document.getElementById('new-world-button');
+const resetButton = document.getElementById('reset-button');
+const seedLabel = document.getElementById('seed-label');
+const hud = document.getElementById('hud');
+const infoLabel = document.getElementById('info');
+const statusLabel = document.getElementById('status');
+const underwaterTint = document.getElementById('underwater');
+const hotbarEl = document.getElementById('hotbar');
+
+seedLabel.textContent = 'Seed: ' + seedStr;
+
+let statusTimer = null;
+function flashStatus(text) {
+ statusLabel.textContent = text;
+ statusLabel.classList.add('visible');
+ if (statusTimer) clearTimeout(statusTimer);
+ statusTimer = setTimeout(() => statusLabel.classList.remove('visible'), 1600);
+}
+
+const slotEls = [];
+function buildHotbar() {
+ for (let i = 0; i < HOTBAR_BLOCKS.length; i++) {
+ const id = HOTBAR_BLOCKS[i];
+ const def = BLOCK_DEFS[id];
+ const slot = document.createElement('div');
+ slot.className = 'slot';
+ slot.title = def.name;
+
+ const icon = document.createElement('canvas');
+ icon.width = 44;
+ icon.height = 44;
+ const ctx = icon.getContext('2d');
+ atlas.drawIsoCube(ctx, 44, def.tiles[0], def.tiles[2]);
+ slot.appendChild(icon);
+
+ const key = document.createElement('span');
+ key.className = 'slot-key';
+ key.textContent = String(i + 1);
+ slot.appendChild(key);
+
+ slot.addEventListener('click', () => selectSlot(i));
+ hotbarEl.appendChild(slot);
+ slotEls.push(slot);
+ }
+}
+
+function selectSlot(i) {
+ if (i < 0 || i >= HOTBAR_BLOCKS.length) return;
+ selectedSlot = i;
+ for (let s = 0; s < slotEls.length; s++) {
+ slotEls[s].classList.toggle('selected', s === i);
+ }
+ flashStatus(BLOCK_DEFS[HOTBAR_BLOCKS[i]].name);
+}
+
+buildHotbar();
+selectSlot(0);
+statusLabel.classList.remove('visible');
+
+// ----------------------------------------------------------- pointer lock
+
+function requestLock() {
+ // unadjustedMovement disables OS mouse acceleration for smoother, more
+ // predictable aiming; fall back gracefully where unsupported.
+ const plainLock = () => {
+ try {
+ const p = canvas.requestPointerLock();
+ if (p && p.catch) p.catch(() => {});
+ } catch {
+ /* ignored */
+ }
+ };
+ try {
+ const p = canvas.requestPointerLock({ unadjustedMovement: true });
+ if (p && p.catch) p.catch(plainLock);
+ } catch {
+ plainLock();
+ }
+}
+
+playButton.addEventListener('click', requestLock);
+
+newWorldButton.addEventListener('click', () => {
+ const newSeed = String(Math.floor(Math.random() * 1e9));
+ try {
+ localStorage.setItem('blockcraft:seed', newSeed);
+ } catch {
+ /* ignored */
+ }
+ location.href = location.pathname + '?seed=' + newSeed;
+});
+
+resetButton.addEventListener('click', () => {
+ try {
+ localStorage.removeItem(world.storageKey);
+ } catch {
+ /* ignored */
+ }
+ location.reload();
+});
+
+document.addEventListener('pointerlockchange', () => {
+ locked = document.pointerLockElement === canvas;
+ overlay.classList.toggle('hidden', locked);
+ hud.classList.toggle('paused', !locked);
+ if (locked) {
+ skipMouseEvents = 2;
+ } else {
+ stopAction();
+ keys.clear();
+ refreshAxes();
+ }
+});
+
+window.addEventListener('resize', () => {
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(window.innerWidth, window.innerHeight);
+});
+
+window.addEventListener('beforeunload', () => world.saveEdits());
+
+// ----------------------------------------------------------------- loop
+
+const clock = new THREE.Clock();
+let fps = 60;
+let wasInWater = false;
+
+function animate() {
+ requestAnimationFrame(animate);
+ const dt = Math.min(clock.getDelta(), 0.05);
+ if (dt > 0) fps += ((1 / dt) - fps) * 0.05;
+
+ if (locked) {
+ player.update(dt, input);
+ if (player.inWater !== wasInWater) {
+ if (player.inWater) playSplash();
+ wasInWater = player.inWater;
+ }
+ }
+
+ player.applyCamera(camera);
+ world.update(player.position.x, player.position.z);
+ sky.update(dt, camera.position);
+ particles.update(dt);
+
+ // Underwater look.
+ if (player.headInWater) {
+ scene.fog.color.set(0x16447e);
+ scene.background.set(0x16447e);
+ scene.fog.near = 1;
+ scene.fog.far = 22;
+ underwaterTint.classList.add('visible');
+ } else {
+ scene.fog.near = defaultFogNear;
+ scene.fog.far = defaultFogFar;
+ underwaterTint.classList.remove('visible');
+ }
+
+ // Targeted block outline.
+ if (locked) {
+ const hit = currentTarget();
+ if (hit) {
+ highlight.position.set(hit.x + 0.5, hit.y + 0.5, hit.z + 0.5);
+ highlight.visible = true;
+ } else {
+ highlight.visible = false;
+ }
+ } else {
+ highlight.visible = false;
+ }
+
+ const p = player.position;
+ infoLabel.textContent =
+ `${Math.round(fps)} fps · ` +
+ `x ${p.x.toFixed(0)} y ${p.y.toFixed(0)} z ${p.z.toFixed(0)} · ` +
+ `${sky.clockString()}` +
+ (player.flying ? ' · flying' : '') +
+ (world.pendingChunks > 0 ? ` · loading ${world.pendingChunks}` : '');
+
+ renderer.render(scene, camera);
+}
+
+// Debug/testing handle.
+window.blockcraft = { world, player, sky, camera };
+
+// Warm up the area around spawn before the first frame renders.
+world.update(player.position.x, player.position.z);
+animate();
diff --git a/minecraft/js/noise.js b/minecraft/js/noise.js
new file mode 100644
index 0000000..468c29a
--- /dev/null
+++ b/minecraft/js/noise.js
@@ -0,0 +1,151 @@
+import { mulberry32, hash3, hashToFloat } from './rng.js';
+
+// 2D simplex noise (Gustavson-style implementation) with a seeded
+// permutation table, plus cheap 3D value noise for cave carving.
+
+const GRAD2 = [
+ [1, 1], [-1, 1], [1, -1], [-1, -1],
+ [1, 0], [-1, 0], [0, 1], [0, -1],
+];
+
+const F2 = 0.5 * (Math.sqrt(3) - 1);
+const G2 = (3 - Math.sqrt(3)) / 6;
+
+export class Noise2D {
+ constructor(seed) {
+ const rng = mulberry32(seed);
+ const p = new Uint8Array(256);
+ for (let i = 0; i < 256; i++) p[i] = i;
+ for (let i = 255; i > 0; i--) {
+ const j = Math.floor(rng() * (i + 1));
+ const tmp = p[i];
+ p[i] = p[j];
+ p[j] = tmp;
+ }
+ this.perm = new Uint8Array(512);
+ for (let i = 0; i < 512; i++) this.perm[i] = p[i & 255];
+ }
+
+ noise(xin, yin) {
+ const perm = this.perm;
+ let n0 = 0;
+ let n1 = 0;
+ let n2 = 0;
+
+ const s = (xin + yin) * F2;
+ const i = Math.floor(xin + s);
+ const j = Math.floor(yin + s);
+ const t = (i + j) * G2;
+ const x0 = xin - (i - t);
+ const y0 = yin - (j - t);
+
+ let i1;
+ let j1;
+ if (x0 > y0) {
+ i1 = 1;
+ j1 = 0;
+ } else {
+ i1 = 0;
+ j1 = 1;
+ }
+
+ const x1 = x0 - i1 + G2;
+ const y1 = y0 - j1 + G2;
+ const x2 = x0 - 1 + 2 * G2;
+ const y2 = y0 - 1 + 2 * G2;
+
+ const ii = i & 255;
+ const jj = j & 255;
+
+ let t0 = 0.5 - x0 * x0 - y0 * y0;
+ if (t0 >= 0) {
+ const g = GRAD2[perm[ii + perm[jj]] & 7];
+ t0 *= t0;
+ n0 = t0 * t0 * (g[0] * x0 + g[1] * y0);
+ }
+
+ let t1 = 0.5 - x1 * x1 - y1 * y1;
+ if (t1 >= 0) {
+ const g = GRAD2[perm[ii + i1 + perm[jj + j1]] & 7];
+ t1 *= t1;
+ n1 = t1 * t1 * (g[0] * x1 + g[1] * y1);
+ }
+
+ let t2 = 0.5 - x2 * x2 - y2 * y2;
+ if (t2 >= 0) {
+ const g = GRAD2[perm[ii + 1 + perm[jj + 1]] & 7];
+ t2 *= t2;
+ n2 = t2 * t2 * (g[0] * x2 + g[1] * y2);
+ }
+
+ // Result scaled to roughly [-1, 1].
+ return 70 * (n0 + n1 + n2);
+ }
+
+ fbm(x, y, octaves, lacunarity = 2, gain = 0.5) {
+ let amp = 1;
+ let freq = 1;
+ let sum = 0;
+ let norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ sum += amp * this.noise(x * freq, y * freq);
+ norm += amp;
+ amp *= gain;
+ freq *= lacunarity;
+ }
+ return sum / norm;
+ }
+}
+
+function fade(t) {
+ return t * t * (3 - 2 * t);
+}
+
+export class ValueNoise3D {
+ constructor(seed) {
+ this.seed = seed >>> 0;
+ }
+
+ noise(x, y, z) {
+ const x0 = Math.floor(x);
+ const y0 = Math.floor(y);
+ const z0 = Math.floor(z);
+ const fx = fade(x - x0);
+ const fy = fade(y - y0);
+ const fz = fade(z - z0);
+ const s = this.seed;
+
+ const c000 = hashToFloat(hash3(x0, y0, z0, s));
+ const c100 = hashToFloat(hash3(x0 + 1, y0, z0, s));
+ const c010 = hashToFloat(hash3(x0, y0 + 1, z0, s));
+ const c110 = hashToFloat(hash3(x0 + 1, y0 + 1, z0, s));
+ const c001 = hashToFloat(hash3(x0, y0, z0 + 1, s));
+ const c101 = hashToFloat(hash3(x0 + 1, y0, z0 + 1, s));
+ const c011 = hashToFloat(hash3(x0, y0 + 1, z0 + 1, s));
+ const c111 = hashToFloat(hash3(x0 + 1, y0 + 1, z0 + 1, s));
+
+ const x00 = c000 + (c100 - c000) * fx;
+ const x10 = c010 + (c110 - c010) * fx;
+ const x01 = c001 + (c101 - c001) * fx;
+ const x11 = c011 + (c111 - c011) * fx;
+
+ const y0v = x00 + (x10 - x00) * fy;
+ const y1v = x01 + (x11 - x01) * fy;
+
+ return y0v + (y1v - y0v) * fz;
+ }
+
+ fbm(x, y, z, octaves, lacunarity = 2, gain = 0.5) {
+ let amp = 1;
+ let freq = 1;
+ let sum = 0;
+ let norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ sum += amp * this.noise(x * freq, y * freq, z * freq);
+ norm += amp;
+ amp *= gain;
+ freq *= lacunarity;
+ }
+ return sum / norm;
+ }
+}
diff --git a/minecraft/js/particles.js b/minecraft/js/particles.js
new file mode 100644
index 0000000..4a3aea0
--- /dev/null
+++ b/minecraft/js/particles.js
@@ -0,0 +1,78 @@
+import * as THREE from 'three';
+
+const MAX_PARTICLES = 768;
+
+export class Particles {
+ constructor(scene) {
+ this.list = [];
+ this.positions = new Float32Array(MAX_PARTICLES * 3);
+ this.colors = new Float32Array(MAX_PARTICLES * 3);
+
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(this.positions, 3));
+ geometry.setAttribute('color', new THREE.BufferAttribute(this.colors, 3));
+ geometry.setDrawRange(0, 0);
+ this.geometry = geometry;
+
+ const material = new THREE.PointsMaterial({
+ size: 0.14,
+ vertexColors: true,
+ sizeAttenuation: true,
+ transparent: true,
+ opacity: 0.95,
+ });
+
+ this.points = new THREE.Points(geometry, material);
+ this.points.frustumCulled = false;
+ scene.add(this.points);
+ }
+
+ burst(x, y, z, rgb, count = 16) {
+ for (let i = 0; i < count; i++) {
+ if (this.list.length >= MAX_PARTICLES) break;
+ const a = Math.random() * Math.PI * 2;
+ const r = Math.random() * 2.4;
+ this.list.push({
+ x: x + (Math.random() - 0.5) * 0.7,
+ y: y + (Math.random() - 0.5) * 0.7,
+ z: z + (Math.random() - 0.5) * 0.7,
+ vx: Math.cos(a) * r,
+ vy: 1.6 + Math.random() * 2.6,
+ vz: Math.sin(a) * r,
+ life: 0.35 + Math.random() * 0.4,
+ r: (rgb[0] / 255) * (0.75 + Math.random() * 0.35),
+ g: (rgb[1] / 255) * (0.75 + Math.random() * 0.35),
+ b: (rgb[2] / 255) * (0.75 + Math.random() * 0.35),
+ });
+ }
+ }
+
+ update(dt) {
+ const list = this.list;
+ let n = 0;
+ for (let i = list.length - 1; i >= 0; i--) {
+ const pt = list[i];
+ pt.life -= dt;
+ if (pt.life <= 0) {
+ list.splice(i, 1);
+ continue;
+ }
+ pt.vy -= 16 * dt;
+ pt.x += pt.vx * dt;
+ pt.y += pt.vy * dt;
+ pt.z += pt.vz * dt;
+ }
+ for (const pt of list) {
+ this.positions[n * 3] = pt.x;
+ this.positions[n * 3 + 1] = pt.y;
+ this.positions[n * 3 + 2] = pt.z;
+ this.colors[n * 3] = pt.r;
+ this.colors[n * 3 + 1] = pt.g;
+ this.colors[n * 3 + 2] = pt.b;
+ n++;
+ }
+ this.geometry.attributes.position.needsUpdate = true;
+ this.geometry.attributes.color.needsUpdate = true;
+ this.geometry.setDrawRange(0, n);
+ }
+}
diff --git a/minecraft/js/player.js b/minecraft/js/player.js
new file mode 100644
index 0000000..45033e4
--- /dev/null
+++ b/minecraft/js/player.js
@@ -0,0 +1,241 @@
+import * as THREE from 'three';
+import {
+ GRAVITY,
+ JUMP_SPEED,
+ WALK_SPEED,
+ SPRINT_SPEED,
+ FLY_SPEED,
+ SWIM_SPEED,
+ PLAYER_HALF_WIDTH,
+ PLAYER_HEIGHT,
+ PLAYER_EYE_HEIGHT,
+ WORLD_HEIGHT,
+} from './constants.js';
+import { Blocks, isSolid } from './blocks.js';
+
+const EPS = 0.001;
+
+// Upward speed applied while pressing into a wall in water with jump held,
+// so the player can climb out onto a shoreline block (like Minecraft's
+// out-of-water hop). Reapplied every frame, so it sustains until the ledge
+// is cleared.
+const WATER_CLIMB_SPEED = 7.4;
+
+export class Player {
+ constructor(world) {
+ this.world = world;
+ this.position = new THREE.Vector3(0.5, 50, 0.5); // feet position
+ this.velocity = new THREE.Vector3();
+ this.yaw = 0;
+ this.pitch = 0;
+ this.onGround = false;
+ this.flying = false;
+ this.inWater = false;
+ this.headInWater = false;
+ this.againstWall = false;
+ this.waterExitTimer = 0;
+ }
+
+ get eyePosition() {
+ return new THREE.Vector3(
+ this.position.x,
+ this.position.y + PLAYER_EYE_HEIGHT,
+ this.position.z
+ );
+ }
+
+ lookDirection() {
+ const cp = Math.cos(this.pitch);
+ return new THREE.Vector3(
+ -Math.sin(this.yaw) * cp,
+ Math.sin(this.pitch),
+ -Math.cos(this.yaw) * cp
+ );
+ }
+
+ applyCamera(camera) {
+ camera.position.copy(this.eyePosition);
+ camera.rotation.set(this.pitch, this.yaw, 0, 'YXZ');
+ }
+
+ rotate(dx, dy, sensitivity) {
+ this.yaw -= dx * sensitivity;
+ this.pitch -= dy * sensitivity;
+ const limit = Math.PI / 2 - 0.01;
+ this.pitch = Math.max(-limit, Math.min(limit, this.pitch));
+ }
+
+ teleportToSurface(x, z) {
+ const h = this.world.gen.heightAt(Math.floor(x), Math.floor(z));
+ this.position.set(x, Math.max(h, 30) + 2.2, z);
+ this.velocity.set(0, 0, 0);
+ }
+
+ update(dt, input) {
+ const world = this.world;
+ const pos = this.position;
+ const vel = this.velocity;
+
+ const feetBlock = world.getBlock(
+ Math.floor(pos.x),
+ Math.floor(pos.y + 0.4),
+ Math.floor(pos.z)
+ );
+ const headBlock = world.getBlock(
+ Math.floor(pos.x),
+ Math.floor(pos.y + PLAYER_EYE_HEIGHT),
+ Math.floor(pos.z)
+ );
+ this.inWater = feetBlock === Blocks.WATER || headBlock === Blocks.WATER;
+ this.headInWater = headBlock === Blocks.WATER;
+
+ // Grace period after leaving water so a climb-out can finish.
+ if (this.inWater) this.waterExitTimer = 0.25;
+ else this.waterExitTimer = Math.max(0, this.waterExitTimer - dt);
+
+ // Wish direction in world space from input axes.
+ const sinY = Math.sin(this.yaw);
+ const cosY = Math.cos(this.yaw);
+ const fwd = input.forward;
+ const strafe = input.strafe;
+ let wishX = -fwd * sinY + strafe * cosY;
+ let wishZ = -fwd * cosY - strafe * sinY;
+ const wishLen = Math.hypot(wishX, wishZ);
+ if (wishLen > 1) {
+ wishX /= wishLen;
+ wishZ /= wishLen;
+ }
+
+ if (this.flying) {
+ const speed = input.sprint ? FLY_SPEED * 1.8 : FLY_SPEED;
+ const targetX = wishX * speed;
+ const targetZ = wishZ * speed;
+ let targetY = 0;
+ if (input.jump) targetY += speed;
+ if (input.down) targetY -= speed;
+ const k = 1 - Math.exp(-12 * dt);
+ vel.x += (targetX - vel.x) * k;
+ vel.y += (targetY - vel.y) * k;
+ vel.z += (targetZ - vel.z) * k;
+ } else if (this.inWater) {
+ const speed = input.sprint ? SWIM_SPEED * 1.4 : SWIM_SPEED;
+ const k = 1 - Math.exp(-7 * dt);
+ vel.x += (wishX * speed - vel.x) * k;
+ vel.z += (wishZ * speed - vel.z) * k;
+ vel.y -= GRAVITY * 0.16 * dt;
+ if (input.jump) vel.y += GRAVITY * 0.42 * dt + 9 * dt;
+ vel.y = Math.max(-4.5, Math.min(4.5, vel.y));
+ if (input.jump) {
+ if (this.onGround) {
+ // Standing on the bottom in shallow water: do a real jump.
+ vel.y = JUMP_SPEED * 0.9;
+ } else if (this.againstWall) {
+ // Pressing into a wall: climb out of the water.
+ vel.y = Math.max(vel.y, WATER_CLIMB_SPEED);
+ }
+ }
+ } else {
+ const speed = input.sprint ? SPRINT_SPEED : WALK_SPEED;
+ const control = this.onGround ? 14 : 3.2;
+ const k = 1 - Math.exp(-control * dt);
+ vel.x += (wishX * speed - vel.x) * k;
+ vel.z += (wishZ * speed - vel.z) * k;
+ vel.y -= GRAVITY * dt;
+ vel.y = Math.max(-50, vel.y);
+ if (input.jump && this.onGround) {
+ vel.y = JUMP_SPEED;
+ this.onGround = false;
+ }
+ // Let an in-progress climb out of water finish even though the body
+ // has already left the water volume.
+ if (input.jump && this.againstWall && this.waterExitTimer > 0) {
+ vel.y = Math.max(vel.y, WATER_CLIMB_SPEED);
+ }
+ }
+
+ this.onGround = false;
+ this.againstWall = false;
+ this.moveAxis(0, vel.x * dt);
+ this.moveAxis(1, vel.y * dt);
+ this.moveAxis(2, vel.z * dt);
+
+ if (pos.y < -16) this.teleportToSurface(pos.x, pos.z);
+ if (pos.y > WORLD_HEIGHT + 40) {
+ pos.y = WORLD_HEIGHT + 40;
+ vel.y = Math.min(vel.y, 0);
+ }
+ }
+
+ collides(minX, minY, minZ, maxX, maxY, maxZ) {
+ const world = this.world;
+ const x0 = Math.floor(minX);
+ const x1 = Math.floor(maxX);
+ const y0 = Math.floor(minY);
+ const y1 = Math.floor(maxY);
+ const z0 = Math.floor(minZ);
+ const z1 = Math.floor(maxZ);
+ for (let y = y0; y <= y1; y++) {
+ for (let z = z0; z <= z1; z++) {
+ for (let x = x0; x <= x1; x++) {
+ if (isSolid(world.getBlock(x, y, z))) return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ moveAxis(axis, amount) {
+ if (amount === 0) return;
+ const pos = this.position;
+ const vel = this.velocity;
+ const hw = PLAYER_HALF_WIDTH;
+
+ if (axis === 0) pos.x += amount;
+ else if (axis === 1) pos.y += amount;
+ else pos.z += amount;
+
+ const minX = pos.x - hw;
+ const maxX = pos.x + hw;
+ const minY = pos.y;
+ const maxY = pos.y + PLAYER_HEIGHT;
+ const minZ = pos.z - hw;
+ const maxZ = pos.z + hw;
+
+ if (!this.collides(minX, minY + EPS, minZ, maxX, maxY - EPS, maxZ)) return;
+
+ if (axis === 0) {
+ if (amount > 0) pos.x = Math.floor(maxX) - hw - EPS;
+ else pos.x = Math.floor(minX) + 1 + hw + EPS;
+ vel.x = 0;
+ this.againstWall = true;
+ } else if (axis === 1) {
+ if (amount > 0) {
+ pos.y = Math.floor(maxY - EPS) - PLAYER_HEIGHT - EPS;
+ vel.y = 0;
+ } else {
+ pos.y = Math.floor(minY) + 1 + EPS;
+ vel.y = 0;
+ this.onGround = true;
+ }
+ } else {
+ if (amount > 0) pos.z = Math.floor(maxZ) - hw - EPS;
+ else pos.z = Math.floor(minZ) + 1 + hw + EPS;
+ vel.z = 0;
+ this.againstWall = true;
+ }
+ }
+
+ // True if placing a block at (x, y, z) would overlap the player's AABB.
+ overlapsBlock(x, y, z) {
+ const hw = PLAYER_HALF_WIDTH;
+ const pos = this.position;
+ return (
+ x + 1 > pos.x - hw &&
+ x < pos.x + hw &&
+ y + 1 > pos.y &&
+ y < pos.y + PLAYER_HEIGHT &&
+ z + 1 > pos.z - hw &&
+ z < pos.z + hw
+ );
+ }
+}
diff --git a/minecraft/js/raycast.js b/minecraft/js/raycast.js
new file mode 100644
index 0000000..b4f6a9a
--- /dev/null
+++ b/minecraft/js/raycast.js
@@ -0,0 +1,62 @@
+import { Blocks } from './blocks.js';
+
+// Amanatides & Woo voxel traversal. Returns the first targetable block hit
+// (anything that is not air or water) along with the face normal, or null.
+export function raycastVoxel(world, origin, dir, maxDist) {
+ let x = Math.floor(origin.x);
+ let y = Math.floor(origin.y);
+ let z = Math.floor(origin.z);
+
+ const stepX = dir.x > 0 ? 1 : -1;
+ const stepY = dir.y > 0 ? 1 : -1;
+ const stepZ = dir.z > 0 ? 1 : -1;
+
+ const tDeltaX = dir.x !== 0 ? Math.abs(1 / dir.x) : Infinity;
+ const tDeltaY = dir.y !== 0 ? Math.abs(1 / dir.y) : Infinity;
+ const tDeltaZ = dir.z !== 0 ? Math.abs(1 / dir.z) : Infinity;
+
+ const fracX = origin.x - x;
+ const fracY = origin.y - y;
+ const fracZ = origin.z - z;
+
+ let tMaxX = dir.x !== 0 ? (dir.x > 0 ? (1 - fracX) : fracX) * tDeltaX : Infinity;
+ let tMaxY = dir.y !== 0 ? (dir.y > 0 ? (1 - fracY) : fracY) * tDeltaY : Infinity;
+ let tMaxZ = dir.z !== 0 ? (dir.z > 0 ? (1 - fracZ) : fracZ) * tDeltaZ : Infinity;
+
+ let nx = 0;
+ let ny = 0;
+ let nz = 0;
+ let t = 0;
+
+ while (t <= maxDist) {
+ const id = world.getBlock(x, y, z);
+ if (id !== Blocks.AIR && id !== Blocks.WATER && t > 0) {
+ return { x, y, z, id, normal: [nx, ny, nz], distance: t };
+ }
+
+ if (tMaxX < tMaxY && tMaxX < tMaxZ) {
+ x += stepX;
+ t = tMaxX;
+ tMaxX += tDeltaX;
+ nx = -stepX;
+ ny = 0;
+ nz = 0;
+ } else if (tMaxY < tMaxZ) {
+ y += stepY;
+ t = tMaxY;
+ tMaxY += tDeltaY;
+ nx = 0;
+ ny = -stepY;
+ nz = 0;
+ } else {
+ z += stepZ;
+ t = tMaxZ;
+ tMaxZ += tDeltaZ;
+ nx = 0;
+ ny = 0;
+ nz = -stepZ;
+ }
+ }
+
+ return null;
+}
diff --git a/minecraft/js/rng.js b/minecraft/js/rng.js
new file mode 100644
index 0000000..3c71b41
--- /dev/null
+++ b/minecraft/js/rng.js
@@ -0,0 +1,49 @@
+// Small deterministic hashing / PRNG helpers used for world generation.
+
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+export function hash2(x, z, seed) {
+ let h = (seed >>> 0) ^ Math.imul(x | 0, 374761393) ^ Math.imul(z | 0, 668265263);
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ return (h ^ (h >>> 16)) >>> 0;
+}
+
+export function hash3(x, y, z, seed) {
+ let h =
+ (seed >>> 0) ^
+ Math.imul(x | 0, 374761393) ^
+ Math.imul(y | 0, 2246822519) ^
+ Math.imul(z | 0, 668265263);
+ h = Math.imul(h ^ (h >>> 13), 1274126177);
+ return (h ^ (h >>> 16)) >>> 0;
+}
+
+export function hashToFloat(h) {
+ return (h >>> 0) / 4294967296;
+}
+
+export function rand2(x, z, seed) {
+ return hashToFloat(hash2(x, z, seed));
+}
+
+export function rand3(x, y, z, seed) {
+ return hashToFloat(hash3(x, y, z, seed));
+}
+
+export function seedFromString(str) {
+ let h = 2166136261;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
diff --git a/minecraft/js/sky.js b/minecraft/js/sky.js
new file mode 100644
index 0000000..c4c6a6a
--- /dev/null
+++ b/minecraft/js/sky.js
@@ -0,0 +1,242 @@
+import * as THREE from 'three';
+import { RENDER_DISTANCE, CHUNK_SIZE, DAY_LENGTH } from './constants.js';
+import { mulberry32 } from './rng.js';
+
+function smoothstep(edge0, edge1, x) {
+ const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
+ return t * t * (3 - 2 * t);
+}
+
+function makeDiscTexture(size, draw) {
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ draw(ctx, size);
+ const tex = new THREE.CanvasTexture(canvas);
+ tex.magFilter = THREE.NearestFilter;
+ tex.minFilter = THREE.NearestFilter;
+ return tex;
+}
+
+function makeCloudTexture() {
+ const size = 256;
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ const ctx = canvas.getContext('2d');
+ const rng = mulberry32(77);
+
+ // Blocky clouds: coarse grid cells switched on by layered random fields.
+ const cells = 32;
+ const cell = size / cells;
+ const field = [];
+ for (let y = 0; y < cells; y++) {
+ field.push([]);
+ for (let x = 0; x < cells; x++) field[y].push(rng());
+ }
+ const sample = (x, y) => field[(y + cells) % cells][(x + cells) % cells];
+
+ ctx.clearRect(0, 0, size, size);
+ ctx.fillStyle = 'rgba(255,255,255,0.92)';
+ for (let y = 0; y < cells; y++) {
+ for (let x = 0; x < cells; x++) {
+ let v = 0;
+ for (let dy = -2; dy <= 2; dy++) {
+ for (let dx = -2; dx <= 2; dx++) {
+ v += sample(x + dx, y + dy);
+ }
+ }
+ v /= 25;
+ if (v > 0.56) ctx.fillRect(x * cell, y * cell, cell, cell);
+ }
+ }
+
+ const tex = new THREE.CanvasTexture(canvas);
+ tex.wrapS = THREE.RepeatWrapping;
+ tex.wrapT = THREE.RepeatWrapping;
+ tex.magFilter = THREE.NearestFilter;
+ tex.minFilter = THREE.NearestFilter;
+ return tex;
+}
+
+const DAY_SKY = new THREE.Color(0x84b9e8);
+const NIGHT_SKY = new THREE.Color(0x0b1026);
+const DUSK_TINT = new THREE.Color(0xe98a4d);
+const DAY_SUNLIGHT = new THREE.Color(0xfff2d8);
+const MOONLIGHT = new THREE.Color(0x91a3cc);
+
+export class Sky {
+ constructor(scene) {
+ this.scene = scene;
+ this.time = 0.3 * DAY_LENGTH; // start mid-morning
+
+ this.sunLight = new THREE.DirectionalLight(0xffffff, 1);
+ scene.add(this.sunLight);
+ scene.add(this.sunLight.target);
+
+ this.hemiLight = new THREE.HemisphereLight(0xbfd8f0, 0x6b5a44, 0.7);
+ scene.add(this.hemiLight);
+
+ this.ambient = new THREE.AmbientLight(0xffffff, 0.25);
+ scene.add(this.ambient);
+
+ const sunTex = makeDiscTexture(64, (ctx, s) => {
+ ctx.fillStyle = '#fff6c8';
+ ctx.fillRect(s * 0.2, s * 0.2, s * 0.6, s * 0.6);
+ ctx.fillStyle = '#ffe89a';
+ ctx.fillRect(s * 0.28, s * 0.28, s * 0.44, s * 0.44);
+ });
+ const moonTex = makeDiscTexture(64, (ctx, s) => {
+ ctx.fillStyle = '#d8dde6';
+ ctx.fillRect(s * 0.25, s * 0.25, s * 0.5, s * 0.5);
+ ctx.fillStyle = '#aab2c2';
+ ctx.fillRect(s * 0.34, s * 0.4, s * 0.12, s * 0.12);
+ ctx.fillStyle = '#b8c0cf';
+ ctx.fillRect(s * 0.52, s * 0.3, s * 0.09, s * 0.09);
+ ctx.fillRect(s * 0.46, s * 0.55, s * 0.1, s * 0.1);
+ });
+
+ this.sun = new THREE.Mesh(
+ new THREE.PlaneGeometry(42, 42),
+ new THREE.MeshBasicMaterial({
+ map: sunTex,
+ transparent: true,
+ fog: false,
+ depthWrite: false,
+ })
+ );
+ scene.add(this.sun);
+
+ this.moon = new THREE.Mesh(
+ new THREE.PlaneGeometry(30, 30),
+ new THREE.MeshBasicMaterial({
+ map: moonTex,
+ transparent: true,
+ fog: false,
+ depthWrite: false,
+ })
+ );
+ scene.add(this.moon);
+
+ // Stars.
+ const starCount = 420;
+ const starPositions = new Float32Array(starCount * 3);
+ const rng = mulberry32(4242);
+ for (let i = 0; i < starCount; i++) {
+ const theta = rng() * Math.PI * 2;
+ const phi = Math.acos(2 * rng() - 1);
+ const r = 460;
+ starPositions[i * 3] = r * Math.sin(phi) * Math.cos(theta);
+ starPositions[i * 3 + 1] = r * Math.cos(phi);
+ starPositions[i * 3 + 2] = r * Math.sin(phi) * Math.sin(theta);
+ }
+ const starGeo = new THREE.BufferGeometry();
+ starGeo.setAttribute('position', new THREE.BufferAttribute(starPositions, 3));
+ this.starMaterial = new THREE.PointsMaterial({
+ color: 0xffffff,
+ size: 1.7,
+ sizeAttenuation: false,
+ transparent: true,
+ opacity: 0,
+ fog: false,
+ depthWrite: false,
+ });
+ this.stars = new THREE.Points(starGeo, this.starMaterial);
+ scene.add(this.stars);
+
+ // Cloud layer.
+ this.cloudTexture = makeCloudTexture();
+ this.cloudTexture.repeat.set(3, 3);
+ this.cloudPlaneSize = 1600;
+ this.cloudMaterial = new THREE.MeshBasicMaterial({
+ map: this.cloudTexture,
+ transparent: true,
+ opacity: 0.85,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+ this.clouds = new THREE.Mesh(
+ new THREE.PlaneGeometry(this.cloudPlaneSize, this.cloudPlaneSize),
+ this.cloudMaterial
+ );
+ this.clouds.rotation.x = -Math.PI / 2;
+ this.clouds.position.y = 118;
+ this.clouds.renderOrder = 2;
+ scene.add(this.clouds);
+
+ const fogFar = RENDER_DISTANCE * CHUNK_SIZE * 0.95;
+ scene.fog = new THREE.Fog(DAY_SKY.clone(), fogFar * 0.55, fogFar);
+ scene.background = DAY_SKY.clone();
+
+ this.skyColor = new THREE.Color();
+ this.daylight = 1;
+ }
+
+ update(dt, camPos) {
+ this.time = (this.time + dt) % DAY_LENGTH;
+ const t = this.time / DAY_LENGTH;
+
+ const angle = (t - 0.25) * Math.PI * 2;
+ const elevation = Math.sin(angle);
+ const daylight = smoothstep(-0.07, 0.22, elevation);
+ this.daylight = daylight;
+
+ const sunDir = new THREE.Vector3(Math.cos(angle), Math.sin(angle), 0.3).normalize();
+ const moonDir = sunDir.clone().negate();
+
+ // Sky / fog colors with a dawn-dusk tint near the horizon.
+ const sky = this.skyColor;
+ sky.copy(NIGHT_SKY).lerp(DAY_SKY, daylight);
+ const duskAmount =
+ Math.max(0, 1 - Math.abs(elevation) / 0.24) * smoothstep(-0.18, 0.0, elevation);
+ sky.lerp(DUSK_TINT, duskAmount * 0.42);
+
+ this.scene.background.copy(sky);
+ this.scene.fog.color.copy(sky);
+
+ // Directional light follows sun by day, moon by night.
+ const usingSun = elevation > -0.04;
+ const lightDir = usingSun ? sunDir : moonDir;
+ this.sunLight.position.copy(camPos).addScaledVector(lightDir, 220);
+ this.sunLight.target.position.copy(camPos);
+ this.sunLight.target.updateMatrixWorld();
+ this.sunLight.color
+ .copy(MOONLIGHT)
+ .lerp(DAY_SUNLIGHT, daylight);
+ this.sunLight.intensity = 0.22 + daylight * 1.05;
+
+ this.hemiLight.intensity = 0.18 + daylight * 0.55;
+ this.ambient.intensity = 0.16 + daylight * 0.14;
+
+ // Celestial bodies.
+ this.sun.position.copy(camPos).addScaledVector(sunDir, 430);
+ this.sun.lookAt(camPos);
+ this.moon.position.copy(camPos).addScaledVector(moonDir, 430);
+ this.moon.lookAt(camPos);
+
+ this.stars.position.copy(camPos);
+ this.starMaterial.opacity = (1 - daylight) * 0.9;
+
+ // Clouds: plane follows the camera, texture offset keeps them
+ // world-anchored while drifting slowly.
+ const unitsPerRepeat = this.cloudPlaneSize / this.cloudTexture.repeat.x;
+ this.clouds.position.x = camPos.x;
+ this.clouds.position.z = camPos.z;
+ this.cloudTexture.offset.set(
+ (camPos.x + performance.now() * 0.0012) / unitsPerRepeat,
+ -camPos.z / unitsPerRepeat
+ );
+ const cloudShade = 0.35 + daylight * 0.65;
+ this.cloudMaterial.color.setScalar(cloudShade);
+ }
+
+ // Returns time of day as "HH:MM" (t=0.25 is 06:00 sunrise).
+ clockString() {
+ const t = this.time / DAY_LENGTH;
+ const totalMinutes = Math.floor(t * 24 * 60);
+ const hh = String(Math.floor(totalMinutes / 60)).padStart(2, '0');
+ const mm = String(totalMinutes % 60).padStart(2, '0');
+ return hh + ':' + mm;
+ }
+}
diff --git a/minecraft/js/textures.js b/minecraft/js/textures.js
new file mode 100644
index 0000000..d18984f
--- /dev/null
+++ b/minecraft/js/textures.js
@@ -0,0 +1,377 @@
+import * as THREE from 'three';
+import { mulberry32 } from './rng.js';
+import { Tiles } from './blocks.js';
+
+export const TILE_PX = 16;
+// Each tile sits in a larger cell with edge-replicated gutters so that MSAA
+// sample extrapolation / glancing-angle sampling never bleeds into neighbors.
+export const GUTTER_PX = 8;
+export const CELL_PX = TILE_PX + GUTTER_PX * 2;
+export const ATLAS_COLS = 8;
+export const ATLAS_ROWS = 4;
+
+function clamp255(v) {
+ return Math.max(0, Math.min(255, Math.round(v)));
+}
+
+class TilePainter {
+ constructor(ctx, ox, oy, rng) {
+ this.ctx = ctx;
+ this.ox = ox;
+ this.oy = oy;
+ this.rng = rng;
+ }
+
+ px(x, y, r, g, b, a = 255) {
+ this.ctx.fillStyle = `rgba(${clamp255(r)},${clamp255(g)},${clamp255(b)},${a / 255})`;
+ this.ctx.fillRect(this.ox + x, this.oy + y, 1, 1);
+ }
+
+ // Fill the whole tile with a base color, jittered per pixel.
+ noisy(r, g, b, jitter, a = 255) {
+ for (let y = 0; y < TILE_PX; y++) {
+ for (let x = 0; x < TILE_PX; x++) {
+ const d = (this.rng() - 0.5) * 2 * jitter;
+ this.px(x, y, r + d, g + d, b + d, a);
+ }
+ }
+ }
+
+ speckle(count, r, g, b, a = 255) {
+ for (let i = 0; i < count; i++) {
+ const x = Math.floor(this.rng() * TILE_PX);
+ const y = Math.floor(this.rng() * TILE_PX);
+ this.px(x, y, r, g, b, a);
+ }
+ }
+}
+
+const painters = {
+ [Tiles.GRASS_TOP](p) {
+ p.noisy(106, 170, 64, 18);
+ p.speckle(26, 84, 140, 48);
+ p.speckle(12, 128, 192, 84);
+ },
+
+ [Tiles.GRASS_SIDE](p) {
+ p.noisy(134, 96, 67, 14);
+ p.speckle(16, 104, 72, 48);
+ for (let x = 0; x < TILE_PX; x++) {
+ const depth = 3 + Math.floor(p.rng() * 2.4);
+ for (let y = 0; y < depth; y++) {
+ const d = (p.rng() - 0.5) * 30;
+ p.px(x, y, 102 + d, 166 + d, 62 + d);
+ }
+ }
+ },
+
+ [Tiles.DIRT](p) {
+ p.noisy(134, 96, 67, 16);
+ p.speckle(20, 104, 72, 48);
+ p.speckle(10, 160, 120, 86);
+ },
+
+ [Tiles.STONE](p) {
+ p.noisy(127, 127, 127, 12);
+ for (let i = 0; i < 7; i++) {
+ const x = Math.floor(p.rng() * 14);
+ const y = Math.floor(p.rng() * 14);
+ const shade = 104 + p.rng() * 18;
+ p.px(x, y, shade, shade, shade);
+ p.px(x + 1, y, shade, shade, shade);
+ p.px(x, y + 1, shade + 8, shade + 8, shade + 8);
+ }
+ },
+
+ [Tiles.COBBLESTONE](p) {
+ p.noisy(72, 72, 74, 8);
+ const stones = [
+ [0, 0, 7, 7], [8, 0, 7, 6], [0, 8, 6, 7], [7, 7, 8, 8],
+ [12, 5, 4, 4], [4, 12, 5, 4],
+ ];
+ for (const [sx, sy, w, h] of stones) {
+ const base = 110 + p.rng() * 35;
+ for (let y = sy + 1; y < Math.min(sy + h, TILE_PX); y++) {
+ for (let x = sx + 1; x < Math.min(sx + w, TILE_PX); x++) {
+ const d = (p.rng() - 0.5) * 22;
+ p.px(x, y, base + d, base + d, base + d + 2);
+ }
+ }
+ }
+ },
+
+ [Tiles.PLANKS](p) {
+ for (let y = 0; y < TILE_PX; y++) {
+ const board = Math.floor(y / 4);
+ const seam = y % 4 === 0;
+ for (let x = 0; x < TILE_PX; x++) {
+ const grain = Math.sin((x + board * 5) * 0.9) * 8;
+ const d = (p.rng() - 0.5) * 14 + grain;
+ if (seam) p.px(x, y, 122 + d * 0.4, 92 + d * 0.4, 52 + d * 0.4);
+ else p.px(x, y, 178 + d, 142 + d, 88 + d);
+ }
+ if (!seam && p.rng() < 0.3) {
+ const x = Math.floor(p.rng() * TILE_PX);
+ p.px(x, y, 130, 100, 58);
+ }
+ }
+ },
+
+ [Tiles.LOG_SIDE](p) {
+ for (let x = 0; x < TILE_PX; x++) {
+ const stripe = Math.sin(x * 1.7) * 12;
+ for (let y = 0; y < TILE_PX; y++) {
+ const d = (p.rng() - 0.5) * 12 + stripe;
+ p.px(x, y, 104 + d, 78 + d, 44 + d);
+ }
+ }
+ p.speckle(10, 70, 50, 26);
+ },
+
+ [Tiles.LOG_TOP](p) {
+ p.noisy(154, 122, 72, 10);
+ const cx = 7.5;
+ const cy = 7.5;
+ for (let y = 0; y < TILE_PX; y++) {
+ for (let x = 0; x < TILE_PX; x++) {
+ const dist = Math.hypot(x - cx, y - cy);
+ if (dist > 7.2) {
+ p.px(x, y, 104, 78, 44);
+ } else if (Math.floor(dist) % 2 === 0) {
+ const d = (p.rng() - 0.5) * 10;
+ p.px(x, y, 168 + d, 136 + d, 84 + d);
+ }
+ }
+ }
+ },
+
+ [Tiles.LEAVES](p) {
+ p.noisy(58, 122, 44, 22);
+ p.speckle(26, 36, 86, 28);
+ p.speckle(16, 88, 158, 64);
+ },
+
+ [Tiles.SAND](p) {
+ p.noisy(219, 206, 160, 12);
+ p.speckle(18, 196, 180, 128);
+ p.speckle(10, 235, 226, 190);
+ },
+
+ [Tiles.GLASS](p) {
+ p.noisy(220, 240, 250, 4, 28);
+ for (let i = 0; i < TILE_PX; i++) {
+ p.px(i, 0, 226, 245, 252, 255);
+ p.px(i, TILE_PX - 1, 226, 245, 252, 255);
+ p.px(0, i, 226, 245, 252, 255);
+ p.px(TILE_PX - 1, i, 226, 245, 252, 255);
+ }
+ for (let i = 3; i < 8; i++) p.px(i, 11 - i, 235, 248, 253, 150);
+ for (let i = 6; i < 12; i++) p.px(i, 17 - i, 235, 248, 253, 110);
+ },
+
+ [Tiles.WATER](p) {
+ for (let y = 0; y < TILE_PX; y++) {
+ for (let x = 0; x < TILE_PX; x++) {
+ const wave = Math.sin((x + y * 2.4) * 0.8) * 12;
+ const d = (p.rng() - 0.5) * 10 + wave;
+ p.px(x, y, 40 + d, 96 + d, 196 + d, 178);
+ }
+ }
+ },
+
+ [Tiles.BEDROCK](p) {
+ p.noisy(70, 70, 72, 26);
+ for (let i = 0; i < 9; i++) {
+ const x = Math.floor(p.rng() * 13);
+ const y = Math.floor(p.rng() * 13);
+ const dark = p.rng() < 0.5;
+ const v = dark ? 34 : 112;
+ for (let dy = 0; dy < 3; dy++) {
+ for (let dx = 0; dx < 3; dx++) {
+ if (p.rng() < 0.7) p.px(x + dx, y + dy, v, v, v + 2);
+ }
+ }
+ }
+ },
+
+ [Tiles.SNOW_TOP](p) {
+ p.noisy(240, 246, 250, 7);
+ p.speckle(14, 214, 226, 238);
+ },
+
+ [Tiles.SNOW_SIDE](p) {
+ p.noisy(134, 96, 67, 14);
+ for (let x = 0; x < TILE_PX; x++) {
+ const depth = 4 + Math.floor(p.rng() * 2.2);
+ for (let y = 0; y < depth; y++) {
+ const d = (p.rng() - 0.5) * 10;
+ p.px(x, y, 240 + d, 246 + d, 250 + d);
+ }
+ }
+ },
+
+ [Tiles.COAL_ORE](p) {
+ painters[Tiles.STONE](p);
+ for (let i = 0; i < 5; i++) {
+ const x = 1 + Math.floor(p.rng() * 12);
+ const y = 1 + Math.floor(p.rng() * 12);
+ for (let dy = 0; dy < 2; dy++) {
+ for (let dx = 0; dx < 2; dx++) {
+ if (p.rng() < 0.85) p.px(x + dx, y + dy, 28, 28, 32);
+ }
+ }
+ }
+ },
+
+ [Tiles.IRON_ORE](p) {
+ painters[Tiles.STONE](p);
+ for (let i = 0; i < 5; i++) {
+ const x = 1 + Math.floor(p.rng() * 12);
+ const y = 1 + Math.floor(p.rng() * 12);
+ for (let dy = 0; dy < 2; dy++) {
+ for (let dx = 0; dx < 2; dx++) {
+ if (p.rng() < 0.85) p.px(x + dx, y + dy, 226, 178, 144);
+ }
+ }
+ }
+ },
+};
+
+export class TextureAtlas {
+ constructor() {
+ const canvas = document.createElement('canvas');
+ canvas.width = ATLAS_COLS * CELL_PX;
+ canvas.height = ATLAS_ROWS * CELL_PX;
+ const ctx = canvas.getContext('2d');
+ ctx.imageSmoothingEnabled = false;
+
+ ctx.fillStyle = '#777';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ const t = TILE_PX;
+ const g = GUTTER_PX;
+ for (const [tileStr, paint] of Object.entries(painters)) {
+ const tile = Number(tileStr);
+ const col = tile % ATLAS_COLS;
+ const row = Math.floor(tile / ATLAS_COLS);
+ ctx.clearRect(col * CELL_PX, row * CELL_PX, CELL_PX, CELL_PX);
+ const ox = col * CELL_PX + g;
+ const oy = row * CELL_PX + g;
+ paint(new TilePainter(ctx, ox, oy, mulberry32(1234 + tile * 7919)));
+
+ // Replicate tile edges into the gutters.
+ ctx.drawImage(canvas, ox, oy, t, 1, ox, oy - g, t, g);
+ ctx.drawImage(canvas, ox, oy + t - 1, t, 1, ox, oy + t, t, g);
+ ctx.drawImage(canvas, ox, oy, 1, t, ox - g, oy, g, t);
+ ctx.drawImage(canvas, ox + t - 1, oy, 1, t, ox + t, oy, g, t);
+ ctx.drawImage(canvas, ox, oy, 1, 1, ox - g, oy - g, g, g);
+ ctx.drawImage(canvas, ox + t - 1, oy, 1, 1, ox + t, oy - g, g, g);
+ ctx.drawImage(canvas, ox, oy + t - 1, 1, 1, ox - g, oy + t, g, g);
+ ctx.drawImage(canvas, ox + t - 1, oy + t - 1, 1, 1, ox + t, oy + t, g, g);
+ }
+
+ this.canvas = canvas;
+ this.ctx = ctx;
+
+ const texture = new THREE.CanvasTexture(canvas);
+ texture.magFilter = THREE.NearestFilter;
+ texture.minFilter = THREE.NearestFilter;
+ texture.generateMipmaps = false;
+ texture.colorSpace = THREE.SRGBColorSpace;
+ this.texture = texture;
+ }
+
+ // Returns [u0, v0, u1, v1] for a tile, slightly inset to avoid bleeding.
+ uvRect(tile) {
+ const col = tile % ATLAS_COLS;
+ const row = Math.floor(tile / ATLAS_COLS);
+ const w = ATLAS_COLS * CELL_PX;
+ const h = ATLAS_ROWS * CELL_PX;
+ const inset = 0.5;
+ const u0 = (col * CELL_PX + GUTTER_PX + inset) / w;
+ const u1 = (col * CELL_PX + GUTTER_PX + TILE_PX - inset) / w;
+ // CanvasTexture flips Y, so v=1 is the canvas top.
+ const v1 = 1 - (row * CELL_PX + GUTTER_PX + inset) / h;
+ const v0 = 1 - (row * CELL_PX + GUTTER_PX + TILE_PX - inset) / h;
+ return [u0, v0, u1, v1];
+ }
+
+ averageColor(tile) {
+ const col = tile % ATLAS_COLS;
+ const row = Math.floor(tile / ATLAS_COLS);
+ const data = this.ctx.getImageData(
+ col * CELL_PX + GUTTER_PX,
+ row * CELL_PX + GUTTER_PX,
+ TILE_PX,
+ TILE_PX
+ ).data;
+ let r = 0;
+ let g = 0;
+ let b = 0;
+ let n = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] < 16) continue;
+ r += data[i];
+ g += data[i + 1];
+ b += data[i + 2];
+ n++;
+ }
+ if (n === 0) return [255, 255, 255];
+ return [r / n, g / n, b / n];
+ }
+
+ // Draws a small isometric cube preview onto a 2d canvas (for hotbar icons).
+ drawIsoCube(targetCtx, size, topTile, sideTile) {
+ const w = size;
+ const h = size;
+ const halfW = w / 2;
+ const quartH = h / 4;
+ const faceH = h * 0.5;
+ const t = TILE_PX;
+
+ const tileCanvas = (tile, brightness) => {
+ const c = document.createElement('canvas');
+ c.width = t;
+ c.height = t;
+ const cc = c.getContext('2d');
+ cc.imageSmoothingEnabled = false;
+ const col = tile % ATLAS_COLS;
+ const row = Math.floor(tile / ATLAS_COLS);
+ cc.drawImage(
+ this.canvas,
+ col * CELL_PX + GUTTER_PX,
+ row * CELL_PX + GUTTER_PX,
+ t,
+ t,
+ 0,
+ 0,
+ t,
+ t
+ );
+ if (brightness < 1) {
+ cc.globalCompositeOperation = 'source-atop';
+ cc.fillStyle = `rgba(0,0,0,${1 - brightness})`;
+ cc.fillRect(0, 0, t, t);
+ }
+ return c;
+ };
+
+ targetCtx.save();
+ targetCtx.imageSmoothingEnabled = false;
+
+ // Top face.
+ targetCtx.setTransform(halfW / t, quartH / t, -halfW / t, quartH / t, halfW, 0);
+ targetCtx.drawImage(tileCanvas(topTile, 1), 0, 0);
+
+ // Left face.
+ targetCtx.setTransform(halfW / t, quartH / t, 0, faceH / t, 0, quartH);
+ targetCtx.drawImage(tileCanvas(sideTile, 0.72), 0, 0);
+
+ // Right face.
+ targetCtx.setTransform(halfW / t, -quartH / t, 0, faceH / t, halfW, quartH * 2);
+ targetCtx.drawImage(tileCanvas(sideTile, 0.55), 0, 0);
+
+ targetCtx.restore();
+ targetCtx.setTransform(1, 0, 0, 1, 0, 0);
+ }
+}
diff --git a/minecraft/js/world.js b/minecraft/js/world.js
new file mode 100644
index 0000000..ea4b64e
--- /dev/null
+++ b/minecraft/js/world.js
@@ -0,0 +1,632 @@
+import * as THREE from 'three';
+import {
+ CHUNK_SIZE,
+ WORLD_HEIGHT,
+ RENDER_DISTANCE,
+ UNLOAD_DISTANCE,
+ MESH_TIME_BUDGET_MS,
+} from './constants.js';
+import { Blocks, BLOCK_DEFS, isOpaque, tileForFace } from './blocks.js';
+import { WorldGen } from './worldgen.js';
+
+const CS = CHUNK_SIZE;
+const LAYER = CS * CS;
+
+// Face winding/uv layout based on the classic three.js voxel example.
+const FACES = [
+ {
+ dir: [-1, 0, 0],
+ shade: 0.72,
+ corners: [
+ { pos: [0, 1, 0], uv: [0, 1] },
+ { pos: [0, 0, 0], uv: [0, 0] },
+ { pos: [0, 1, 1], uv: [1, 1] },
+ { pos: [0, 0, 1], uv: [1, 0] },
+ ],
+ },
+ {
+ dir: [1, 0, 0],
+ shade: 0.72,
+ corners: [
+ { pos: [1, 1, 1], uv: [0, 1] },
+ { pos: [1, 0, 1], uv: [0, 0] },
+ { pos: [1, 1, 0], uv: [1, 1] },
+ { pos: [1, 0, 0], uv: [1, 0] },
+ ],
+ },
+ {
+ dir: [0, -1, 0],
+ shade: 0.55,
+ corners: [
+ { pos: [1, 0, 1], uv: [1, 0] },
+ { pos: [0, 0, 1], uv: [0, 0] },
+ { pos: [1, 0, 0], uv: [1, 1] },
+ { pos: [0, 0, 0], uv: [0, 1] },
+ ],
+ },
+ {
+ dir: [0, 1, 0],
+ shade: 1.0,
+ corners: [
+ { pos: [0, 1, 1], uv: [1, 1] },
+ { pos: [1, 1, 1], uv: [0, 1] },
+ { pos: [0, 1, 0], uv: [1, 0] },
+ { pos: [1, 1, 0], uv: [0, 0] },
+ ],
+ },
+ {
+ dir: [0, 0, -1],
+ shade: 0.85,
+ corners: [
+ { pos: [1, 0, 0], uv: [0, 0] },
+ { pos: [0, 0, 0], uv: [1, 0] },
+ { pos: [1, 1, 0], uv: [0, 1] },
+ { pos: [0, 1, 0], uv: [1, 1] },
+ ],
+ },
+ {
+ dir: [0, 0, 1],
+ shade: 0.85,
+ corners: [
+ { pos: [0, 0, 1], uv: [0, 0] },
+ { pos: [1, 0, 1], uv: [1, 0] },
+ { pos: [0, 1, 1], uv: [0, 1] },
+ { pos: [1, 1, 1], uv: [1, 1] },
+ ],
+ },
+];
+
+for (const face of FACES) {
+ face.axis = face.dir.findIndex((v) => v !== 0);
+ face.t1 = face.axis === 0 ? 1 : 0;
+ face.t2 = face.axis === 2 ? 1 : 2;
+}
+
+const AO_CURVE = [0.45, 0.66, 0.83, 1.0];
+
+function chunkKey(cx, cz) {
+ return cx + ',' + cz;
+}
+
+function grow(arr, minLen) {
+ const next = new arr.constructor(Math.max(minLen, arr.length * 2));
+ next.set(arr);
+ return next;
+}
+
+// Reusable scratch buffers for mesh building. Persisting these across chunk
+// rebuilds avoids re-allocating millions of array slots per build, which
+// otherwise causes GC hitches while flying around.
+class MeshBuilder {
+ constructor() {
+ this.positions = new Float32Array(16384 * 3);
+ this.normals = new Float32Array(16384 * 3);
+ this.uvs = new Float32Array(16384 * 2);
+ this.colors = new Float32Array(16384 * 3);
+ this.indices = new Uint32Array(24576);
+ this.vertexCount = 0;
+ this.indexCount = 0;
+ }
+
+ reset() {
+ this.vertexCount = 0;
+ this.indexCount = 0;
+ }
+
+ ensureQuad() {
+ const v = this.vertexCount + 4;
+ if (v * 3 > this.positions.length) {
+ this.positions = grow(this.positions, v * 3);
+ this.normals = grow(this.normals, v * 3);
+ this.colors = grow(this.colors, v * 3);
+ this.uvs = grow(this.uvs, v * 2);
+ }
+ if (this.indexCount + 6 > this.indices.length) {
+ this.indices = grow(this.indices, this.indexCount + 6);
+ }
+ }
+}
+
+const solidBuilder = new MeshBuilder();
+const transBuilder = new MeshBuilder();
+
+class Chunk {
+ constructor(cx, cz, data, heights) {
+ this.cx = cx;
+ this.cz = cz;
+ this.data = data;
+ this.heights = heights;
+ this.solidMesh = null;
+ this.transMesh = null;
+ this.hasMesh = false;
+ this.dirty = false;
+ this.inDirtyQueue = false;
+ }
+}
+
+export class World {
+ constructor(scene, atlas, seed) {
+ this.scene = scene;
+ this.atlas = atlas;
+ this.seed = seed >>> 0;
+ this.gen = new WorldGen(this.seed);
+ this.chunks = new Map();
+ this.edits = new Map(); // chunkKey -> Map(localIdx -> blockId)
+ this.loadQueue = [];
+ this.dirtyQueue = [];
+ this.freshMeshes = [];
+ this.lastCenter = null;
+ this.unloadCounter = 0;
+ this.saveTimer = null;
+ this.storageKey = 'blockcraft:edits:' + this.seed;
+
+ this.solidMaterial = new THREE.MeshLambertMaterial({
+ map: atlas.texture,
+ vertexColors: true,
+ });
+ this.transMaterial = new THREE.MeshLambertMaterial({
+ map: atlas.texture,
+ vertexColors: true,
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+
+ this.loadEdits();
+ }
+
+ // ------------------------------------------------------------ persistence
+
+ loadEdits() {
+ try {
+ const raw = localStorage.getItem(this.storageKey);
+ if (!raw) return;
+ const parsed = JSON.parse(raw);
+ for (const [key, entries] of Object.entries(parsed.chunks || {})) {
+ const map = new Map();
+ for (const [idx, id] of entries) map.set(idx, id);
+ this.edits.set(key, map);
+ }
+ } catch (err) {
+ console.warn('Could not load saved edits', err);
+ }
+ }
+
+ saveEdits() {
+ try {
+ const chunks = {};
+ for (const [key, map] of this.edits) {
+ chunks[key] = Array.from(map.entries());
+ }
+ localStorage.setItem(this.storageKey, JSON.stringify({ version: 1, chunks }));
+ } catch (err) {
+ console.warn('Could not save edits', err);
+ }
+ }
+
+ scheduleSave() {
+ if (this.saveTimer) clearTimeout(this.saveTimer);
+ this.saveTimer = setTimeout(() => {
+ this.saveTimer = null;
+ // Serialize during idle time so a big edit log never steals a frame.
+ if (window.requestIdleCallback) {
+ requestIdleCallback(() => this.saveEdits(), { timeout: 3000 });
+ } else {
+ this.saveEdits();
+ }
+ }, 1500);
+ }
+
+ // ---------------------------------------------------------------- chunks
+
+ getChunk(cx, cz) {
+ return this.chunks.get(chunkKey(cx, cz));
+ }
+
+ ensureChunkData(cx, cz) {
+ const key = chunkKey(cx, cz);
+ let chunk = this.chunks.get(key);
+ if (chunk) return chunk;
+
+ const { data, heights } = this.gen.generateChunk(cx, cz);
+ chunk = new Chunk(cx, cz, data, heights);
+
+ const editMap = this.edits.get(key);
+ if (editMap) {
+ for (const [idx, id] of editMap) {
+ data[idx] = id;
+ }
+ this.recomputeHeights(chunk);
+ }
+
+ this.chunks.set(key, chunk);
+ return chunk;
+ }
+
+ recomputeHeights(chunk) {
+ const { data, heights } = chunk;
+ for (let lz = 0; lz < CS; lz++) {
+ for (let lx = 0; lx < CS; lx++) {
+ let top = 0;
+ for (let y = WORLD_HEIGHT - 1; y >= 0; y--) {
+ const id = data[lx + lz * CS + y * LAYER];
+ if (id !== Blocks.AIR && id !== Blocks.WATER) {
+ top = y;
+ break;
+ }
+ }
+ heights[lx + lz * CS] = top;
+ }
+ }
+ }
+
+ getBlock(wx, wy, wz) {
+ if (wy < 0) return Blocks.BEDROCK;
+ if (wy >= WORLD_HEIGHT) return Blocks.AIR;
+ const chunk = this.ensureChunkData(wx >> 4, wz >> 4);
+ return chunk.data[(wx & 15) + (wz & 15) * CS + wy * LAYER];
+ }
+
+ setBlock(wx, wy, wz, id) {
+ if (wy <= 0 || wy >= WORLD_HEIGHT) return false;
+ const cx = wx >> 4;
+ const cz = wz >> 4;
+ const chunk = this.ensureChunkData(cx, cz);
+ const lx = wx & 15;
+ const lz = wz & 15;
+ const idx = lx + lz * CS + wy * LAYER;
+ if (chunk.data[idx] === id) return false;
+
+ chunk.data[idx] = id;
+
+ const key = chunkKey(cx, cz);
+ let editMap = this.edits.get(key);
+ if (!editMap) {
+ editMap = new Map();
+ this.edits.set(key, editMap);
+ }
+ editMap.set(idx, id);
+
+ // Keep the column-height lighting heuristic up to date.
+ const hIdx = lx + lz * CS;
+ const isSky = id === Blocks.AIR || id === Blocks.WATER;
+ if (!isSky && wy > chunk.heights[hIdx]) {
+ chunk.heights[hIdx] = wy;
+ } else if (isSky && wy === chunk.heights[hIdx]) {
+ let top = 0;
+ for (let y = wy; y >= 0; y--) {
+ const b = chunk.data[lx + lz * CS + y * LAYER];
+ if (b !== Blocks.AIR && b !== Blocks.WATER) {
+ top = y;
+ break;
+ }
+ }
+ chunk.heights[hIdx] = top;
+ }
+
+ this.markDirty(chunk);
+ const markNeighbor = (dx, dz) => {
+ const n = this.getChunk(cx + dx, cz + dz);
+ if (n && n.hasMesh) this.markDirty(n);
+ };
+ if (lx === 0) markNeighbor(-1, 0);
+ if (lx === CS - 1) markNeighbor(1, 0);
+ if (lz === 0) markNeighbor(0, -1);
+ if (lz === CS - 1) markNeighbor(0, 1);
+ if (lx === 0 && lz === 0) markNeighbor(-1, -1);
+ if (lx === 0 && lz === CS - 1) markNeighbor(-1, 1);
+ if (lx === CS - 1 && lz === 0) markNeighbor(1, -1);
+ if (lx === CS - 1 && lz === CS - 1) markNeighbor(1, 1);
+
+ this.scheduleSave();
+ return true;
+ }
+
+ // ---------------------------------------------------------------- update
+
+ markDirty(chunk) {
+ chunk.dirty = true;
+ if (!chunk.inDirtyQueue) {
+ chunk.inDirtyQueue = true;
+ this.dirtyQueue.push(chunk);
+ }
+ }
+
+ update(px, pz) {
+ const pcx = Math.floor(px / CS);
+ const pcz = Math.floor(pz / CS);
+
+ // Meshes added last frame have been uploaded to the GPU by now; let the
+ // frustum cull them normally again.
+ if (this.freshMeshes.length > 0) {
+ for (const mesh of this.freshMeshes) mesh.frustumCulled = true;
+ this.freshMeshes.length = 0;
+ }
+
+ const center = pcx + ',' + pcz;
+ if (center !== this.lastCenter) {
+ this.lastCenter = center;
+ this.loadQueue = [];
+ for (let dz = -RENDER_DISTANCE; dz <= RENDER_DISTANCE; dz++) {
+ for (let dx = -RENDER_DISTANCE; dx <= RENDER_DISTANCE; dx++) {
+ const cx = pcx + dx;
+ const cz = pcz + dz;
+ const chunk = this.getChunk(cx, cz);
+ if (chunk && chunk.hasMesh) continue;
+ this.loadQueue.push({ cx, cz, d: dx * dx + dz * dz });
+ }
+ }
+ this.loadQueue.sort((a, b) => b.d - a.d);
+ }
+
+ // Mesh building is time-budgeted so it never tanks the frame rate.
+ const start = performance.now();
+ let built = 0;
+
+ // Edited chunks first, for snappy block break/place feedback.
+ while (
+ this.dirtyQueue.length > 0 &&
+ (built === 0 || performance.now() - start < MESH_TIME_BUDGET_MS)
+ ) {
+ const chunk = this.dirtyQueue.shift();
+ chunk.inDirtyQueue = false;
+ if (!chunk.dirty) continue;
+ if (this.chunks.get(chunkKey(chunk.cx, chunk.cz)) !== chunk) continue;
+ this.buildChunkMesh(chunk);
+ built++;
+ }
+
+ while (
+ this.loadQueue.length > 0 &&
+ (built === 0 || performance.now() - start < MESH_TIME_BUDGET_MS)
+ ) {
+ const { cx, cz } = this.loadQueue.pop();
+ if (Math.max(Math.abs(cx - pcx), Math.abs(cz - pcz)) > RENDER_DISTANCE) continue;
+ const chunk = this.ensureChunkData(cx, cz);
+ if (chunk.hasMesh && !chunk.dirty) continue;
+ this.buildChunkMesh(chunk);
+ built++;
+ }
+
+ // Unload far-away chunks, a few at a time to avoid disposal bursts when
+ // flying across the world quickly.
+ if (++this.unloadCounter >= 30) {
+ this.unloadCounter = 0;
+ let disposed = 0;
+ for (const [key, chunk] of this.chunks) {
+ const d = Math.max(Math.abs(chunk.cx - pcx), Math.abs(chunk.cz - pcz));
+ if (d > UNLOAD_DISTANCE) {
+ this.disposeChunkMeshes(chunk);
+ this.chunks.delete(key);
+ if (++disposed >= 8) break;
+ }
+ }
+ }
+ }
+
+ get pendingChunks() {
+ return this.loadQueue.length;
+ }
+
+ disposeChunkMeshes(chunk) {
+ for (const meshName of ['solidMesh', 'transMesh']) {
+ const mesh = chunk[meshName];
+ if (mesh) {
+ this.scene.remove(mesh);
+ mesh.geometry.dispose();
+ chunk[meshName] = null;
+ }
+ }
+ chunk.hasMesh = false;
+ }
+
+ // --------------------------------------------------------------- meshing
+
+ makeSampler(cx, cz) {
+ const neighborhood = [];
+ for (let dz = -1; dz <= 1; dz++) {
+ for (let dx = -1; dx <= 1; dx++) {
+ neighborhood.push(this.ensureChunkData(cx + dx, cz + dz));
+ }
+ }
+ return {
+ block: (wx, wy, wz) => {
+ if (wy < 0) return Blocks.BEDROCK;
+ if (wy >= WORLD_HEIGHT) return Blocks.AIR;
+ const ix = (wx >> 4) - cx + 1;
+ const iz = (wz >> 4) - cz + 1;
+ const chunk = neighborhood[ix + iz * 3];
+ return chunk.data[(wx & 15) + (wz & 15) * CS + wy * LAYER];
+ },
+ height: (wx, wz) => {
+ const ix = (wx >> 4) - cx + 1;
+ const iz = (wz >> 4) - cz + 1;
+ const chunk = neighborhood[ix + iz * 3];
+ return chunk.heights[(wx & 15) + (wz & 15) * CS];
+ },
+ };
+ }
+
+ buildChunkMesh(chunk) {
+ const sampler = this.makeSampler(chunk.cx, chunk.cz);
+ const x0 = chunk.cx * CS;
+ const z0 = chunk.cz * CS;
+ const solid = solidBuilder;
+ const trans = transBuilder;
+ solid.reset();
+ trans.reset();
+ const data = chunk.data;
+ const ao = [0, 0, 0, 0];
+
+ for (let y = 0; y < WORLD_HEIGHT; y++) {
+ for (let lz = 0; lz < CS; lz++) {
+ for (let lx = 0; lx < CS; lx++) {
+ const id = data[lx + lz * CS + y * LAYER];
+ if (id === Blocks.AIR) continue;
+ const def = BLOCK_DEFS[id];
+ const wx = x0 + lx;
+ const wz = z0 + lz;
+
+ const isWater = id === Blocks.WATER;
+ let waterTopOffset = 0;
+ if (isWater && sampler.block(wx, y + 1, wz) !== Blocks.WATER) {
+ waterTopOffset = 0.12;
+ }
+
+ for (const face of FACES) {
+ const dir = face.dir;
+ const nx = wx + dir[0];
+ const ny = y + dir[1];
+ const nz = wz + dir[2];
+ const nId = sampler.block(nx, ny, nz);
+
+ if (def.translucent) {
+ if (nId === id || isOpaque(nId)) continue;
+ } else if (isOpaque(nId)) {
+ continue;
+ }
+
+ const target = def.translucent ? trans : solid;
+ const [u0, v0, u1, v1] = this.atlas.uvRect(tileForFace(id, dir[1]));
+
+ const hcol = sampler.height(nx, nz);
+ let light;
+ if (ny >= hcol) light = 1;
+ else light = Math.max(0.32, 1 - (hcol - ny) * 0.08);
+ const base = light * face.shade;
+
+ target.ensureQuad();
+ const vBase = target.vertexCount;
+ const { positions, normals, uvs, colors, indices } = target;
+
+ for (let ci = 0; ci < 4; ci++) {
+ const corner = face.corners[ci];
+ const p = corner.pos;
+
+ let vy = y + p[1];
+ if (isWater && p[1] === 1 && dir[1] >= 0) vy -= waterTopOffset;
+
+ const vi = (vBase + ci) * 3;
+ positions[vi] = lx + p[0];
+ positions[vi + 1] = vy;
+ positions[vi + 2] = lz + p[2];
+ normals[vi] = dir[0];
+ normals[vi + 1] = dir[1];
+ normals[vi + 2] = dir[2];
+
+ const ti = (vBase + ci) * 2;
+ uvs[ti] = u0 + (u1 - u0) * corner.uv[0];
+ uvs[ti + 1] = v0 + (v1 - v0) * corner.uv[1];
+
+ let brightness = base;
+ if (!def.translucent) {
+ const s1 = p[face.t1] === 1 ? 1 : -1;
+ const s2 = p[face.t2] === 1 ? 1 : -1;
+ const o1 = [0, 0, 0];
+ const o2 = [0, 0, 0];
+ o1[face.t1] = s1;
+ o2[face.t2] = s2;
+ const side1 = isOpaque(
+ sampler.block(nx + o1[0], ny + o1[1], nz + o1[2])
+ )
+ ? 1
+ : 0;
+ const side2 = isOpaque(
+ sampler.block(nx + o2[0], ny + o2[1], nz + o2[2])
+ )
+ ? 1
+ : 0;
+ let aoLevel;
+ if (side1 && side2) {
+ aoLevel = 0;
+ } else {
+ const cornerB = isOpaque(
+ sampler.block(nx + o1[0] + o2[0], ny + o1[1] + o2[1], nz + o1[2] + o2[2])
+ )
+ ? 1
+ : 0;
+ aoLevel = 3 - (side1 + side2 + cornerB);
+ }
+ ao[ci] = aoLevel;
+ brightness *= AO_CURVE[aoLevel];
+ } else {
+ ao[ci] = 3;
+ }
+
+ colors[vi] = brightness;
+ colors[vi + 1] = brightness;
+ colors[vi + 2] = brightness;
+ }
+
+ // Flip the quad diagonal when it reduces AO interpolation artifacts.
+ const ii = target.indexCount;
+ if (ao[0] + ao[3] > ao[1] + ao[2]) {
+ indices[ii] = vBase;
+ indices[ii + 1] = vBase + 1;
+ indices[ii + 2] = vBase + 3;
+ indices[ii + 3] = vBase;
+ indices[ii + 4] = vBase + 3;
+ indices[ii + 5] = vBase + 2;
+ } else {
+ indices[ii] = vBase;
+ indices[ii + 1] = vBase + 1;
+ indices[ii + 2] = vBase + 2;
+ indices[ii + 3] = vBase + 2;
+ indices[ii + 4] = vBase + 1;
+ indices[ii + 5] = vBase + 3;
+ }
+ target.vertexCount += 4;
+ target.indexCount += 6;
+ }
+ }
+ }
+ }
+
+ this.replaceMesh(chunk, 'solidMesh', solid, this.solidMaterial, x0, z0, 0);
+ this.replaceMesh(chunk, 'transMesh', trans, this.transMaterial, x0, z0, 1);
+ chunk.hasMesh = true;
+ chunk.dirty = false;
+ }
+
+ replaceMesh(chunk, slot, builder, material, x0, z0, renderOrder) {
+ if (chunk[slot]) {
+ this.scene.remove(chunk[slot]);
+ chunk[slot].geometry.dispose();
+ chunk[slot] = null;
+ }
+ if (builder.indexCount === 0) return;
+
+ const vc = builder.vertexCount;
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute(
+ 'position',
+ new THREE.BufferAttribute(builder.positions.slice(0, vc * 3), 3)
+ );
+ geometry.setAttribute(
+ 'normal',
+ new THREE.BufferAttribute(builder.normals.slice(0, vc * 3), 3)
+ );
+ geometry.setAttribute('uv', new THREE.BufferAttribute(builder.uvs.slice(0, vc * 2), 2));
+ geometry.setAttribute(
+ 'color',
+ new THREE.BufferAttribute(builder.colors.slice(0, vc * 3), 3)
+ );
+ geometry.setIndex(
+ new THREE.BufferAttribute(builder.indices.slice(0, builder.indexCount), 1)
+ );
+ geometry.computeBoundingSphere();
+
+ const mesh = new THREE.Mesh(geometry, material);
+ mesh.position.set(x0, 0, z0);
+ mesh.renderOrder = renderOrder;
+ mesh.matrixAutoUpdate = false;
+ mesh.updateMatrix();
+ // Render un-culled for one frame so the GPU upload happens now, not on
+ // the first frame the camera happens to turn toward this chunk (which
+ // would cause a visible hitch while looking around).
+ mesh.frustumCulled = false;
+ this.freshMeshes.push(mesh);
+ this.scene.add(mesh);
+ chunk[slot] = mesh;
+ }
+}
diff --git a/minecraft/js/worldgen.js b/minecraft/js/worldgen.js
new file mode 100644
index 0000000..4e201e2
--- /dev/null
+++ b/minecraft/js/worldgen.js
@@ -0,0 +1,205 @@
+import { CHUNK_SIZE, WORLD_HEIGHT, SEA_LEVEL } from './constants.js';
+import { Noise2D, ValueNoise3D } from './noise.js';
+import { Blocks } from './blocks.js';
+import { hash2, rand2, rand3 } from './rng.js';
+
+export const Biomes = {
+ GRASS: 0,
+ DESERT: 1,
+ SNOW: 2,
+};
+
+export class WorldGen {
+ constructor(seed) {
+ this.seed = seed >>> 0;
+ this.continentNoise = new Noise2D(seed ^ 0x10501);
+ this.hillNoise = new Noise2D(seed ^ 0x20a02);
+ this.mountainNoise = new Noise2D(seed ^ 0x35703);
+ this.biomeNoise = new Noise2D(seed ^ 0x4b104);
+ this.caveNoise = new ValueNoise3D(seed ^ 0x5c205);
+ this.heightCache = new Map();
+ }
+
+ heightAt(x, z) {
+ const key = x + ',' + z;
+ const cached = this.heightCache.get(key);
+ if (cached !== undefined) return cached;
+
+ const c = this.continentNoise.fbm(x * 0.004, z * 0.004, 3);
+ const hills = this.hillNoise.fbm(x * 0.02, z * 0.02, 3);
+ let m = this.mountainNoise.fbm(x * 0.007 + 13.1, z * 0.007 - 7.7, 3);
+ m = Math.max(0, m + 0.15);
+
+ let h = Math.round(33 + c * 13 + hills * 6 + Math.pow(m, 1.8) * 42);
+ h = Math.max(5, Math.min(WORLD_HEIGHT - 14, h));
+
+ if (this.heightCache.size > 120000) this.heightCache.clear();
+ this.heightCache.set(key, h);
+ return h;
+ }
+
+ biomeAt(x, z) {
+ const b = this.biomeNoise.fbm(x * 0.0045 + 9.7, z * 0.0045 - 3.1, 2);
+ if (b < -0.38) return Biomes.DESERT;
+ if (b > 0.42) return Biomes.SNOW;
+ return Biomes.GRASS;
+ }
+
+ hasTreeAt(x, z) {
+ const h = this.heightAt(x, z);
+ if (h <= SEA_LEVEL + 1) return false;
+ const biome = this.biomeAt(x, z);
+ if (biome === Biomes.DESERT) return false;
+ const r = rand2(x, z, this.seed ^ 0x7ee5);
+ const chance = biome === Biomes.SNOW ? 0.004 : 0.009;
+ return r < chance;
+ }
+
+ trunkHeightAt(x, z) {
+ return 4 + (hash2(x, z, this.seed ^ 0x771a) % 3);
+ }
+
+ generateChunk(cx, cz) {
+ const data = new Uint8Array(CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT);
+ const heights = new Uint8Array(CHUNK_SIZE * CHUNK_SIZE);
+ const x0 = cx * CHUNK_SIZE;
+ const z0 = cz * CHUNK_SIZE;
+ const seed = this.seed;
+
+ for (let lz = 0; lz < CHUNK_SIZE; lz++) {
+ for (let lx = 0; lx < CHUNK_SIZE; lx++) {
+ const wx = x0 + lx;
+ const wz = z0 + lz;
+ const h = this.heightAt(wx, wz);
+ const biome = this.biomeAt(wx, wz);
+ const beach = h <= SEA_LEVEL + 1;
+ const snowy = biome === Biomes.SNOW || h >= 70;
+
+ let topBlock;
+ let fillBlock;
+ if (beach || biome === Biomes.DESERT) {
+ topBlock = Blocks.SAND;
+ fillBlock = Blocks.SAND;
+ } else if (snowy) {
+ topBlock = Blocks.SNOWY_GRASS;
+ fillBlock = Blocks.DIRT;
+ } else {
+ topBlock = Blocks.GRASS;
+ fillBlock = Blocks.DIRT;
+ }
+
+ const colTop = Math.max(h, SEA_LEVEL);
+ for (let y = 0; y <= colTop; y++) {
+ const idx = lx + lz * CHUNK_SIZE + y * CHUNK_SIZE * CHUNK_SIZE;
+ let id = Blocks.AIR;
+
+ if (y === 0) {
+ id = Blocks.BEDROCK;
+ } else if (y <= h) {
+ if (y === h) {
+ id = topBlock;
+ } else if (y >= h - 3) {
+ id = fillBlock;
+ } else {
+ id = Blocks.STONE;
+ if (
+ y < 48 &&
+ rand3(wx >> 2, y >> 2, wz >> 2, seed ^ 0xc0a1) < 0.14 &&
+ rand3(wx, y, wz, seed ^ 0xc0a2) < 0.42
+ ) {
+ id = Blocks.COAL_ORE;
+ } else if (
+ y < 34 &&
+ rand3(wx >> 2, y >> 2, wz >> 2, seed ^ 0x1407) < 0.1 &&
+ rand3(wx, y, wz, seed ^ 0x1408) < 0.36
+ ) {
+ id = Blocks.IRON_ORE;
+ }
+
+ // Cave carving.
+ if (y >= 6 && y <= h - 6) {
+ const n = this.caveNoise.fbm(wx * 0.075, y * 0.105, wz * 0.075, 2);
+ if (n > 0.665) id = Blocks.AIR;
+ }
+ }
+ } else if (y <= SEA_LEVEL) {
+ id = Blocks.WATER;
+ }
+
+ data[idx] = id;
+ }
+ }
+ }
+
+ this.placeTrees(data, x0, z0);
+
+ // Column heights (topmost non-air, non-water block), used for lighting.
+ for (let lz = 0; lz < CHUNK_SIZE; lz++) {
+ for (let lx = 0; lx < CHUNK_SIZE; lx++) {
+ let top = 0;
+ for (let y = WORLD_HEIGHT - 1; y >= 0; y--) {
+ const id = data[lx + lz * CHUNK_SIZE + y * CHUNK_SIZE * CHUNK_SIZE];
+ if (id !== Blocks.AIR && id !== Blocks.WATER) {
+ top = y;
+ break;
+ }
+ }
+ heights[lx + lz * CHUNK_SIZE] = top;
+ }
+ }
+
+ return { data, heights };
+ }
+
+ placeTrees(data, x0, z0) {
+ const margin = 3;
+ for (let wz = z0 - margin; wz < z0 + CHUNK_SIZE + margin; wz++) {
+ for (let wx = x0 - margin; wx < x0 + CHUNK_SIZE + margin; wx++) {
+ if (!this.hasTreeAt(wx, wz)) continue;
+
+ const h = this.heightAt(wx, wz);
+ const trunkH = this.trunkHeightAt(wx, wz);
+ const topY = h + trunkH;
+ const seed = this.seed;
+
+ // Canopy first, trunk overrides.
+ for (let dy = -1; dy <= 2; dy++) {
+ const y = topY + dy;
+ if (y < 0 || y >= WORLD_HEIGHT) continue;
+ let r;
+ if (dy <= 0) r = 2;
+ else if (dy === 1) r = 1;
+ else r = 1;
+ for (let dz = -r; dz <= r; dz++) {
+ for (let dx = -r; dx <= r; dx++) {
+ if (dy === 2 && dx !== 0 && dz !== 0) continue;
+ const isCorner = Math.abs(dx) === r && Math.abs(dz) === r;
+ if (isCorner && (r === 0 || rand3(wx + dx, y, wz + dz, seed ^ 0x1eaf) < 0.55)) {
+ continue;
+ }
+ this.setLocal(data, x0, z0, wx + dx, y, wz + dz, Blocks.LEAVES, true);
+ }
+ }
+ }
+
+ for (let y = h + 1; y <= topY; y++) {
+ this.setLocal(data, x0, z0, wx, y, wz, Blocks.LOG, false);
+ }
+ }
+ }
+ }
+
+ setLocal(data, x0, z0, wx, y, wz, id, onlyIfAir) {
+ const lx = wx - x0;
+ const lz = wz - z0;
+ if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE) return;
+ if (y < 0 || y >= WORLD_HEIGHT) return;
+ const idx = lx + lz * CHUNK_SIZE + y * CHUNK_SIZE * CHUNK_SIZE;
+ if (onlyIfAir && data[idx] !== Blocks.AIR) return;
+ data[idx] = id;
+ }
+
+ surfaceAt(x, z) {
+ return this.heightAt(x, z);
+ }
+}
diff --git a/minecraft/styles.css b/minecraft/styles.css
new file mode 100644
index 0000000..688d37c
--- /dev/null
+++ b/minecraft/styles.css
@@ -0,0 +1,305 @@
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+html,
+body {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background: #0b1026;
+ font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
+ user-select: none;
+}
+
+#game {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: block;
+ cursor: crosshair;
+}
+
+/* ------------------------------------------------------------------ HUD */
+
+#hud {
+ position: fixed;
+ inset: 0;
+ pointer-events: none;
+ z-index: 5;
+}
+
+#hud.paused #crosshair,
+#hud.paused #hotbar,
+#hud.paused #status {
+ opacity: 0;
+}
+
+#info {
+ position: absolute;
+ top: 10px;
+ left: 12px;
+ color: rgba(255, 255, 255, 0.92);
+ font-size: 12px;
+ letter-spacing: 0.04em;
+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
+ background: rgba(0, 0, 0, 0.28);
+ padding: 5px 9px;
+ border-radius: 6px;
+}
+
+#crosshair {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ width: 18px;
+ height: 18px;
+ transform: translate(-50%, -50%);
+ transition: opacity 0.2s;
+}
+
+#crosshair::before,
+#crosshair::after {
+ content: '';
+ position: absolute;
+ background: rgba(255, 255, 255, 0.85);
+ mix-blend-mode: difference;
+}
+
+#crosshair::before {
+ left: 50%;
+ top: 0;
+ width: 2px;
+ height: 100%;
+ transform: translateX(-50%);
+}
+
+#crosshair::after {
+ top: 50%;
+ left: 0;
+ height: 2px;
+ width: 100%;
+ transform: translateY(-50%);
+}
+
+#status {
+ position: absolute;
+ bottom: 86px;
+ left: 50%;
+ transform: translateX(-50%);
+ color: #fff;
+ font-size: 15px;
+ font-weight: 600;
+ text-shadow: 0 1px 4px rgba(0, 0, 0, 0.9);
+ opacity: 0;
+ transition: opacity 0.25s;
+}
+
+#status.visible {
+ opacity: 1;
+}
+
+#hotbar {
+ position: absolute;
+ bottom: 14px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ gap: 5px;
+ padding: 6px;
+ background: rgba(10, 12, 20, 0.55);
+ border: 2px solid rgba(255, 255, 255, 0.22);
+ border-radius: 10px;
+ pointer-events: auto;
+ transition: opacity 0.2s;
+}
+
+.slot {
+ position: relative;
+ width: 54px;
+ height: 54px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(255, 255, 255, 0.06);
+ border: 2px solid rgba(255, 255, 255, 0.14);
+ border-radius: 7px;
+ cursor: pointer;
+ transition: border-color 0.12s, background 0.12s, transform 0.12s;
+}
+
+.slot:hover {
+ background: rgba(255, 255, 255, 0.12);
+}
+
+.slot.selected {
+ border-color: #ffffff;
+ background: rgba(255, 255, 255, 0.16);
+ transform: translateY(-3px);
+}
+
+.slot canvas {
+ image-rendering: pixelated;
+ width: 38px;
+ height: 38px;
+}
+
+.slot-key {
+ position: absolute;
+ top: 2px;
+ left: 5px;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.75);
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.9);
+}
+
+#underwater {
+ position: absolute;
+ inset: 0;
+ background: radial-gradient(
+ ellipse at center,
+ rgba(20, 60, 130, 0.18) 0%,
+ rgba(10, 40, 100, 0.45) 100%
+ );
+ opacity: 0;
+ transition: opacity 0.25s;
+}
+
+#underwater.visible {
+ opacity: 1;
+}
+
+/* -------------------------------------------------------------- overlay */
+
+#overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(8, 10, 22, 0.62);
+ backdrop-filter: blur(6px);
+ transition: opacity 0.25s;
+}
+
+#overlay.hidden {
+ opacity: 0;
+ pointer-events: none;
+}
+
+.panel {
+ width: min(440px, calc(100vw - 32px));
+ max-height: calc(100vh - 32px);
+ overflow-y: auto;
+ background: linear-gradient(160deg, rgba(30, 36, 60, 0.96), rgba(16, 20, 38, 0.96));
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ border-radius: 16px;
+ padding: 28px 30px;
+ color: #e8ecf6;
+ text-align: center;
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.55);
+}
+
+.panel h1 {
+ font-size: 34px;
+ letter-spacing: 0.06em;
+ background: linear-gradient(180deg, #9be07a, #4f9e3c);
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ text-shadow: 0 2px 0 rgba(0, 0, 0, 0.25);
+}
+
+.tagline {
+ margin-top: 6px;
+ font-size: 13px;
+ color: rgba(232, 236, 246, 0.72);
+}
+
+.controls {
+ margin: 18px 0 6px;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 7px 14px;
+ text-align: left;
+ font-size: 12.5px;
+ color: rgba(232, 236, 246, 0.85);
+}
+
+.key {
+ display: inline-block;
+ min-width: 30px;
+ padding: 2px 7px;
+ margin-right: 6px;
+ font-size: 11px;
+ font-weight: 600;
+ text-align: center;
+ color: #fff;
+ background: rgba(255, 255, 255, 0.1);
+ border: 1px solid rgba(255, 255, 255, 0.22);
+ border-bottom-width: 2px;
+ border-radius: 5px;
+}
+
+#play-button {
+ margin-top: 18px;
+ width: 100%;
+ padding: 13px 0;
+ font-size: 17px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ color: #08130a;
+ background: linear-gradient(180deg, #a4e784, #5cab44);
+ border: none;
+ border-radius: 10px;
+ cursor: pointer;
+ transition: filter 0.15s, transform 0.1s;
+}
+
+#play-button:hover {
+ filter: brightness(1.08);
+}
+
+#play-button:active {
+ transform: scale(0.985);
+}
+
+.secondary-actions {
+ margin-top: 10px;
+ display: flex;
+ gap: 8px;
+}
+
+.secondary-actions button {
+ flex: 1;
+ padding: 9px 0;
+ font-size: 12.5px;
+ font-weight: 600;
+ color: rgba(232, 236, 246, 0.9);
+ background: rgba(255, 255, 255, 0.07);
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background 0.15s;
+}
+
+.secondary-actions button:hover {
+ background: rgba(255, 255, 255, 0.14);
+}
+
+.seed {
+ margin-top: 14px;
+ font-size: 12px;
+ color: rgba(232, 236, 246, 0.6);
+}
+
+.footnote {
+ margin-top: 8px;
+ font-size: 11px;
+ line-height: 1.5;
+ color: rgba(232, 236, 246, 0.42);
+}
diff --git a/minecraft/vendor/three.module.min.js b/minecraft/vendor/three.module.min.js
new file mode 100644
index 0000000..97f39bf
--- /dev/null
+++ b/minecraft/vendor/three.module.min.js
@@ -0,0 +1,6 @@
+/**
+ * @license
+ * Copyright 2010-2024 Three.js Authors
+ * SPDX-License-Identifier: MIT
+ */
+const t="165",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},n={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,s=2,a=3,o=0,l=1,c=2,h=3,u=0,d=1,p=2,m=0,f=1,g=2,v=3,_=4,x=5,y=100,M=101,S=102,b=103,w=104,T=200,E=201,A=202,R=203,C=204,P=205,L=206,I=207,U=208,N=209,D=210,O=211,F=212,B=213,z=214,k=0,V=1,H=2,G=3,W=4,X=5,j=6,q=7,Y=0,Z=1,J=2,K=0,$=1,Q=2,tt=3,et=4,nt=5,it=6,rt=7,st="attached",at="detached",ot=300,lt=301,ct=302,ht=303,ut=304,dt=306,pt=1e3,mt=1001,ft=1002,gt=1003,vt=1004,_t=1004,xt=1005,yt=1005,Mt=1006,St=1007,bt=1007,wt=1008,Tt=1008,Et=1009,At=1010,Rt=1011,Ct=1012,Pt=1013,Lt=1014,It=1015,Ut=1016,Nt=1017,Dt=1018,Ot=1020,Ft=35902,Bt=1021,zt=1022,kt=1023,Vt=1024,Ht=1025,Gt=1026,Wt=1027,Xt=1028,jt=1029,qt=1030,Yt=1031,Zt=1033,Jt=33776,Kt=33777,$t=33778,Qt=33779,te=35840,ee=35841,ne=35842,ie=35843,re=36196,se=37492,ae=37496,oe=37808,le=37809,ce=37810,he=37811,ue=37812,de=37813,pe=37814,me=37815,fe=37816,ge=37817,ve=37818,_e=37819,xe=37820,ye=37821,Me=36492,Se=36494,be=36495,we=36283,Te=36284,Ee=36285,Ae=36286,Re=2200,Ce=2201,Pe=2202,Le=2300,Ie=2301,Ue=2302,Ne=2400,De=2401,Oe=2402,Fe=2500,Be=2501,ze=0,ke=1,Ve=2,He=3200,Ge=3201,We=0,Xe=1,je="",qe="srgb",Ye="srgb-linear",Ze="display-p3",Je="display-p3-linear",Ke="linear",$e="srgb",Qe="rec709",tn="p3",en=0,nn=7680,rn=7681,sn=7682,an=7683,on=34055,ln=34056,cn=5386,hn=512,un=513,dn=514,pn=515,mn=516,fn=517,gn=518,vn=519,_n=512,xn=513,yn=514,Mn=515,Sn=516,bn=517,wn=518,Tn=519,En=35044,An=35048,Rn=35040,Cn=35045,Pn=35049,Ln=35041,In=35046,Un=35050,Nn=35042,Dn="100",On="300 es",Fn=2e3,Bn=2001;class zn{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e>8&255]+kn[t>>16&255]+kn[t>>24&255]+"-"+kn[255&e]+kn[e>>8&255]+"-"+kn[e>>16&15|64]+kn[e>>24&255]+"-"+kn[63&n|128]+kn[n>>8&255]+"-"+kn[n>>16&255]+kn[n>>24&255]+kn[255&i]+kn[i>>8&255]+kn[i>>16&255]+kn[i>>24&255]).toLowerCase()}function Xn(t,e,n){return Math.max(e,Math.min(n,t))}function jn(t,e){return(t%e+e)%e}function qn(t,e,n){return(1-n)*t+n*e}function Yn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Zn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Jn={DEG2RAD:Hn,RAD2DEG:Gn,generateUUID:Wn,clamp:Xn,euclideanModulo:jn,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:qn,damp:function(t,e,n,i){return qn(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(jn(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(Vn=t);let e=Vn+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*Hn},radToDeg:function(t){return t*Gn},isPowerOfTwo:function(t){return 0==(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Zn,denormalize:Yn};class Kn{constructor(t=0,e=0){Kn.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Xn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class $n{constructor(t,e,n,i,r,s,a,o,l){$n.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l)}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],_=i[4],x=i[7],y=i[2],M=i[5],S=i[8];return r[0]=s*m+a*v+o*y,r[3]=s*f+a*_+o*M,r[6]=s*g+a*x+o*S,r[1]=l*m+c*v+h*y,r[4]=l*f+c*_+h*M,r[7]=l*g+c*x+h*S,r[2]=u*m+d*v+p*y,r[5]=u*f+d*_+p*M,r[8]=u*g+d*x+p*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(Qn.makeScale(t,e)),this}rotate(t){return this.premultiply(Qn.makeRotation(-t)),this}translate(t,e){return this.premultiply(Qn.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const Qn=new $n;function ti(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const ei={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function ni(t,e){return new ei[t](e)}function ii(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function ri(){const t=ii("canvas");return t.style.display="block",t}const si={};function ai(t){t in si||(si[t]=!0,console.warn(t))}const oi=(new $n).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),li=(new $n).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),ci={[Ye]:{transfer:Ke,primaries:Qe,toReference:t=>t,fromReference:t=>t},[qe]:{transfer:$e,primaries:Qe,toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[Je]:{transfer:Ke,primaries:tn,toReference:t=>t.applyMatrix3(li),fromReference:t=>t.applyMatrix3(oi)},[Ze]:{transfer:$e,primaries:tn,toReference:t=>t.convertSRGBToLinear().applyMatrix3(li),fromReference:t=>t.applyMatrix3(oi).convertLinearToSRGB()}},hi=new Set([Ye,Je]),ui={enabled:!0,_workingColorSpace:Ye,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!hi.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(!1===this.enabled||e===n||!e||!n)return t;const i=ci[e].toReference;return(0,ci[n].fromReference)(i(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return ci[t].primaries},getTransfer:function(t){return t===je?Ke:ci[t].transfer}};function di(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function pi(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let mi;class fi{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===mi&&(mi=ii("canvas")),mi.width=t.width,mi.height=t.height;const n=mi.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=mi}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=ii("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),r=i.data;for(let t=0;t0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==ot)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case pt:t.x=t.x-Math.floor(t.x);break;case mt:t.x=t.x<0?0:1;break;case ft:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case pt:t.y=t.y-Math.floor(t.y);break;case mt:t.y=t.y<0?0:1;break;case ft:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}yi.DEFAULT_IMAGE=null,yi.DEFAULT_MAPPING=ot,yi.DEFAULT_ANISOTROPY=1;class Mi{constructor(t=0,e=0,n=0,i=1){Mi.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(Xn(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ci{constructor(t=0,e=0,n=0){Ci.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Li.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Li.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=2*(s*i-a*n),c=2*(a*e-r*i),h=2*(r*n-s*e);return this.x=e+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Pi.copy(this).projectOnVector(t),this.sub(Pi)}reflect(t){return this.sub(Pi.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Xn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Pi=new Ci,Li=new Ri;class Ii{constructor(t=new Ci(1/0,1/0,1/0),e=new Ci(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;ethis.max.x||t.ythis.max.y||t.zthis.max.z)}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return!(t.max.xthis.max.x||t.max.ythis.max.y||t.max.zthis.max.z)}intersectsSphere(t){return this.clampPoint(t.center,Ni),Ni.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Hi),Gi.subVectors(this.max,Hi),Oi.subVectors(t.a,Hi),Fi.subVectors(t.b,Hi),Bi.subVectors(t.c,Hi),zi.subVectors(Fi,Oi),ki.subVectors(Bi,Fi),Vi.subVectors(Oi,Bi);let e=[0,-zi.z,zi.y,0,-ki.z,ki.y,0,-Vi.z,Vi.y,zi.z,0,-zi.x,ki.z,0,-ki.x,Vi.z,0,-Vi.x,-zi.y,zi.x,0,-ki.y,ki.x,0,-Vi.y,Vi.x,0];return!!ji(e,Oi,Fi,Bi,Gi)&&(e=[1,0,0,0,1,0,0,0,1],!!ji(e,Oi,Fi,Bi,Gi)&&(Wi.crossVectors(zi,ki),e=[Wi.x,Wi.y,Wi.z],ji(e,Oi,Fi,Bi,Gi)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Ni).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(Ni).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Ui)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Ui=[new Ci,new Ci,new Ci,new Ci,new Ci,new Ci,new Ci,new Ci],Ni=new Ci,Di=new Ii,Oi=new Ci,Fi=new Ci,Bi=new Ci,zi=new Ci,ki=new Ci,Vi=new Ci,Hi=new Ci,Gi=new Ci,Wi=new Ci,Xi=new Ci;function ji(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Xi.fromArray(t,s);const a=r.x*Math.abs(Xi.x)+r.y*Math.abs(Xi.y)+r.z*Math.abs(Xi.z),o=e.dot(Xi),l=n.dot(Xi),c=i.dot(Xi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const qi=new Ii,Yi=new Ci,Zi=new Ci;class Ji{constructor(t=new Ci,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):qi.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Yi.subVectors(t,this.center);const e=Yi.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.addScaledVector(Yi,n/t),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):(Zi.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Yi.copy(t.center).add(Zi)),this.expandByPoint(Yi.copy(t.center).sub(Zi))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Ki=new Ci,$i=new Ci,Qi=new Ci,tr=new Ci,er=new Ci,nr=new Ci,ir=new Ci;class rr{constructor(t=new Ci,e=new Ci(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,Ki)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=Ki.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(Ki.copy(this.origin).addScaledVector(this.direction,e),Ki.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){$i.copy(t).add(e).multiplyScalar(.5),Qi.copy(e).sub(t).normalize(),tr.copy(this.origin).sub($i);const r=.5*t.distanceTo(e),s=-this.direction.dot(Qi),a=tr.dot(this.direction),o=-tr.dot(Qi),l=tr.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy($i).addScaledVector(Qi,u),d}intersectSphere(t,e){Ki.subVectors(t.center,this.origin);const n=Ki.dot(this.direction),i=Ki.dot(Ki)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,Ki)}intersectTriangle(t,e,n,i,r){er.subVectors(e,t),nr.subVectors(n,t),ir.crossVectors(er,nr);let s,a=this.direction.dot(ir);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}tr.subVectors(this.origin,t);const o=s*this.direction.dot(nr.crossVectors(tr,nr));if(o<0)return null;const l=s*this.direction.dot(er.cross(tr));if(l<0)return null;if(o+l>a)return null;const c=-s*tr.dot(ir);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class sr{constructor(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){sr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f)}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new sr).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/ar.setFromMatrixColumn(t,0).length(),r=1/ar.setFromMatrixColumn(t,1).length(),s=1/ar.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(lr,t,cr)}lookAt(t,e,n){const i=this.elements;return dr.subVectors(t,e),0===dr.lengthSq()&&(dr.z=1),dr.normalize(),hr.crossVectors(n,dr),0===hr.lengthSq()&&(1===Math.abs(n.z)?dr.x+=1e-4:dr.z+=1e-4,dr.normalize(),hr.crossVectors(n,dr)),hr.normalize(),ur.crossVectors(dr,hr),i[0]=hr.x,i[4]=ur.x,i[8]=dr.x,i[1]=hr.y,i[5]=ur.y,i[9]=dr.y,i[2]=hr.z,i[6]=ur.z,i[10]=dr.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],x=n[11],y=n[15],M=i[0],S=i[4],b=i[8],w=i[12],T=i[1],E=i[5],A=i[9],R=i[13],C=i[2],P=i[6],L=i[10],I=i[14],U=i[3],N=i[7],D=i[11],O=i[15];return r[0]=s*M+a*T+o*C+l*U,r[4]=s*S+a*E+o*P+l*N,r[8]=s*b+a*A+o*L+l*D,r[12]=s*w+a*R+o*I+l*O,r[1]=c*M+h*T+u*C+d*U,r[5]=c*S+h*E+u*P+d*N,r[9]=c*b+h*A+u*L+d*D,r[13]=c*w+h*R+u*I+d*O,r[2]=p*M+m*T+f*C+g*U,r[6]=p*S+m*E+f*P+g*N,r[10]=p*b+m*A+f*L+g*D,r[14]=p*w+m*R+f*I+g*O,r[3]=v*M+_*T+x*C+y*U,r[7]=v*S+_*E+x*P+y*N,r[11]=v*b+_*A+x*L+y*D,r[15]=v*w+_*R+x*I+y*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,_=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,y=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*_+i*x+r*y;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/M;return t[0]=v*S,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*S,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*S,t[4]=_*S,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*S,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*S,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*S,t[8]=x*S,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*S,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*S,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*S,t[12]=y*S,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*S,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*S,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*S,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,_=o*c,x=o*h,y=n.x,M=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-_)*y,i[3]=0,i[4]=(d-x)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+_)*S,i[9]=(f-v)*S,i[10]=(1-(u+m))*S,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=ar.set(i[0],i[1],i[2]).length();const s=ar.set(i[4],i[5],i[6]).length(),a=ar.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],or.copy(this);const o=1/r,l=1/s,c=1/a;return or.elements[0]*=o,or.elements[1]*=o,or.elements[2]*=o,or.elements[4]*=l,or.elements[5]*=l,or.elements[6]*=l,or.elements[8]*=c,or.elements[9]*=c,or.elements[10]*=c,e.setFromRotationMatrix(or),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(e-t),c=2*r/(n-i),h=(e+t)/(e-t),u=(n+i)/(n-i);let d,p;if(a===Fn)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Bn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,n,i,r,s,a=2e3){const o=this.elements,l=1/(e-t),c=1/(n-i),h=1/(s-r),u=(e+t)*l,d=(n+i)*c;let p,m;if(a===Fn)p=(s+r)*h,m=-2*h;else{if(a!==Bn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const ar=new Ci,or=new sr,lr=new Ci(0,0,0),cr=new Ci(1,1,1),hr=new Ci,ur=new Ci,dr=new Ci,pr=new sr,mr=new Ri;class fr{constructor(t=0,e=0,n=0,i=fr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(Xn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Xn(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(Xn(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Xn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Xn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Xn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return pr.makeRotationFromQuaternion(t),this.setFromRotationMatrix(pr,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return mr.setFromEuler(this),this.setFromQuaternion(mr,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}fr.DEFAULT_ORDER="XYZ";class gr{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((t=>({boxInitialized:t.boxInitialized,boxMin:t.box.min.toArray(),boxMax:t.box.max.toArray(),sphereInitialized:t.sphereInitialized,sphereRadius:t.sphere.radius,sphereCenter:t.sphere.center.toArray()}))),i.maxGeometryCount=this._maxGeometryCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(t),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e0){i.children=[];for(let e=0;e0){i.animations=[];for(let e=0;e0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){Ur.subVectors(i,e),Nr.subVectors(n,e),Dr.subVectors(t,e);const s=Ur.dot(Ur),a=Ur.dot(Nr),o=Ur.dot(Dr),l=Nr.dot(Nr),c=Nr.dot(Dr),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return null!==this.getBarycoord(t,e,n,i,Or)&&(Or.x>=0&&Or.y>=0&&Or.x+Or.y<=1)}static getInterpolation(t,e,n,i,r,s,a,o){return null===this.getBarycoord(t,e,n,i,Or)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Or.x),o.addScaledVector(s,Or.y),o.addScaledVector(a,Or.z),o)}static isFrontFacing(t,e,n,i){return Ur.subVectors(n,e),Nr.subVectors(t,e),Ur.cross(Nr).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Ur.subVectors(this.c,this.b),Nr.subVectors(this.a,this.b),.5*Ur.cross(Nr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Gr.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Gr.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,r){return Gr.getInterpolation(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return Gr.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Gr.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;Fr.subVectors(i,n),Br.subVectors(r,n),kr.subVectors(t,n);const o=Fr.dot(kr),l=Br.dot(kr);if(o<=0&&l<=0)return e.copy(n);Vr.subVectors(t,i);const c=Fr.dot(Vr),h=Br.dot(Vr);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(Fr,s);Hr.subVectors(t,r);const d=Fr.dot(Hr),p=Br.dot(Hr);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Br,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return zr.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(zr,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(Fr,s).addScaledVector(Br,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Wr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Xr={h:0,s:0,l:0},jr={h:0,s:0,l:0};function qr(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}class Yr{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(void 0===e&&void 0===n){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=qe){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,ui.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=ui.workingColorSpace){return this.r=t,this.g=e,this.b=n,ui.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=ui.workingColorSpace){if(t=jn(t,1),e=Xn(e,0,1),n=Xn(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=qr(r,i,t+1/3),this.g=qr(r,i,t),this.b=qr(r,i,t-1/3)}return ui.toWorkingColorSpace(this,i),this}setStyle(t,e=qe){function n(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(n,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=qe){const n=Wr[t.toLowerCase()];return void 0!==n?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=di(t.r),this.g=di(t.g),this.b=di(t.b),this}copyLinearToSRGB(t){return this.r=pi(t.r),this.g=pi(t.g),this.b=pi(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=qe){return ui.fromWorkingColorSpace(Zr.copy(this),t),65536*Math.round(Xn(255*Zr.r,0,255))+256*Math.round(Xn(255*Zr.g,0,255))+Math.round(Xn(255*Zr.b,0,255))}getHexString(t=qe){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=ui.workingColorSpace){ui.fromWorkingColorSpace(Zr.copy(this),e);const n=Zr.r,i=Zr.g,r=Zr.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case n:o=(i-r)/t+(i0!=t>0&&this.version++,this._alphaTest=t}onBuild(){}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),this.side!==u&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==C&&(n.blendSrc=this.blendSrc),this.blendDst!==P&&(n.blendDst=this.blendDst),this.blendEquation!==y&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==nn&&(n.stencilFail=this.stencilFail),this.stencilZFail!==nn&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==nn&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}}class $r extends Kr{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Yr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new fr,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Qr=ts();function ts(){const t=new ArrayBuffer(4),e=new Float32Array(t),n=new Uint32Array(t),i=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(i[t]=0,i[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(i[t]=1024>>-e-14,i[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(i[t]=e+15<<10,i[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(i[t]=31744,i[256|t]=64512,r[t]=24,r[256|t]=24):(i[t]=31744,i[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,n=0;for(;0==(8388608&e);)e<<=1,n-=8388608;e&=-8388609,n+=947912704,s[t]=e|n}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function es(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=Xn(t,-65504,65504),Qr.floatView[0]=t;const e=Qr.uint32View[0],n=e>>23&511;return Qr.baseTable[n]+((8388607&e)>>Qr.shiftTable[n])}function ns(t){const e=t>>10;return Qr.uint32View[0]=Qr.mantissaTable[Qr.offsetTable[e]+(1023&t)]+Qr.exponentTable[e],Qr.floatView[0]}const is={toHalfFloat:es,fromHalfFloat:ns},rs=new Ci,ss=new Kn;class as{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=n,this.usage=En,this._updateRange={offset:0,count:-1},this.updateRanges=[],this.gpuType=It,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}get updateRange(){return ai("THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead."),this._updateRange}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t(t.far-t.near)**2)return}ws.copy(r).invert(),Ts.copy(t.ray).applyMatrix4(ws),null!==n.boundingBox&&!1===Ts.intersectsBox(n.boundingBox)||this._computeIntersections(t,e,Ts)}}_computeIntersections(t,e,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=u.length;rn.far?null:{distance:c,point:ks.clone(),object:t}}(t,e,n,i,Rs,Cs,Ps,zs);if(h){r&&(Us.fromBufferAttribute(r,o),Ns.fromBufferAttribute(r,l),Ds.fromBufferAttribute(r,c),h.uv=Gr.getInterpolation(zs,Rs,Cs,Ps,Us,Ns,Ds,new Kn)),s&&(Us.fromBufferAttribute(s,o),Ns.fromBufferAttribute(s,l),Ds.fromBufferAttribute(s,c),h.uv1=Gr.getInterpolation(zs,Rs,Cs,Ps,Us,Ns,Ds,new Kn)),a&&(Os.fromBufferAttribute(a,o),Fs.fromBufferAttribute(a,l),Bs.fromBufferAttribute(a,c),h.normal=Gr.getInterpolation(zs,Rs,Cs,Ps,Os,Fs,Bs,new Ci),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const t={a:o,b:l,c:c,normal:new Ci,materialIndex:0};Gr.getNormal(Rs,Cs,Ps,t.normal),h.face=t}return h}class Gs extends bs{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const _=s/f,x=p/g,y=s/2,M=p/2,S=m/2,b=f+1,w=g+1;let T=0,E=0;const A=new Ci;for(let s=0;s0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class Zs extends Ir{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new sr,this.projectionMatrix=new sr,this.projectionMatrixInverse=new sr,this.coordinateSystem=Fn}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Js=new Ci,Ks=new Kn,$s=new Kn;class Qs extends Zs{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*Gn*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Hn*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*Gn*Math.atan(Math.tan(.5*Hn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){Js.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(Js.x,Js.y).multiplyScalar(-t/Js.z),Js.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Js.x,Js.y).multiplyScalar(-t/Js.z)}getViewSize(t,e){return this.getViewBounds(t,Ks,$s),e.subVectors($s,Ks)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Hn*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const ta=-90;class ea extends Ir{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Qs(ta,1,t,e);i.layers=this.layers,this.add(i);const r=new Qs(ta,1,t,e);r.layers=this.layers,this.add(r);const s=new Qs(ta,1,t,e);s.layers=this.layers,this.add(s);const a=new Qs(ta,1,t,e);a.layers=this.layers,this.add(a);const o=new Qs(ta,1,t,e);o.layers=this.layers,this.add(o);const l=new Qs(ta,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,r,s,a,o]=e;for(const t of e)this.remove(t);if(t===Fn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==Bn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,r),t.setRenderTarget(n,1,i),t.render(e,s),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,o),t.setRenderTarget(n,4,i),t.render(e,l),n.texture.generateMipmaps=m,t.setRenderTarget(n,5,i),t.render(e,c),t.setRenderTarget(h,u,d),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class na extends yi{constructor(t,e,n,i,r,s,a,o,l,c){super(t=void 0!==t?t:[],e=void 0!==e?e:lt,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class ia extends bi{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new na(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:Mt}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Gs(5,5,5),r=new Ys({name:"CubemapFromEquirect",uniforms:Ws(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:d,blending:0});r.uniforms.tEquirect.value=e;const s=new Vs(i,r),a=e.minFilter;e.minFilter===wt&&(e.minFilter=Mt);return new ea(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}const ra=new Ci,sa=new Ci,aa=new $n;class oa{constructor(t=new Ci(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=ra.subVectors(n,e).cross(sa.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(ra),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||aa.getNormalMatrix(t),i=this.coplanarPoint(ra).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const la=new Ji,ca=new Ci;class ha{constructor(t=new oa,e=new oa,n=new oa,i=new oa,r=new oa,s=new oa){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],v=i[13],_=i[14],x=i[15];if(n[0].setComponents(o-r,u-l,f-d,x-g).normalize(),n[1].setComponents(o+r,u+l,f+d,x+g).normalize(),n[2].setComponents(o+s,u+c,f+p,x+v).normalize(),n[3].setComponents(o-s,u-c,f-p,x-v).normalize(),n[4].setComponents(o-a,u-h,f-m,x-_).normalize(),e===Fn)n[5].setComponents(o+a,u+h,f+m,x+_).normalize();else{if(e!==Bn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);n[5].setComponents(a,h,m,_).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),la.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),la.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(la)}intersectsSprite(t){return la.center.set(0,0,0),la.radius=.7071067811865476,la.applyMatrix4(t.matrixWorld),this.intersectsSphere(la)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)0?t.max.x:t.min.x,ca.y=i.normal.y>0?t.max.y:t.min.y,ca.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(ca)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function ua(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function da(t){const e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=e.get(n);i&&(t.deleteBuffer(i.buffer),e.delete(n))},update:function(n,i){if(n.isGLBufferAttribute){const t=e.get(n);return void((!t||t.version 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( batchId );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include