depthview-r3f-bridge 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/look.js ADDED
@@ -0,0 +1,2223 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // src/lookRuntime.ts
6
+ import * as THREE from "three";
7
+ import { BokehPass } from "three/examples/jsm/postprocessing/BokehPass.js";
8
+ import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
9
+ import { GTAOPass } from "three/examples/jsm/postprocessing/GTAOPass.js";
10
+ import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
11
+ import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
12
+ import { SMAAPass } from "three/examples/jsm/postprocessing/SMAAPass.js";
13
+ import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass.js";
14
+ import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
15
+
16
+ // src/look.ts
17
+ var TONE_MAPPING = {
18
+ none: 0,
19
+ linear: 1,
20
+ reinhard: 2,
21
+ cineon: 3,
22
+ aces: 4,
23
+ agx: 6,
24
+ neutral: 7
25
+ };
26
+ var TONE_MAPPING_MIN_REVISION = {
27
+ agx: 160,
28
+ neutral: 162
29
+ };
30
+ var NEUTRAL_SKY = {
31
+ top: "#2b2f38",
32
+ horizon: "#3c4048",
33
+ ground: "#15161a",
34
+ intensity: 1
35
+ };
36
+ function defaultLook() {
37
+ return {
38
+ version: 1,
39
+ color: { toneMapping: "site", exposure: null },
40
+ quality: { pixelRatio: null, anisotropy: false, supersample: false },
41
+ world: {
42
+ preset: "site",
43
+ strength: 1,
44
+ rotation: 0,
45
+ background: false,
46
+ sky: { ...NEUTRAL_SKY },
47
+ boxes: []
48
+ },
49
+ shadows: { mode: "site", softness: 3, resolution: 2048 },
50
+ materials: [],
51
+ bevel: { mode: "off", amount: 0.06, segments: 4, targets: [] },
52
+ effects: {
53
+ antialias: false,
54
+ ao: { on: false, intensity: 1, radius: 0.5 },
55
+ // Only what is brighter than white glows, and only a little: more reads as a filter.
56
+ bloom: { on: false, strength: 0.15, threshold: 1.1, radius: 0.4 },
57
+ dof: { on: false, focus: 8, aperture: 8e-4, maxBlur: 8e-3 },
58
+ vignette: 0,
59
+ grain: 0
60
+ },
61
+ performance: { adaptive: false, targetFps: 60 },
62
+ adapt: { follow: true, textures: false },
63
+ models: []
64
+ };
65
+ }
66
+ var box = (id, name, azimuth, elevation, width, height, intensity, color = "#ffffff", softness = 0.35) => ({ id, name, azimuth, elevation, width, height, intensity, color, softness });
67
+ var WORLD_PRESETS = {
68
+ studio: {
69
+ label: "Studio",
70
+ hint: "Dark room, three softboxes: the product-shot look for metal and glass.",
71
+ sky: { top: "#1b1d22", horizon: "#2a2d34", ground: "#0c0d10", intensity: 1 },
72
+ boxes: [
73
+ box("key", "Key", -42, 34, 62, 44, 7, "#fff4e6"),
74
+ box("fill", "Fill", 62, 12, 58, 70, 2.2, "#dfeaff", 0.6),
75
+ box("rim", "Rim", 158, 26, 34, 80, 6, "#ffffff", 0.25),
76
+ box("top", "Top", 0, 86, 80, 80, 3, "#ffffff", 0.5),
77
+ // A big dim card in front, so surfaces facing the camera are never left reflecting black.
78
+ box("front", "Front card", 0, 4, 150, 80, 1.1, "#eef1f6", 1)
79
+ ]
80
+ },
81
+ softbox: {
82
+ label: "Softbox",
83
+ hint: "Bright, even light from all sides: clean e-commerce product.",
84
+ sky: { top: "#a9adb5", horizon: "#c3c6cc", ground: "#55575c", intensity: 1 },
85
+ boxes: [
86
+ box("top", "Top", 0, 88, 120, 120, 3.2, "#ffffff", 0.7),
87
+ box("left", "Left", -75, 10, 70, 90, 2.4, "#ffffff", 0.6),
88
+ box("right", "Right", 75, 10, 70, 90, 2.4, "#ffffff", 0.6)
89
+ ]
90
+ },
91
+ sunset: {
92
+ label: "Sunset",
93
+ hint: "Low warm sun, deep blue sky.",
94
+ sky: { top: "#16264d", horizon: "#e2854a", ground: "#1c1410", intensity: 1.1 },
95
+ boxes: [
96
+ box("sun", "Sun", -58, 7, 10, 10, 40, "#ffb469", 0.5),
97
+ box("glow", "Glow", -58, 6, 70, 30, 2.5, "#ff9a5c", 1),
98
+ box("sky", "Sky fill", 120, 40, 90, 70, 0.9, "#7fa2ff", 1)
99
+ ]
100
+ },
101
+ overcast: {
102
+ label: "Overcast",
103
+ hint: "Soft daylight with no direct sun: matte, honest materials.",
104
+ sky: { top: "#c9d2dc", horizon: "#aab3bd", ground: "#3a3b3d", intensity: 1.15 },
105
+ boxes: [box("zenith", "Sky", 0, 80, 150, 150, 1.4, "#eef3ff", 1)]
106
+ },
107
+ night: {
108
+ label: "Night",
109
+ hint: "Dark blue world, a cool moon and one warm accent.",
110
+ sky: { top: "#050a18", horizon: "#101b33", ground: "#04050a", intensity: 1 },
111
+ boxes: [
112
+ box("moon", "Moon", -35, 48, 26, 26, 6, "#bcd4ff", 0.4),
113
+ box("accent", "Accent", 110, 6, 26, 40, 3.5, "#ff9a4a", 0.6),
114
+ box("rim", "Rim", 170, 22, 28, 70, 2.2, "#8fb4ff", 0.4)
115
+ ]
116
+ }
117
+ };
118
+ var num = (v, fallback, min, max) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;
119
+ var hexColor = (v, fallback) => typeof v === "string" && /^#[0-9a-fA-F]{6}$/.test(v) ? v.toLowerCase() : fallback;
120
+ var oneOf = (v, values, fallback) => typeof v === "string" && values.includes(v) ? v : fallback;
121
+ var rec = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
122
+ var optional = (v, min, max) => typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : void 0;
123
+ var TONES = ["site", "none", "linear", "reinhard", "cineon", "aces", "agx", "neutral"];
124
+ var WORLDS = ["site", "studio", "softbox", "sunset", "overcast", "night"];
125
+ var MATERIALS = [
126
+ "custom",
127
+ "polished-metal",
128
+ "brushed-metal",
129
+ "gold",
130
+ "car-paint",
131
+ "glass",
132
+ "plastic",
133
+ "ceramic",
134
+ "rubber"
135
+ ];
136
+ var DETAILS = ["brushed", "rings", "hammered", "knurl", "text"];
137
+ var DETAIL_SCALE = {
138
+ brushed: 60,
139
+ rings: 14,
140
+ hammered: 18,
141
+ knurl: 40,
142
+ text: 1
143
+ };
144
+ var DETAIL_STRENGTH = {
145
+ brushed: 0.3,
146
+ rings: 0.8,
147
+ hammered: 0.55,
148
+ knurl: 0.7,
149
+ text: 1
150
+ };
151
+ function readBox(v, index) {
152
+ const b = rec(v);
153
+ return {
154
+ id: typeof b.id === "string" && b.id ? b.id.slice(0, 40) : `box${index + 1}`,
155
+ name: typeof b.name === "string" && b.name ? b.name.slice(0, 40) : `Light ${index + 1}`,
156
+ azimuth: num(b.azimuth, 0, -360, 360),
157
+ elevation: num(b.elevation, 30, -90, 90),
158
+ width: num(b.width, 40, 1, 180),
159
+ height: num(b.height, 40, 1, 180),
160
+ intensity: num(b.intensity, 4, 0, 100),
161
+ color: hexColor(b.color, "#ffffff"),
162
+ softness: num(b.softness, 0.35, 0, 1)
163
+ };
164
+ }
165
+ function readMaterial(v) {
166
+ const m = rec(v);
167
+ const name = typeof m.name === "string" ? m.name.slice(0, 128) : "";
168
+ const uuid = typeof m.uuid === "string" ? m.uuid.slice(0, 64) : void 0;
169
+ if (!name && !uuid) return null;
170
+ const out = { name, preset: oneOf(m.preset, MATERIALS, "custom") };
171
+ if (uuid) out.uuid = uuid;
172
+ if (typeof m.color === "string" && /^#[0-9a-fA-F]{6}$/.test(m.color))
173
+ out.color = m.color.toLowerCase();
174
+ const fields = [
175
+ ["metalness", 0, 1],
176
+ ["roughness", 0, 1],
177
+ ["clearcoat", 0, 1],
178
+ ["clearcoatRoughness", 0, 1],
179
+ ["transmission", 0, 1],
180
+ ["ior", 1, 2.333],
181
+ ["thickness", 0, 100],
182
+ ["envMapIntensity", 0, 10]
183
+ ];
184
+ for (const [key, min, max] of fields) {
185
+ const value = optional(m[key], min, max);
186
+ if (value !== void 0) out[key] = value;
187
+ }
188
+ const detail = rec(m.detail);
189
+ if (typeof detail.pattern === "string" && DETAILS.includes(detail.pattern)) {
190
+ out.detail = {
191
+ pattern: detail.pattern,
192
+ strength: num(detail.strength, DETAIL_STRENGTH[detail.pattern], 0, 2),
193
+ scale: num(detail.scale, DETAIL_SCALE[detail.pattern], 1, 200)
194
+ };
195
+ if (typeof detail.text === "string" && detail.text.trim())
196
+ out.detail.text = detail.text.slice(0, 120);
197
+ }
198
+ return out;
199
+ }
200
+ function readModel(v) {
201
+ const m = rec(v);
202
+ const name = typeof m.name === "string" ? m.name.slice(0, 128) : "";
203
+ const uuid = typeof m.uuid === "string" ? m.uuid.slice(0, 64) : void 0;
204
+ if (!name && !uuid) return null;
205
+ const scale = optional(m.scale, 1e-4, 1e4);
206
+ const lift = optional(m.lift, -1e5, 1e5);
207
+ const reflection = optional(m.reflection, 0, 10);
208
+ const out = { ...uuid ? { uuid } : {}, name };
209
+ if (scale !== void 0 && Math.abs(scale - 1) > 1e-9) out.scale = scale;
210
+ if (lift !== void 0 && Math.abs(lift) > 1e-9) out.lift = lift;
211
+ if (reflection !== void 0 && Math.abs(reflection - 1) > 1e-9) out.reflection = reflection;
212
+ return out.scale === void 0 && out.lift === void 0 && out.reflection === void 0 ? null : out;
213
+ }
214
+ function normalizeLook(input) {
215
+ const d = defaultLook();
216
+ const i = rec(input);
217
+ const color = rec(i.color);
218
+ const quality = rec(i.quality);
219
+ const world = rec(i.world);
220
+ const sky = rec(world.sky);
221
+ const shadows = rec(i.shadows);
222
+ const bevel = rec(i.bevel);
223
+ const effects = rec(i.effects);
224
+ const ao = rec(effects.ao);
225
+ const bloom = rec(effects.bloom);
226
+ const dof = rec(effects.dof);
227
+ const performance2 = rec(i.performance);
228
+ const adapt = rec(i.adapt);
229
+ const preset = oneOf(world.preset, WORLDS, "site");
230
+ const base = preset === "site" ? null : WORLD_PRESETS[preset];
231
+ const targets = (Array.isArray(bevel.targets) ? bevel.targets : []).map((t) => rec(t)).filter((t) => typeof t.name === "string" || typeof t.uuid === "string").slice(0, 200).map((t) => ({
232
+ ...typeof t.uuid === "string" ? { uuid: t.uuid.slice(0, 64) } : {},
233
+ name: typeof t.name === "string" ? t.name.slice(0, 128) : ""
234
+ }));
235
+ return {
236
+ version: 1,
237
+ color: {
238
+ toneMapping: oneOf(color.toneMapping, TONES, "site"),
239
+ exposure: color.exposure === null || color.exposure === void 0 ? null : num(color.exposure, 1, 0, 10)
240
+ },
241
+ quality: {
242
+ pixelRatio: quality.pixelRatio === null || quality.pixelRatio === void 0 ? null : num(quality.pixelRatio, 2, 0.5, 3),
243
+ anisotropy: quality.anisotropy === true,
244
+ supersample: quality.supersample === true
245
+ },
246
+ world: {
247
+ preset,
248
+ strength: num(world.strength, 1, 0, 10),
249
+ rotation: num(world.rotation, 0, -360, 360),
250
+ background: world.background === true,
251
+ sky: {
252
+ top: hexColor(sky.top, base?.sky.top ?? d.world.sky.top),
253
+ horizon: hexColor(sky.horizon, base?.sky.horizon ?? d.world.sky.horizon),
254
+ ground: hexColor(sky.ground, base?.sky.ground ?? d.world.sky.ground),
255
+ intensity: num(sky.intensity, base?.sky.intensity ?? 1, 0, 10)
256
+ },
257
+ boxes: Array.isArray(world.boxes) ? world.boxes.slice(0, 12).map(readBox) : base?.boxes.map((b) => ({ ...b })) ?? []
258
+ },
259
+ shadows: {
260
+ mode: oneOf(shadows.mode, ["site", "on", "off"], "site"),
261
+ softness: num(shadows.softness, d.shadows.softness, 0, 10),
262
+ resolution: [1024, 2048, 4096].includes(shadows.resolution) ? shadows.resolution : d.shadows.resolution
263
+ },
264
+ materials: (Array.isArray(i.materials) ? i.materials : []).map(readMaterial).filter((m) => m !== null).slice(0, 200),
265
+ bevel: {
266
+ mode: oneOf(bevel.mode, ["off", "all", "selected"], "off"),
267
+ amount: num(bevel.amount, d.bevel.amount, 0, 0.5),
268
+ segments: Math.round(num(bevel.segments, d.bevel.segments, 1, 8)),
269
+ targets
270
+ },
271
+ effects: {
272
+ antialias: effects.antialias === true,
273
+ ao: {
274
+ on: ao.on === true,
275
+ intensity: num(ao.intensity, d.effects.ao.intensity, 0, 3),
276
+ radius: num(ao.radius, d.effects.ao.radius, 0.01, 5)
277
+ },
278
+ bloom: {
279
+ on: bloom.on === true,
280
+ strength: num(bloom.strength, d.effects.bloom.strength, 0, 3),
281
+ threshold: num(bloom.threshold, d.effects.bloom.threshold, 0, 5),
282
+ radius: num(bloom.radius, d.effects.bloom.radius, 0, 1)
283
+ },
284
+ dof: {
285
+ on: dof.on === true,
286
+ focus: num(dof.focus, d.effects.dof.focus, 0.01, 1e4),
287
+ aperture: num(dof.aperture, d.effects.dof.aperture, 0, 0.01),
288
+ maxBlur: num(dof.maxBlur, d.effects.dof.maxBlur, 0, 0.05)
289
+ },
290
+ vignette: num(effects.vignette, 0, 0, 1),
291
+ grain: num(effects.grain, 0, 0, 1)
292
+ },
293
+ performance: {
294
+ adaptive: performance2.adaptive === true,
295
+ targetFps: [30, 45, 60].includes(performance2.targetFps) ? performance2.targetFps : 60
296
+ },
297
+ adapt: { follow: adapt.follow !== false, textures: adapt.textures === true },
298
+ models: (Array.isArray(i.models) ? i.models : []).map(readModel).filter((m) => m !== null).slice(0, 200)
299
+ };
300
+ }
301
+ function mergeLook(look, patch) {
302
+ const p = rec(patch);
303
+ const merged = { ...look };
304
+ for (const key of [
305
+ "color",
306
+ "quality",
307
+ "world",
308
+ "shadows",
309
+ "bevel",
310
+ "effects",
311
+ "performance",
312
+ "adapt"
313
+ ]) {
314
+ if (p[key] === void 0) continue;
315
+ const section = rec(p[key]);
316
+ const current = look[key];
317
+ const next = { ...current };
318
+ for (const [k, v] of Object.entries(section)) {
319
+ const cur = current[k];
320
+ next[k] = cur && typeof cur === "object" && !Array.isArray(cur) && v && typeof v === "object" && !Array.isArray(v) ? { ...cur, ...v } : v;
321
+ }
322
+ if (key === "world" && typeof section.preset === "string" && section.preset !== look.world.preset) {
323
+ if (section.sky === void 0) delete next.sky;
324
+ if (section.boxes === void 0) delete next.boxes;
325
+ }
326
+ merged[key] = next;
327
+ }
328
+ if (Array.isArray(p.materials)) merged.materials = p.materials;
329
+ if (Array.isArray(p.models)) merged.models = p.models;
330
+ return normalizeLook(merged);
331
+ }
332
+ function isNeutral(look) {
333
+ return JSON.stringify(look) === JSON.stringify(defaultLook());
334
+ }
335
+ function hexToLinear(hex) {
336
+ const n = parseInt(hex.slice(1), 16);
337
+ const lin = (c) => {
338
+ const s = c / 255;
339
+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
340
+ };
341
+ return [lin(n >> 16 & 255), lin(n >> 8 & 255), lin(n & 255)];
342
+ }
343
+ var DEG = Math.PI / 180;
344
+ var smoothstep = (a, b, x) => {
345
+ if (b <= a) return x < a ? 0 : 1;
346
+ const t = Math.min(1, Math.max(0, (x - a) / (b - a)));
347
+ return t * t * (3 - 2 * t);
348
+ };
349
+ function boxDirection(azimuth, elevation) {
350
+ const az = azimuth * DEG;
351
+ const el = elevation * DEG;
352
+ return [Math.cos(el) * Math.sin(az), Math.sin(el), Math.cos(el) * Math.cos(az)];
353
+ }
354
+ function environmentPixels(world, width = 1024, height = 512) {
355
+ const data = new Float32Array(width * height * 4);
356
+ const top = hexToLinear(world.sky.top);
357
+ const horizon = hexToLinear(world.sky.horizon);
358
+ const ground = hexToLinear(world.sky.ground);
359
+ const skyGain = world.sky.intensity * world.strength;
360
+ const boxes = world.boxes.map((b) => {
361
+ const c = boxDirection(b.azimuth + world.rotation, b.elevation);
362
+ let right = [c[2], 0, -c[0]];
363
+ const rl = Math.hypot(right[0], right[2]);
364
+ right = rl < 1e-6 ? [1, 0, 0] : [right[0] / rl, 0, right[2] / rl];
365
+ const up = [
366
+ c[1] * right[2] - c[2] * right[1],
367
+ c[2] * right[0] - c[0] * right[2],
368
+ c[0] * right[1] - c[1] * right[0]
369
+ ];
370
+ const hx = Math.tan(Math.min(178, b.width) / 2 * DEG);
371
+ const hy = Math.tan(Math.min(178, b.height) / 2 * DEG);
372
+ const soft = Math.max(0.02, b.softness);
373
+ const rgb = hexToLinear(b.color);
374
+ const gain = b.intensity * world.strength;
375
+ return {
376
+ c,
377
+ right,
378
+ up,
379
+ hx,
380
+ hy,
381
+ soft,
382
+ color: [rgb[0] * gain, rgb[1] * gain, rgb[2] * gain]
383
+ };
384
+ });
385
+ const cosLon = new Float32Array(width);
386
+ const sinLon = new Float32Array(width);
387
+ for (let x = 0; x < width; x++) {
388
+ const lon = ((x + 0.5) / width - 0.5) * Math.PI * 2;
389
+ cosLon[x] = Math.cos(lon);
390
+ sinLon[x] = Math.sin(lon);
391
+ }
392
+ for (let y = 0; y < height; y++) {
393
+ const lat = ((y + 0.5) / height - 0.5) * Math.PI;
394
+ const cl = Math.cos(lat);
395
+ const dy = Math.sin(lat);
396
+ const t = dy >= 0 ? Math.pow(dy, 0.6) : Math.pow(-dy, 0.5);
397
+ const to = dy >= 0 ? top : ground;
398
+ const sr = (horizon[0] + (to[0] - horizon[0]) * t) * skyGain;
399
+ const sg = (horizon[1] + (to[1] - horizon[1]) * t) * skyGain;
400
+ const sb = (horizon[2] + (to[2] - horizon[2]) * t) * skyGain;
401
+ for (let x = 0; x < width; x++) {
402
+ const dx = cl * cosLon[x];
403
+ const dz = cl * sinLon[x];
404
+ let r = sr;
405
+ let g = sg;
406
+ let b = sb;
407
+ for (const bx of boxes) {
408
+ const facing = dx * bx.c[0] + dy * bx.c[1] + dz * bx.c[2];
409
+ if (facing <= 0.02) continue;
410
+ const px = Math.abs((dx * bx.right[0] + dy * bx.right[1] + dz * bx.right[2]) / facing);
411
+ if (px >= bx.hx) continue;
412
+ const py = Math.abs((dx * bx.up[0] + dy * bx.up[1] + dz * bx.up[2]) / facing);
413
+ if (py >= bx.hy) continue;
414
+ const w = (1 - smoothstep(bx.hx * (1 - bx.soft), bx.hx, px)) * (1 - smoothstep(bx.hy * (1 - bx.soft), bx.hy, py));
415
+ r += bx.color[0] * w;
416
+ g += bx.color[1] * w;
417
+ b += bx.color[2] * w;
418
+ }
419
+ const i = (y * width + x) * 4;
420
+ data[i] = r;
421
+ data[i + 1] = g;
422
+ data[i + 2] = b;
423
+ data[i + 3] = 1;
424
+ }
425
+ }
426
+ return data;
427
+ }
428
+ var floatView = new Float32Array(1);
429
+ var intView = new Uint32Array(floatView.buffer);
430
+ function toHalf(value) {
431
+ floatView[0] = Math.min(65504, Math.max(-65504, value));
432
+ const x = intView[0];
433
+ const sign = x >> 16 & 32768;
434
+ let mantissa = x >> 12 & 2047;
435
+ const exponent = x >> 23 & 255;
436
+ if (exponent < 103) return sign;
437
+ if (exponent > 142) return sign | 31744;
438
+ if (exponent < 113) {
439
+ mantissa |= 2048;
440
+ return sign | (mantissa >> 114 - exponent) + (mantissa >> 113 - exponent & 1);
441
+ }
442
+ return (sign | exponent - 112 << 10 | mantissa >> 1) + (mantissa & 1);
443
+ }
444
+ function toHalfFloats(data) {
445
+ const out = new Uint16Array(data.length);
446
+ for (let i = 0; i < data.length; i++) out[i] = toHalf(data[i]);
447
+ return out;
448
+ }
449
+ var hash2 = (x, y) => {
450
+ const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;
451
+ return s - Math.floor(s);
452
+ };
453
+ function valueNoise(x, y) {
454
+ const xi = Math.floor(x);
455
+ const yi = Math.floor(y);
456
+ const xf = x - xi;
457
+ const yf = y - yi;
458
+ const u = xf * xf * (3 - 2 * xf);
459
+ const v = yf * yf * (3 - 2 * yf);
460
+ const a = hash2(xi, yi);
461
+ const b = hash2(xi + 1, yi);
462
+ const c = hash2(xi, yi + 1);
463
+ const d = hash2(xi + 1, yi + 1);
464
+ return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
465
+ }
466
+ function detailHeight(detail, size, mask) {
467
+ const h = new Float32Array(size * size);
468
+ const scale = detail.scale;
469
+ for (let y = 0; y < size; y++) {
470
+ const v = (y + 0.5) / size;
471
+ for (let x = 0; x < size; x++) {
472
+ const u = (x + 0.5) / size;
473
+ let value = 0.5;
474
+ switch (detail.pattern) {
475
+ case "rings": {
476
+ const r = Math.hypot(u - 0.5, v - 0.5) * 2;
477
+ const wave = 0.5 + 0.5 * Math.cos(r * scale * Math.PI * 2);
478
+ value = smoothstep(0.25, 0.75, wave) * smoothstep(0.08, 0.16, r) * (1 - smoothstep(0.86, 0.94, r));
479
+ break;
480
+ }
481
+ case "brushed":
482
+ value = 0.6 * valueNoise(u * 3, v * scale * 6) + 0.3 * valueNoise(u * 7 + 13, v * scale * 14) + 0.1 * valueNoise(u * 40, v * scale * 30 + 5);
483
+ break;
484
+ case "hammered": {
485
+ const gx = u * scale;
486
+ const gy = v * scale;
487
+ let nearest = 1;
488
+ for (let j = -1; j <= 1; j++)
489
+ for (let i = -1; i <= 1; i++) {
490
+ const cx = Math.floor(gx) + i;
491
+ const cy = Math.floor(gy) + j;
492
+ const px = cx + hash2(cx, cy);
493
+ const py = cy + hash2(cy + 31, cx + 17);
494
+ nearest = Math.min(nearest, Math.hypot(gx - px, gy - py));
495
+ }
496
+ value = smoothstep(0, 0.75, nearest);
497
+ break;
498
+ }
499
+ case "knurl": {
500
+ const a = Math.abs((u + v) * scale % 1 - 0.5) * 2;
501
+ const b = Math.abs(((u - v) * scale % 1 + 1) % 1 - 0.5) * 2;
502
+ value = Math.min(a, b);
503
+ break;
504
+ }
505
+ case "text":
506
+ value = mask ? mask[y * size + x] / 255 : 0;
507
+ break;
508
+ }
509
+ h[y * size + x] = value;
510
+ }
511
+ }
512
+ if (detail.pattern === "text" && mask) {
513
+ const blurred = new Float32Array(h.length);
514
+ for (let pass = 0; pass < 2; pass++) {
515
+ for (let y = 0; y < size; y++)
516
+ for (let x = 0; x < size; x++) {
517
+ const xm = x > 0 ? x - 1 : x;
518
+ const xp = x < size - 1 ? x + 1 : x;
519
+ const ym = y > 0 ? y - 1 : y;
520
+ const yp = y < size - 1 ? y + 1 : y;
521
+ blurred[y * size + x] = (h[y * size + x] * 4 + h[y * size + xm] + h[y * size + xp] + h[ym * size + x] + h[yp * size + x]) / 8;
522
+ }
523
+ h.set(blurred);
524
+ }
525
+ }
526
+ return h;
527
+ }
528
+ function heightToNormal(height, size, strength) {
529
+ const out = new Uint8Array(size * size * 4);
530
+ const k = strength * size * 0.012;
531
+ const at = (x, y) => height[Math.min(size - 1, Math.max(0, y)) * size + Math.min(size - 1, Math.max(0, x))];
532
+ for (let y = 0; y < size; y++)
533
+ for (let x = 0; x < size; x++) {
534
+ const dx = (at(x + 1, y) - at(x - 1, y)) * k;
535
+ const dy = (at(x, y + 1) - at(x, y - 1)) * k;
536
+ const length = Math.hypot(dx, dy, 1);
537
+ const i = (y * size + x) * 4;
538
+ out[i] = Math.round(-dx / length * 127.5 + 127.5);
539
+ out[i + 1] = Math.round(-dy / length * 127.5 + 127.5);
540
+ out[i + 2] = Math.round(1 / length * 127.5 + 127.5);
541
+ out[i + 3] = 255;
542
+ }
543
+ return out;
544
+ }
545
+ function normalMipmaps(base, size) {
546
+ const levels = [base];
547
+ let from = base;
548
+ for (let s = size; s > 1; s >>= 1) {
549
+ const half = s >> 1;
550
+ const to = new Uint8Array(half * half * 4);
551
+ for (let y = 0; y < half; y++)
552
+ for (let x = 0; x < half; x++) {
553
+ let nx = 0;
554
+ let ny = 0;
555
+ let nz = 0;
556
+ for (let j = 0; j < 2; j++)
557
+ for (let i = 0; i < 2; i++) {
558
+ const p = ((y * 2 + j) * s + x * 2 + i) * 4;
559
+ nx += from[p] - 127.5;
560
+ ny += from[p + 1] - 127.5;
561
+ nz += from[p + 2] - 127.5;
562
+ }
563
+ const length = Math.hypot(nx, ny, nz) || 1;
564
+ const q = (y * half + x) * 4;
565
+ to[q] = Math.round(nx / length * 127.5 + 127.5);
566
+ to[q + 1] = Math.round(ny / length * 127.5 + 127.5);
567
+ to[q + 2] = Math.round(nz / length * 127.5 + 127.5);
568
+ to[q + 3] = 255;
569
+ }
570
+ levels.push(to);
571
+ from = to;
572
+ }
573
+ return levels;
574
+ }
575
+ var DETAIL_SIZE = 1024;
576
+ function sideStops(half, radius, segments) {
577
+ const inner = half - radius;
578
+ const stops = [];
579
+ for (let k = segments; k >= 1; k--)
580
+ stops.push(-inner - radius * Math.tan(45 * k / segments * DEG));
581
+ stops.push(-inner);
582
+ if (inner > 1e-9) stops.push(inner);
583
+ for (let k = 1; k <= segments; k++)
584
+ stops.push(inner + radius * Math.tan(45 * k / segments * DEG));
585
+ return stops;
586
+ }
587
+ function roundedBox(width, height, depth, radius, segments, scale = [1, 1, 1]) {
588
+ const s = [Math.abs(scale[0]) || 1, Math.abs(scale[1]) || 1, Math.abs(scale[2]) || 1];
589
+ const half = [width * s[0] / 2, height * s[1] / 2, depth * s[2] / 2];
590
+ const r = Math.max(0, Math.min(radius, Math.min(half[0], half[1], half[2])));
591
+ const n = Math.max(1, Math.round(segments));
592
+ const stops = [sideStops(half[0], r, n), sideStops(half[1], r, n), sideStops(half[2], r, n)];
593
+ const position = [];
594
+ const normal = [];
595
+ const uv = [];
596
+ const faces = [
597
+ [0, 1, 1, 2],
598
+ [0, -1, 2, 1],
599
+ [1, 1, 2, 0],
600
+ [1, -1, 0, 2],
601
+ [2, 1, 0, 1],
602
+ [2, -1, 1, 0]
603
+ ];
604
+ const vertex = (axis, sign, ua, va, u, v) => {
605
+ const p = [0, 0, 0];
606
+ p[axis] = sign * half[axis];
607
+ p[ua] = u;
608
+ p[va] = v;
609
+ const inner = [0, 0, 0];
610
+ const dir = [0, 0, 0];
611
+ for (let a = 0; a < 3; a++) {
612
+ const limit = half[a] - r;
613
+ inner[a] = Math.min(limit, Math.max(-limit, p[a]));
614
+ dir[a] = p[a] - inner[a];
615
+ }
616
+ const length = Math.hypot(dir[0], dir[1], dir[2]) || 1;
617
+ const nrm = [dir[0] / length, dir[1] / length, dir[2] / length];
618
+ if (r === 0) {
619
+ nrm[0] = nrm[1] = nrm[2] = 0;
620
+ nrm[axis] = sign;
621
+ }
622
+ position.push(
623
+ (inner[0] + nrm[0] * r) / s[0],
624
+ (inner[1] + nrm[1] * r) / s[1],
625
+ (inner[2] + nrm[2] * r) / s[2]
626
+ );
627
+ const ln = [nrm[0] * s[0], nrm[1] * s[1], nrm[2] * s[2]];
628
+ const ll = Math.hypot(ln[0], ln[1], ln[2]) || 1;
629
+ normal.push(ln[0] / ll, ln[1] / ll, ln[2] / ll);
630
+ uv.push(u / (2 * half[ua]) + 0.5, v / (2 * half[va]) + 0.5);
631
+ };
632
+ for (const [axis, sign, ua, va] of faces) {
633
+ const us = stops[ua];
634
+ const vs = stops[va];
635
+ for (let i = 0; i < us.length - 1; i++)
636
+ for (let j = 0; j < vs.length - 1; j++) {
637
+ const u0 = us[i];
638
+ const u1 = us[i + 1];
639
+ const v0 = vs[j];
640
+ const v1 = vs[j + 1];
641
+ vertex(axis, sign, ua, va, u0, v0);
642
+ vertex(axis, sign, ua, va, u1, v0);
643
+ vertex(axis, sign, ua, va, u1, v1);
644
+ vertex(axis, sign, ua, va, u0, v0);
645
+ vertex(axis, sign, ua, va, u1, v1);
646
+ vertex(axis, sign, ua, va, u0, v1);
647
+ }
648
+ }
649
+ return {
650
+ position: new Float32Array(position),
651
+ normal: new Float32Array(normal),
652
+ uv: new Float32Array(uv)
653
+ };
654
+ }
655
+ function roundedCylinder(radius, height, radialSegments, bevel, segments) {
656
+ const sides = Math.max(3, Math.round(radialSegments));
657
+ const r = Math.max(0, Math.min(bevel, radius * 0.95, height / 2));
658
+ const n = Math.max(1, Math.round(segments));
659
+ const faceted = sides <= 12;
660
+ const profile = [];
661
+ profile.push([0, -height / 2, 0, -1], [radius - r, -height / 2, 0, -1]);
662
+ for (let k = 0; k <= n; k++) {
663
+ const a = (-90 + 90 * k / n) * DEG;
664
+ profile.push([
665
+ radius - r + r * Math.cos(a),
666
+ -height / 2 + r + r * Math.sin(a),
667
+ Math.cos(a),
668
+ Math.sin(a)
669
+ ]);
670
+ }
671
+ for (let k = 0; k <= n; k++) {
672
+ const a = 90 * k / n * DEG;
673
+ profile.push([
674
+ radius - r + r * Math.cos(a),
675
+ height / 2 - r + r * Math.sin(a),
676
+ Math.cos(a),
677
+ Math.sin(a)
678
+ ]);
679
+ }
680
+ profile.push([radius - r, height / 2, 0, 1], [0, height / 2, 0, 1]);
681
+ const position = [];
682
+ const normal = [];
683
+ const uv = [];
684
+ const total = profile.length - 1;
685
+ for (let j = 0; j < sides; j++) {
686
+ const t0 = j / sides * Math.PI * 2;
687
+ const t1 = (j + 1) / sides * Math.PI * 2;
688
+ const tm = (t0 + t1) / 2;
689
+ const put = (p, t, row, cap) => {
690
+ const x = p[0] * Math.sin(t);
691
+ const z = p[0] * Math.cos(t);
692
+ position.push(x, p[1], z);
693
+ const tn = faceted ? tm : t;
694
+ normal.push(p[2] * Math.sin(tn), p[3], p[2] * Math.cos(tn));
695
+ if (cap) uv.push(0.5 + cap * x / (2 * radius), 0.5 - z / (2 * radius));
696
+ else uv.push(t / (Math.PI * 2), row / total);
697
+ };
698
+ for (let i = 0; i < total; i++) {
699
+ const a = profile[i];
700
+ const b = profile[i + 1];
701
+ if (Math.abs(a[0] - b[0]) < 1e-12 && Math.abs(a[1] - b[1]) < 1e-12) continue;
702
+ const cap = i === 0 ? -1 : i === total - 1 ? 1 : 0;
703
+ if (a[0] > 1e-12) {
704
+ put(a, t0, i, cap);
705
+ put(a, t1, i, cap);
706
+ put(b, t1, i + 1, cap);
707
+ }
708
+ if (b[0] > 1e-12) {
709
+ put(a, t0, i, cap);
710
+ put(b, t1, i + 1, cap);
711
+ put(b, t0, i + 1, cap);
712
+ }
713
+ }
714
+ }
715
+ return {
716
+ position: new Float32Array(position),
717
+ normal: new Float32Array(normal),
718
+ uv: new Float32Array(uv)
719
+ };
720
+ }
721
+ function lighten(look) {
722
+ const { quality, shadows, effects } = look;
723
+ const ratio = quality.pixelRatio;
724
+ const to = (patch, step) => ({
725
+ look: mergeLook(look, patch),
726
+ step
727
+ });
728
+ if (quality.supersample)
729
+ return to({ quality: { supersample: false } }, "Extra resolution on 1\xD7 screens off");
730
+ if (shadows.mode === "on" && shadows.resolution > 2048)
731
+ return to({ shadows: { resolution: 2048 } }, "Shadow detail 4096 \u2192 2048");
732
+ if (effects.antialias && ratio !== null && ratio > 1.5)
733
+ return to(
734
+ { quality: { pixelRatio: 1.5 } },
735
+ `Pixel ratio ${ratio} \u2192 1.5 (edges are already smoothed)`
736
+ );
737
+ if (effects.dof.on) return to({ effects: { dof: { on: false } } }, "Depth of field off");
738
+ if (shadows.mode === "on" && shadows.resolution > 1024)
739
+ return to({ shadows: { resolution: 1024 } }, "Shadow detail 2048 \u2192 1024");
740
+ if (ratio !== null && ratio > 1.5)
741
+ return to({ quality: { pixelRatio: 1.5 } }, `Pixel ratio ${ratio} \u2192 1.5`);
742
+ if (effects.ao.on) return to({ effects: { ao: { on: false } } }, "Ambient occlusion off");
743
+ if (effects.bloom.on) return to({ effects: { bloom: { on: false } } }, "Bloom off");
744
+ if (ratio !== null && ratio > 1.25)
745
+ return to({ quality: { pixelRatio: 1.25 } }, `Pixel ratio ${ratio} \u2192 1.25`);
746
+ if (effects.antialias) return to({ effects: { antialias: false } }, "Smooth edges off");
747
+ if (ratio !== null && ratio > 1)
748
+ return to({ quality: { pixelRatio: 1 } }, `Pixel ratio ${ratio} \u2192 1`);
749
+ if (shadows.mode === "on") return to({ shadows: { mode: "off" } }, "Shadows off");
750
+ return null;
751
+ }
752
+ var effectsOn = (e) => e.antialias || e.ao.on || e.bloom.on || e.dof.on || e.vignette > 0 || e.grain > 0;
753
+ var HEAVY_TEXTURE_PIXELS = 4 * 2048 * 2048;
754
+
755
+ // src/lookRaster.ts
756
+ function rasterRingText(text, size) {
757
+ const legend = text.trim();
758
+ if (!legend) return null;
759
+ let canvas;
760
+ try {
761
+ if (typeof document !== "undefined") {
762
+ canvas = document.createElement("canvas");
763
+ canvas.width = canvas.height = size;
764
+ } else if (typeof OffscreenCanvas !== "undefined") canvas = new OffscreenCanvas(size, size);
765
+ else return null;
766
+ } catch {
767
+ return null;
768
+ }
769
+ const g = canvas.getContext("2d", { willReadFrequently: true });
770
+ if (!g) return null;
771
+ g.fillStyle = "#000";
772
+ g.fillRect(0, 0, size, size);
773
+ g.fillStyle = "#fff";
774
+ const fontSize = size * 0.062;
775
+ g.font = `700 ${fontSize}px "Helvetica Neue", Helvetica, Arial, sans-serif`;
776
+ g.textAlign = "center";
777
+ g.textBaseline = "middle";
778
+ const radius = size * 0.405;
779
+ const unit = `${legend} \xB7 `;
780
+ const unitWidth = g.measureText(unit).width;
781
+ const circumference = 2 * Math.PI * radius;
782
+ const repeats = Math.max(1, Math.floor(circumference / Math.max(1, unitWidth)));
783
+ const chars = [...unit.repeat(repeats)];
784
+ const widths = chars.map((c) => g.measureText(c).width);
785
+ const total = widths.reduce((a, b) => a + b, 0);
786
+ const stretch = circumference / total;
787
+ let along = 0;
788
+ chars.forEach((char, i) => {
789
+ const angle = (along + widths[i] / 2) * stretch / radius - Math.PI / 2;
790
+ along += widths[i];
791
+ g.save();
792
+ g.translate(size / 2 + Math.cos(angle) * radius, size / 2 + Math.sin(angle) * radius);
793
+ g.rotate(angle + Math.PI / 2);
794
+ g.fillText(char, 0, 0);
795
+ g.restore();
796
+ });
797
+ const pixels = g.getImageData(0, 0, size, size).data;
798
+ const mask = new Uint8Array(size * size);
799
+ for (let y = 0; y < size; y++)
800
+ for (let x = 0; x < size; x++) mask[(size - 1 - y) * size + x] = pixels[(y * size + x) * 4];
801
+ return mask;
802
+ }
803
+
804
+ // src/lookApply.ts
805
+ var WORLD_SIZE = { width: 1024, height: 512 };
806
+ var TEXTURE_SLOTS = [
807
+ "map",
808
+ "normalMap",
809
+ "roughnessMap",
810
+ "metalnessMap",
811
+ "aoMap",
812
+ "emissiveMap",
813
+ "bumpMap",
814
+ "alphaMap",
815
+ "clearcoatNormalMap",
816
+ "clearcoatRoughnessMap",
817
+ "sheenColorMap",
818
+ "specularMap"
819
+ ];
820
+ var MATERIAL_NUMBERS = [
821
+ "metalness",
822
+ "roughness",
823
+ "clearcoat",
824
+ "clearcoatRoughness",
825
+ "transmission",
826
+ "ior",
827
+ "thickness",
828
+ "envMapIntensity"
829
+ ];
830
+ var PHYSICAL_ONLY = /* @__PURE__ */ new Set([
831
+ "clearcoat",
832
+ "clearcoatRoughness",
833
+ "transmission",
834
+ "ior",
835
+ "thickness"
836
+ ]);
837
+ var materialsOf = (o) => Array.isArray(o.material) ? o.material : o.material ? [o.material] : [];
838
+ function walk(root, visit, limit = 2e4) {
839
+ const stack = [root];
840
+ let seen = 0;
841
+ while (stack.length && seen < limit) {
842
+ const o = stack.pop();
843
+ seen++;
844
+ visit(o);
845
+ const kids = o.children;
846
+ if (Array.isArray(kids)) for (let i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);
847
+ }
848
+ }
849
+ function worldScale(o) {
850
+ const e = o.matrixWorld?.elements;
851
+ if (!e) return [1, 1, 1];
852
+ return [
853
+ Math.hypot(e[0], e[1], e[2]),
854
+ Math.hypot(e[4], e[5], e[6]),
855
+ Math.hypot(e[8], e[9], e[10])
856
+ ];
857
+ }
858
+ function boundsCenter(geometry) {
859
+ try {
860
+ if (!geometry.boundingBox) geometry.computeBoundingBox?.();
861
+ const b = geometry.boundingBox;
862
+ if (b) return [(b.min.x + b.max.x) / 2, (b.min.y + b.max.y) / 2, (b.min.z + b.max.z) / 2];
863
+ } catch {
864
+ }
865
+ return [0, 0, 0];
866
+ }
867
+ function worldUpInParent(parent, lift) {
868
+ const e = parent?.matrixWorld?.elements;
869
+ if (!e) return [0, lift, 0];
870
+ const [a, b, c, d, f, g, h, i, j] = [e[0], e[4], e[8], e[1], e[5], e[9], e[2], e[6], e[10]];
871
+ const det = a * (f * j - g * i) - b * (d * j - g * h) + c * (d * i - f * h);
872
+ if (!Number.isFinite(det) || Math.abs(det) < 1e-12) return [0, lift, 0];
873
+ return [
874
+ (c * i - b * j) / det * lift,
875
+ (a * j - c * h) / det * lift,
876
+ (b * h - a * i) / det * lift
877
+ ];
878
+ }
879
+ function onScreen(camera, box2, center) {
880
+ const world = camera?.matrixWorld?.elements;
881
+ const view = camera?.matrixWorldInverse?.elements;
882
+ const proj = camera?.projectionMatrix?.elements;
883
+ if (!world || !view || !proj) return { distance: null, screen: null };
884
+ const distance = Math.hypot(center[0] - world[12], center[1] - world[13], center[2] - world[14]);
885
+ let x0 = Infinity;
886
+ let y0 = Infinity;
887
+ let x1 = -Infinity;
888
+ let y1 = -Infinity;
889
+ for (let k = 0; k < 8; k++) {
890
+ const x = k & 1 ? box2.max[0] : box2.min[0];
891
+ const y = k & 2 ? box2.max[1] : box2.min[1];
892
+ const z = k & 4 ? box2.max[2] : box2.min[2];
893
+ const vx = view[0] * x + view[4] * y + view[8] * z + view[12];
894
+ const vy = view[1] * x + view[5] * y + view[9] * z + view[13];
895
+ const vz = view[2] * x + view[6] * y + view[10] * z + view[14];
896
+ const w = proj[3] * vx + proj[7] * vy + proj[11] * vz + proj[15];
897
+ if (w <= 1e-6) return { distance, screen: null };
898
+ const nx = (proj[0] * vx + proj[4] * vy + proj[8] * vz + proj[12]) / w;
899
+ const ny = (proj[1] * vx + proj[5] * vy + proj[9] * vz + proj[13]) / w;
900
+ x0 = Math.min(x0, nx);
901
+ x1 = Math.max(x1, nx);
902
+ y0 = Math.min(y0, -ny);
903
+ y1 = Math.max(y1, -ny);
904
+ }
905
+ const clamp = (v) => Math.min(1, Math.max(0, v * 0.5 + 0.5));
906
+ const screen = [clamp(x0), clamp(y0), clamp(x1), clamp(y1)];
907
+ if (screen[2] - screen[0] < 1e-4 || screen[3] - screen[1] < 1e-4)
908
+ return { distance, screen: null };
909
+ return { distance, screen };
910
+ }
911
+ function bevelKind(o) {
912
+ if (!o.isMesh || Array.isArray(o.material)) return null;
913
+ const g = o.geometry;
914
+ const p = g?.parameters;
915
+ if (!g || !p) return null;
916
+ if (g.type === "BoxGeometry" && p.width > 0 && p.height > 0 && p.depth > 0) return "box";
917
+ if (g.type === "CylinderGeometry" && p.radiusTop > 0 && Math.abs(p.radiusTop - p.radiusBottom) < 1e-9 && p.height > 0 && p.openEnded !== true && (p.thetaLength === void 0 || Math.abs(p.thetaLength - Math.PI * 2) < 1e-6))
918
+ return "cylinder";
919
+ return null;
920
+ }
921
+ function sceneSphere(scene) {
922
+ const min = [Infinity, Infinity, Infinity];
923
+ const max = [-Infinity, -Infinity, -Infinity];
924
+ let count = 0;
925
+ walk(scene, (o) => {
926
+ if (!o.isMesh || o.visible === false || !o.geometry || count > 4e3) return;
927
+ try {
928
+ const g = o.geometry;
929
+ if (!g.boundingBox) g.computeBoundingBox?.();
930
+ const b = g.boundingBox;
931
+ const e = o.matrixWorld?.elements;
932
+ if (!b || !e || !Number.isFinite(b.min.x) || !Number.isFinite(b.max.x)) return;
933
+ count++;
934
+ for (let i = 0; i < 8; i++) {
935
+ const x = i & 1 ? b.max.x : b.min.x;
936
+ const y = i & 2 ? b.max.y : b.min.y;
937
+ const z = i & 4 ? b.max.z : b.min.z;
938
+ const w = [
939
+ e[0] * x + e[4] * y + e[8] * z + e[12],
940
+ e[1] * x + e[5] * y + e[9] * z + e[13],
941
+ e[2] * x + e[6] * y + e[10] * z + e[14]
942
+ ];
943
+ for (let a = 0; a < 3; a++) {
944
+ if (w[a] < min[a]) min[a] = w[a];
945
+ if (w[a] > max[a]) max[a] = w[a];
946
+ }
947
+ }
948
+ } catch {
949
+ }
950
+ });
951
+ if (!count) return { center: [0, 0, 0], radius: 10 };
952
+ const center = [
953
+ (min[0] + max[0]) / 2,
954
+ (min[1] + max[1]) / 2,
955
+ (min[2] + max[2]) / 2
956
+ ];
957
+ const radius = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]) / 2;
958
+ return { center, radius: Math.max(radius, 1e-3) };
959
+ }
960
+ function meshBox(o) {
961
+ try {
962
+ const g = o.geometry;
963
+ if (!g) return null;
964
+ if (!g.boundingBox) g.computeBoundingBox?.();
965
+ const b = g.boundingBox;
966
+ const e = o.matrixWorld?.elements;
967
+ if (!b || !e || !Number.isFinite(b.min.x) || !Number.isFinite(b.max.x)) return null;
968
+ const min = [Infinity, Infinity, Infinity];
969
+ const max = [-Infinity, -Infinity, -Infinity];
970
+ for (let i = 0; i < 8; i++) {
971
+ const x = i & 1 ? b.max.x : b.min.x;
972
+ const y = i & 2 ? b.max.y : b.min.y;
973
+ const z = i & 4 ? b.max.z : b.min.z;
974
+ const w = [
975
+ e[0] * x + e[4] * y + e[8] * z + e[12],
976
+ e[1] * x + e[5] * y + e[9] * z + e[13],
977
+ e[2] * x + e[6] * y + e[10] * z + e[14]
978
+ ];
979
+ for (let a = 0; a < 3; a++) {
980
+ if (w[a] < min[a]) min[a] = w[a];
981
+ if (w[a] > max[a]) max[a] = w[a];
982
+ }
983
+ }
984
+ return { min, max };
985
+ } catch {
986
+ return null;
987
+ }
988
+ }
989
+ function solid(o) {
990
+ if (!o.isMesh || o.visible === false || !o.geometry) return false;
991
+ const m = materialsOf(o)[0];
992
+ return !!m && m.side !== 1 && m.depthWrite !== false;
993
+ }
994
+ var COLOR_SLOTS = ["map", "emissiveMap", "sheenColorMap", "specularColorMap"];
995
+ var DATA_SLOTS = [
996
+ "normalMap",
997
+ "roughnessMap",
998
+ "metalnessMap",
999
+ "aoMap",
1000
+ "bumpMap",
1001
+ "alphaMap",
1002
+ "displacementMap",
1003
+ "clearcoatNormalMap",
1004
+ "clearcoatRoughnessMap"
1005
+ ];
1006
+ var isPbr = (m) => !!(m.isMeshStandardMaterial || m.isMeshPhysicalMaterial);
1007
+ function colorFaults(materials) {
1008
+ const use = /* @__PURE__ */ new Map();
1009
+ for (const m of materials) {
1010
+ if (!isPbr(m)) continue;
1011
+ for (const [slots, kind] of [
1012
+ [COLOR_SLOTS, "color"],
1013
+ [DATA_SLOTS, "data"]
1014
+ ])
1015
+ for (const slot of slots) {
1016
+ const t = m[slot];
1017
+ if (!t?.isTexture || typeof t.colorSpace !== "string") continue;
1018
+ if (t.isRenderTargetTexture || t.isCompressedTexture || t.isCubeTexture) continue;
1019
+ const u = use.get(t) ?? { color: false, data: false };
1020
+ u[kind] = true;
1021
+ use.set(t, u);
1022
+ }
1023
+ }
1024
+ const out = /* @__PURE__ */ new Map();
1025
+ for (const [t, u] of use) {
1026
+ if (u.color && u.data) continue;
1027
+ if (u.color && t.colorSpace === "" && (t.type === void 0 || t.type === 1009))
1028
+ out.set(t, "srgb");
1029
+ else if (u.data && t.colorSpace === "srgb") out.set(t, "");
1030
+ }
1031
+ return out;
1032
+ }
1033
+ var GROUND_TRIANGLE_BUDGET = 6e5;
1034
+ var LookApplier = class {
1035
+ constructor(target, kit) {
1036
+ this.target = target;
1037
+ this.kit = kit;
1038
+ __publicField(this, "applied", null);
1039
+ __publicField(this, "undo", {});
1040
+ /** Site values of things the look has replaced, so the realism check still sees the site. */
1041
+ __publicField(this, "site", {
1042
+ toneMapping: null,
1043
+ exposure: null,
1044
+ pixelRatio: null,
1045
+ environment: void 0,
1046
+ shadowsEnabled: null,
1047
+ bevelled: /* @__PURE__ */ new Map(),
1048
+ anisotropy: /* @__PURE__ */ new Map()
1049
+ });
1050
+ __publicField(this, "notes", []);
1051
+ /** Notes of each part of the look, so fitting one part again keeps what the others said. */
1052
+ __publicField(this, "partNotes", {});
1053
+ __publicField(this, "part", "");
1054
+ /** Which meshes and lights the scene held when the look was last fitted. */
1055
+ __publicField(this, "fitted", "");
1056
+ /** Checks in a row that found the scene changed. */
1057
+ __publicField(this, "churn", 0);
1058
+ __publicField(this, "seen", "");
1059
+ /** Meshes seen so far: a model made only of others arrived later. */
1060
+ __publicField(this, "known", /* @__PURE__ */ new Set());
1061
+ /** Generated detail maps, kept while a look uses them: a slider drag must not redraw them. */
1062
+ __publicField(this, "detailMaps", /* @__PURE__ */ new Map());
1063
+ walk(target.scene, (o) => {
1064
+ if (o.isMesh) this.known.add(o.uuid);
1065
+ });
1066
+ this.fitted = this.signature();
1067
+ }
1068
+ note(message) {
1069
+ var _a, _b;
1070
+ ((_a = this.partNotes)[_b = this.part] ?? (_a[_b] = [])).push(message);
1071
+ }
1072
+ revision() {
1073
+ const g = globalThis;
1074
+ const r = parseInt(String(g.__THREE__ ?? ""), 10);
1075
+ return Number.isFinite(r) ? r : null;
1076
+ }
1077
+ restore(section) {
1078
+ const list = this.undo[section];
1079
+ if (!list) return;
1080
+ for (let i = list.length - 1; i >= 0; i--)
1081
+ try {
1082
+ list[i]();
1083
+ } catch {
1084
+ }
1085
+ delete this.undo[section];
1086
+ }
1087
+ touchMaterials() {
1088
+ const seen = /* @__PURE__ */ new Set();
1089
+ walk(this.target.scene, (o) => {
1090
+ for (const m of materialsOf(o))
1091
+ if (!seen.has(m)) {
1092
+ seen.add(m);
1093
+ m.needsUpdate = true;
1094
+ }
1095
+ });
1096
+ }
1097
+ /** Applies the look. Sections that did not change since the last call are left alone. */
1098
+ apply(look) {
1099
+ return this.fit(look, false);
1100
+ }
1101
+ /**
1102
+ * True when the scene gained or lost meshes or lights since the last call. The parts of the
1103
+ * look that depend on them are then fitted again (`adapt.follow`). Cheap enough to call twice
1104
+ * a second: one walk over the scene.
1105
+ */
1106
+ follow() {
1107
+ const now = this.signature();
1108
+ if (now === this.fitted) {
1109
+ this.churn = 0;
1110
+ return false;
1111
+ }
1112
+ const settled = now === this.seen;
1113
+ this.seen = now;
1114
+ if (++this.churn > 3 && this.churn % 8 !== 0 && !settled) return false;
1115
+ const look = this.applied;
1116
+ if (look?.adapt.follow) this.fit(look, true);
1117
+ else this.fitted = now;
1118
+ return true;
1119
+ }
1120
+ /** Which meshes and lights the scene holds, as one short string. */
1121
+ signature() {
1122
+ let count = 0;
1123
+ let hash = 2166136261;
1124
+ walk(this.target.scene, (o) => {
1125
+ if (!o.isMesh && !o.isLight) return;
1126
+ count++;
1127
+ const id = String(o.uuid ?? "");
1128
+ for (let i = 0; i < id.length && i < 13; i++)
1129
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
1130
+ });
1131
+ return `${count}:${hash >>> 0}`;
1132
+ }
1133
+ fit(look, sceneChanged) {
1134
+ const prev = this.applied;
1135
+ const diff = (key) => !look || !prev || JSON.stringify(prev[key]) !== JSON.stringify(look[key]);
1136
+ const run = (part, keys, scene, fn) => {
1137
+ if (!(scene && sceneChanged) && !keys.some(diff)) return;
1138
+ this.restore(part);
1139
+ delete this.partNotes[part];
1140
+ if (!look) return;
1141
+ this.undo[part] = [];
1142
+ this.part = part;
1143
+ try {
1144
+ fn();
1145
+ } catch (err) {
1146
+ this.note(`${part}: ${err instanceof Error ? err.message : String(err)}`);
1147
+ }
1148
+ };
1149
+ const reflection = sceneChanged || diff("models") || diff("materials");
1150
+ if (reflection) this.restore("reflection");
1151
+ run("color", ["color"], false, () => this.color(look));
1152
+ run("quality", ["quality"], false, () => this.quality(look));
1153
+ run("world", ["world"], false, () => this.world(look));
1154
+ run("models", ["models"], true, () => this.models(look));
1155
+ run("anisotropy", ["quality"], true, () => this.anisotropy(look));
1156
+ run("textures", ["adapt"], true, () => this.textures(look));
1157
+ run("shadows", ["shadows", "models"], true, () => this.shadows(look));
1158
+ run("materials", ["materials"], true, () => this.materials(look));
1159
+ if (reflection && look) {
1160
+ this.undo.reflection = [];
1161
+ this.part = "reflection";
1162
+ try {
1163
+ this.reflection(look);
1164
+ } catch {
1165
+ }
1166
+ }
1167
+ run("bevel", ["bevel", "models"], true, () => this.bevel(look));
1168
+ const used = new Set(
1169
+ (look?.materials ?? []).map((m) => m.detail ? JSON.stringify(m.detail) : "")
1170
+ );
1171
+ for (const [key, texture] of this.detailMaps)
1172
+ if (!used.has(key)) {
1173
+ this.kit.dispose(texture);
1174
+ this.detailMaps.delete(key);
1175
+ }
1176
+ this.applied = look ? JSON.parse(JSON.stringify(look)) : null;
1177
+ if (!look) this.partNotes = {};
1178
+ this.fitted = this.signature();
1179
+ this.notes = Object.values(this.partNotes).flat();
1180
+ return this.notes;
1181
+ }
1182
+ /** Puts the site back exactly as it was. */
1183
+ reset() {
1184
+ this.apply(null);
1185
+ }
1186
+ color(look) {
1187
+ const { renderer } = this.target;
1188
+ const undo = this.undo.color;
1189
+ const { toneMapping, exposure } = look.color;
1190
+ if (toneMapping !== "site" && typeof renderer.toneMapping === "number") {
1191
+ let wanted = toneMapping;
1192
+ const need = TONE_MAPPING_MIN_REVISION[toneMapping];
1193
+ const have = this.revision();
1194
+ if (need && have !== null && have < need) {
1195
+ this.note(
1196
+ `${toneMapping === "agx" ? "AgX" : "Neutral"} tone mapping needs three.js r${need} (this page has r${have}): ACES is used.`
1197
+ );
1198
+ wanted = "aces";
1199
+ }
1200
+ const before = renderer.toneMapping;
1201
+ this.site.toneMapping = before;
1202
+ renderer.toneMapping = TONE_MAPPING[wanted];
1203
+ this.touchMaterials();
1204
+ undo.push(() => {
1205
+ renderer.toneMapping = before;
1206
+ this.site.toneMapping = null;
1207
+ this.touchMaterials();
1208
+ });
1209
+ }
1210
+ if (exposure !== null && typeof renderer.toneMappingExposure === "number") {
1211
+ const before = renderer.toneMappingExposure;
1212
+ this.site.exposure = before;
1213
+ renderer.toneMappingExposure = exposure;
1214
+ undo.push(() => {
1215
+ renderer.toneMappingExposure = before;
1216
+ this.site.exposure = null;
1217
+ });
1218
+ }
1219
+ }
1220
+ quality(look) {
1221
+ const { renderer } = this.target;
1222
+ const undo = this.undo.quality;
1223
+ const device = this.kit.devicePixelRatio();
1224
+ const above = look.quality.supersample && device < 1.5;
1225
+ if ((look.quality.pixelRatio !== null || above) && typeof renderer.setPixelRatio === "function") {
1226
+ const before = renderer.getPixelRatio?.() ?? 1;
1227
+ const cap = above ? 1.5 : device;
1228
+ const next = look.quality.pixelRatio !== null ? Math.min(cap, look.quality.pixelRatio) : Math.max(before, cap);
1229
+ this.site.pixelRatio = before;
1230
+ if (Math.abs(next - before) > 1e-3) renderer.setPixelRatio(next);
1231
+ undo.push(() => {
1232
+ if (Math.abs((renderer.getPixelRatio?.() ?? before) - before) > 1e-3)
1233
+ renderer.setPixelRatio(before);
1234
+ this.site.pixelRatio = null;
1235
+ });
1236
+ }
1237
+ }
1238
+ anisotropy(look) {
1239
+ const { renderer, scene } = this.target;
1240
+ const undo = this.undo.anisotropy;
1241
+ if (look.quality.anisotropy) {
1242
+ let max = 1;
1243
+ try {
1244
+ max = renderer.capabilities?.getMaxAnisotropy?.() ?? 1;
1245
+ } catch {
1246
+ }
1247
+ if (max > 1) {
1248
+ const want = Math.min(max, 16);
1249
+ walk(scene, (o) => {
1250
+ for (const m of materialsOf(o))
1251
+ for (const slot of TEXTURE_SLOTS) {
1252
+ const t = m[slot];
1253
+ if (!t?.isTexture || this.site.anisotropy.has(t) || (t.anisotropy ?? 1) >= want)
1254
+ continue;
1255
+ this.site.anisotropy.set(t, t.anisotropy ?? 1);
1256
+ t.anisotropy = want;
1257
+ t.needsUpdate = true;
1258
+ }
1259
+ });
1260
+ undo.push(() => {
1261
+ for (const [t, before] of this.site.anisotropy) {
1262
+ t.anisotropy = before;
1263
+ t.needsUpdate = true;
1264
+ }
1265
+ this.site.anisotropy.clear();
1266
+ });
1267
+ }
1268
+ }
1269
+ }
1270
+ world(look) {
1271
+ const { scene } = this.target;
1272
+ if (look.world.preset === "site") return;
1273
+ const pixels = environmentPixels(look.world, WORLD_SIZE.width, WORLD_SIZE.height);
1274
+ const texture = this.kit.texture(toHalfFloats(pixels), WORLD_SIZE.width, WORLD_SIZE.height);
1275
+ if (!texture) {
1276
+ this.note(
1277
+ "The world could not be made on this page. Set scene.environment in the code instead."
1278
+ );
1279
+ return;
1280
+ }
1281
+ const before = { environment: scene.environment, background: scene.background };
1282
+ this.site.environment = before.environment ?? null;
1283
+ scene.environment = texture;
1284
+ if (look.world.background) scene.background = texture;
1285
+ this.undo.world.push(() => {
1286
+ scene.environment = before.environment;
1287
+ scene.background = before.background;
1288
+ this.site.environment = void 0;
1289
+ this.kit.dispose(texture);
1290
+ });
1291
+ }
1292
+ shadows(look) {
1293
+ const { renderer, scene } = this.target;
1294
+ const undo = this.undo.shadows;
1295
+ const map = renderer.shadowMap;
1296
+ if (look.shadows.mode === "site" || !map) return;
1297
+ const before = { enabled: map.enabled, type: map.type };
1298
+ this.site.shadowsEnabled = !!before.enabled;
1299
+ undo.push(() => {
1300
+ map.enabled = before.enabled;
1301
+ map.type = before.type;
1302
+ map.needsUpdate = true;
1303
+ this.site.shadowsEnabled = null;
1304
+ this.touchMaterials();
1305
+ });
1306
+ if (look.shadows.mode === "off") {
1307
+ map.enabled = false;
1308
+ this.touchMaterials();
1309
+ return;
1310
+ }
1311
+ map.enabled = true;
1312
+ map.type = (this.revision() ?? 0) >= 182 ? 1 : 2;
1313
+ const sphere = sceneSphere(scene);
1314
+ const size = look.shadows.resolution;
1315
+ let lights = 0;
1316
+ walk(scene, (o) => {
1317
+ if (o.isLight && (o.isDirectionalLight || o.isSpotLight) && o.shadow && lights < 4) {
1318
+ lights++;
1319
+ const s = o.shadow;
1320
+ const cam = s.camera;
1321
+ const saved = {
1322
+ cast: o.castShadow,
1323
+ w: s.mapSize?.x,
1324
+ h: s.mapSize?.y,
1325
+ bias: s.bias,
1326
+ normalBias: s.normalBias,
1327
+ radius: s.radius,
1328
+ cam: cam ? [cam.left, cam.right, cam.top, cam.bottom, cam.near, cam.far] : null
1329
+ };
1330
+ o.castShadow = true;
1331
+ s.mapSize?.set?.(size, size);
1332
+ s.bias = -2e-4;
1333
+ s.normalBias = Math.max(5e-3, sphere.radius * 4e-3);
1334
+ s.radius = look.shadows.softness;
1335
+ if (o.isDirectionalLight && cam && typeof cam.left === "number") {
1336
+ const e = o.matrixWorld?.elements;
1337
+ const lp = e ? [e[12], e[13], e[14]] : [0, 0, 0];
1338
+ const away = Math.hypot(
1339
+ lp[0] - sphere.center[0],
1340
+ lp[1] - sphere.center[1],
1341
+ lp[2] - sphere.center[2]
1342
+ );
1343
+ const half = sphere.radius * 1.05 + Math.min(away, sphere.radius);
1344
+ cam.left = -half;
1345
+ cam.right = half;
1346
+ cam.top = half;
1347
+ cam.bottom = -half;
1348
+ cam.near = Math.max(0.01, away - sphere.radius * 2.2);
1349
+ cam.far = away + sphere.radius * 2.2;
1350
+ cam.updateProjectionMatrix?.();
1351
+ }
1352
+ try {
1353
+ s.map?.dispose?.();
1354
+ } catch {
1355
+ }
1356
+ s.map = null;
1357
+ undo.push(() => {
1358
+ o.castShadow = saved.cast;
1359
+ if (saved.w !== void 0) s.mapSize?.set?.(saved.w, saved.h);
1360
+ s.bias = saved.bias;
1361
+ s.normalBias = saved.normalBias;
1362
+ s.radius = saved.radius;
1363
+ if (saved.cam && cam) {
1364
+ [cam.left, cam.right, cam.top, cam.bottom, cam.near, cam.far] = saved.cam;
1365
+ cam.updateProjectionMatrix?.();
1366
+ }
1367
+ try {
1368
+ s.map?.dispose?.();
1369
+ } catch {
1370
+ }
1371
+ s.map = null;
1372
+ });
1373
+ return;
1374
+ }
1375
+ if (o.isMesh) {
1376
+ const m = materialsOf(o)[0];
1377
+ if (!m || m.transparent === true || m.side === 1 || m.depthWrite === false) return;
1378
+ const saved = { cast: o.castShadow, receive: o.receiveShadow };
1379
+ o.castShadow = true;
1380
+ o.receiveShadow = true;
1381
+ undo.push(() => {
1382
+ o.castShadow = saved.cast;
1383
+ o.receiveShadow = saved.receive;
1384
+ });
1385
+ }
1386
+ });
1387
+ if (!lights)
1388
+ this.note(
1389
+ "Shadows are on, but the scene has no directional or spot light to cast them. Add one in the code."
1390
+ );
1391
+ map.needsUpdate = true;
1392
+ this.touchMaterials();
1393
+ }
1394
+ find(ref) {
1395
+ const out = [];
1396
+ walk(this.target.scene, (o) => {
1397
+ if (ref.uuid ? o.uuid === ref.uuid : !!ref.name && o.name === ref.name) out.push(o);
1398
+ });
1399
+ if (!out.length && ref.uuid && ref.name)
1400
+ walk(this.target.scene, (o) => {
1401
+ if (o.name === ref.name) out.push(o);
1402
+ });
1403
+ return out;
1404
+ }
1405
+ /** The normal map of a detail pattern, made once per distinct setting. */
1406
+ detailMap(detail) {
1407
+ const key = JSON.stringify(detail);
1408
+ const cached = this.detailMaps.get(key);
1409
+ if (cached) return cached;
1410
+ const mask = detail.pattern === "text" ? rasterRingText(detail.text ?? "", DETAIL_SIZE) : null;
1411
+ if (detail.pattern === "text" && !mask) return null;
1412
+ const height = detailHeight(detail, DETAIL_SIZE, mask);
1413
+ const texture = this.kit.image(
1414
+ normalMipmaps(heightToNormal(height, DETAIL_SIZE, detail.strength), DETAIL_SIZE),
1415
+ DETAIL_SIZE
1416
+ );
1417
+ if (texture) this.detailMaps.set(key, texture);
1418
+ return texture;
1419
+ }
1420
+ materials(look) {
1421
+ const undo = this.undo.materials;
1422
+ for (const entry of look.materials) {
1423
+ const objects = this.find(entry);
1424
+ if (!objects.length) {
1425
+ this.note(`No object named "${entry.name || entry.uuid}" for its material settings.`);
1426
+ continue;
1427
+ }
1428
+ const skipped = /* @__PURE__ */ new Set();
1429
+ for (const o of objects) {
1430
+ const m = materialsOf(o)[0];
1431
+ if (!m) continue;
1432
+ if (entry.color !== void 0 && m.color?.isColor) {
1433
+ const before = `#${m.color.getHexString()}`;
1434
+ m.color.set(entry.color);
1435
+ undo.push(() => m.color.set(before));
1436
+ }
1437
+ for (const key of MATERIAL_NUMBERS) {
1438
+ const value = entry[key];
1439
+ if (typeof value !== "number") continue;
1440
+ if (typeof m[key] !== "number") {
1441
+ if (PHYSICAL_ONLY.has(key) && value !== 0) skipped.add(key);
1442
+ continue;
1443
+ }
1444
+ const before = m[key];
1445
+ m[key] = value;
1446
+ undo.push(() => {
1447
+ m[key] = before;
1448
+ m.needsUpdate = true;
1449
+ });
1450
+ }
1451
+ if (entry.detail && entry.detail.strength > 0) {
1452
+ if (!("normalMap" in m)) skipped.add("surface detail");
1453
+ else if (!o.geometry?.attributes?.uv)
1454
+ this.note(
1455
+ `"${entry.name || entry.uuid}" has no UV coordinates, so surface detail cannot be mapped onto it.`
1456
+ );
1457
+ else if (entry.detail.pattern === "text" && !entry.detail.text?.trim())
1458
+ this.note(`"${entry.name || entry.uuid}": engraved text needs the text to engrave.`);
1459
+ else {
1460
+ const map = this.detailMap(entry.detail);
1461
+ if (!map) this.note("Surface detail could not be made on this page.");
1462
+ else {
1463
+ const before = { map: m.normalMap, x: m.normalScale?.x, y: m.normalScale?.y };
1464
+ m.normalMap = map;
1465
+ m.normalScale?.set?.(1, 1);
1466
+ undo.push(() => {
1467
+ m.normalMap = before.map;
1468
+ if (before.x !== void 0) m.normalScale?.set?.(before.x, before.y);
1469
+ m.needsUpdate = true;
1470
+ });
1471
+ }
1472
+ }
1473
+ }
1474
+ m.needsUpdate = true;
1475
+ }
1476
+ if (skipped.size)
1477
+ this.note(
1478
+ `"${entry.name || entry.uuid}": ${[...skipped].join(", ")} need${skipped.size === 1 ? "s" : ""} MeshPhysicalMaterial (it uses ${materialsOf(objects[0])[0]?.type ?? "another material"}). Change the material in the code.`
1479
+ );
1480
+ }
1481
+ }
1482
+ /** Size, height and reflection strength of whole models. */
1483
+ models(look) {
1484
+ const undo = this.undo.models;
1485
+ for (const entry of look.models) {
1486
+ if (entry.scale === void 0 && entry.lift === void 0) continue;
1487
+ const objects = this.find(entry);
1488
+ if (!objects.length) {
1489
+ this.note(`No object named "${entry.name || entry.uuid}" to place.`);
1490
+ continue;
1491
+ }
1492
+ for (const o of objects) {
1493
+ if (!o.position || !o.scale) continue;
1494
+ const before = {
1495
+ p: [o.position.x, o.position.y, o.position.z],
1496
+ s: [o.scale.x, o.scale.y, o.scale.z]
1497
+ };
1498
+ if (entry.scale !== void 0)
1499
+ o.scale.set(
1500
+ before.s[0] * entry.scale,
1501
+ before.s[1] * entry.scale,
1502
+ before.s[2] * entry.scale
1503
+ );
1504
+ if (entry.lift !== void 0) {
1505
+ const d = worldUpInParent(o.parent, entry.lift);
1506
+ o.position.set(before.p[0] + d[0], before.p[1] + d[1], before.p[2] + d[2]);
1507
+ }
1508
+ o.updateMatrixWorld?.(true);
1509
+ undo.push(() => {
1510
+ o.position.set(before.p[0], before.p[1], before.p[2]);
1511
+ o.scale.set(before.s[0], before.s[1], before.s[2]);
1512
+ o.updateMatrixWorld?.(true);
1513
+ });
1514
+ }
1515
+ }
1516
+ }
1517
+ reflection(look) {
1518
+ const undo = this.undo.reflection;
1519
+ const done = /* @__PURE__ */ new Set();
1520
+ for (const entry of look.models) {
1521
+ if (entry.reflection === void 0) continue;
1522
+ for (const root of this.find(entry))
1523
+ walk(root, (o) => {
1524
+ for (const m of materialsOf(o)) {
1525
+ if (done.has(m) || !isPbr(m) || typeof m.envMapIntensity !== "number") continue;
1526
+ done.add(m);
1527
+ const before = m.envMapIntensity;
1528
+ m.envMapIntensity = before * entry.reflection;
1529
+ undo.push(() => {
1530
+ m.envMapIntensity = before;
1531
+ });
1532
+ }
1533
+ });
1534
+ }
1535
+ }
1536
+ /** Colour maps as sRGB, data maps as plain numbers (`adapt.textures`). */
1537
+ textures(look) {
1538
+ if (!look.adapt.textures) return;
1539
+ const undo = this.undo.textures;
1540
+ const materials = /* @__PURE__ */ new Set();
1541
+ walk(this.target.scene, (o) => {
1542
+ for (const m of materialsOf(o)) materials.add(m);
1543
+ });
1544
+ const faults = colorFaults(materials);
1545
+ if (!faults.size) return;
1546
+ for (const [t, wanted] of faults) {
1547
+ const before = t.colorSpace;
1548
+ t.colorSpace = wanted;
1549
+ t.needsUpdate = true;
1550
+ undo.push(() => {
1551
+ t.colorSpace = before;
1552
+ t.needsUpdate = true;
1553
+ });
1554
+ }
1555
+ for (const m of materials) m.needsUpdate = true;
1556
+ undo.push(() => {
1557
+ for (const m of materials) m.needsUpdate = true;
1558
+ });
1559
+ }
1560
+ /**
1561
+ * The models of the scene: its top-level objects, looking through wrapper groups that hold
1562
+ * everything.
1563
+ */
1564
+ roots() {
1565
+ const withMesh = (o) => {
1566
+ let found = false;
1567
+ walk(
1568
+ o,
1569
+ (c) => {
1570
+ if (solid(c)) found = true;
1571
+ },
1572
+ 4e3
1573
+ );
1574
+ return found;
1575
+ };
1576
+ let node = this.target.scene;
1577
+ let kids = [];
1578
+ for (let depth = 0; depth < 4; depth++) {
1579
+ kids = (Array.isArray(node.children) ? node.children : []).filter(
1580
+ (c) => c.visible !== false && withMesh(c)
1581
+ );
1582
+ if (kids.length === 1 && !kids[0].isMesh && kids[0].children?.length) node = kids[0];
1583
+ else break;
1584
+ }
1585
+ return kids.slice(0, 80);
1586
+ }
1587
+ /**
1588
+ * Measures every model: size, triangles, textures, how it sits on what is under it, where it
1589
+ * is on screen. `acknowledge` then counts the models seen as no longer new.
1590
+ */
1591
+ measure(acknowledge = false) {
1592
+ const { scene, camera } = this.target;
1593
+ try {
1594
+ scene.updateMatrixWorld?.(true);
1595
+ } catch {
1596
+ }
1597
+ const roots = this.roots();
1598
+ const owner = /* @__PURE__ */ new Map();
1599
+ const parts = roots.map(() => ({
1600
+ meshes: [],
1601
+ box: null
1602
+ }));
1603
+ roots.forEach(
1604
+ (root, index) => walk(root, (o) => {
1605
+ if (!solid(o)) return;
1606
+ owner.set(o, index);
1607
+ const part = parts[index];
1608
+ part.meshes.push(o);
1609
+ const b = meshBox(o);
1610
+ if (!b) return;
1611
+ if (!part.box) part.box = { min: [...b.min], max: [...b.max] };
1612
+ else
1613
+ for (let a = 0; a < 3; a++) {
1614
+ part.box.min[a] = Math.min(part.box.min[a], b.min[a]);
1615
+ part.box.max[a] = Math.max(part.box.max[a], b.max[a]);
1616
+ }
1617
+ })
1618
+ );
1619
+ const solids = [];
1620
+ walk(scene, (o) => {
1621
+ if (solid(o)) solids.push(o);
1622
+ });
1623
+ const largest = parts.map(
1624
+ (p) => p.box ? Math.max(...p.box.max.map((v, a) => v - p.box.min[a])) : 0
1625
+ );
1626
+ let budget = GROUND_TRIANGLE_BUDGET;
1627
+ const models = [];
1628
+ roots.forEach((root, index) => {
1629
+ const { meshes, box: box2 } = parts[index];
1630
+ if (!box2 || !meshes.length) return;
1631
+ const size = [
1632
+ box2.max[0] - box2.min[0],
1633
+ box2.max[1] - box2.min[1],
1634
+ box2.max[2] - box2.min[2]
1635
+ ];
1636
+ const center = [
1637
+ (box2.min[0] + box2.max[0]) / 2,
1638
+ (box2.min[1] + box2.max[1]) / 2,
1639
+ (box2.min[2] + box2.max[2]) / 2
1640
+ ];
1641
+ let triangles = 0;
1642
+ const materials = /* @__PURE__ */ new Set();
1643
+ const textures = /* @__PURE__ */ new Set();
1644
+ let casts = true;
1645
+ let receives = true;
1646
+ for (const o of meshes) {
1647
+ const g = o.geometry;
1648
+ const count = g.index ? g.index.count : g.attributes?.position?.count ?? 0;
1649
+ triangles += Math.floor(count / 3) * (o.isInstancedMesh ? o.count ?? 1 : 1);
1650
+ const first = materialsOf(o)[0];
1651
+ if (first?.transparent !== true) {
1652
+ if (!o.castShadow) casts = false;
1653
+ if (!o.receiveShadow) receives = false;
1654
+ }
1655
+ for (const m of materialsOf(o)) {
1656
+ materials.add(m);
1657
+ for (const slot of TEXTURE_SLOTS) if (m[slot]?.isTexture) textures.add(m[slot]);
1658
+ }
1659
+ }
1660
+ let pbr = 0;
1661
+ const simple = /* @__PURE__ */ new Set();
1662
+ for (const m of materials) {
1663
+ if (isPbr(m)) pbr++;
1664
+ else if (m.isMeshBasicMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial || m.isMeshToonMaterial)
1665
+ simple.add(String(m.type));
1666
+ }
1667
+ let largestTexture = 0;
1668
+ let pixels = 0;
1669
+ let noAniso = 0;
1670
+ for (const t of textures) {
1671
+ const w = Number(t.image?.width ?? t.image?.videoWidth ?? 0) || 0;
1672
+ const h = Number(t.image?.height ?? t.image?.videoHeight ?? 0) || 0;
1673
+ largestTexture = Math.max(largestTexture, w, h);
1674
+ pixels += w * h;
1675
+ if ((t.anisotropy ?? 1) <= 1) noAniso++;
1676
+ }
1677
+ const others = largest.filter((v, i) => i !== index && v > 0).sort((a, b) => a - b);
1678
+ const median = others.length ? others[Math.floor(others.length / 2)] : null;
1679
+ const ground = this.ground(index, box2, solids, owner, budget);
1680
+ budget -= ground.tested;
1681
+ models.push({
1682
+ uuid: String(root.uuid),
1683
+ name: String(root.name ?? ""),
1684
+ added: this.known.size > 0 && meshes.every((o) => !this.known.has(o.uuid)),
1685
+ meshes: meshes.length,
1686
+ triangles,
1687
+ size,
1688
+ center,
1689
+ relativeSize: median ? largest[index] / median : null,
1690
+ gap: ground.gap,
1691
+ gapExact: ground.exact,
1692
+ support: ground.support,
1693
+ ...onScreen(camera, box2, center),
1694
+ castsShadow: casts,
1695
+ receivesShadow: receives,
1696
+ pbrMaterials: pbr,
1697
+ simpleMaterials: [...simple],
1698
+ textures: textures.size,
1699
+ largestTexture,
1700
+ texturePixels: pixels,
1701
+ wrongColorSpace: colorFaults(materials).size,
1702
+ texturesWithoutAnisotropy: noAniso
1703
+ });
1704
+ });
1705
+ if (acknowledge) for (const o of solids) this.known.add(o.uuid);
1706
+ return { radius: sceneSphere(scene).radius, models };
1707
+ }
1708
+ /**
1709
+ * The surface under a model: straight down from the middle and the four quarters of its
1710
+ * footprint, against the triangles of everything that is not the model itself.
1711
+ */
1712
+ ground(index, box2, solids, owner, budget) {
1713
+ const bottom = box2.min[1];
1714
+ const height = Math.max(box2.max[1] - bottom, 1e-9);
1715
+ const ceiling = bottom + height * 0.5;
1716
+ const cx = (box2.min[0] + box2.max[0]) / 2;
1717
+ const cz = (box2.min[2] + box2.max[2]) / 2;
1718
+ const qx = (box2.max[0] - box2.min[0]) * 0.3;
1719
+ const qz = (box2.max[2] - box2.min[2]) * 0.3;
1720
+ const points = [
1721
+ [cx, cz],
1722
+ [cx - qx, cz - qz],
1723
+ [cx + qx, cz - qz],
1724
+ [cx - qx, cz + qz],
1725
+ [cx + qx, cz + qz]
1726
+ ];
1727
+ let top = -Infinity;
1728
+ let support = null;
1729
+ let exact = true;
1730
+ let tested = 0;
1731
+ const hit = (y, o) => {
1732
+ if (y <= ceiling && y > top) {
1733
+ top = y;
1734
+ support = o;
1735
+ }
1736
+ };
1737
+ for (const o of solids) {
1738
+ if (owner.get(o) === index) continue;
1739
+ const b = meshBox(o);
1740
+ if (!b || b.min[1] > ceiling) continue;
1741
+ const over = points.filter(
1742
+ ([x, z]) => x >= b.min[0] && x <= b.max[0] && z >= b.min[2] && z <= b.max[2]
1743
+ );
1744
+ if (!over.length) continue;
1745
+ const g = o.geometry;
1746
+ const pos = g.attributes?.position;
1747
+ const count = g.index ? g.index.count : pos?.count ?? 0;
1748
+ const e = o.matrixWorld?.elements;
1749
+ const readable = pos && typeof pos.getX === "function" && e && !o.isInstancedMesh && !o.isSkinnedMesh;
1750
+ if (!readable || count / 3 > budget - tested) {
1751
+ exact = false;
1752
+ if (b.max[1] <= ceiling) hit(b.max[1], o);
1753
+ continue;
1754
+ }
1755
+ tested += count / 3;
1756
+ const index3 = g.index;
1757
+ const v = [0, 0, 0, 0, 0, 0, 0, 0, 0];
1758
+ for (let i = 0; i + 2 < count; i += 3) {
1759
+ for (let k = 0; k < 3; k++) {
1760
+ const vi = index3 ? index3.getX(i + k) : i + k;
1761
+ const x = pos.getX(vi);
1762
+ const y = pos.getY(vi);
1763
+ const z = pos.getZ(vi);
1764
+ v[k * 3] = e[0] * x + e[4] * y + e[8] * z + e[12];
1765
+ v[k * 3 + 1] = e[1] * x + e[5] * y + e[9] * z + e[13];
1766
+ v[k * 3 + 2] = e[2] * x + e[6] * y + e[10] * z + e[14];
1767
+ }
1768
+ const minX = Math.min(v[0], v[3], v[6]);
1769
+ const maxX = Math.max(v[0], v[3], v[6]);
1770
+ const minZ = Math.min(v[2], v[5], v[8]);
1771
+ const maxZ = Math.max(v[2], v[5], v[8]);
1772
+ for (const [px, pz] of over) {
1773
+ if (px < minX || px > maxX || pz < minZ || pz > maxZ) continue;
1774
+ const d = (v[5] - v[8]) * (v[0] - v[6]) + (v[6] - v[3]) * (v[2] - v[8]);
1775
+ if (Math.abs(d) < 1e-12) continue;
1776
+ const a = ((v[5] - v[8]) * (px - v[6]) + (v[6] - v[3]) * (pz - v[8])) / d;
1777
+ const c = ((v[8] - v[2]) * (px - v[6]) + (v[0] - v[6]) * (pz - v[8])) / d;
1778
+ const f = 1 - a - c;
1779
+ if (a < -1e-6 || c < -1e-6 || f < -1e-6) continue;
1780
+ hit(a * v[1] + c * v[4] + f * v[7], o);
1781
+ }
1782
+ }
1783
+ }
1784
+ if (!support) return { gap: null, exact, support: null, tested };
1785
+ const s = support;
1786
+ return { gap: bottom - top, exact, support: String(s.name || s.type || ""), tested };
1787
+ }
1788
+ /** Meshes the bevel can round: all of them, or the chosen ones. */
1789
+ bevelCandidates() {
1790
+ const out = [];
1791
+ walk(this.target.scene, (o) => {
1792
+ const original = this.site.bevelled.get(o);
1793
+ if (original ? true : bevelKind(o)) out.push(o);
1794
+ });
1795
+ return out;
1796
+ }
1797
+ bevel(look) {
1798
+ const undo = this.undo.bevel;
1799
+ if (look.bevel.mode === "off") return;
1800
+ let targets;
1801
+ if (look.bevel.mode === "all") targets = this.bevelCandidates();
1802
+ else {
1803
+ targets = [];
1804
+ for (const ref of look.bevel.targets) targets.push(...this.find(ref));
1805
+ }
1806
+ let made = 0;
1807
+ const unsupported = [];
1808
+ for (const o of targets) {
1809
+ const kind = bevelKind(o);
1810
+ if (!kind) {
1811
+ unsupported.push(o.name || o.type);
1812
+ continue;
1813
+ }
1814
+ const g = o.geometry;
1815
+ const p = g.parameters;
1816
+ const scale = worldScale(o);
1817
+ let data;
1818
+ if (kind === "box") {
1819
+ const smallest = Math.min(p.width * scale[0], p.height * scale[1], p.depth * scale[2]);
1820
+ data = roundedBox(
1821
+ p.width,
1822
+ p.height,
1823
+ p.depth,
1824
+ smallest * look.bevel.amount,
1825
+ look.bevel.segments,
1826
+ // Instances carry their own scale on top, which the geometry cannot follow.
1827
+ o.isInstancedMesh ? [1, 1, 1] : scale
1828
+ );
1829
+ } else {
1830
+ const smallest = Math.min(p.radiusTop * 2, p.height);
1831
+ data = roundedCylinder(
1832
+ p.radiusTop,
1833
+ p.height,
1834
+ p.radialSegments ?? 32,
1835
+ smallest * look.bevel.amount,
1836
+ look.bevel.segments
1837
+ );
1838
+ }
1839
+ const center = boundsCenter(g);
1840
+ if (center[0] || center[1] || center[2])
1841
+ for (let i = 0; i < data.position.length; i += 3) {
1842
+ data.position[i] = data.position[i] + center[0];
1843
+ data.position[i + 1] = data.position[i + 1] + center[1];
1844
+ data.position[i + 2] = data.position[i + 2] + center[2];
1845
+ }
1846
+ const next = this.kit.geometry(data);
1847
+ if (!next) {
1848
+ this.note("Bevelled geometry could not be made on this page.");
1849
+ break;
1850
+ }
1851
+ this.site.bevelled.set(o, g);
1852
+ o.geometry = next;
1853
+ made++;
1854
+ undo.push(() => {
1855
+ o.geometry = g;
1856
+ this.site.bevelled.delete(o);
1857
+ this.kit.dispose(next);
1858
+ });
1859
+ }
1860
+ if (unsupported.length)
1861
+ this.note(
1862
+ `Only box and cylinder meshes can be bevelled here (not ${unsupported.slice(0, 4).join(", ")}${unsupported.length > 4 ? "\u2026" : ""}). For other shapes, bevel the model in the modelling tool.`
1863
+ );
1864
+ if (!made && look.bevel.mode === "all" && !unsupported.length)
1865
+ this.note("No box or cylinder meshes to bevel in this scene.");
1866
+ }
1867
+ /** What the realism check needs to know about the site as it is without the look. */
1868
+ facts(extra) {
1869
+ const { renderer, scene, camera } = this.target;
1870
+ let antialias = null;
1871
+ try {
1872
+ antialias = renderer.getContext?.()?.getContextAttributes?.()?.antialias ?? null;
1873
+ } catch {
1874
+ }
1875
+ const srgb = typeof renderer.outputColorSpace === "string" ? renderer.outputColorSpace === "srgb" : typeof renderer.outputEncoding === "number" ? renderer.outputEncoding === 3001 : null;
1876
+ let lights = 0;
1877
+ let shadowLights = 0;
1878
+ let shadowCapable = 0;
1879
+ let hardEdges = 0;
1880
+ let lowPoly = 0;
1881
+ const materials = /* @__PURE__ */ new Set();
1882
+ const textures = /* @__PURE__ */ new Set();
1883
+ walk(scene, (o) => {
1884
+ if (o.isLight) {
1885
+ lights++;
1886
+ if (o.isDirectionalLight || o.isSpotLight) {
1887
+ shadowCapable++;
1888
+ if (o.castShadow) shadowLights++;
1889
+ }
1890
+ }
1891
+ if (!o.isMesh || o.visible === false) return;
1892
+ const original = this.site.bevelled.get(o);
1893
+ if (original || bevelKind(o)) hardEdges++;
1894
+ const g = original ?? o.geometry;
1895
+ const p = g?.parameters;
1896
+ if (p && g.type === "SphereGeometry" && (p.widthSegments ?? 32) < 24) lowPoly++;
1897
+ else if (p && (g.type === "CylinderGeometry" || g.type === "ConeGeometry") && (p.radialSegments ?? 32) > 12 && (p.radialSegments ?? 32) < 24)
1898
+ lowPoly++;
1899
+ for (const m of materialsOf(o)) {
1900
+ materials.add(m);
1901
+ for (const slot of TEXTURE_SLOTS) if (m[slot]?.isTexture) textures.add(m[slot]);
1902
+ }
1903
+ });
1904
+ let pbr = 0;
1905
+ let simple = 0;
1906
+ let metals = 0;
1907
+ for (const m of materials) {
1908
+ if (m.isMeshStandardMaterial || m.isMeshPhysicalMaterial) {
1909
+ pbr++;
1910
+ if ((m.metalness ?? 0) >= 0.9) metals++;
1911
+ } else if (m.isMeshBasicMaterial || m.isMeshLambertMaterial || m.isMeshPhongMaterial || m.isMeshToonMaterial)
1912
+ simple++;
1913
+ }
1914
+ let noAniso = 0;
1915
+ for (const t of textures)
1916
+ if ((this.site.anisotropy.get(t) ?? t.anisotropy ?? 1) <= 1) noAniso++;
1917
+ const environment = this.site.environment !== void 0 ? this.site.environment : scene.environment;
1918
+ const near = camera?.near;
1919
+ const far = camera?.far;
1920
+ return {
1921
+ revision: this.revision(),
1922
+ toneMapping: this.site.toneMapping ?? (typeof renderer.toneMapping === "number" ? renderer.toneMapping : null),
1923
+ exposure: this.site.exposure ?? (typeof renderer.toneMappingExposure === "number" ? renderer.toneMappingExposure : null),
1924
+ srgbOutput: srgb,
1925
+ pixelRatio: this.site.pixelRatio ?? renderer.getPixelRatio?.() ?? 1,
1926
+ devicePixelRatio: this.kit.devicePixelRatio(),
1927
+ antialias,
1928
+ hasEnvironment: !!environment,
1929
+ lights,
1930
+ pbrMaterials: pbr,
1931
+ simpleMaterials: simple,
1932
+ metals,
1933
+ shadowsEnabled: this.site.shadowsEnabled ?? !!renderer.shadowMap?.enabled,
1934
+ shadowLights,
1935
+ shadowCapableLights: shadowCapable,
1936
+ hardEdgeMeshes: hardEdges,
1937
+ lowPolyRound: lowPoly,
1938
+ textures: textures.size,
1939
+ texturesWithoutAnisotropy: noAniso,
1940
+ depthRatio: typeof near === "number" && typeof far === "number" && near > 0 ? far / near : null,
1941
+ sitePostProcessing: extra.sitePostProcessing,
1942
+ effectsAvailable: extra.effectsAvailable
1943
+ };
1944
+ }
1945
+ };
1946
+
1947
+ // src/lookRuntime.ts
1948
+ var sameThree = (renderer) => renderer instanceof THREE.WebGLRenderer;
1949
+ var FinishShader = {
1950
+ uniforms: {
1951
+ tDiffuse: { value: null },
1952
+ uVignette: { value: 0 },
1953
+ uGrain: { value: 0 },
1954
+ uTime: { value: 0 }
1955
+ },
1956
+ vertexShader: (
1957
+ /* glsl */
1958
+ `
1959
+ varying vec2 vUv;
1960
+ void main() {
1961
+ vUv = uv;
1962
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1963
+ }`
1964
+ ),
1965
+ fragmentShader: (
1966
+ /* glsl */
1967
+ `
1968
+ uniform sampler2D tDiffuse;
1969
+ uniform float uVignette;
1970
+ uniform float uGrain;
1971
+ uniform float uTime;
1972
+ varying vec2 vUv;
1973
+ void main() {
1974
+ vec4 color = texture2D(tDiffuse, vUv);
1975
+ float d = distance(vUv, vec2(0.5));
1976
+ color.rgb *= mix(1.0, smoothstep(0.85, 0.25, d), uVignette);
1977
+ float n = fract(sin(dot(vUv * 913.7 + uTime, vec2(12.9898, 78.233))) * 43758.5453) - 0.5;
1978
+ color.rgb += n * uGrain * 0.14;
1979
+ gl_FragColor = color;
1980
+ }`
1981
+ )
1982
+ };
1983
+ function createEffects(renderer) {
1984
+ let settings = null;
1985
+ let composer = null;
1986
+ let renderPass = null;
1987
+ let finish = null;
1988
+ const sceneAware = [];
1989
+ const size = new THREE.Vector2();
1990
+ let canvasSmooth = false;
1991
+ try {
1992
+ canvasSmooth = renderer.getContext().getContextAttributes()?.antialias === true;
1993
+ } catch {
1994
+ }
1995
+ let builtFor = "";
1996
+ let last = { w: 0, h: 0, ratio: 0 };
1997
+ const dispose = () => {
1998
+ if (!composer) return;
1999
+ for (const pass of composer.passes) pass.dispose?.();
2000
+ composer.dispose();
2001
+ composer = null;
2002
+ renderPass = null;
2003
+ finish = null;
2004
+ sceneAware.length = 0;
2005
+ builtFor = "";
2006
+ };
2007
+ function build(scene, camera) {
2008
+ const e = settings;
2009
+ dispose();
2010
+ renderer.getSize(size);
2011
+ const ratio = renderer.getPixelRatio();
2012
+ const w = Math.max(1, Math.round(size.x * ratio));
2013
+ const h = Math.max(1, Math.round(size.y * ratio));
2014
+ const target = new THREE.WebGLRenderTarget(w, h, {
2015
+ type: THREE.HalfFloatType,
2016
+ samples: e.antialias || canvasSmooth ? 4 : 0
2017
+ });
2018
+ composer = new EffectComposer(renderer, target);
2019
+ composer.setPixelRatio(ratio);
2020
+ composer.setSize(size.x, size.y);
2021
+ renderPass = new RenderPass(scene, camera);
2022
+ composer.addPass(renderPass);
2023
+ if (e.ao.on) {
2024
+ const ao = new GTAOPass(scene, camera, w, h);
2025
+ ao.blendIntensity = e.ao.intensity;
2026
+ ao.updateGtaoMaterial({ radius: e.ao.radius });
2027
+ sceneAware.push(ao);
2028
+ composer.addPass(ao);
2029
+ }
2030
+ if (e.dof.on) {
2031
+ const dof = new BokehPass(scene, camera, {
2032
+ focus: e.dof.focus,
2033
+ aperture: e.dof.aperture,
2034
+ maxblur: e.dof.maxBlur
2035
+ });
2036
+ sceneAware.push(dof);
2037
+ composer.addPass(dof);
2038
+ }
2039
+ if (e.bloom.on)
2040
+ composer.addPass(
2041
+ new UnrealBloomPass(
2042
+ new THREE.Vector2(w, h),
2043
+ e.bloom.strength,
2044
+ e.bloom.radius,
2045
+ e.bloom.threshold
2046
+ )
2047
+ );
2048
+ composer.addPass(new OutputPass());
2049
+ if (e.vignette > 0 || e.grain > 0) {
2050
+ finish = new ShaderPass(FinishShader);
2051
+ finish.uniforms.uVignette.value = e.vignette;
2052
+ finish.uniforms.uGrain.value = e.grain;
2053
+ composer.addPass(finish);
2054
+ }
2055
+ if (e.antialias) {
2056
+ const Smaa = SMAAPass;
2057
+ composer.addPass(new Smaa(w, h));
2058
+ }
2059
+ last = { w: size.x, h: size.y, ratio };
2060
+ builtFor = JSON.stringify(e);
2061
+ }
2062
+ return {
2063
+ set(next) {
2064
+ settings = next && effectsOn(next) ? JSON.parse(JSON.stringify(next)) : null;
2065
+ if (!settings) dispose();
2066
+ },
2067
+ get active() {
2068
+ return settings !== null;
2069
+ },
2070
+ render(scene, camera) {
2071
+ if (!settings) {
2072
+ renderer.render(scene, camera);
2073
+ return;
2074
+ }
2075
+ if (!composer || builtFor !== JSON.stringify(settings)) build(scene, camera);
2076
+ renderer.getSize(size);
2077
+ const ratio = renderer.getPixelRatio();
2078
+ if (size.x !== last.w || size.y !== last.h || ratio !== last.ratio) {
2079
+ composer.setPixelRatio(ratio);
2080
+ composer.setSize(size.x, size.y);
2081
+ last = { w: size.x, h: size.y, ratio };
2082
+ }
2083
+ renderPass.scene = scene;
2084
+ renderPass.camera = camera;
2085
+ for (const pass of sceneAware) {
2086
+ pass.scene = scene;
2087
+ pass.camera = camera;
2088
+ }
2089
+ if (finish) finish.uniforms.uTime.value = performance.now() / 1e3 % 100;
2090
+ composer.render();
2091
+ },
2092
+ dispose
2093
+ };
2094
+ }
2095
+ function threeKit() {
2096
+ return {
2097
+ texture(data, width, height) {
2098
+ const texture = new THREE.DataTexture(
2099
+ data,
2100
+ width,
2101
+ height,
2102
+ THREE.RGBAFormat,
2103
+ THREE.HalfFloatType
2104
+ );
2105
+ texture.mapping = THREE.EquirectangularReflectionMapping;
2106
+ texture.colorSpace = THREE.LinearSRGBColorSpace;
2107
+ texture.magFilter = THREE.LinearFilter;
2108
+ texture.minFilter = THREE.LinearFilter;
2109
+ texture.generateMipmaps = false;
2110
+ texture.needsUpdate = true;
2111
+ return texture;
2112
+ },
2113
+ image(levels, size) {
2114
+ const texture = new THREE.DataTexture(
2115
+ levels[0],
2116
+ size,
2117
+ size,
2118
+ THREE.RGBAFormat,
2119
+ THREE.UnsignedByteType
2120
+ );
2121
+ texture.mipmaps = levels.map((data, i) => ({ data, width: size >> i, height: size >> i }));
2122
+ texture.colorSpace = THREE.NoColorSpace;
2123
+ texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
2124
+ texture.magFilter = THREE.LinearFilter;
2125
+ texture.minFilter = THREE.LinearMipmapLinearFilter;
2126
+ texture.generateMipmaps = false;
2127
+ texture.anisotropy = 8;
2128
+ texture.needsUpdate = true;
2129
+ return texture;
2130
+ },
2131
+ geometry(data) {
2132
+ const geometry = new THREE.BufferGeometry();
2133
+ geometry.setAttribute("position", new THREE.BufferAttribute(data.position, 3));
2134
+ geometry.setAttribute("normal", new THREE.BufferAttribute(data.normal, 3));
2135
+ geometry.setAttribute("uv", new THREE.BufferAttribute(data.uv, 2));
2136
+ return geometry;
2137
+ },
2138
+ dispose(resource) {
2139
+ resource?.dispose?.();
2140
+ },
2141
+ devicePixelRatio: () => typeof window === "undefined" ? 1 : window.devicePixelRatio || 1
2142
+ };
2143
+ }
2144
+ function applyLook(target, look) {
2145
+ const applier = new LookApplier(target, threeKit());
2146
+ const effects = createEffects(target.renderer);
2147
+ let notes = [];
2148
+ let current = normalizeLook(look);
2149
+ const lightened = [];
2150
+ const show = (next) => {
2151
+ current = next;
2152
+ target.scene.updateMatrixWorld(true);
2153
+ notes = applier.apply(next);
2154
+ effects.set(next.effects);
2155
+ };
2156
+ const update = (next) => {
2157
+ lightened.length = 0;
2158
+ watch = { last: 0, frames: 0, total: 0, slow: 0, settle: SETTLE_FRAMES };
2159
+ show(normalizeLook(next));
2160
+ return notes;
2161
+ };
2162
+ const WINDOW = 90;
2163
+ const SETTLE_FRAMES = 45;
2164
+ let watch = { last: 0, frames: 0, total: 0, slow: 0, settle: SETTLE_FRAMES };
2165
+ const measure = () => {
2166
+ if (!current.performance.adaptive) return;
2167
+ const now = performance.now();
2168
+ const dt = now - watch.last;
2169
+ watch.last = now;
2170
+ if (watch.settle > 0) {
2171
+ watch.settle--;
2172
+ return;
2173
+ }
2174
+ if (dt <= 0 || dt > 500) return;
2175
+ watch.total += dt;
2176
+ if (++watch.frames < WINDOW) return;
2177
+ const average = watch.total / watch.frames;
2178
+ watch.frames = 0;
2179
+ watch.total = 0;
2180
+ watch.slow = average > 1e3 / current.performance.targetFps * 1.2 ? watch.slow + 1 : 0;
2181
+ if (watch.slow < 2) return;
2182
+ const lighter = lighten(current);
2183
+ watch.slow = 0;
2184
+ if (!lighter) return;
2185
+ lightened.push(lighter.step);
2186
+ watch.settle = SETTLE_FRAMES;
2187
+ show(lighter.look);
2188
+ };
2189
+ const FOLLOW_EVERY = 30;
2190
+ let frames = 0;
2191
+ show(current);
2192
+ return {
2193
+ render(scene = target.scene, camera = target.camera) {
2194
+ measure();
2195
+ if (++frames % FOLLOW_EVERY === 0 && applier.follow()) notes = applier.notes;
2196
+ effects.render(scene, camera);
2197
+ },
2198
+ update,
2199
+ get notes() {
2200
+ return notes;
2201
+ },
2202
+ get lightened() {
2203
+ return lightened;
2204
+ },
2205
+ dispose() {
2206
+ effects.dispose();
2207
+ applier.reset();
2208
+ }
2209
+ };
2210
+ }
2211
+ export {
2212
+ LookApplier,
2213
+ applyLook,
2214
+ createEffects,
2215
+ defaultLook,
2216
+ effectsOn,
2217
+ isNeutral,
2218
+ lighten,
2219
+ mergeLook,
2220
+ normalizeLook,
2221
+ sameThree,
2222
+ threeKit
2223
+ };