three实现三维巨树之国场景代码
代码语言:html
所属分类:其他
代码由glm-5.4 ai生成,可能有错误,仅供参考:点击查看提示词
代码描述:three实现三维巨树之国场景代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TREEFOLK · 巨树之国</title>
<style>
:root{
--cream:#f4ead6;
--cream-dim:rgba(244,234,214,.62);
--ink:#1d241c;
--glass:rgba(22,28,22,.46);
--glass-line:rgba(244,234,214,.18);
--accent:#c9a86a;
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#0d120e;}
body{
font-family:"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans SC",system-ui,sans-serif;
color:var(--cream);
-webkit-font-smoothing:antialiased;
}
#app{position:fixed;inset:0}
#scene{position:absolute;inset:0;width:100%;height:100%;display:block;outline:none}
#vignette{
position:absolute;inset:0;pointer-events:none;
background:radial-gradient(ellipse at 50% 46%,transparent 42%,rgba(18,24,18,.18) 78%,rgba(14,18,14,.42) 100%);
mix-blend-mode:multiply;
}
#letterbox .bar{
position:absolute;left:0;right:0;height:9.5vh;background:#0a0d0a;z-index:6;
transition:transform 1.1s cubic-bezier(.22,.61,.36,1);
}
#letterbox .bar.top{top:0;transform:translateY(-100%)}
#letterbox .bar.bottom{bottom:0;transform:translateY(100%)}
#letterbox.show .bar{transform:translateY(0)}
#letterbox.hidden{display:none}
#brand{
position:absolute;left:34px;top:30px;z-index:5;pointer-events:none;
text-shadow:0 2px 18px rgba(10,16,10,.55);
}
.brand-mark{
font-size:11px;letter-spacing:.42em;font-weight:600;color:var(--accent);
opacity:.95;margin-bottom:6px;
}
#brand h1{
margin:0;font-family:"Songti SC","Noto Serif SC",serif;
font-size:30px;font-weight:500;letter-spacing:.22em;line-height:1.1;
}
#brand p{
margin:8px 0 0;font-size:12px;letter-spacing:.14em;color:var(--cream-dim);
}
#hint{
position:absolute;left:50%;bottom:78px;transform:translateX(-50%);z-index:5;
font-size:11px;letter-spacing:.18em;color:rgba(244,234,214,.42);
pointer-events:none;transition:opacity .6s;
}
#dock{
position:absolute;left:50%;bottom:26px;transform:translateX(-50%);z-index:7;
display:flex;align-items:center;gap:2px;padding:6px;
background:var(--glass);border:1px solid var(--glass-line);border-radius:999px;
backdrop-filter:blur(14px) saturate(1.1);
box-shadow:0 12px 40px rgba(8,12,8,.35);
transition:opacity .45s,transform .45s;
}
#dock button{
appearance:none;border:0;background:transparent;color:var(--cream-dim);
font-family:inherit;font-size:12px;letter-spacing:.1em;padding:8px 14px;border-radius:999px;
cursor:pointer;transition:color .2s,background .2s;white-space:nowrap;
}
#dock button:hover{color:var(--cream);background:rgba(244,234,214,.07)}
#dock button.on{color:var(--ink);background:var(--cream)}
#dock .sep{width:1px;height:16px;background:var(--glass-line);margin:0 6px}
#loader{
position:absolute;inset:0;z-index:20;background:#10150f;
display:flex;align-items:center;justify-content:center;
transition:opacity 1.2s ease;
}
#loader.done{opacity:0;pointer-events:none}
.loader-inner{text-align:center;width:260px}
.loader-title{font-size:12px;letter-spacing:.5em;color:var(--accent);margin-bottom:14px}
.loader-sub{font-size:12px;letter-spacing:.16em;color:var(--cream-dim);margin-bottom:22px}
.loader-bar{height:1px;background:rgba(244,234,214,.16);overflow:hidden}
.loader-bar i{display:block;height:100%;width:0%;background:var(--accent);transition:width .35s ease}
.loader-pct{margin-top:12px;font-size:10px;letter-spacing:.2em;color:rgba(244,234,214,.35)}
#toast{
position:absolute;left:50%;top:30px;transform:translate(-50%,-12px);z-index:8;
padding:8px 16px;border-radius:999px;background:var(--glass);border:1px solid var(--glass-line);
backdrop-filter:blur(12px);font-size:11px;letter-spacing:.14em;color:var(--cream);
opacity:0;pointer-events:none;transition:opacity .3s,transform .3s;
}
#toast.show{opacity:1;transform:translate(-50%,0)}
body.ui-hidden #brand,body.ui-hidden #dock,body.ui-hidden #hint,body.ui-hidden #toast{opacity:0;pointer-events:none}
body.ui-hidden{cursor:none}
@media (max-width:720px){
#brand{left:20px;top:20px}
#brand h1{font-size:22px}
#dock{bottom:16px;gap:0;padding:4px}
#dock button{padding:7px 9px;font-size:11px;letter-spacing:.04em}
#hint{display:none}
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene"></canvas>
<div id="vignette"></div>
<div id="letterbox" class="hidden"><div class="bar top"></div><div class="bar bottom"></div></div>
<header id="brand">
<div class="brand-mark">TREEFOLK</div>
<h1>巨树之国</h1>
<p>一座生长在千年古树上的童话村落</p>
</header>
<div id="hint">拖拽旋转 · 滚轮缩放 · 右键平移</div>
<nav id="dock">
<button data-act="cinematic" class="on">电影运镜</button>
<button data-act="free">自由探索</button>
<span class="sep"></span>
<button data-act="day" class="on">白天</button>
<button data-act="dusk">黄昏</button>
<span class="sep"></span>
<button data-act="pause">暂停</button>
<button data-act="reset">重置镜头</button>
<button data-act="fullscreen">全屏</button>
<button data-act="hide">隐藏界面</button>
</nav>
<div id="loader">
<div class="loader-inner">
<div class="loader-title">TREEFOLK</div>
<div class="loader-sub">正在种植巨树…</div>
<div class="loader-bar"><i></i></div>
<div class="loader-pct">0%</div>
</div>
</div>
<div id="toast"></div>
</div>
<script>
(() => {
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
// vendor/three.module.js
function generateUUID() {
const d0 = Math.random() * 4294967295 | 0;
const d1 = Math.random() * 4294967295 | 0;
const d2 = Math.random() * 4294967295 | 0;
const d3 = Math.random() * 4294967295 | 0;
const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255];
return uuid.toLowerCase();
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function euclideanModulo(n, m) {
return (n % m + m) % m;
}
function mapLinear(x, a1, a2, b1, b2) {
return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
}
function inverseLerp(x, y, value) {
if (x !== y) {
return (value - x) / (y - x);
} else {
return 0;
}
}
function lerp(x, y, t) {
return (1 - t) * x + t * y;
}
function damp(x, y, lambda, dt) {
return lerp(x, y, 1 - Math.exp(-lambda * dt));
}
function pingpong(x, length = 1) {
return length - Math.abs(euclideanModulo(x, length * 2) - length);
}
function smoothstep(x, min, max) {
if (x <= min)
return 0;
if (x >= max)
return 1;
x = (x - min) / (max - min);
return x * x * (3 - 2 * x);
}
function smootherstep(x, min, max) {
if (x <= min)
return 0;
if (x >= max)
return 1;
x = (x - min) / (max - min);
return x * x * x * (x * (x * 6 - 15) + 10);
}
function randInt(low, high) {
return low + Math.floor(Math.random() * (high - low + 1));
}
function randFloat(low, high) {
return low + Math.random() * (high - low);
}
function randFloatSpread(range) {
return range * (0.5 - Math.random());
}
function seededRandom(s) {
if (s !== void 0)
_seed = s;
let t = _seed += 1831565813;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function degToRad(degrees) {
return degrees * DEG2RAD;
}
function radToDeg(radians) {
return radians * RAD2DEG;
}
function isPowerOfTwo(value) {
return (value & value - 1) === 0 && value !== 0;
}
function ceilPowerOfTwo(value) {
return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
}
function floorPowerOfTwo(value) {
return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
}
function setQuaternionFromProperEuler(q, a, b, c, order) {
const cos = Math.cos;
const sin = Math.sin;
const c2 = cos(b / 2);
const s2 = sin(b / 2);
const c13 = cos((a + c) / 2);
const s13 = sin((a + c) / 2);
const c1_3 = cos((a - c) / 2);
const s1_3 = sin((a - c) / 2);
const c3_1 = cos((c - a) / 2);
const s3_1 = sin((c - a) / 2);
switch (order) {
case "XYX":
q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
break;
case "YZY":
q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
break;
case "ZXZ":
q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
break;
case "XZX":
q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
break;
case "YXY":
q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
break;
case "ZYZ":
q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
break;
default:
console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order);
}
}
function denormalize(value, array) {
switch (array.constructor) {
case Float32Array:
return value;
case Uint32Array:
return value / 4294967295;
case Uint16Array:
return value / 65535;
case Uint8Array:
return value / 255;
case Int32Array:
return Math.max(value / 2147483647, -1);
case Int16Array:
return Math.max(value / 32767, -1);
case Int8Array:
return Math.max(value / 127, -1);
default:
throw new Error("Invalid component type.");
}
}
function normalize(value, array) {
switch (array.constructor) {
case Float32Array:
return value;
case Uint32Array:
return Math.round(value * 4294967295);
case Uint16Array:
return Math.round(value * 65535);
case Uint8Array:
return Math.round(value * 255);
case Int32Array:
return Math.round(value * 2147483647);
case Int16Array:
return Math.round(value * 32767);
case Int8Array:
return Math.round(value * 127);
default:
throw new Error("Invalid component type.");
}
}
function arrayNeedsUint32(array) {
for (let i = array.length - 1; i >= 0; --i) {
if (array[i] >= 65535)
return true;
}
return false;
}
function createElementNS(name) {
return document.createElementNS("http://www.w3.org/1999/xhtml", name);
}
function createCanvasElement() {
const canvas = createElementNS("canvas");
canvas.style.display = "block";
return canvas;
}
function warnOnce(message) {
if (message in _cache)
return;
_cache[message] = true;
console.warn(message);
}
function SRGBToLinear(c) {
return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
}
function LinearToSRGB(c) {
return c < 31308e-7 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
}
function serializeImage(image) {
if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
return ImageUtils.getDataURL(image);
} else {
if (image.data) {
return {
data: Array.from(image.data),
width: image.width,
height: image.height,
type: image.data.constructor.name
};
} else {
console.warn("THREE.Texture: Unable to serialize Texture.");
return {};
}
}
}
function satForAxes(axes, v0, v1, v2, extents) {
for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
_testAxis.fromArray(axes, i);
const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z);
const p0 = v0.dot(_testAxis);
const p1 = v1.dot(_testAxis);
const p2 = v2.dot(_testAxis);
if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
return false;
}
}
return true;
}
function hue2rgb(p, q, t) {
if (t < 0)
t += 1;
if (t > 1)
t -= 1;
if (t < 1 / 6)
return p + (q - p) * 6 * t;
if (t < 1 / 2)
return q;
if (t < 2 / 3)
return p + (q - p) * 6 * (2 / 3 - t);
return p;
}
function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
let intersect;
if (material.side === BackSide) {
intersect = ray.intersectTriangle(pC, pB, pA, true, point);
} else {
intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point);
}
if (intersect === null)
return null;
_intersectionPointWorld.copy(point);
_intersectionPointWorld.applyMatrix4(object.matrixWorld);
const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
if (distance < raycaster.near || distance > raycaster.far)
return null;
return {
distance,
point: _intersectionPointWorld.clone(),
object
};
}
function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) {
object.getVertexPosition(a, _vA$1);
object.getVertexPosition(b, _vB$1);
object.getVertexPosition(c, _vC$1);
const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
if (intersection) {
if (uv) {
_uvA$1.fromBufferAttribute(uv, a);
_uvB$1.fromBufferAttribute(uv, b);
_uvC$1.fromBufferAttribute(uv, c);
intersection.uv = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
}
if (uv1) {
_uvA$1.fromBufferAttribute(uv1, a);
_uvB$1.fromBufferAttribute(uv1, b);
_uvC$1.fromBufferAttribute(uv1, c);
intersection.uv1 = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
intersection.uv2 = intersection.uv1;
}
if (normal) {
_normalA.fromBufferAttribute(normal, a);
_normalB.fromBufferAttribute(normal, b);
_normalC.fromBufferAttribute(normal, c);
intersection.normal = Triangle.getInterpolation(_intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3());
if (intersection.normal.dot(ray.direction) > 0) {
intersection.normal.multiplyScalar(-1);
}
}
const face = {
a,
b,
c,
normal: new Vector3(),
materialIndex: 0
};
Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
intersection.face = face;
}
return intersection;
}
function cloneUniforms(src) {
const dst = {};
for (const u in src) {
dst[u] = {};
for (const p in src[u]) {
const property = src[u][p];
if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
if (property.isRenderTargetTexture) {
console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().");
dst[u][p] = null;
} else {
dst[u][p] = property.clone();
}
} else if (Array.isArray(property)) {
dst[u][p] = property.slice();
} else {
dst[u][p] = property;
}
}
}
return dst;
}
function mergeUniforms(uniforms) {
const merged = {};
for (let u = 0; u < uniforms.length; u++) {
const tmp2 = cloneUniforms(uniforms[u]);
for (const p in tmp2) {
merged[p] = tmp2[p];
}
}
return merged;
}
function cloneUniformsGroups(src) {
const dst = [];
for (let u = 0; u < src.length; u++) {
dst.push(src[u].clone());
}
return dst;
}
function getUnlitUniformColorSpace(renderer) {
if (renderer.getRenderTarget() === null) {
return renderer.outputColorSpace;
}
return ColorManagement.workingColorSpace;
}
function WebGLAnimation() {
let context = null;
let isAnimating = false;
let animationLoop = null;
let requestId = null;
function onAnimationFrame(time, frame) {
animationLoop(time, frame);
requestId = context.requestAnimationFrame(onAnimationFrame);
}
return {
start: function() {
if (isAnimating === true)
return;
if (animationLoop === null)
return;
requestId = context.requestAnimationFrame(onAnimationFrame);
isAnimating = true;
},
stop: function() {
context.cancelAnimationFrame(requestId);
isAnimating = false;
},
setAnimationLoop: function(callback) {
animationLoop = callback;
},
setContext: function(value) {
context = value;
}
};
}
function WebGLAttributes(gl, capabilities) {
const isWebGL2 = capabilities.isWebGL2;
const buffers = /* @__PURE__ */ new WeakMap();
function createBuffer(attribute, bufferType) {
const array = attribute.array;
const usage = attribute.usage;
const size = array.byteLength;
const buffer = gl.createBuffer();
gl.bindBuffer(bufferType, buffer);
gl.bufferData(bufferType, array, usage);
attribute.onUploadCallback();
let type;
if (array instanceof Float32Array) {
type = gl.FLOAT;
} else if (array instanceof Uint16Array) {
if (attribute.isFloat16BufferAttribute) {
if (isWebGL2) {
type = gl.HALF_FLOAT;
} else {
throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.");
}
} else {
type = gl.UNSIGNED_SHORT;
}
} else if (array instanceof Int16Array) {
type = gl.SHORT;
} else if (array instanceof Uint32Array) {
type = gl.UNSIGNED_INT;
} else if (array instanceof Int32Array) {
type = gl.INT;
} else if (array instanceof Int8Array) {
type = gl.BYTE;
} else if (array instanceof Uint8Array) {
type = gl.UNSIGNED_BYTE;
} else if (array instanceof Uint8ClampedArray) {
type = gl.UNSIGNED_BYTE;
} else {
throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array);
}
return {
buffer,
type,
bytesPerElement: array.BYTES_PER_ELEMENT,
version: attribute.version,
size
};
}
function updateBuffer(buffer, attribute, bufferType) {
const array = attribute.array;
const updateRange = attribute._updateRange;
const updateRanges = attribute.updateRanges;
gl.bindBuffer(bufferType, buffer);
if (updateRange.count === -1 && updateRanges.length === 0) {
gl.bufferSubData(bufferType, 0, array);
}
if (updateRanges.length !== 0) {
for (let i = 0, l = updateRanges.length; i < l; i++) {
const range = updateRanges[i];
if (isWebGL2) {
gl.bufferSubData(
bufferType,
range.start * array.BYTES_PER_ELEMENT,
array,
range.start,
range.count
);
} else {
gl.bufferSubData(
bufferType,
range.start * array.BYTES_PER_ELEMENT,
array.subarray(range.start, range.start + range.count)
);
}
}
attribute.clearUpdateRanges();
}
if (updateRange.count !== -1) {
if (isWebGL2) {
gl.bufferSubData(
bufferType,
updateRange.offset * array.BYTES_PER_ELEMENT,
array,
updateRange.offset,
updateRange.count
);
} else {
gl.bufferSubData(
bufferType,
updateRange.offset * array.BYTES_PER_ELEMENT,
array.subarray(updateRange.offset, updateRange.offset + updateRange.count)
);
}
updateRange.count = -1;
}
attribute.onUploadCallback();
}
function get(attribute) {
if (attribute.isInterleavedBufferAttribute)
attribute = attribute.data;
return buffers.get(attribute);
}
function remove(attribute) {
if (attribute.isInterleavedBufferAttribute)
attribute = attribute.data;
const data = buffers.get(attribute);
if (data) {
gl.deleteBuffer(data.buffer);
buffers.delete(attribute);
}
}
function update(attribute, bufferType) {
if (attribute.isGLBufferAttribute) {
const cached = buffers.get(attribute);
if (!cached || cached.version < attribute.version) {
buffers.set(attribute, {
buffer: attribute.buffer,
type: attribute.type,
bytesPerElement: attribute.elementSize,
version: attribute.version
});
}
return;
}
if (attribute.isInterleavedBufferAttribute)
attribute = attribute.data;
const data = buffers.get(attribute);
if (data === void 0) {
buffers.set(attribute, createBuffer(attribute, bufferType));
} else if (data.version < attribute.version) {
if (data.size !== attribute.array.byteLength) {
throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");
}
updateBuffer(data.buffer, attribute, bufferType);
data.version = attribute.version;
}
}
return {
get,
remove,
update
};
}
function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) {
const clearColor = new Color(0);
let clearAlpha = alpha === true ? 0 : 1;
let planeMesh;
let boxMesh;
let currentBackground = null;
let currentBackgroundVersion = 0;
let currentTonemapping = null;
function render(renderList, scene) {
let forceClear = false;
let background = scene.isScene === true ? scene.background : null;
if (background && background.isTexture) {
const usePMREM = scene.backgroundBlurriness > 0;
background = (usePMREM ? cubeuvmaps : cubemaps).get(background);
}
if (background === null) {
setClear(clearColor, clearAlpha);
} else if (background && background.isColor) {
setClear(background, 1);
forceClear = true;
}
const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
if (environmentBlendMode === "additive") {
state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha);
} else if (environmentBlendMode === "alpha-blend") {
state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha);
}
if (renderer.autoClear || forceClear) {
renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
}
if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
if (boxMesh === void 0) {
boxMesh = new Mesh(
new BoxGeometry(1, 1, 1),
new ShaderMaterial({
name: "BackgroundCubeMaterial",
uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms),
vertexShader: ShaderLib.backgroundCube.vertexShader,
fragmentShader: ShaderLib.backgroundCube.fragmentShader,
side: BackSide,
depthTest: false,
depthWrite: false,
fog: false
})
);
boxMesh.geometry.deleteAttribute("normal");
boxMesh.geometry.deleteAttribute("uv");
boxMesh.onBeforeRender = function(renderer2, scene2, camera) {
this.matrixWorld.copyPosition(camera.matrixWorld);
};
Object.defineProperty(boxMesh.material, "envMap", {
get: function() {
return this.uniforms.envMap.value;
}
});
objects.update(boxMesh);
}
boxMesh.material.uniforms.envMap.value = background;
boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer;
if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
boxMesh.material.needsUpdate = true;
currentBackground = background;
currentBackgroundVersion = background.version;
currentTonemapping = renderer.toneMapping;
}
boxMesh.layers.enableAll();
renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
} else if (background && background.isTexture) {
if (planeMesh === void 0) {
planeMesh = new Mesh(
new PlaneGeometry(2, 2),
new ShaderMaterial({
name: "BackgroundMaterial",
uniforms: cloneUniforms(ShaderLib.background.uniforms),
vertexShader: ShaderLib.background.vertexShader,
fragmentShader: ShaderLib.background.fragmentShader,
side: FrontSide,
depthTest: false,
depthWrite: false,
fog: false
})
);
planeMesh.geometry.deleteAttribute("normal");
Object.defineProperty(planeMesh.material, "map", {
get: function() {
return this.uniforms.t2D.value;
}
});
objects.update(planeMesh);
}
planeMesh.material.uniforms.t2D.value = background;
planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer;
if (background.matrixAutoUpdate === true) {
background.updateMatrix();
}
planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
planeMesh.material.needsUpdate = true;
currentBackground = background;
currentBackgroundVersion = background.version;
currentTonemapping = renderer.toneMapping;
}
planeMesh.layers.enableAll();
renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
}
}
function setClear(color, alpha2) {
color.getRGB(_rgb, getUnlitUniformColorSpace(renderer));
state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha);
}
return {
getClearColor: function() {
return clearColor;
},
setClearColor: function(color, alpha2 = 1) {
clearColor.set(color);
clearAlpha = alpha2;
setClear(clearColor, clearAlpha);
},
getClearAlpha: function() {
return clearAlpha;
},
setClearAlpha: function(alpha2) {
clearAlpha = alpha2;
setClear(clearColor, clearAlpha);
},
render
};
}
function WebGLBindingStates(gl, extensions, attributes, capabilities) {
const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
const extension = capabilities.isWebGL2 ? null : extensions.get("OES_vertex_array_object");
const vaoAvailable = capabilities.isWebGL2 || extension !== null;
const bindingStates = {};
const defaultState = createBindingState(null);
let currentState = defaultState;
let forceUpdate = false;
function setup(object, material, program, geometry, index) {
let updateBuffers = false;
if (vaoAvailable) {
const state = getBindingState(geometry, program, material);
if (currentState !== state) {
currentState = state;
bindVertexArrayObject(currentState.object);
}
updateBuffers = needsUpdate(object, geometry, program, index);
if (updateBuffers)
saveCache(object, geometry, program, index);
} else {
const wireframe = material.wireframe === true;
if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
currentState.geometry = geometry.id;
currentState.program = program.id;
currentState.wireframe = wireframe;
updateBuffers = true;
}
}
if (index !== null) {
attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
}
if (updateBuffers || forceUpdate) {
forceUpdate = false;
setupVertexAttributes(object, material, program, geometry);
if (index !== null) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
}
}
}
function createVertexArrayObject() {
if (capabilities.isWebGL2)
return gl.createVertexArray();
return extension.createVertexArrayOES();
}
function bindVertexArrayObject(vao) {
if (capabilities.isWebGL2)
return gl.bindVertexArray(vao);
return extension.bindVertexArrayOES(vao);
}
function deleteVertexArrayObject(vao) {
if (capabilities.isWebGL2)
return gl.deleteVertexArray(vao);
return extension.deleteVertexArrayOES(vao);
}
function getBindingState(geometry, program, material) {
const wireframe = material.wireframe === true;
let programMap = bindingStates[geometry.id];
if (programMap === void 0) {
programMap = {};
bindingStates[geometry.id] = programMap;
}
let stateMap = programMap[program.id];
if (stateMap === void 0) {
stateMap = {};
programMap[program.id] = stateMap;
}
let state = stateMap[wireframe];
if (state === void 0) {
state = createBindingState(createVertexArrayObject());
stateMap[wireframe] = state;
}
return state;
}
function createBindingState(vao) {
const newAttributes = [];
const enabledAttributes = [];
const attributeDivisors = [];
for (let i = 0; i < maxVertexAttributes; i++) {
newAttributes[i] = 0;
enabledAttributes[i] = 0;
attributeDivisors[i] = 0;
}
return {
// for backward compatibility on non-VAO support browser
geometry: null,
program: null,
wireframe: false,
newAttributes,
enabledAttributes,
attributeDivisors,
object: vao,
attributes: {},
index: null
};
}
function needsUpdate(object, geometry, program, index) {
const cachedAttributes = currentState.attributes;
const geometryAttributes = geometry.attributes;
let attributesNum = 0;
const programAttributes = program.getAttributes();
for (const name in programAttributes) {
const programAttribute = programAttributes[name];
if (programAttribute.location >= 0) {
const cachedAttribute = cachedAttributes[name];
let geometryAttribute = geometryAttributes[name];
if (geometryAttribute === void 0) {
if (name === "instanceMatrix" && object.instanceMatrix)
geometryAttribute = object.instanceMatrix;
if (name === "instanceColor" && object.instanceColor)
geometryAttribute = object.instanceColor;
}
if (cachedAttribute === void 0)
return true;
if (cachedAttribute.attribute !== geometryAttribute)
return true;
if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data)
return true;
attributesNum++;
}
}
if (currentState.attributesNum !== attributesNum)
return true;
if (currentState.index !== index)
return true;
return false;
}
function saveCache(object, geometry, program, index) {
const cache = {};
const attributes2 = geometry.attributes;
let attributesNum = 0;
const programAttributes = program.getAttributes();
for (const name in programAttributes) {
const programAttribute = programAttributes[name];
if (programAttribute.location >= 0) {
let attribute = attributes2[name];
if (attribute === void 0) {
if (name === "instanceMatrix" && object.instanceMatrix)
attribute = object.instanceMatrix;
if (name === "instanceColor" && object.instanceColor)
attribute = object.instanceColor;
}
const data = {};
data.attribute = attribute;
if (attribute && attribute.data) {
data.data = attribute.data;
}
cache[name] = data;
attributesNum++;
}
}
currentState.attributes = cache;
currentState.attributesNum = attributesNum;
currentState.index = index;
}
function initAttributes() {
const newAttributes = currentState.newAttributes;
for (let i = 0, il = newAttributes.length; i < il; i++) {
newAttributes[i] = 0;
}
}
function enableAttribute(attribute) {
enableAttributeAndDivisor(attribute, 0);
}
function enableAttributeAndDivisor(attribute, meshPerAttribute) {
const newAttributes = currentState.newAttributes;
const enabledAttributes = currentState.enabledAttributes;
const attributeDivisors = currentState.attributeDivisors;
newAttributes[attribute] = 1;
if (enabledAttributes[attribute] === 0) {
gl.enableVertexAttribArray(attribute);
enabledAttributes[attribute] = 1;
}
if (attributeDivisors[attribute] !== meshPerAttribute) {
const extension2 = capabilities.isWebGL2 ? gl : extensions.get("ANGLE_instanced_arrays");
extension2[capabilities.isWebGL2 ? "vertexAttribDivisor" : "vertexAttribDivisorANGLE"](attribute, meshPerAttribute);
attributeDivisors[attribute] = meshPerAttribute;
}
}
function disableUnusedAttributes() {
const newAttributes = currentState.newAttributes;
const enabledAttributes = currentState.enabledAttributes;
for (let i = 0, il = enabledAttributes.length; i < il; i++) {
if (enabledAttributes[i] !== newAttributes[i]) {
gl.disableVertexAttribArray(i);
enabledAttributes[i] = 0;
}
}
}
function vertexAttribPointer(index, size, type, normalized, stride, offset, integer) {
if (integer === true) {
gl.vertexAttribIPointer(index, size, type, stride, offset);
} else {
gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
}
}
function setupVertexAttributes(object, material, program, geometry) {
if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
if (extensions.get("ANGLE_instanced_arrays") === null)
return;
}
initAttributes();
const geometryAttributes = geometry.attributes;
const programAttributes = program.getAttributes();
const materialDefaultAttributeValues = material.defaultAttributeValues;
for (const name in programAttributes) {
const programAttribute = programAttributes[name];
if (programAttribute.location >= 0) {
let geometryAttribute = geometryAttributes[name];
if (geometryAttribute === void 0) {
if (name === "instanceMatrix" && object.instanceMatrix)
geometryAttribute = object.instanceMatrix;
if (name === "instanceColor" && object.instanceColor)
geometryAttribute = object.instanceColor;
}
if (geometryAttribute !== void 0) {
const normalized = geometryAttribute.normalized;
const size = geometryAttribute.itemSize;
const attribute = attributes.get(geometryAttribute);
if (attribute === void 0)
continue;
const buffer = attribute.buffer;
const type = attribute.type;
const bytesPerElement = attribute.bytesPerElement;
const integer = capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType);
if (geometryAttribute.isInterleavedBufferAttribute) {
const data = geometryAttribute.data;
const stride = data.stride;
const offset = geometryAttribute.offset;
if (data.isInstancedInterleavedBuffer) {
for (let i = 0; i < programAttribute.locationSize; i++) {
enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
}
if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) {
geometry._maxInstanceCount = data.meshPerAttribute * data.count;
}
} else {
for (let i = 0; i < programAttribute.locationSize; i++) {
enableAttribute(programAttribute.location + i);
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
for (let i = 0; i < programAttribute.locationSize; i++) {
vertexAttribPointer(
programAttribute.location + i,
size / programAttribute.locationSize,
type,
normalized,
stride * bytesPerElement,
(offset + size / programAttribute.locationSize * i) * bytesPerElement,
integer
);
}
} else {
if (geometryAttribute.isInstancedBufferAttribute) {
for (let i = 0; i < programAttribute.locationSize; i++) {
enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
}
if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) {
geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
}
} else {
for (let i = 0; i < programAttribute.locationSize; i++) {
enableAttribute(programAttribute.location + i);
}
}
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
for (let i = 0; i < programAttribute.locationSize; i++) {
vertexAttribPointer(
programAttribute.location + i,
size / programAttribute.locationSize,
type,
normalized,
size * bytesPerElement,
size / programAttribute.locationSize * i * bytesPerElement,
integer
);
}
}
} else if (materialDefaultAttributeValues !== void 0) {
const value = materialDefaultAttributeValues[name];
if (value !== void 0) {
switch (value.length) {
case 2:
gl.vertexAttrib2fv(programAttribute.location, value);
break;
case 3:
gl.vertexAttrib3fv(programAttribute.location, value);
break;
case 4:
gl.vertexAttrib4fv(programAttribute.location, value);
break;
default:
gl.vertexAttrib1fv(programAttribute.location, value);
}
}
}
}
}
disableUnusedAttributes();
}
function dispose() {
reset();
for (const geometryId in bindingStates) {
const programMap = bindingStates[geometryId];
for (const programId in programMap) {
const stateMap = programMap[programId];
for (const wireframe in stateMap) {
deleteVertexArrayObject(stateMap[wireframe].object);
delete stateMap[wireframe];
}
delete programMap[programId];
}
delete bindingStates[geometryId];
}
}
function releaseStatesOfGeometry(geometry) {
if (bindingStates[geometry.id] === void 0)
return;
const programMap = bindingStates[geometry.id];
for (const programId in programMap) {
const stateMap = programMap[programId];
for (const wireframe in stateMap) {
deleteVertexArrayObject(stateMap[wireframe].object);
delete stateMap[wireframe];
}
delete programMap[programId];
}
delete bindingStates[geometry.id];
}
function releaseStatesOfProgram(program) {
for (const geometryId in bindingStates) {
const programMap = bindingStates[geometryId];
if (programMap[program.id] === void 0)
continue;
const stateMap = programMap[program.id];
for (const wireframe in stateMap) {
deleteVertexArrayObject(stateMap[wireframe].object);
delete stateMap[wireframe];
}
delete programMap[program.id];
}
}
function reset() {
resetDefaultState();
forceUpdate = true;
if (currentState === defaultState)
return;
currentState = defaultState;
bindVertexArrayObject(currentState.object);
}
function resetDefaultState() {
defaultState.geometry = null;
defaultState.program = null;
defaultState.wireframe = false;
}
return {
setup,
reset,
resetDefaultState,
dispose,
releaseStatesOfGeometry,
releaseStatesOfProgram,
initAttributes,
enableAttribute,
disableUnusedAttributes
};
}
function WebGLBufferRenderer(gl, extensions, info, capabilities) {
const isWebGL2 = capabilities.isWebGL2;
let mode;
function setMode(value) {
mode = value;
}
function render(start, count) {
gl.drawArrays(mode, start, count);
info.update(count, mode, 1);
}
function renderInstances(start, count, primcount) {
if (primcount === 0)
return;
let extension, methodName;
if (isWebGL2) {
extension = gl;
methodName = "drawArraysInstanced";
} else {
extension = extensions.get("ANGLE_instanced_arrays");
methodName = "drawArraysInstancedANGLE";
if (extension === null) {
console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
return;
}
}
extension[methodName](mode, start, count, primcount);
info.update(count, mode, primcount);
}
function renderMultiDraw(starts, counts, drawCount) {
if (drawCount === 0)
return;
const extension = extensions.get("WEBGL_multi_draw");
if (extension === null) {
for (let i = 0; i < drawCount; i++) {
this.render(starts[i], counts[i]);
}
} else {
extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount);
let elementCount = 0;
for (let i = 0; i < drawCount; i++) {
elementCount += counts[i];
}
info.update(elementCount, mode, 1);
}
}
this.setMode = setMode;
this.render = render;
this.renderInstances = renderInstances;
this.renderMultiDraw = renderMultiDraw;
}
function WebGLCapabilities(gl, extensions, parameters) {
let maxAnisotropy;
function getMaxAnisotropy() {
if (maxAnisotropy !== void 0)
return maxAnisotropy;
if (extensions.has("EXT_texture_filter_anisotropic") === true) {
const extension = extensions.get("EXT_texture_filter_anisotropic");
maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
} else {
maxAnisotropy = 0;
}
return maxAnisotropy;
}
function getMaxPrecision(precision2) {
if (precision2 === "highp") {
if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
return "highp";
}
precision2 = "mediump";
}
if (precision2 === "mediump") {
if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
return "mediump";
}
}
return "lowp";
}
const isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl.constructor.name === "WebGL2RenderingContext";
let precision = parameters.precision !== void 0 ? parameters.precision : "highp";
const maxPrecision = getMaxPrecision(precision);
if (maxPrecision !== precision) {
console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead.");
precision = maxPrecision;
}
const drawBuffers = isWebGL2 || extensions.has("WEBGL_draw_buffers");
const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
const vertexTextures = maxVertexTextures > 0;
const floatFragmentTextures = isWebGL2 || extensions.has("OES_texture_float");
const floatVertexTextures = vertexTextures && floatFragmentTextures;
const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
return {
isWebGL2,
drawBuffers,
getMaxAnisotropy,
getMaxPrecision,
precision,
logarithmicDepthBuffer,
maxTextures,
maxVertexTextures,
maxTextureSize,
maxCubemapSize,
maxAttributes,
maxVertexUniforms,
maxVaryings,
maxFragmentUniforms,
vertexTextures,
floatFragmentTextures,
floatVertexTextures,
maxSamples
};
}
function WebGLClipping(properties) {
const scope = this;
let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false;
const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false };
this.uniform = uniform;
this.numPlanes = 0;
this.numIntersection = 0;
this.init = function(planes, enableLocalClipping) {
const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
// run another frame in order to reset the state:
numGlobalPlanes !== 0 || localClippingEnabled;
localClippingEnabled = enableLocalClipping;
numGlobalPlanes = planes.length;
return enabled;
};
this.beginShadows = function() {
renderingShadows = true;
projectPlanes(null);
};
this.endShadows = function() {
renderingShadows = false;
};
this.setGlobalState = function(planes, camera) {
globalState = projectPlanes(planes, camera, 0);
};
this.setState = function(material, camera, useCache) {
const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows;
const materialProperties = properties.get(material);
if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
if (renderingShadows) {
projectPlanes(null);
} else {
resetGlobalState();
}
} else {
const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4;
let dstArray = materialProperties.clippingState || null;
uniform.value = dstArray;
dstArray = projectPlanes(planes, camera, lGlobal, useCache);
for (let i = 0; i !== lGlobal; ++i) {
dstArray[i] = globalState[i];
}
materialProperties.clippingState = dstArray;
this.numIntersection = clipIntersection ? this.numPlanes : 0;
this.numPlanes += nGlobal;
}
};
function resetGlobalState() {
if (uniform.value !== globalState) {
uniform.value = globalState;
uniform.needsUpdate = numGlobalPlanes > 0;
}
scope.numPlanes = numGlobalPlanes;
scope.numIntersection = 0;
}
function projectPlanes(planes, camera, dstOffset, skipTransform) {
const nPlanes = planes !== null ? planes.length : 0;
let dstArray = null;
if (nPlanes !== 0) {
dstArray = uniform.value;
if (skipTransform !== true || dstArray === null) {
const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse;
viewNormalMatrix.getNormalMatrix(viewMatrix);
if (dstArray === null || dstArray.length < flatSize) {
dstArray = new Float32Array(flatSize);
}
for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
plane.normal.toArray(dstArray, i4);
dstArray[i4 + 3] = plane.constant;
}
}
uniform.value = dstArray;
uniform.needsUpdate = true;
}
scope.numPlanes = nPlanes;
scope.numIntersection = 0;
return dstArray;
}
}
function WebGLCubeMaps(renderer) {
let cubemaps = /* @__PURE__ */ new WeakMap();
function mapTextureMapping(texture, mapping) {
if (mapping === EquirectangularReflectionMapping) {
texture.mapping = CubeReflectionMapping;
} else if (mapping === EquirectangularRefractionMapping) {
texture.mapping = CubeRefractionMapping;
}
return texture;
}
function get(texture) {
if (texture && texture.isTexture) {
const mapping = texture.mapping;
if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
if (cubemaps.has(texture)) {
const cubemap = cubemaps.get(texture).texture;
return mapTextureMapping(cubemap, texture.mapping);
} else {
const image = texture.image;
if (image && image.height > 0) {
const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
renderTarget.fromEquirectangularTexture(renderer, texture);
cubemaps.set(texture, renderTarget);
texture.addEventListener("dispose", onTextureDispose);
return mapTextureMapping(renderTarget.texture, texture.mapping);
} else {
return null;
}
}
}
}
return texture;
}
function onTextureDispose(event) {
const texture = event.target;
texture.removeEventListener("dispose", onTextureDispose);
const cubemap = cubemaps.get(texture);
if (cubemap !== void 0) {
cubemaps.delete(texture);
cubemap.dispose();
}
}
function dispose() {
cubemaps = /* @__PURE__ */ new WeakMap();
}
return {
get,
dispose
};
}
function _createPlanes(lodMax) {
const lodPlanes = [];
const sizeLods = [];
const sigmas = [];
let lod = lodMax;
const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
for (let i = 0; i < totalLods; i++) {
const sizeLod = Math.pow(2, lod);
sizeLods.push(sizeLod);
let sigma = 1 / sizeLod;
if (i > lodMax - LOD_MIN) {
sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
} else if (i === 0) {
sigma = 0;
}
sigmas.push(sigma);
const texelSize = 1 / (sizeLod - 2);
const min = -texelSize;
const max = 1 + texelSize;
const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
const cubeFaces = 6;
const vertices = 6;
const positionSize = 3;
const uvSize = 2;
const faceIndexSize = 1;
const position = new Float32Array(positionSize * vertices * cubeFaces);
const uv = new Float32Array(uvSize * vertices * cubeFaces);
const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
for (let face = 0; face < cubeFaces; face++) {
const x = face % 3 * 2 / 3 - 1;
const y = face > 2 ? 0 : -1;
const coordinates = [
x,
y,
0,
x + 2 / 3,
y,
0,
x + 2 / 3,
y + 1,
0,
x,
y,
0,
x + 2 / 3,
y + 1,
0,
x,
y + 1,
0
];
position.set(coordinates, positionSize * vertices * face);
uv.set(uv1, uvSize * vertices * face);
const fill = [face, face, face, face, face, face];
faceIndex.set(fill, faceIndexSize * vertices * face);
}
const planes = new BufferGeometry();
planes.setAttribute("position", new BufferAttribute(position, positionSize));
planes.setAttribute("uv", new BufferAttribute(uv, uvSize));
planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize));
lodPlanes.push(planes);
if (lod > LOD_MIN) {
lod--;
}
}
return { lodPlanes, sizeLods, sigmas };
}
function _createRenderTarget(width, height, params) {
const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
cubeUVRenderTarget.texture.name = "PMREM.cubeUv";
cubeUVRenderTarget.scissorTest = true;
return cubeUVRenderTarget;
}
function _setViewport(target, x, y, width, height) {
target.viewport.set(x, y, width, height);
target.scissor.set(x, y, width, height);
}
function _getBlurShader(lodMax, width, height) {
const weights = new Float32Array(MAX_SAMPLES);
const poleAxis = new Vector3(0, 1, 0);
const shaderMaterial = new ShaderMaterial({
name: "SphericalGaussianBlur",
defines: {
"n": MAX_SAMPLES,
"CUBEUV_TEXEL_WIDTH": 1 / width,
"CUBEUV_TEXEL_HEIGHT": 1 / height,
"CUBEUV_MAX_MIP": `${lodMax}.0`
},
uniforms: {
"envMap": { value: null },
"samples": { value: 1 },
"weights": { value: weights },
"latitudinal": { value: false },
"dTheta": { value: 0 },
"mipInt": { value: 0 },
"poleAxis": { value: poleAxis }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: (
/* glsl */
`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform int samples;
uniform float weights[ n ];
uniform bool latitudinal;
uniform float dTheta;
uniform float mipInt;
uniform vec3 poleAxis;
#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>
vec3 getSample( float theta, vec3 axis ) {
float cosTheta = cos( theta );
// Rodrigues' axis-angle rotation
vec3 sampleDirection = vOutputDirection * cosTheta
+ cross( axis, vOutputDirection ) * sin( theta )
+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
return bilinearCubeUV( envMap, sampleDirection, mipInt );
}
void main() {
vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
}
axis = normalize( axis );
gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
for ( int i = 1; i < n; i++ ) {
if ( i >= samples ) {
break;
}
float theta = dTheta * float( i );
gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
}
}
`
),
blending: NoBlending,
depthTest: false,
depthWrite: false
});
return shaderMaterial;
}
function _getEquirectMaterial() {
return new ShaderMaterial({
name: "EquirectangularToCubeUV",
uniforms: {
"envMap": { value: null }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: (
/* glsl */
`
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
#include <common>
void main() {
vec3 outputDirection = normalize( vOutputDirection );
vec2 uv = equirectUv( outputDirection );
gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
}
`
),
blending: NoBlending,
depthTest: false,
depthWrite: false
});
}
function _getCubemapMaterial() {
return new ShaderMaterial({
name: "CubemapToCubeUV",
uniforms: {
"envMap": { value: null },
"flipEnvMap": { value: -1 }
},
vertexShader: _getCommonVertexShader(),
fragmentShader: (
/* glsl */
`
precision mediump float;
precision mediump int;
uniform float flipEnvMap;
varying vec3 vOutputDirection;
uniform samplerCube envMap;
void main() {
gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
}
`
),
blending: NoBlending,
depthTest: false,
depthWrite: false
});
}
function _getCommonVertexShader() {
return (
/* glsl */
`
precision mediump float;
precision mediump int;
attribute float faceIndex;
varying vec3 vOutputDirection;
// RH coordinate system; PMREM face-indexing convention
vec3 getDirection( vec2 uv, float face ) {
uv = 2.0 * uv - 1.0;
vec3 direction = vec3( uv, 1.0 );
if ( face == 0.0 ) {
direction = direction.zyx; // ( 1, v, u ) pos x
} else if ( face == 1.0 ) {
direction = direction.xzy;
direction.xz *= -1.0; // ( -u, 1, -v ) pos y
} else if ( face == 2.0 ) {
direction.x *= -1.0; // ( -u, v, 1 ) pos z
} else if ( face == 3.0 ) {
direction = direction.zyx;
direction.xz *= -1.0; // ( -1, v, -u ) neg x
} else if ( face == 4.0 ) {
direction = direction.xzy;
direction.xy *= -1.0; // ( -u, -1, v ) neg y
} else if ( face == 5.0 ) {
direction.z *= -1.0; // ( u, v, -1 ) neg z
}
return direction;
}
void main() {
vOutputDirection = getDirection( uv, faceIndex );
gl_Position = vec4( position, 1.0 );
}
`
);
}
function WebGLCubeUVMaps(renderer) {
let cubeUVmaps = /* @__PURE__ */ new WeakMap();
let pmremGenerator = null;
function get(texture) {
if (texture && texture.isTexture) {
const mapping = texture.mapping;
const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
if (isEquirectMap || isCubeMap) {
if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
texture.needsPMREMUpdate = false;
let renderTarget = cubeUVmaps.get(texture);
if (pmremGenerator === null)
pmremGenerator = new PMREMGenerator(renderer);
renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
cubeUVmaps.set(texture, renderTarget);
return renderTarget.texture;
} else {
if (cubeUVmaps.has(texture)) {
return cubeUVmaps.get(texture).texture;
} else {
const image = texture.image;
if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
if (pmremGenerator === null)
pmremGenerator = new PMREMGenerator(renderer);
const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
cubeUVmaps.set(texture, renderTarget);
texture.addEventListener("dispose", onTextureDispose);
return renderTarget.texture;
} else {
return null;
}
}
}
}
}
return texture;
}
function isCubeTextureComplete(image) {
let count = 0;
const length = 6;
for (let i = 0; i < length; i++) {
if (image[i] !== void 0)
count++;
}
return count === length;
}
function onTextureDispose(event) {
const texture = event.target;
texture.removeEventListener("dispose", onTextureDispose);
const cubemapUV = cubeUVmaps.get(texture);
if (cubemapUV !== void 0) {
cubeUVmaps.delete(texture);
cubemapUV.dispose();
}
}
function dispose() {
cubeUVmaps = /* @__PURE__ */ new WeakMap();
if (pmremGenerator !== null) {
pmremGenerator.dispose();
pmremGenerator = null;
}
}
return {
get,
dispose
};
}
function WebGLExtensions(gl) {
const extensions = {};
function getExtension(name) {
if (extensions[name] !== void 0) {
return extensions[name];
}
let extension;
switch (name) {
case "WEBGL_depth_texture":
extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture");
break;
case "EXT_texture_filter_anisotropic":
extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
break;
case "WEBGL_compressed_texture_s3tc":
extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
break;
case "WEBGL_compressed_texture_pvrtc":
extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
break;
default:
extension = gl.getExtension(name);
}
extensions[name] = extension;
return extension;
}
return {
has: function(name) {
return getExtension(name) !== null;
},
init: function(capabilities) {
if (capabilities.isWebGL2) {
getExtension("EXT_color_buffer_float");
getExtension("WEBGL_clip_cull_distance");
} else {
getExtension("WEBGL_depth_texture");
getExtension("OES_texture_float");
getExtension("OES_texture_half_float");
getExtension("OES_texture_half_float_linear");
getExtension("OES_standard_derivatives");
getExtension("OES_element_index_uint");
getExtension("OES_vertex_array_object");
getExtension("ANGLE_instanced_arrays");
}
getExtension("OES_texture_float_linear");
getExtension("EXT_color_buffer_half_float");
getExtension("WEBGL_multisampled_render_to_texture");
},
get: function(name) {
const extension = getExtension(name);
if (extension === null) {
console.warn("THREE.WebGLRenderer: " + name + " extension not supported.");
}
return extension;
}
};
}
function WebGLGeometries(gl, attributes, info, bindingStates) {
const geometries = {};
const wireframeAttributes = /* @__PURE__ */ new WeakMap();
function onGeometryDispose(event) {
const geometry = event.target;
if (geometry.index !== null) {
attributes.remove(geometry.index);
}
for (const name in geometry.attributes) {
attributes.remove(geometry.attributes[name]);
}
for (const name in geometry.morphAttributes) {
const array = geometry.morphAttributes[name];
for (let i = 0, l = array.length; i < l; i++) {
attributes.remove(array[i]);
}
}
geometry.removeEventListener("dispose", onGeometryDispose);
delete geometries[geometry.id];
const attribute = wireframeAttributes.get(geometry);
if (attribute) {
attributes.remove(attribute);
wireframeAttributes.delete(geometry);
}
bindingStates.releaseStatesOfGeometry(geometry);
if (geometry.isInstancedBufferGeometry === true) {
delete geometry._maxInstanceCount;
}
info.memory.geometries--;
}
function get(object, geometry) {
if (geometries[geometry.id] === true)
return geometry;
geometry.addEventListener("dispose", onGeometryDispose);
geometries[geometry.id] = true;
info.memory.geometries++;
return geometry;
}
function update(geometry) {
const geometryAttributes = geometry.attributes;
for (const name in geometryAttributes) {
attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
}
const morphAttributes = geometry.morphAttributes;
for (const name in morphAttributes) {
const array = morphAttributes[name];
for (let i = 0, l = array.length; i < l; i++) {
attributes.update(array[i], gl.ARRAY_BUFFER);
}
}
}
function updateWireframeAttribute(geometry) {
const indices = [];
const geometryIndex = geometry.index;
const geometryPosition = geometry.attributes.position;
let version = 0;
if (geometryIndex !== null) {
const array = geometryIndex.array;
version = geometryIndex.version;
for (let i = 0, l = array.length; i < l; i += 3) {
const a = array[i + 0];
const b = array[i + 1];
const c = array[i + 2];
indices.push(a, b, b, c, c, a);
}
} else if (geometryPosition !== void 0) {
const array = geometryPosition.array;
version = geometryPosition.version;
for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
const a = i + 0;
const b = i + 1;
const c = i + 2;
indices.push(a, b, b, c, c, a);
}
} else {
return;
}
const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
attribute.version = version;
const previousAttribute = wireframeAttributes.get(geometry);
if (previousAttribute)
attributes.remove(previousAttribute);
wireframeAttributes.set(geometry, attribute);
}
function getWireframeAttribute(geometry) {
const currentAttribute = wireframeAttributes.get(geometry);
if (currentAttribute) {
const geometryIndex = geometry.index;
if (geometryIndex !== null) {
if (currentAttribute.version < geometryIndex.version) {
updateWireframeAttribute(geometry);
}
}
} else {
updateWireframeAttribute(geometry);
}
return wireframeAttributes.get(geometry);
}
return {
get,
update,
getWireframeAttribute
};
}
function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
const isWebGL2 = capabilities.isWebGL2;
let mode;
function setMode(value) {
mode = value;
}
let type, bytesPerElement;
function setIndex(value) {
type = value.type;
bytesPerElement = value.bytesPerElement;
}
function render(start, count) {
gl.drawElements(mode, count, type, start * bytesPerElement);
info.update(count, mode, 1);
}
function renderInstances(start, count, primcount) {
if (primcount === 0)
return;
let extension, methodName;
if (isWebGL2) {
extension = gl;
methodName = "drawElementsInstanced";
} else {
extension = extensions.get("ANGLE_instanced_arrays");
methodName = "drawElementsInstancedANGLE";
if (extension === null) {
console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");
return;
}
}
extension[methodName](mode, count, type, start * bytesPerElement, primcount);
info.update(count, mode, primcount);
}
function renderMultiDraw(starts, counts, drawCount) {
if (drawCount === 0)
return;
const extension = extensions.get("WEBGL_multi_draw");
if (extension === null) {
for (let i = 0; i < drawCount; i++) {
this.render(starts[i] / bytesPerElement, counts[i]);
}
} else {
extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount);
let elementCount = 0;
for (let i = 0; i < drawCount; i++) {
elementCount += counts[i];
}
info.update(elementCount, mode, 1);
}
}
this.setMode = setMode;
this.setIndex = setIndex;
this.render = render;
this.renderInstances = renderInstances;
this.renderMultiDraw = renderMultiDraw;
}
function WebGLInfo(gl) {
const memory = {
geometries: 0,
textures: 0
};
const render = {
frame: 0,
calls: 0,
triangles: 0,
points: 0,
lines: 0
};
function update(count, mode, instanceCount) {
render.calls++;
switch (mode) {
case gl.TRIANGLES:
render.triangles += instanceCount * (count / 3);
break;
case gl.LINES:
render.lines += instanceCount * (count / 2);
break;
case gl.LINE_STRIP:
render.lines += instanceCount * (count - 1);
break;
case gl.LINE_LOOP:
render.lines += instanceCount * count;
break;
case gl.POINTS:
render.points += instanceCount * count;
break;
default:
console.error("THREE.WebGLInfo: Unknown draw mode:", mode);
break;
}
}
function reset() {
render.calls = 0;
render.triangles = 0;
render.points = 0;
render.lines = 0;
}
return {
memory,
render,
programs: null,
autoReset: true,
reset,
update
};
}
function numericalSort(a, b) {
return a[0] - b[0];
}
function absNumericalSort(a, b) {
return Math.abs(b[1]) - Math.abs(a[1]);
}
function WebGLMorphtargets(gl, capabilities, textures) {
const influencesList = {};
const morphInfluences = new Float32Array(8);
const morphTextures = /* @__PURE__ */ new WeakMap();
const morph = new Vector4();
const workInfluences = [];
for (let i = 0; i < 8; i++) {
workInfluences[i] = [i, 0];
}
function update(object, geometry, program) {
const objectInfluences = object.morphTargetInfluences;
if (capabilities.isWebGL2 === true) {
const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0;
let entry = morphTextures.get(geometry);
if (entry === void 0 || entry.count !== morphTargetsCount) {
let disposeTexture = function() {
texture.dispose();
morphTextures.delete(geometry);
geometry.removeEventListener("dispose", disposeTexture);
};
if (entry !== void 0)
entry.texture.dispose();
const hasMorphPosition = geometry.morphAttributes.position !== void 0;
const hasMorphNormals = geometry.morphAttributes.normal !== void 0;
const hasMorphColors = geometry.morphAttributes.color !== void 0;
const morphTargets = geometry.morphAttributes.position || [];
const morphNormals = geometry.morphAttributes.normal || [];
const morphColors = geometry.morphAttributes.color || [];
let vertexDataCount = 0;
if (hasMorphPosition === true)
vertexDataCount = 1;
if (hasMorphNormals === true)
vertexDataCount = 2;
if (hasMorphColors === true)
vertexDataCount = 3;
let width = geometry.attributes.position.count * vertexDataCount;
let height = 1;
if (width > capabilities.maxTextureSize) {
height = Math.ceil(width / capabilities.maxTextureSize);
width = capabilities.maxTextureSize;
}
const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
texture.type = FloatType;
texture.needsUpdate = true;
const vertexDataStride = vertexDataCount * 4;
for (let i = 0; i < morphTargetsCount; i++) {
const morphTarget = morphTargets[i];
const morphNormal = morphNormals[i];
const morphColor = morphColors[i];
const offset = width * height * 4 * i;
for (let j = 0; j < morphTarget.count; j++) {
const stride = j * vertexDataStride;
if (hasMorphPosition === true) {
morph.fromBufferAttribute(morphTarget, j);
buffer[offset + stride + 0] = morph.x;
buffer[offset + stride + 1] = morph.y;
buffer[offset + stride + 2] = morph.z;
buffer[offset + stride + 3] = 0;
}
if (hasMorphNormals === true) {
morph.fromBufferAttribute(morphNormal, j);
buffer[offset + stride + 4] = morph.x;
buffer[offset + stride + 5] = morph.y;
buffer[offset + stride + 6] = morph.z;
buffer[offset + stride + 7] = 0;
}
if (hasMorphColors === true) {
morph.fromBufferAttribute(morphColor, j);
buffer[offset + stride + 8] = morph.x;
buffer[offset + stride + 9] = morph.y;
buffer[offset + stride + 10] = morph.z;
buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
}
}
}
entry = {
count: morphTargetsCount,
texture,
size: new Vector2(width, height)
};
morphTextures.set(geometry, entry);
geometry.addEventListener("dispose", disposeTexture);
}
let morphInfluencesSum = 0;
for (let i = 0; i < objectInfluences.length; i++) {
morphInfluencesSum += objectInfluences[i];
}
const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence);
program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences);
program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures);
program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size);
} else {
const length = objectInfluences === void 0 ? 0 : objectInfluences.length;
let influences = influencesList[geometry.id];
if (influences === void 0 || influences.length !== length) {
influences = [];
for (let i = 0; i < length; i++) {
influences[i] = [i, 0];
}
influencesList[geometry.id] = influences;
}
for (let i = 0; i < length; i++) {
const influence = influences[i];
influence[0] = i;
influence[1] = objectInfluences[i];
}
influences.sort(absNumericalSort);
for (let i = 0; i < 8; i++) {
if (i < length && influences[i][1]) {
workInfluences[i][0] = influences[i][0];
workInfluences[i][1] = influences[i][1];
} else {
workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
workInfluences[i][1] = 0;
}
}
workInfluences.sort(numericalSort);
const morphTargets = geometry.morphAttributes.position;
const morphNormals = geometry.morphAttributes.normal;
let morphInfluencesSum = 0;
for (let i = 0; i < 8; i++) {
const influence = workInfluences[i];
const index = influence[0];
const value = influence[1];
if (index !== Number.MAX_SAFE_INTEGER && value) {
if (morphTargets && geometry.getAttribute("morphTarget" + i) !== morphTargets[index]) {
geometry.setAttribute("morphTarget" + i, morphTargets[index]);
}
if (morphNormals && geometry.getAttribute("morphNormal" + i) !== morphNormals[index]) {
geometry.setAttribute("morphNormal" + i, morphNormals[index]);
}
morphInfluences[i] = value;
morphInfluencesSum += value;
} else {
if (morphTargets && geometry.hasAttribute("morphTarget" + i) === true) {
geometry.deleteAttribute("morphTarget" + i);
}
if (morphNormals && geometry.hasAttribute("morphNormal" + i) === true) {
geometry.deleteAttribute("morphNormal" + i);
}
morphInfluences[i] = 0;
}
}
const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence);
program.getUniforms().setValue(gl, "morphTargetInfluences", morphInfluences);
}
}
return {
update
};
}
function WebGLObjects(gl, geometries, attributes, info) {
let updateMap = /* @__PURE__ */ new WeakMap();
function update(object) {
const frame = info.render.frame;
const geometry = object.geometry;
const buffergeometry = geometries.get(object, geometry);
if (updateMap.get(buffergeometry) !== frame) {
geometries.update(buffergeometry);
updateMap.set(buffergeometry, frame);
}
if (object.isInstancedMesh) {
if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) {
object.addEventListener("dispose", onInstancedMeshDispose);
}
if (updateMap.get(object) !== frame) {
attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
if (object.instanceColor !== null) {
attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
}
updateMap.set(object, frame);
}
}
if (object.isSkinnedMesh) {
const skeleton = object.skeleton;
if (updateMap.get(skeleton) !== frame) {
skeleton.update();
updateMap.set(skeleton, frame);
}
}
return buffergeometry;
}
function dispose() {
updateMap = /* @__PURE__ */ new WeakMap();
}
function onInstancedMeshDispose(event) {
const instancedMesh = event.target;
instancedMesh.removeEventListener("dispose", onInstancedMeshDispose);
attributes.remove(instancedMesh.instanceMatrix);
if (instancedMesh.instanceColor !== null)
attributes.remove(instancedMesh.instanceColor);
}
return {
update,
dispose
};
}
function flatten(array, nBlocks, blockSize) {
const firstElem = array[0];
if (firstElem <= 0 || firstElem > 0)
return array;
const n = nBlocks * blockSize;
let r = arrayCacheF32[n];
if (r === void 0) {
r = new Float32Array(n);
arrayCacheF32[n] = r;
}
if (nBlocks !== 0) {
firstElem.toArray(r, 0);
for (let i = 1, offset = 0; i !== nBlocks; ++i) {
offset += blockSize;
array[i].toArray(r, offset);
}
}
return r;
}
function arraysEqual(a, b) {
if (a.length !== b.length)
return false;
for (let i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i])
return false;
}
return true;
}
function copyArray(a, b) {
for (let i = 0, l = b.length; i < l; i++) {
a[i] = b[i];
}
}
function allocTexUnits(textures, n) {
let r = arrayCacheI32[n];
if (r === void 0) {
r = new Int32Array(n);
arrayCacheI32[n] = r;
}
for (let i = 0; i !== n; ++i) {
r[i] = textures.allocateTextureUnit();
}
return r;
}
function setValueV1f(gl, v2) {
const cache = this.cache;
if (cache[0] === v2)
return;
gl.uniform1f(this.addr, v2);
cache[0] = v2;
}
function setValueV2f(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y) {
gl.uniform2f(this.addr, v2.x, v2.y);
cache[0] = v2.x;
cache[1] = v2.y;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform2fv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV3f(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) {
gl.uniform3f(this.addr, v2.x, v2.y, v2.z);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
}
} else if (v2.r !== void 0) {
if (cache[0] !== v2.r || cache[1] !== v2.g || cache[2] !== v2.b) {
gl.uniform3f(this.addr, v2.r, v2.g, v2.b);
cache[0] = v2.r;
cache[1] = v2.g;
cache[2] = v2.b;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform3fv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV4f(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) {
gl.uniform4f(this.addr, v2.x, v2.y, v2.z, v2.w);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
cache[3] = v2.w;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform4fv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueM2(gl, v2) {
const cache = this.cache;
const elements = v2.elements;
if (elements === void 0) {
if (arraysEqual(cache, v2))
return;
gl.uniformMatrix2fv(this.addr, false, v2);
copyArray(cache, v2);
} else {
if (arraysEqual(cache, elements))
return;
mat2array.set(elements);
gl.uniformMatrix2fv(this.addr, false, mat2array);
copyArray(cache, elements);
}
}
function setValueM3(gl, v2) {
const cache = this.cache;
const elements = v2.elements;
if (elements === void 0) {
if (arraysEqual(cache, v2))
return;
gl.uniformMatrix3fv(this.addr, false, v2);
copyArray(cache, v2);
} else {
if (arraysEqual(cache, elements))
return;
mat3array.set(elements);
gl.uniformMatrix3fv(this.addr, false, mat3array);
copyArray(cache, elements);
}
}
function setValueM4(gl, v2) {
const cache = this.cache;
const elements = v2.elements;
if (elements === void 0) {
if (arraysEqual(cache, v2))
return;
gl.uniformMatrix4fv(this.addr, false, v2);
copyArray(cache, v2);
} else {
if (arraysEqual(cache, elements))
return;
mat4array.set(elements);
gl.uniformMatrix4fv(this.addr, false, mat4array);
copyArray(cache, elements);
}
}
function setValueV1i(gl, v2) {
const cache = this.cache;
if (cache[0] === v2)
return;
gl.uniform1i(this.addr, v2);
cache[0] = v2;
}
function setValueV2i(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y) {
gl.uniform2i(this.addr, v2.x, v2.y);
cache[0] = v2.x;
cache[1] = v2.y;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform2iv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV3i(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) {
gl.uniform3i(this.addr, v2.x, v2.y, v2.z);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform3iv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV4i(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) {
gl.uniform4i(this.addr, v2.x, v2.y, v2.z, v2.w);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
cache[3] = v2.w;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform4iv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV1ui(gl, v2) {
const cache = this.cache;
if (cache[0] === v2)
return;
gl.uniform1ui(this.addr, v2);
cache[0] = v2;
}
function setValueV2ui(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y) {
gl.uniform2ui(this.addr, v2.x, v2.y);
cache[0] = v2.x;
cache[1] = v2.y;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform2uiv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV3ui(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) {
gl.uniform3ui(this.addr, v2.x, v2.y, v2.z);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform3uiv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueV4ui(gl, v2) {
const cache = this.cache;
if (v2.x !== void 0) {
if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) {
gl.uniform4ui(this.addr, v2.x, v2.y, v2.z, v2.w);
cache[0] = v2.x;
cache[1] = v2.y;
cache[2] = v2.z;
cache[3] = v2.w;
}
} else {
if (arraysEqual(cache, v2))
return;
gl.uniform4uiv(this.addr, v2);
copyArray(cache, v2);
}
}
function setValueT1(gl, v2, textures) {
const cache = this.cache;
const unit = textures.allocateTextureUnit();
if (cache[0] !== unit) {
gl.uniform1i(this.addr, unit);
cache[0] = unit;
}
const emptyTexture2D = this.type === gl.SAMPLER_2D_SHADOW ? emptyShadowTexture : emptyTexture;
textures.setTexture2D(v2 || emptyTexture2D, unit);
}
function setValueT3D1(gl, v2, textures) {
const cache = this.cache;
const unit = textures.allocateTextureUnit();
if (cache[0] !== unit) {
gl.uniform1i(this.addr, unit);
cache[0] = unit;
}
textures.setTexture3D(v2 || empty3dTexture, unit);
}
function setValueT6(gl, v2, textures) {
const cache = this.cache;
const unit = textures.allocateTextureUnit();
if (cache[0] !== unit) {
gl.uniform1i(this.addr, unit);
cache[0] = unit;
}
textures.setTextureCube(v2 || emptyCubeTexture, unit);
}
function setValueT2DArray1(gl, v2, textures) {
const cache = this.cache;
const unit = textures.allocateTextureUnit();
if (cache[0] !== unit) {
gl.uniform1i(this.addr, unit);
cache[0] = unit;
}
textures.setTexture2DArray(v2 || emptyArrayTexture, unit);
}
function getSingularSetter(type) {
switch (type) {
case 5126:
return setValueV1f;
case 35664:
return setValueV2f;
case 35665:
return setValueV3f;
case 35666:
return setValueV4f;
case 35674:
return setValueM2;
case 35675:
return setValueM3;
case 35676:
return setValueM4;
case 5124:
case 35670:
return setValueV1i;
case 35667:
case 35671:
return setValueV2i;
case 35668:
case 35672:
return setValueV3i;
case 35669:
case 35673:
return setValueV4i;
case 5125:
return setValueV1ui;
case 36294:
return setValueV2ui;
case 36295:
return setValueV3ui;
case 36296:
return setValueV4ui;
case 35678:
case 36198:
case 36298:
case 36306:
case 35682:
return setValueT1;
case 35679:
case 36299:
case 36307:
return setValueT3D1;
case 35680:
case 36300:
case 36308:
case 36293:
return setValueT6;
case 36289:
case 36303:
case 36311:
case 36292:
return setValueT2DArray1;
}
}
function setValueV1fArray(gl, v2) {
gl.uniform1fv(this.addr, v2);
}
function setValueV2fArray(gl, v2) {
const data = flatten(v2, this.size, 2);
gl.uniform2fv(this.addr, data);
}
function setValueV3fArray(gl, v2) {
const data = flatten(v2, this.size, 3);
gl.uniform3fv(this.addr, data);
}
function setValueV4fArray(gl, v2) {
const data = flatten(v2, this.size, 4);
gl.uniform4fv(this.addr, data);
}
function setValueM2Array(gl, v2) {
const data = flatten(v2, this.size, 4);
gl.uniformMatrix2fv(this.addr, false, data);
}
function setValueM3Array(gl, v2) {
const data = flatten(v2, this.size, 9);
gl.uniformMatrix3fv(this.addr, false, data);
}
function setValueM4Array(gl, v2) {
const data = flatten(v2, this.size, 16);
gl.uniformMatrix4fv(this.addr, false, data);
}
function setValueV1iArray(gl, v2) {
gl.uniform1iv(this.addr, v2);
}
function setValueV2iArray(gl, v2) {
gl.uniform2iv(this.addr, v2);
}
function setValueV3iArray(gl, v2) {
gl.uniform3iv(this.addr, v2);
}
function setValueV4iArray(gl, v2) {
gl.uniform4iv(this.addr, v2);
}
function setValueV1uiArray(gl, v2) {
gl.uniform1uiv(this.addr, v2);
}
function setValueV2uiArray(gl, v2) {
gl.uniform2uiv(this.addr, v2);
}
function setValueV3uiArray(gl, v2) {
gl.uniform3uiv(this.addr, v2);
}
function setValueV4uiArray(gl, v2) {
gl.uniform4uiv(this.addr, v2);
}
function setValueT1Array(gl, v2, textures) {
const cache = this.cache;
const n = v2.length;
const units = allocTexUnits(textures, n);
if (!arraysEqual(cache, units)) {
gl.uniform1iv(this.addr, units);
copyArray(cache, units);
}
for (let i = 0; i !== n; ++i) {
textures.setTexture2D(v2[i] || emptyTexture, units[i]);
}
}
function setValueT3DArray(gl, v2, textures) {
const cache = this.cache;
const n = v2.length;
const units = allocTexUnits(textures, n);
if (!arraysEqual(cache, units)) {
gl.uniform1iv(this.addr, units);
copyArray(cache, units);
}
for (let i = 0; i !== n; ++i) {
textures.setTexture3D(v2[i] || empty3dTexture, units[i]);
}
}
function setValueT6Array(gl, v2, textures) {
const cache = this.cache;
const n = v2.length;
const units = allocTexUnits(textures, n);
if (!arraysEqual(cache, units)) {
gl.uniform1iv(this.addr, units);
copyArray(cache, units);
}
for (let i = 0; i !== n; ++i) {
textures.setTextureCube(v2[i] || emptyCubeTexture, units[i]);
}
}
function setValueT2DArrayArray(gl, v2, textures) {
const cache = this.cache;
const n = v2.length;
const units = allocTexUnits(textures, n);
if (!arraysEqual(cache, units)) {
gl.uniform1iv(this.addr, units);
copyArray(cache, units);
}
for (let i = 0; i !== n; ++i) {
textures.setTexture2DArray(v2[i] || emptyArrayTexture, units[i]);
}
}
function getPureArraySetter(type) {
switch (type) {
case 5126:
return setValueV1fArray;
case 35664:
return setValueV2fArray;
case 35665:
return setValueV3fArray;
case 35666:
return setValueV4fArray;
case 35674:
return setValueM2Array;
case 35675:
return setValueM3Array;
case 35676:
return setValueM4Array;
case 5124:
case 35670:
return setValueV1iArray;
case 35667:
case 35671:
return setValueV2iArray;
case 35668:
case 35672:
return setValueV3iArray;
case 35669:
case 35673:
return setValueV4iArray;
case 5125:
return setValueV1uiArray;
case 36294:
return setValueV2uiArray;
case 36295:
return setValueV3uiArray;
case 36296:
return setValueV4uiArray;
case 35678:
case 36198:
case 36298:
case 36306:
case 35682:
return setValueT1Array;
case 35679:
case 36299:
case 36307:
return setValueT3DArray;
case 35680:
case 36300:
case 36308:
case 36293:
return setValueT6Array;
case 36289:
case 36303:
case 36311:
case 36292:
return setValueT2DArrayArray;
}
}
function addUniform(container, uniformObject) {
container.seq.push(uniformObject);
container.map[uniformObject.id] = uniformObject;
}
function parseUniform(activeInfo, addr, container) {
const path = activeInfo.name, pathLength = path.length;
RePathPart.lastIndex = 0;
while (true) {
const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex;
let id = match[1];
const idIsIndex = match[2] === "]", subscript = match[3];
if (idIsIndex)
id = id | 0;
if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) {
addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
break;
} else {
const map = container.map;
let next = map[id];
if (next === void 0) {
next = new StructuredUniform(id);
addUniform(container, next);
}
container = next;
}
}
}
function WebGLShader(gl, type, string) {
const shader = gl.createShader(type);
gl.shaderSource(shader, string);
gl.compileShader(shader);
return shader;
}
function handleSource(string, errorLine) {
const lines = string.split("\n");
const lines2 = [];
const from = Math.max(errorLine - 6, 0);
const to = Math.min(errorLine + 6, lines.length);
for (let i = from; i < to; i++) {
const line = i + 1;
lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`);
}
return lines2.join("\n");
}
function getEncodingComponents(colorSpace) {
const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace);
const encodingPrimaries = ColorManagement.getPrimaries(colorSpace);
let gamutMapping;
if (workingPrimaries === encodingPrimaries) {
gamutMapping = "";
} else if (workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries) {
gamutMapping = "LinearDisplayP3ToLinearSRGB";
} else if (workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries) {
gamutMapping = "LinearSRGBToLinearDisplayP3";
}
switch (colorSpace) {
case LinearSRGBColorSpace:
case LinearDisplayP3ColorSpace:
return [gamutMapping, "LinearTransferOETF"];
case SRGBColorSpace:
case DisplayP3ColorSpace:
return [gamutMapping, "sRGBTransferOETF"];
default:
console.warn("THREE.WebGLProgram: Unsupported color space:", colorSpace);
return [gamutMapping, "LinearTransferOETF"];
}
}
function getShaderErrors(gl, shader, type) {
const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
const errors = gl.getShaderInfoLog(shader).trim();
if (status && errors === "")
return "";
const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
if (errorMatches) {
const errorLine = parseInt(errorMatches[1]);
return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine);
} else {
return errors;
}
}
function getTexelEncodingFunction(functionName, colorSpace) {
const components = getEncodingComponents(colorSpace);
return `vec4 ${functionName}( vec4 value ) { return ${components[0]}( ${components[1]}( value ) ); }`;
}
function getToneMappingFunction(functionName, toneMapping) {
let toneMappingName;
switch (toneMapping) {
case LinearToneMapping:
toneMappingName = "Linear";
break;
case ReinhardToneMapping:
toneMappingName = "Reinhard";
break;
case CineonToneMapping:
toneMappingName = "OptimizedCineon";
break;
case ACESFilmicToneMapping:
toneMappingName = "ACESFilmic";
break;
case AgXToneMapping:
toneMappingName = "AgX";
break;
case CustomToneMapping:
toneMappingName = "Custom";
break;
default:
console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping);
toneMappingName = "Linear";
}
return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
}
function generateExtensions(parameters) {
const chunks = [
parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === "physical" ? "#extension GL_OES_standard_derivatives : enable" : "",
(parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? "#extension GL_EXT_frag_depth : enable" : "",
parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? "#extension GL_EXT_draw_buffers : require" : "",
(parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? "#extension GL_EXT_shader_texture_lod : enable" : ""
];
return chunks.filter(filterEmptyLine).join("\n");
}
function generateVertexExtensions(parameters) {
const chunks = [
parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : ""
];
return chunks.filter(filterEmptyLine).join("\n");
}
function generateDefines(defines) {
const chunks = [];
for (const name in defines) {
const value = defines[name];
if (value === false)
continue;
chunks.push("#define " + name + " " + value);
}
return chunks.join("\n");
}
function fetchAttributeLocations(gl, program) {
const attributes = {};
const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (let i = 0; i < n; i++) {
const info = gl.getActiveAttrib(program, i);
const name = info.name;
let locationSize = 1;
if (info.type === gl.FLOAT_MAT2)
locationSize = 2;
if (info.type === gl.FLOAT_MAT3)
locationSize = 3;
if (info.type === gl.FLOAT_MAT4)
locationSize = 4;
attributes[name] = {
type: info.type,
location: gl.getAttribLocation(program, name),
locationSize
};
}
return attributes;
}
function filterEmptyLine(string) {
return string !== "";
}
function replaceLightNums(string, parameters) {
const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
}
function replaceClippingPlaneNums(string, parameters) {
return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
}
function resolveIncludes(string) {
return string.replace(includePattern, includeReplacer);
}
function includeReplacer(match, include) {
let string = ShaderChunk[include];
if (string === void 0) {
const newInclude = shaderChunkMap.get(include);
if (newInclude !== void 0) {
string = ShaderChunk[newInclude];
console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude);
} else {
throw new Error("Can not resolve #include <" + include + ">");
}
}
return resolveIncludes(string);
}
function unrollLoops(string) {
return string.replace(unrollLoopPattern, loopReplacer);
}
function loopReplacer(match, start, end, snippet) {
let string = "";
for (let i = parseInt(start); i < parseInt(end); i++) {
string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i);
}
return string;
}
function generatePrecision(parameters) {
let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
if (parameters.precision === "highp") {
precisionstring += "\n#define HIGH_PRECISION";
} else if (parameters.precision === "mediump") {
precisionstring += "\n#define MEDIUM_PRECISION";
} else if (parameters.precision === "lowp") {
precisionstring += "\n#define LOW_PRECISION";
}
return precisionstring;
}
function generateShadowMapTypeDefine(parameters) {
let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
if (parameters.shadowMapType === PCFShadowMap) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
} else if (parameters.shadowMapType === PCFSoftShadowMap) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
} else if (parameters.shadowMapType === VSMShadowMap) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM";
}
return shadowMapTypeDefine;
}
function generateEnvMapTypeDefine(parameters) {
let envMapTypeDefine = "ENVMAP_TYPE_CUBE";
if (parameters.envMap) {
switch (parameters.envMapMode) {
case CubeReflectionMapping:
case CubeRefractionMapping:
envMapTypeDefine = "ENVMAP_TYPE_CUBE";
break;
case CubeUVReflectionMapping:
envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV";
break;
}
}
return envMapTypeDefine;
}
function generateEnvMapModeDefine(parameters) {
let envMapModeDefine = "ENVMAP_MODE_REFLECTION";
if (parameters.envMap) {
switch (parameters.envMapMode) {
case CubeRefractionMapping:
envMapModeDefine = "ENVMAP_MODE_REFRACTION";
break;
}
}
return envMapModeDefine;
}
function generateEnvMapBlendingDefine(parameters) {
let envMapBlendingDefine = "ENVMAP_BLENDING_NONE";
if (parameters.envMap) {
switch (parameters.combine) {
case MultiplyOperation:
envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY";
break;
case MixOperation:
envMapBlendingDefine = "ENVMAP_BLENDING_MIX";
break;
case AddOperation:
envMapBlendingDefine = "ENVMAP_BLENDING_ADD";
break;
}
}
return envMapBlendingDefine;
}
function generateCubeUVSize(parameters) {
const imageHeight = parameters.envMapCubeUVHeight;
if (imageHeight === null)
return null;
const maxMip = Math.log2(imageHeight) - 2;
const texelHeight = 1 / imageHeight;
const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
return { texelWidth, texelHeight, maxMip };
}
function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
const gl = renderer.getContext();
const defines = parameters.defines;
let vertexShader = parameters.vertexShader;
let fragmentShader = parameters.fragmentShader;
const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
const envMapModeDefine = generateEnvMapModeDefine(parameters);
const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
const envMapCubeUVSize = generateCubeUVSize(parameters);
const customExtensions = parameters.isWebGL2 ? "" : generateExtensions(parameters);
const customVertexExtensions = generateVertexExtensions(parameters);
const customDefines = generateDefines(defines);
const program = gl.createProgram();
let prefixVertex, prefixFragment;
let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : "";
if (parameters.isRawShaderMaterial) {
prefixVertex = [
"#define SHADER_TYPE " + parameters.shaderType,
"#define SHADER_NAME " + parameters.shaderName,
customDefines
].filter(filterEmptyLine).join("\n");
if (prefixVertex.length > 0) {
prefixVertex += "\n";
}
prefixFragment = [
customExtensions,
"#define SHADER_TYPE " + parameters.shaderType,
"#define SHADER_NAME " + parameters.shaderName,
customDefines
].filter(filterEmptyLine).join("\n");
if (prefixFragment.length > 0) {
prefixFragment += "\n";
}
} else {
prefixVertex = [
generatePrecision(parameters),
"#define SHADER_TYPE " + parameters.shaderType,
"#define SHADER_NAME " + parameters.shaderName,
customDefines,
parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "",
parameters.batching ? "#define USE_BATCHING" : "",
parameters.instancing ? "#define USE_INSTANCING" : "",
parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "",
parameters.useFog && parameters.fog ? "#define USE_FOG" : "",
parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "",
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.envMap ? "#define " + envMapModeDefine : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.aoMap ? "#define USE_AOMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "",
parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
parameters.anisotropy ? "#define USE_ANISOTROPY" : "",
parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
parameters.metalnessMap ? "#define USE_METALNESSMAP" : "",
parameters.alphaMap ? "#define USE_ALPHAMAP" : "",
parameters.alphaHash ? "#define USE_ALPHAHASH" : "",
parameters.transmission ? "#define USE_TRANSMISSION" : "",
parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "",
parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
//
parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "",
parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "",
parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "",
parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "",
parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "",
parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "",
parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "",
parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "",
parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "",
parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "",
parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "",
parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "",
parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "",
parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "",
parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "",
parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "",
parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "",
parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "",
parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "",
parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "",
parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "",
parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "",
parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "",
//
parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
parameters.vertexUv1s ? "#define USE_UV1" : "",
parameters.vertexUv2s ? "#define USE_UV2" : "",
parameters.vertexUv3s ? "#define USE_UV3" : "",
parameters.pointsUvs ? "#define USE_POINTS_UV" : "",
parameters.flatShading ? "#define FLAT_SHADED" : "",
parameters.skinning ? "#define USE_SKINNING" : "",
parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "",
parameters.morphColors && parameters.isWebGL2 ? "#define USE_MORPHCOLORS" : "",
parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE" : "",
parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "",
parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
parameters.useLegacyLights ? "#define LEGACY_LIGHTS" : "",
parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
"uniform mat4 modelMatrix;",
"uniform mat4 modelViewMatrix;",
"uniform mat4 projectionMatrix;",
"uniform mat4 viewMatrix;",
"uniform mat3 normalMatrix;",
"uniform vec3 cameraPosition;",
"uniform bool isOrthographic;",
"#ifdef USE_INSTANCING",
" attribute mat4 instanceMatrix;&q.........完整代码请登录后点击上方下载按钮下载查看















网友评论0