stack3js 0.2.0 → 0.6.4
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/COMMAND.md +145 -0
- package/README.md +167 -4
- package/bin/stack3.mjs +1386 -186
- package/blender/import_stack.py +89 -0
- package/meshing/blocks.py +82 -0
- package/meshing/branches.py +62 -0
- package/meshing/dexel.py +67 -0
- package/meshing/field_data.py +19 -0
- package/meshing/finish_blender.py +203 -0
- package/meshing/finishing.py +155 -0
- package/meshing/geometry.py +71 -0
- package/meshing/guided.py +150 -0
- package/meshing/implicit.py +178 -0
- package/meshing/intersection.py +33 -0
- package/meshing/material.py +115 -0
- package/meshing/mesh.py +103 -0
- package/meshing/network.py +136 -0
- package/meshing/regularization.py +213 -0
- package/meshing/sections.py +165 -0
- package/meshing/signed_distance.py +93 -0
- package/package.json +9 -2
- package/references/hard-surface/README.md +40 -0
- package/references/hard-surface/atlas/concrete-barrier-4view.png +0 -0
- package/references/hard-surface/atlas/preview.pipeline.yaml +14 -0
- package/references/hard-surface/case-studies/benchmark/README.md +22 -0
- package/references/hard-surface/case-studies/benchmark/lod-bevel.pipeline.yaml +258 -0
- package/references/hard-surface/finishing/exports.yaml +10 -0
- package/references/hard-surface/finishing/finish-lod.pipeline.yaml +33 -0
- package/references/hard-surface/finishing/inputs/stack/stack.json +1 -0
- package/references/hard-surface/finishing/inputs/stack/stack.png +0 -0
- package/references/hard-surface/finishing/regularize.pipeline.yaml +46 -0
- package/references/hard-surface/measured-depth/sdf/compare.pipeline.yaml +12 -0
- package/references/hard-surface/measured-depth/sdf/inputs/field.npy +0 -0
- package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.json +1 -0
- package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.png +0 -0
- package/references/hard-surface/measured-depth/sdf/inputs/truth.json +1 -0
- package/references/hard-surface/measured-depth/sdf/sdf.guide.json +3 -0
- package/references/hard-surface/measured-depth/triple-dexel/compare.pipeline.yaml +12 -0
- package/references/hard-surface/measured-depth/triple-dexel/dexel.guide.json +3 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/fixture.json +22 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.json +22 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.png +0 -0
- package/references/hard-surface/measured-depth/triple-dexel/inputs/triple-dexel.npz +0 -0
- package/references/hard-surface/schema/pipeline-fragment.schema.json +5 -0
- package/references/hard-surface/schema/pipeline.schema.json +181 -0
- package/schema/pipeline-fragment.schema.json +5 -0
- package/schema/pipeline.schema.json +181 -0
- package/verification/assembly.py +96 -0
- package/verification/landmarks.py +53 -0
- package/verification/panels.py +137 -0
- package/verification/projections.py +135 -0
- package/verification/verify.py +108 -0
- package/viewer/dist/assets/{GLTFExporter--hziUXc8.js → GLTFExporter-xdVCArY-.js} +1 -1
- package/viewer/dist/assets/compare-Du4RoRQO.js +6 -0
- package/viewer/dist/assets/compare.worker-CgJq-znx.js +21 -0
- package/viewer/dist/assets/presets-jXE0t1fU.js +1 -0
- package/viewer/dist/assets/preview-cache-BKV0EZl9.js +1 -0
- package/viewer/dist/assets/project-DtHHhfo-.js +17 -0
- package/viewer/dist/assets/reconstruct.worker-ONc9GyFO.js +21 -0
- package/viewer/dist/assets/{script-engine-CLj7QMLe.js → script-engine-Bs3azDYZ.js} +1 -1
- package/viewer/dist/assets/style-D6eZHs3D.js +4004 -0
- package/viewer/dist/assets/viewer-DIjS0No7.js +2 -0
- package/viewer/dist/compare.html +4 -4
- package/viewer/dist/index.html +9 -8
- package/viewer/dist/project.html +3 -3
- package/viewer/dist/assets/compare-DJ8rV3Rn.js +0 -6
- package/viewer/dist/assets/compare.worker-DK2lJl0n.js +0 -21
- package/viewer/dist/assets/presets-DwdZVYhs.js +0 -1
- package/viewer/dist/assets/preview-cache-DRF_H5pq.js +0 -58
- package/viewer/dist/assets/project-D8tR6U-_.js +0 -17
- package/viewer/dist/assets/reconstruct.worker-Cf8iZwT3.js +0 -21
- package/viewer/dist/assets/style-CWGgpweN.js +0 -3947
- package/viewer/dist/assets/viewer-CyGodHLY.js +0 -2
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Orthographic registration in pixel-center coordinates, without resampling source pixels."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
import cv2
|
|
6
|
+
import numpy as np
|
|
7
|
+
import yaml
|
|
8
|
+
from PIL import Image, ImageDraw
|
|
9
|
+
|
|
10
|
+
AXES = {"top": ("x", "y"), "left": ("y", "z"), "front": ("x", "z"), "rear": ("x", "z")}
|
|
11
|
+
SIGNS = {"top": (1, 1), "left": (-1, -1), "front": (1, -1), "rear": (-1, -1)}
|
|
12
|
+
RED, CYAN, GOLD, GREEN = (205, 38, 58), (0, 152, 177), (241, 139, 0), (41, 155, 81)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def read_manifest(path):
|
|
16
|
+
data = yaml.safe_load(Path(path).read_text(encoding="utf8"))
|
|
17
|
+
if not isinstance(data, dict):
|
|
18
|
+
raise ValueError(f"{path}: expected a YAML mapping")
|
|
19
|
+
return data
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def scalar(value, label):
|
|
23
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
24
|
+
raise ValueError(f"{label}: expected a finite number")
|
|
25
|
+
return float(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def point(value, label):
|
|
29
|
+
if not isinstance(value, list) or len(value) != 2:
|
|
30
|
+
raise ValueError(f"{label}: expected [u, v]")
|
|
31
|
+
return [scalar(v, label) for v in value]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Panel:
|
|
35
|
+
def __init__(self, view, config, folder, images):
|
|
36
|
+
self.view = view
|
|
37
|
+
self.axes, self.signs = AXES[view], SIGNS[view]
|
|
38
|
+
path = folder / config["image"]
|
|
39
|
+
if path not in images:
|
|
40
|
+
with Image.open(path) as source:
|
|
41
|
+
images[path] = source.convert("RGBA")
|
|
42
|
+
img = images[path]
|
|
43
|
+
if "crop" in config:
|
|
44
|
+
x, y, w, h = config["crop"]
|
|
45
|
+
if any(type(n) is not int for n in (x, y, w, h)) or min(x, y) < 0 or min(w, h) < 1 or x+w > img.width or y+h > img.height:
|
|
46
|
+
raise ValueError(f"{view}: invalid crop [x,y,width,height]")
|
|
47
|
+
img = img.crop((x, y, x+w, y+h))
|
|
48
|
+
pixels = np.asarray(img)
|
|
49
|
+
mode = config.get("mask", "alpha")
|
|
50
|
+
self.mask = pixels[:, :, 3] >= 128
|
|
51
|
+
if mode == "white":
|
|
52
|
+
threshold = scalar(config.get("threshold", 238), "threshold")
|
|
53
|
+
if not 0 <= threshold <= 255:
|
|
54
|
+
raise ValueError("threshold must be in [0,255]")
|
|
55
|
+
self.mask &= pixels[:, :, :3].min(axis=2) < threshold
|
|
56
|
+
elif mode == "alpha" and self.mask.all() and "mask" not in config:
|
|
57
|
+
raise ValueError(f"{view}: opaque panel; choose mask: white or explicitly confirm mask: alpha")
|
|
58
|
+
elif mode != "alpha":
|
|
59
|
+
raise ValueError(f"{view}: mask must be alpha or white")
|
|
60
|
+
if not self.mask.any():
|
|
61
|
+
raise ValueError(f"{view}: empty foreground")
|
|
62
|
+
self.image = Image.new("RGB", img.size, "white")
|
|
63
|
+
self.image.paste(img, mask=img.getchannel("A"))
|
|
64
|
+
self.origin = point(config["origin"], f"{view}.origin") if "origin" in config else None
|
|
65
|
+
self.scale = scalar(config["scale"], f"{view}.scale") if "scale" in config else None
|
|
66
|
+
if self.scale is not None and self.scale <= 0:
|
|
67
|
+
raise ValueError(f"{view}: scale must be positive")
|
|
68
|
+
self.contours = [c[:, 0, :] for c in cv2.findContours(self.mask.astype("uint8"), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[0]]
|
|
69
|
+
self.lines = {}
|
|
70
|
+
|
|
71
|
+
def world(self, pixel):
|
|
72
|
+
return {a: (pixel[i] - self.origin[i]) * self.signs[i] / self.scale for i, a in enumerate(self.axes)}
|
|
73
|
+
|
|
74
|
+
def pixel(self, world):
|
|
75
|
+
return [self.origin[i] + world[a] * self.signs[i] * self.scale for i, a in enumerate(self.axes)]
|
|
76
|
+
|
|
77
|
+
def annotation(self, value, label):
|
|
78
|
+
coord = point(value, label)
|
|
79
|
+
if not all(0 <= c < limit for c, limit in zip(coord, self.image.size)):
|
|
80
|
+
raise ValueError(f"{label}: point outside {self.view} panel")
|
|
81
|
+
return coord
|
|
82
|
+
|
|
83
|
+
def intervals(self, axis, constant):
|
|
84
|
+
"""All foreground pixel footprints on one scanline, in increasing world coordinates."""
|
|
85
|
+
i = self.axes.index(axis)
|
|
86
|
+
index = math.floor(self.origin[i] + constant*self.scale*self.signs[i] + .5)
|
|
87
|
+
key = (i, index)
|
|
88
|
+
if key not in self.lines:
|
|
89
|
+
result = []
|
|
90
|
+
if 0 <= index < self.image.size[i]:
|
|
91
|
+
line = self.mask[:, index] if i == 0 else self.mask[index, :]
|
|
92
|
+
runs = np.flatnonzero(np.diff(np.pad(line.astype(np.int8), 1))).reshape(-1, 2)
|
|
93
|
+
j = 1-i
|
|
94
|
+
for start, end in runs:
|
|
95
|
+
pair = [((float(n)-.5)-self.origin[j])*self.signs[j]/self.scale for n in (start, end)]
|
|
96
|
+
result.append(sorted(pair))
|
|
97
|
+
self.lines[key] = sorted(result)
|
|
98
|
+
return self.lines[key]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def atlas(path, data=None):
|
|
102
|
+
if data is None:
|
|
103
|
+
data = read_manifest(path)
|
|
104
|
+
configs = data["views"]
|
|
105
|
+
if not isinstance(configs, dict) or set(configs) != set(AXES):
|
|
106
|
+
raise ValueError("views must map top, left, front and rear")
|
|
107
|
+
images = {}
|
|
108
|
+
panels = {v: Panel(v, configs[v], path.parent, images) for v in AXES}
|
|
109
|
+
return data, panels
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def unregistered(panels):
|
|
113
|
+
return [v for v, p in panels.items() if p.origin is None or p.scale is None]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def dot(draw, xy, color, radius=4):
|
|
117
|
+
x, y = xy
|
|
118
|
+
draw.ellipse((x-radius, y-radius, x+radius, y+radius), outline=color, width=2)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def sheet(images, title, legend):
|
|
122
|
+
# Keep pixel geometry untouched in each panel; pad cells only.
|
|
123
|
+
width = max(360, max(im.width for im in images.values()) + 16)
|
|
124
|
+
height = max(im.height for im in images.values()) + 32
|
|
125
|
+
result = Image.new("RGB", (2*width, 2*height+54), (235, 238, 241))
|
|
126
|
+
d = ImageDraw.Draw(result)
|
|
127
|
+
d.text((8, 5), title, fill="black")
|
|
128
|
+
d.text((8, 26), legend, fill="black")
|
|
129
|
+
for i, (v, im) in enumerate(images.items()):
|
|
130
|
+
x, y = i%2*width+8, i//2*height+56
|
|
131
|
+
d.text((x, y), v.upper(), fill="black")
|
|
132
|
+
result.paste(im, (x, y+16))
|
|
133
|
+
return result
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def canvas(panels):
|
|
137
|
+
return {v: p.image.copy() for v, p in panels.items()}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import math
|
|
2
|
+
|
|
3
|
+
import cv2
|
|
4
|
+
import numpy as np
|
|
5
|
+
from PIL import ImageDraw
|
|
6
|
+
|
|
7
|
+
from panels import RED, CYAN, GOLD, canvas, dot, sheet
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def gap(intervals):
|
|
11
|
+
"""Smallest gap between a simultaneous choice of one interval per row."""
|
|
12
|
+
if any(not row for row in intervals):
|
|
13
|
+
return None
|
|
14
|
+
at = [0]*len(intervals)
|
|
15
|
+
best = math.inf
|
|
16
|
+
while True:
|
|
17
|
+
current = [row[pos] for row, pos in zip(intervals, at)]
|
|
18
|
+
first_end = min(range(len(current)), key=lambda i: current[i][1])
|
|
19
|
+
separation = max(a for a, _ in current) - current[first_end][1]
|
|
20
|
+
if separation <= 1e-9:
|
|
21
|
+
return 0
|
|
22
|
+
best = min(best, separation)
|
|
23
|
+
at[first_end] += 1
|
|
24
|
+
if at[first_end] == len(intervals[first_end]):
|
|
25
|
+
return best
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sample(source, xy, panels, distances):
|
|
29
|
+
world = source.world(xy)
|
|
30
|
+
lines, parallel = {}, []
|
|
31
|
+
missing = next(a for a in "xyz" if a not in world)
|
|
32
|
+
for name, target in panels.items():
|
|
33
|
+
if target is source:
|
|
34
|
+
continue
|
|
35
|
+
if missing not in target.axes:
|
|
36
|
+
u, v = target.pixel(world)
|
|
37
|
+
i, j = math.floor(u+.5), math.floor(v+.5)
|
|
38
|
+
if not (0 <= i < target.image.width and 0 <= j < target.image.height):
|
|
39
|
+
parallel.append(dict(view=name, pixel=[u, v], gapPx=None, reason="outside panel"))
|
|
40
|
+
elif not target.mask[j, i]:
|
|
41
|
+
parallel.append(dict(view=name, pixel=[u, v], gapPx=float(distances[name][j, i])*source.scale/target.scale,
|
|
42
|
+
reason="outside silhouette"))
|
|
43
|
+
else:
|
|
44
|
+
axis = next(a for a in target.axes if a in world)
|
|
45
|
+
lines[name] = dict(axis=axis, coordinate=world[axis], intervals=target.intervals(axis, world[axis]))
|
|
46
|
+
separation = gap([line["intervals"] for line in lines.values()])
|
|
47
|
+
return dict(pixel=xy, missingAxis=missing, scanlines=lines,
|
|
48
|
+
gapPx=None if separation is None else separation*source.scale, opposingView=parallel)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def failed(detail, tolerance):
|
|
52
|
+
return (detail["gapPx"] is None or detail["gapPx"] > tolerance or
|
|
53
|
+
any(p["gapPx"] is None or p["gapPx"] > tolerance for p in detail["opposingView"]))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def severity(detail):
|
|
57
|
+
values = [detail["gapPx"], *(p["gapPx"] for p in detail["opposingView"])]
|
|
58
|
+
return math.inf if None in values else max(values)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def runs(flags):
|
|
62
|
+
"""Consecutive failed contour samples, including a run crossing index zero."""
|
|
63
|
+
if all(flags):
|
|
64
|
+
yield list(range(len(flags)))
|
|
65
|
+
return
|
|
66
|
+
start = flags.index(False)
|
|
67
|
+
run = []
|
|
68
|
+
for delta in range(1, len(flags)+1):
|
|
69
|
+
i = (start+delta) % len(flags)
|
|
70
|
+
if flags[i]:
|
|
71
|
+
run.append(i)
|
|
72
|
+
elif run:
|
|
73
|
+
yield run
|
|
74
|
+
run = []
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def mark_lines(detail, panels, images):
|
|
78
|
+
for name, line in detail["scanlines"].items():
|
|
79
|
+
panel = panels[name]
|
|
80
|
+
i = panel.axes.index(line["axis"])
|
|
81
|
+
fixed = panel.origin[i]+line["coordinate"]*panel.signs[i]*panel.scale
|
|
82
|
+
def xy(free):
|
|
83
|
+
return (fixed, free) if i == 0 else (free, fixed)
|
|
84
|
+
d = ImageDraw.Draw(images[name])
|
|
85
|
+
d.line([xy(0), xy(panel.image.size[1-i]-1)], fill=GOLD, width=1)
|
|
86
|
+
for start, end in line["intervals"]:
|
|
87
|
+
d.line([xy(panel.origin[1-i]+n*panel.signs[1-i]*panel.scale) for n in (start, end)], fill=CYAN, width=2)
|
|
88
|
+
for other in detail["opposingView"]:
|
|
89
|
+
dot(ImageDraw.Draw(images[other["view"]]), other["pixel"], GOLD)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def projections(panels, tolerance):
|
|
93
|
+
images = canvas(panels)
|
|
94
|
+
distances = {v: cv2.distanceTransform((~p.mask).astype("uint8"), cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
|
|
95
|
+
for v, p in panels.items() if v in ("front", "rear")}
|
|
96
|
+
findings = {}
|
|
97
|
+
selected = None
|
|
98
|
+
for name, p in panels.items():
|
|
99
|
+
groups = []
|
|
100
|
+
failed_count = total = 0
|
|
101
|
+
d = ImageDraw.Draw(images[name])
|
|
102
|
+
for contour_id, contour in enumerate(p.contours):
|
|
103
|
+
details = [sample(p, xy, panels, distances) for xy in contour.tolist()]
|
|
104
|
+
flags = [failed(s, tolerance) for s in details]
|
|
105
|
+
total += len(flags)
|
|
106
|
+
failed_count += sum(flags)
|
|
107
|
+
for run in runs(flags):
|
|
108
|
+
worst = max((details[i] for i in run), key=severity)
|
|
109
|
+
points = [tuple(details[i]["pixel"]) for i in run]
|
|
110
|
+
if len(points) > 1:
|
|
111
|
+
d.line(points, fill=RED, width=3)
|
|
112
|
+
else:
|
|
113
|
+
dot(d, points[0], RED, 2)
|
|
114
|
+
available = [details[i]["gapPx"] for i in run if details[i]["gapPx"] is not None]
|
|
115
|
+
numeric = [severity(details[i]) for i in run if math.isfinite(severity(details[i]))]
|
|
116
|
+
groups.append(dict(minSeparationPx=min(numeric, default=None), contour=contour_id, start=points[0], end=points[-1],
|
|
117
|
+
count=len(run), minScanlineGapPx=min(available, default=None), sample=worst))
|
|
118
|
+
# Prefer an actual finite gap between occupied intervals for the illustration.
|
|
119
|
+
finite_gaps = [details[i] for i in run if (details[i]["gapPx"] or 0) > tolerance]
|
|
120
|
+
illustration = max(finite_gaps, key=lambda row: row["gapPx"]) if finite_gaps else worst
|
|
121
|
+
rank = (bool(finite_gaps), len(run))
|
|
122
|
+
if selected is None or rank > selected[0]:
|
|
123
|
+
selected = (rank, name, illustration)
|
|
124
|
+
findings[name] = dict(boundarySamples=total, unsupportedSamples=failed_count, runs=groups)
|
|
125
|
+
if selected:
|
|
126
|
+
_, name, detail = selected
|
|
127
|
+
mark_lines(detail, panels, images)
|
|
128
|
+
dot(ImageDraw.Draw(images[name]), detail["pixel"], GOLD, 7)
|
|
129
|
+
count = sum(item["boundarySamples"] for item in findings.values())
|
|
130
|
+
unsupported = sum(item["unsupportedSamples"] for item in findings.values())
|
|
131
|
+
return (dict(status="measured", views=findings,
|
|
132
|
+
boundarySamples=count, unsupportedSamples=unsupported, unsupportedFraction=unsupported/count,
|
|
133
|
+
illustrated=None if not selected else dict(view=selected[1], **selected[2])),
|
|
134
|
+
sheet(images, "Silhouette projection consistency",
|
|
135
|
+
"Red: unsupported contour Gold: selected point / scanline Cyan: occupied intervals"))
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11,<3.14"
|
|
3
|
+
# dependencies = ["numpy==2.2.6", "pillow==11.3.0", "opencv-python-headless==4.11.0.86", "pyyaml==6.0.2"]
|
|
4
|
+
# ///
|
|
5
|
+
"""Verification entry point shared by the workspace CLI and the packaged executable."""
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
from assembly import assemble
|
|
13
|
+
from landmarks import landmarks
|
|
14
|
+
from panels import atlas, read_manifest, scalar, unregistered
|
|
15
|
+
from projections import projections
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def tolerance(config):
|
|
19
|
+
value = scalar(config.get("tolerancePx", 1), "tolerancePx")
|
|
20
|
+
if value < 0:
|
|
21
|
+
raise ValueError("tolerancePx must be nonnegative")
|
|
22
|
+
return value
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def measure_atlas(data, panels, save_overlay, prefix="", check=None):
|
|
26
|
+
tol = tolerance(data)
|
|
27
|
+
missing = unregistered(panels)
|
|
28
|
+
results = {}
|
|
29
|
+
for name in ([check] if check else ["projections", "landmarks"]):
|
|
30
|
+
if name == "landmarks" and not data.get("landmarks"):
|
|
31
|
+
result, image = dict(status="skipped", reason="No annotated landmarks"), None
|
|
32
|
+
elif name == "projections" and missing:
|
|
33
|
+
result, image = dict(status="registration-needed", reason="Missing origin or scale", views=missing), None
|
|
34
|
+
elif name == "projections":
|
|
35
|
+
result, image = projections(panels, tol)
|
|
36
|
+
else:
|
|
37
|
+
result, image = landmarks(panels, data["landmarks"], tol)
|
|
38
|
+
save_overlay(prefix + name, result, image)
|
|
39
|
+
results[name] = result
|
|
40
|
+
return dict(kind="atlas", tolerancePx=tol, results=results)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run(args):
|
|
44
|
+
path = Path(args.file).resolve()
|
|
45
|
+
config = read_manifest(path)
|
|
46
|
+
kind = config.get("kind")
|
|
47
|
+
if kind is None:
|
|
48
|
+
is_atlas = "views" in config
|
|
49
|
+
is_assembly = "whole" in config and "parts" in config
|
|
50
|
+
if is_atlas == is_assembly:
|
|
51
|
+
raise ValueError("specify kind: atlas or assembly for this manifest")
|
|
52
|
+
kind = "atlas" if is_atlas else "assembly"
|
|
53
|
+
if kind not in ("atlas", "assembly") or (args.kind and kind != args.kind):
|
|
54
|
+
raise ValueError("expected an atlas or assembly manifest matching the requested resource")
|
|
55
|
+
|
|
56
|
+
out = Path(args.output_dir) if args.output_dir else None
|
|
57
|
+
overlays = []
|
|
58
|
+
def save_overlay(name, result, image):
|
|
59
|
+
if out and image is not None:
|
|
60
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
filename = name + ".png"
|
|
62
|
+
image.save(out / filename)
|
|
63
|
+
result["overlay"] = filename
|
|
64
|
+
overlays.append(filename)
|
|
65
|
+
|
|
66
|
+
if kind == "atlas":
|
|
67
|
+
data, panels = atlas(path, config)
|
|
68
|
+
report = measure_atlas(data, panels, save_overlay, check=args.check)
|
|
69
|
+
else:
|
|
70
|
+
parts = config["parts"]
|
|
71
|
+
if not isinstance(parts, dict) or not parts or (args.part and args.part not in parts):
|
|
72
|
+
raise ValueError("expected a manifest with matching named parts")
|
|
73
|
+
whole_data, whole = atlas(path.parent / config["whole"])
|
|
74
|
+
atlases = dict(whole=measure_atlas(whole_data, whole, save_overlay, "whole-"), parts={})
|
|
75
|
+
tol = tolerance(config)
|
|
76
|
+
results = {}
|
|
77
|
+
missing = unregistered(whole)
|
|
78
|
+
for i, (name, spec) in enumerate(parts.items(), start=1):
|
|
79
|
+
if args.part and name != args.part:
|
|
80
|
+
continue
|
|
81
|
+
part_data, local = atlas(path.parent / spec["atlas"])
|
|
82
|
+
atlases["parts"][name] = measure_atlas(part_data, local, save_overlay, f"part-{i}-")
|
|
83
|
+
if missing:
|
|
84
|
+
result, image = dict(status="registration-needed", reason="Missing whole registration", views=missing), None
|
|
85
|
+
else:
|
|
86
|
+
result, image = assemble(whole, local, spec, tol)
|
|
87
|
+
save_overlay(f"assembly-{i}", result, image)
|
|
88
|
+
results[name] = result
|
|
89
|
+
report = dict(kind=kind, tolerancePx=tol, atlases=atlases, results=results)
|
|
90
|
+
if out:
|
|
91
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
report["overlays"] = overlays
|
|
93
|
+
output = json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False)
|
|
94
|
+
if out:
|
|
95
|
+
(out/"report.json").write_text(output+"\n", encoding="utf8")
|
|
96
|
+
print(output)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
if __name__ == "__main__":
|
|
100
|
+
parser = argparse.ArgumentParser()
|
|
101
|
+
parser.add_argument("--kind", choices=["atlas", "assembly"])
|
|
102
|
+
parser.add_argument("file")
|
|
103
|
+
for option in ("check","part","output-dir"):
|
|
104
|
+
parser.add_argument("--"+option)
|
|
105
|
+
try:
|
|
106
|
+
run(parser.parse_args())
|
|
107
|
+
except (ValueError, KeyError, TypeError, OSError, yaml.YAMLError) as error:
|
|
108
|
+
sys.exit(f"Invalid verification input: {error}")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as $,M as J,V as v,Q as ee,B as S,R as se,a as D,S as te,N as ne,b as k,c as ie,I as re,D as oe,P as z,d as ae,e as Y,f as ce,g as ue,h as le,i as fe,L as he,j as pe,k as de,l as xe,m as ye,n as ge,o as Te}from"./style-CWGgpweN.js";const j={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class H{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register(function(e){return new Le(e)}),this.register(function(e){return new _e(e)}),this.register(function(e){return new Oe(e)}),this.register(function(e){return new ve(e)}),this.register(function(e){return new ze(e)}),this.register(function(e){return new Be(e)}),this.register(function(e){return new Ce(e)}),this.register(function(e){return new Ue(e)}),this.register(function(e){return new Fe(e)}),this.register(function(e){return new De(e)}),this.register(function(e){return new Ge(e)}),this.register(function(e){return new Pe(e)}),this.register(function(e){return new ke(e)}),this.register(function(e){return new He(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}setTextureUtils(e){return this.textureUtils=e,this}parse(e,s,n,t){const i=new Se,r=[];for(let o=0,c=this.pluginCallbacks.length;o<c;o++)r.push(this.pluginCallbacks[o](i));i.setPlugins(r),i.setTextureUtils(this.textureUtils),i.writeAsync(e,s,t).catch(n)}parseAsync(e,s){const n=this;return new Promise(function(t,i){n.parse(e,t,i,s)})}}const g={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},G="KHR_mesh_quantization",R={};R[ue]=g.NEAREST;R[le]=g.NEAREST_MIPMAP_NEAREST;R[fe]=g.NEAREST_MIPMAP_LINEAR;R[he]=g.LINEAR;R[pe]=g.LINEAR_MIPMAP_NEAREST;R[de]=g.LINEAR_MIPMAP_LINEAR;R[xe]=g.CLAMP_TO_EDGE;R[ye]=g.REPEAT;R[ge]=g.MIRRORED_REPEAT;const K={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},we=new $,q=12,me=1179937895,Me=2,W=8,Ae=1313821514,Ee=5130562;function F(a,e){return a.length===e.length&&a.every(function(s,n){return s===e[n]})}function Ie(a){return new TextEncoder().encode(a).buffer}function Re(a){return F(a.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function Ne(a,e,s){const n={min:new Array(a.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(a.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let t=e;t<e+s;t++)for(let i=0;i<a.itemSize;i++){let r;a.itemSize>4?r=a.array[t*a.itemSize+i]:(i===0?r=a.getX(t):i===1?r=a.getY(t):i===2?r=a.getZ(t):i===3&&(r=a.getW(t)),a.normalized===!0&&(r=k.normalize(r,a.array))),n.min[i]=Math.min(n.min[i],r),n.max[i]=Math.max(n.max[i],r)}return n}function Z(a){return Math.ceil(a/4)*4}function P(a,e=0){const s=Z(a.byteLength);if(s!==a.byteLength){const n=new Uint8Array(s);if(n.set(new Uint8Array(a)),e!==0)for(let t=a.byteLength;t<s;t++)n[t]=e;return n.buffer}return a}function X(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function be(a,e){if(typeof OffscreenCanvas<"u"&&a instanceof OffscreenCanvas){let s;return e==="image/jpeg"?s=.92:e==="image/webp"&&(s=.8),a.convertToBlob({type:e,quality:s})}else return new Promise(s=>a.toBlob(s,e))}class Se{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+se}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,s,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},n),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const t=this,i=t.buffers,r=t.json;n=t.options;const o=t.extensionsUsed,c=t.extensionsRequired,l=new Blob(i,{type:"application/octet-stream"}),h=Object.keys(o),u=Object.keys(c);if(h.length>0&&(r.extensionsUsed=h),u.length>0&&(r.extensionsRequired=u),r.buffers&&r.buffers.length>0&&(r.buffers[0].byteLength=l.size),n.binary===!0){const T=new FileReader;T.readAsArrayBuffer(l),T.onloadend=function(){const f=P(T.result),d=new DataView(new ArrayBuffer(W));d.setUint32(0,f.byteLength,!0),d.setUint32(4,Ee,!0);const x=P(Ie(JSON.stringify(r)),32),y=new DataView(new ArrayBuffer(W));y.setUint32(0,x.byteLength,!0),y.setUint32(4,Ae,!0);const M=new ArrayBuffer(q),N=new DataView(M);N.setUint32(0,me,!0),N.setUint32(4,Me,!0);const O=q+y.byteLength+x.byteLength+d.byteLength+f.byteLength;N.setUint32(8,O,!0);const p=new Blob([M,y,x,d,f],{type:"application/octet-stream"}),w=new FileReader;w.readAsArrayBuffer(p),w.onloadend=function(){s(w.result)}}}else if(r.buffers&&r.buffers.length>0){const T=new FileReader;T.readAsDataURL(l),T.onloadend=function(){const f=T.result;r.buffers[0].uri=f,s(r)}}else s(r)}serializeUserData(e,s){if(Object.keys(e.userData).length===0)return;const n=this.options,t=this.extensionsUsed;try{const i=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&i.gltfExtensions){s.extensions===void 0&&(s.extensions={});for(const r in i.gltfExtensions)s.extensions[r]=i.gltfExtensions[r],t[r]=!0;delete i.gltfExtensions}Object.keys(i).length>0&&(s.extras=i)}catch(i){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+i.message)}}getUID(e,s=!1){if(this.uids.has(e)===!1){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(s)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const n=new v;for(let t=0,i=e.count;t<i;t++)if(Math.abs(n.fromBufferAttribute(e,t).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const s=this.cache;if(s.attributesNormalized.has(e))return s.attributesNormalized.get(e);const n=e.clone(),t=new v;for(let i=0,r=n.count;i<r;i++)t.fromBufferAttribute(n,i),t.x===0&&t.y===0&&t.z===0?t.setX(1):t.normalize(),n.setXYZ(i,t.x,t.y,t.z);return s.attributesNormalized.set(e,n),n}applyTextureTransform(e,s){let n=!1;const t={};(s.offset.x!==0||s.offset.y!==0)&&(t.offset=s.offset.toArray(),n=!0),s.rotation!==0&&(t.rotation=s.rotation,n=!0),(s.repeat.x!==1||s.repeat.y!==1)&&(t.scale=s.repeat.toArray(),n=!0),n&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=t,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,s){if(e===s)return e;function n(f){return f.colorSpace===ce?function(x){return x<.04045?x*.0773993808:Math.pow(x*.9478672986+.0521327014,2.4)}:function(x){return x}}e instanceof D&&(e=await this.decompressTextureAsync(e)),s instanceof D&&(s=await this.decompressTextureAsync(s));const t=e?e.image:null,i=s?s.image:null,r=Math.max(t?t.width:0,i?i.width:0),o=Math.max(t?t.height:0,i?i.height:0),c=X();c.width=r,c.height=o;const l=c.getContext("2d",{willReadFrequently:!0});l.fillStyle="#00ffff",l.fillRect(0,0,r,o);const h=l.getImageData(0,0,r,o);if(t){l.drawImage(t,0,0,r,o);const f=n(e),d=l.getImageData(0,0,r,o).data;for(let x=2;x<d.length;x+=4)h.data[x]=f(d[x]/256)*256}if(i){l.drawImage(i,0,0,r,o);const f=n(s),d=l.getImageData(0,0,r,o).data;for(let x=1;x<d.length;x+=4)h.data[x]=f(d[x]/256)*256}l.putImageData(h,0,0);const T=(e||s).clone();return T.source=new te(c),T.colorSpace=ne,T.channel=(e||s).channel,e&&s&&e.channel!==s.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),T}async decompressTextureAsync(e,s=1/0){if(this.textureUtils===null)throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");return await this.textureUtils.decompress(e,s)}processBuffer(e){const s=this.json,n=this.buffers;return s.buffers||(s.buffers=[{byteLength:0}]),n.push(e),0}processBufferView(e,s,n,t,i){const r=this.json;r.bufferViews||(r.bufferViews=[]);let o;switch(s){case g.BYTE:case g.UNSIGNED_BYTE:o=1;break;case g.SHORT:case g.UNSIGNED_SHORT:o=2;break;default:o=4}let c=e.itemSize*o;i===g.ARRAY_BUFFER&&(c=Math.ceil(c/4)*4);const l=Z(t*c),h=new DataView(new ArrayBuffer(l));let u=0;for(let d=n;d<n+t;d++){for(let x=0;x<e.itemSize;x++){let y;e.itemSize>4?y=e.array[d*e.itemSize+x]:(x===0?y=e.getX(d):x===1?y=e.getY(d):x===2?y=e.getZ(d):x===3&&(y=e.getW(d)),e.normalized===!0&&(y=k.normalize(y,e.array))),s===g.FLOAT?h.setFloat32(u,y,!0):s===g.INT?h.setInt32(u,y,!0):s===g.UNSIGNED_INT?h.setUint32(u,y,!0):s===g.SHORT?h.setInt16(u,y,!0):s===g.UNSIGNED_SHORT?h.setUint16(u,y,!0):s===g.BYTE?h.setInt8(u,y):s===g.UNSIGNED_BYTE&&h.setUint8(u,y),u+=o}u%c!==0&&(u+=c-u%c)}const T={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:l};return i!==void 0&&(T.target=i),i===g.ARRAY_BUFFER&&(T.byteStride=c),this.byteOffset+=l,r.bufferViews.push(T),{id:r.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const s=this,n=s.json;return n.bufferViews||(n.bufferViews=[]),new Promise(function(t){const i=new FileReader;i.readAsArrayBuffer(e),i.onloadend=function(){const r=P(i.result),o={buffer:s.processBuffer(r),byteOffset:s.byteOffset,byteLength:r.byteLength};s.byteOffset+=r.byteLength,t(n.bufferViews.push(o)-1)}})}processAccessor(e,s,n,t){const i=this.json,r={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let o;if(e.array.constructor===Float32Array)o=g.FLOAT;else if(e.array.constructor===Int32Array)o=g.INT;else if(e.array.constructor===Uint32Array)o=g.UNSIGNED_INT;else if(e.array.constructor===Int16Array)o=g.SHORT;else if(e.array.constructor===Uint16Array)o=g.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)o=g.BYTE;else if(e.array.constructor===Uint8Array)o=g.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(n===void 0&&(n=0),(t===void 0||t===1/0)&&(t=e.count),t===0)return null;const c=Ne(e,n,t);let l;s!==void 0&&(l=e===s.index?g.ELEMENT_ARRAY_BUFFER:g.ARRAY_BUFFER);const h=this.processBufferView(e,o,n,t,l),u={bufferView:h.id,byteOffset:h.byteOffset,componentType:o,count:t,max:c.max,min:c.min,type:r[e.itemSize]};return e.normalized===!0&&(u.normalized=!0),i.accessors||(i.accessors=[]),i.accessors.push(u)-1}processImage(e,s,n,t="image/png"){if(e!==null){const i=this,r=i.cache,o=i.json,c=i.options,l=i.pending;r.images.has(e)||r.images.set(e,{});const h=r.images.get(e),u=t+":flipY/"+n.toString();if(h[u]!==void 0)return h[u];o.images||(o.images=[]);const T={mimeType:t},f=X();f.width=Math.min(e.width,c.maxTextureSize),f.height=Math.min(e.height,c.maxTextureSize);const d=f.getContext("2d",{willReadFrequently:!0});if(n===!0&&(d.translate(0,f.height),d.scale(1,-1)),e.data!==void 0){s!==ie&&console.error("GLTFExporter: Only RGBAFormat is supported.",s),(e.width>c.maxTextureSize||e.height>c.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const y=new Uint8ClampedArray(e.height*e.width*4);for(let M=0;M<y.length;M+=4)y[M+0]=e.data[M+0],y[M+1]=e.data[M+1],y[M+2]=e.data[M+2],y[M+3]=e.data[M+3];d.putImageData(new ImageData(y,e.width,e.height),0,0)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)d.drawImage(e,0,0,f.width,f.height);else throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");c.binary===!0?l.push(be(f,t).then(y=>i.processBufferViewImage(y)).then(y=>{T.bufferView=y})):T.uri=re.getDataURL(f,t);const x=o.images.push(T)-1;return h[u]=x,x}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const s=this.json;s.samplers||(s.samplers=[]);const n={magFilter:R[e.magFilter],minFilter:R[e.minFilter],wrapS:R[e.wrapS],wrapT:R[e.wrapT]};return s.samplers.push(n)-1}async processTextureAsync(e){const n=this.options,t=this.cache,i=this.json;if(t.textures.has(e))return t.textures.get(e);i.textures||(i.textures=[]),e instanceof D&&(e=await this.decompressTextureAsync(e,n.maxTextureSize));let r=e.userData.mimeType;r==="image/webp"&&(r="image/png");const o={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,r)};e.name&&(o.name=e.name),await this._invokeAllAsync(async function(l){l.writeTexture&&await l.writeTexture(e,o)});const c=i.textures.push(o)-1;return t.textures.set(e,c),c}async processMaterialAsync(e){const s=this.cache,n=this.json;if(s.materials.has(e))return s.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;n.materials||(n.materials=[]);const t={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const i=e.color.toArray().concat([e.opacity]);if(F(i,[1,1,1,1])||(t.pbrMetallicRoughness.baseColorFactor=i),e.isMeshStandardMaterial?(t.pbrMetallicRoughness.metallicFactor=e.metalness,t.pbrMetallicRoughness.roughnessFactor=e.roughness):(t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){const o=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),c={index:await this.processTextureAsync(o),texCoord:o.channel};this.applyTextureTransform(c,o),t.pbrMetallicRoughness.metallicRoughnessTexture=c}if(e.map){const o={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(o,e.map),t.pbrMetallicRoughness.baseColorTexture=o}if(e.emissive){const o=e.emissive;if(Math.max(o.r,o.g,o.b)>0&&(t.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const l={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(l,e.emissiveMap),t.emissiveTexture=l}}if(e.normalMap){const o={index:await this.processTextureAsync(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(o.scale=e.normalScale.x),this.applyTextureTransform(o,e.normalMap),t.normalTexture=o}if(e.aoMap){const o={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(o.strength=e.aoMapIntensity),this.applyTextureTransform(o,e.aoMap),t.occlusionTexture=o}e.transparent?t.alphaMode="BLEND":e.alphaTest>0&&(t.alphaMode="MASK",t.alphaCutoff=e.alphaTest),e.side===oe&&(t.doubleSided=!0),e.name!==""&&(t.name=e.name),this.serializeUserData(e,t),await this._invokeAllAsync(async function(o){o.writeMaterialAsync&&await o.writeMaterialAsync(e,t)});const r=n.materials.push(t)-1;return s.materials.set(e,r),r}async processMeshAsync(e){const s=this.cache,n=this.json,t=[e.geometry.uuid];if(Array.isArray(e.material))for(let p=0,w=e.material.length;p<w;p++)t.push(e.material[p].uuid);else t.push(e.material.uuid);const i=t.join(":");if(s.meshes.has(i))return s.meshes.get(i);const r=e.geometry;let o;e.isLineSegments?o=g.LINES:e.isLineLoop?o=g.LINE_LOOP:e.isLine?o=g.LINE_STRIP:e.isPoints?o=g.POINTS:o=e.material.wireframe?g.LINES:g.TRIANGLES;const c={},l={},h=[],u=[],T={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},f=r.getAttribute("normal");f!==void 0&&!this.isNormalizedNormalAttribute(f)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),r.setAttribute("normal",this.createNormalizedNormalAttribute(f)));let d=null;for(let p in r.attributes){if(p.slice(0,5)==="morph")continue;const w=r.attributes[p];if(p=T[p]||p.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(p)||(p="_"+p),s.attributes.has(this.getUID(w))){l[p]=s.attributes.get(this.getUID(w));continue}d=null;const m=w.array;p==="JOINTS_0"&&!(m instanceof Uint16Array)&&!(m instanceof Uint8Array)?(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),d=new S(new Uint16Array(m),w.itemSize,w.normalized)):(m instanceof Uint32Array||m instanceof Int32Array)&&!p.startsWith("_")&&(console.warn(`GLTFExporter: Attribute "${p}" converted to type FLOAT.`),d=H.Utils.toFloat32BufferAttribute(w));const I=this.processAccessor(d||w,r);I!==null&&(p.startsWith("_")||this.detectMeshQuantization(p,w),l[p]=I,s.attributes.set(this.getUID(w),I))}if(f!==void 0&&r.setAttribute("normal",f),Object.keys(l).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const p=[],w=[],A={};if(e.morphTargetDictionary!==void 0)for(const m in e.morphTargetDictionary)A[e.morphTargetDictionary[m]]=m;for(let m=0;m<e.morphTargetInfluences.length;++m){const I={};let V=!1;for(const _ in r.morphAttributes){if(_!=="position"&&_!=="normal"){V||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),V=!0);continue}const b=r.morphAttributes[_][m],B=_.toUpperCase(),C=r.attributes[_];if(s.attributes.has(this.getUID(b,!0))){I[B]=s.attributes.get(this.getUID(b,!0));continue}const U=b.clone();if(!r.morphTargetsRelative)for(let E=0,Q=b.count;E<Q;E++)for(let L=0;L<b.itemSize;L++)L===0&&U.setX(E,b.getX(E)-C.getX(E)),L===1&&U.setY(E,b.getY(E)-C.getY(E)),L===2&&U.setZ(E,b.getZ(E)-C.getZ(E)),L===3&&U.setW(E,b.getW(E)-C.getW(E));I[B]=this.processAccessor(U,r),s.attributes.set(this.getUID(C,!0),I[B])}u.push(I),p.push(e.morphTargetInfluences[m]),e.morphTargetDictionary!==void 0&&w.push(A[m])}c.weights=p,w.length>0&&(c.extras={},c.extras.targetNames=w)}const x=Array.isArray(e.material);if(x&&r.groups.length===0)return null;let y=!1;if(x&&r.index===null){const p=[];for(let w=0,A=r.attributes.position.count;w<A;w++)p[w]=w;r.setIndex(p),y=!0}const M=x?e.material:[e.material],N=x?r.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let p=0,w=N.length;p<w;p++){const A={mode:o,attributes:l};if(this.serializeUserData(r,A),u.length>0&&(A.targets=u),r.index!==null){let I=this.getUID(r.index);(N[p].start!==void 0||N[p].count!==void 0)&&(I+=":"+N[p].start+":"+N[p].count),s.attributes.has(I)?A.indices=s.attributes.get(I):(A.indices=this.processAccessor(r.index,r,N[p].start,N[p].count),s.attributes.set(I,A.indices)),A.indices===null&&delete A.indices}const m=await this.processMaterialAsync(M[N[p].materialIndex]);m!==null&&(A.material=m),h.push(A)}y===!0&&r.setIndex(null),c.primitives=h,n.meshes||(n.meshes=[]),await this._invokeAllAsync(function(p){p.writeMesh&&p.writeMesh(e,c)});const O=n.meshes.push(c)-1;return s.meshes.set(i,O),O}detectMeshQuantization(e,s){if(this.extensionsUsed[G])return;let n;switch(s.array.constructor){case Int8Array:n="byte";break;case Uint8Array:n="unsigned byte";break;case Int16Array:n="short";break;case Uint16Array:n="unsigned short";break;default:return}s.normalized&&(n+=" normalized");const t=e.split("_",1)[0];j[t]&&j[t].includes(n)&&(this.extensionsUsed[G]=!0,this.extensionsRequired[G]=!0)}processCamera(e){const s=this.json;s.cameras||(s.cameras=[]);const n=e.isOrthographicCamera,t={type:n?"orthographic":"perspective"};return n?t.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:t.perspective={aspectRatio:e.aspect,yfov:k.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(t.name=e.type),s.cameras.push(t)-1}processAnimation(e,s){const n=this.json,t=this.nodeMap;n.animations||(n.animations=[]),e=H.Utils.mergeMorphTargetTracks(e.clone(),s);const i=e.tracks,r=[],o=[];for(let l=0;l<i.length;++l){const h=i[l],u=z.parseTrackName(h.name);let T=z.findNode(s,u.nodeName);const f=K[u.propertyName];if(u.objectName==="bones"&&(T.isSkinnedMesh===!0?T=T.skeleton.getBoneByName(u.objectIndex):T=void 0),!T||!f){console.warn('THREE.GLTFExporter: Could not export animation track "%s".',h.name);continue}const d=1;let x=h.values.length/h.times.length;f===K.morphTargetInfluences&&(x/=T.morphTargetInfluences.length);let y;h.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline===!0?(y="CUBICSPLINE",x/=3):h.getInterpolation()===ae?y="STEP":y="LINEAR",o.push({input:this.processAccessor(new S(h.times,d)),output:this.processAccessor(new S(h.values,x)),interpolation:y}),r.push({sampler:o.length-1,target:{node:t.get(T),path:f}})}const c={name:e.name||"clip_"+n.animations.length,samplers:o,channels:r};return this.serializeUserData(e,c),n.animations.push(c),n.animations.length-1}processSkin(e){const s=this.json,n=this.nodeMap,t=s.nodes[n.get(e)],i=e.skeleton;if(i===void 0)return null;const r=e.skeleton.bones[0];if(r===void 0)return null;const o=[],c=new Float32Array(i.bones.length*16),l=new J;for(let u=0;u<i.bones.length;++u)o.push(n.get(i.bones[u])),l.copy(i.boneInverses[u]),l.multiply(e.bindMatrix).toArray(c,u*16);return s.skins===void 0&&(s.skins=[]),s.skins.push({inverseBindMatrices:this.processAccessor(new S(c,16)),joints:o,skeleton:n.get(r)}),t.skin=s.skins.length-1}async processNodeAsync(e){const s=this.json,n=this.options,t=this.nodeMap;s.nodes||(s.nodes=[]);const i={};if(n.trs){const o=e.quaternion.toArray(),c=e.position.toArray(),l=e.scale.toArray();F(o,[0,0,0,1])||(i.rotation=o),F(c,[0,0,0])||(i.translation=c),F(l,[1,1,1])||(i.scale=l)}else e.matrixAutoUpdate&&e.updateMatrix(),Re(e.matrix)===!1&&(i.matrix=e.matrix.elements);if(e.name!==""&&(i.name=String(e.name)),this.serializeUserData(e,i),e.isMesh||e.isLine||e.isPoints){const o=await this.processMeshAsync(e);o!==null&&(i.mesh=o)}else e.isCamera&&(i.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const r=s.nodes.push(i)-1;if(t.set(e,r),e.children.length>0){const o=[];for(let c=0,l=e.children.length;c<l;c++){const h=e.children[c];if(h.visible||n.onlyVisible===!1){const u=await this.processNodeAsync(h);u!==null&&o.push(u)}}o.length>0&&(i.children=o)}return await this._invokeAllAsync(function(o){o.writeNode&&o.writeNode(e,i)}),r}async processSceneAsync(e){const s=this.json,n=this.options;s.scenes||(s.scenes=[],s.scene=0);const t={};e.name!==""&&(t.name=e.name),s.scenes.push(t);const i=[];for(let r=0,o=e.children.length;r<o;r++){const c=e.children[r];if(c.visible||n.onlyVisible===!1){const l=await this.processNodeAsync(c);l!==null&&i.push(l)}}i.length>0&&(t.nodes=i),this.serializeUserData(e,t)}async processObjectsAsync(e){const s=new Y;s.name="AuxScene";for(let n=0;n<e.length;n++)s.children.push(e[n]);await this.processSceneAsync(s)}async processInputAsync(e){const s=this.options;e=e instanceof Array?e:[e],await this._invokeAllAsync(function(t){t.beforeParse&&t.beforeParse(e)});const n=[];for(let t=0;t<e.length;t++)e[t]instanceof Y?await this.processSceneAsync(e[t]):n.push(e[t]);n.length>0&&await this.processObjectsAsync(n);for(let t=0;t<this.skins.length;++t)this.processSkin(this.skins[t]);for(let t=0;t<s.animations.length;++t)this.processAnimation(s.animations[t],e[0]);await this._invokeAllAsync(function(t){t.afterParse&&t.afterParse(e)})}async _invokeAllAsync(e){for(let s=0,n=this.plugins.length;s<n;s++)await e(this.plugins[s])}}class Le{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,s){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight){console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);return}const n=this.writer,t=n.json,i=n.extensionsUsed,r={};e.name&&(r.name=e.name),r.color=e.color.toArray(),r.intensity=e.intensity,e.isDirectionalLight?r.type="directional":e.isPointLight?(r.type="point",e.distance>0&&(r.range=e.distance)):e.isSpotLight&&(r.type="spot",e.distance>0&&(r.range=e.distance),r.spot={},r.spot.innerConeAngle=(1-e.penumbra)*e.angle,r.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),i[this.name]||(t.extensions=t.extensions||{},t.extensions[this.name]={lights:[]},i[this.name]=!0);const o=t.extensions[this.name].lights;o.push(r),s.extensions=s.extensions||{},s.extensions[this.name]={light:o.length-1}}}class _e{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,s){if(!e.isMeshBasicMaterial)return;const t=this.writer.extensionsUsed;s.extensions=s.extensions||{},s.extensions[this.name]={},t[this.name]=!0,s.pbrMetallicRoughness.metallicFactor=0,s.pbrMetallicRoughness.roughnessFactor=.9}}class Ce{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.clearcoat===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.clearcoatFactor=e.clearcoat,e.clearcoatMap){const r={index:await n.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};n.applyTextureTransform(r,e.clearcoatMap),i.clearcoatTexture=r}if(i.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const r={index:await n.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};n.applyTextureTransform(r,e.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=r}if(e.clearcoatNormalMap){const r={index:await n.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};e.clearcoatNormalScale.x!==1&&(r.scale=e.clearcoatNormalScale.x),n.applyTextureTransform(r,e.clearcoatNormalMap),i.clearcoatNormalTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Ue{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.dispersion===0)return;const t=this.writer.extensionsUsed,i={};i.dispersion=e.dispersion,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Fe{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.iridescence===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.iridescenceFactor=e.iridescence,e.iridescenceMap){const r={index:await n.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};n.applyTextureTransform(r,e.iridescenceMap),i.iridescenceTexture=r}if(i.iridescenceIor=e.iridescenceIOR,i.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){const r={index:await n.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};n.applyTextureTransform(r,e.iridescenceThicknessMap),i.iridescenceThicknessTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Oe{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.transmissionFactor=e.transmission,e.transmissionMap){const r={index:await n.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};n.applyTextureTransform(r,e.transmissionMap),i.transmissionTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ve{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.thicknessFactor=e.thickness,e.thicknessMap){const r={index:await n.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};n.applyTextureTransform(r,e.thicknessMap),i.thicknessTexture=r}e.attenuationDistance!==1/0&&(i.attenuationDistance=e.attenuationDistance),i.attenuationColor=e.attenuationColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ze{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.ior===1.5)return;const t=this.writer.extensionsUsed,i={};i.ior=e.ior,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Be{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.specularIntensity===1&&e.specularColor.equals(we)&&!e.specularIntensityMap&&!e.specularColorMap)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.specularIntensityMap){const r={index:await n.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};n.applyTextureTransform(r,e.specularIntensityMap),i.specularTexture=r}if(e.specularColorMap){const r={index:await n.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};n.applyTextureTransform(r,e.specularColorMap),i.specularColorTexture=r}i.specularFactor=e.specularIntensity,i.specularColorFactor=e.specularColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class De{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.sheen==0)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.sheenRoughnessMap){const r={index:await n.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};n.applyTextureTransform(r,e.sheenRoughnessMap),i.sheenRoughnessTexture=r}if(e.sheenColorMap){const r={index:await n.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};n.applyTextureTransform(r,e.sheenColorMap),i.sheenColorTexture=r}i.sheenRoughnessFactor=e.sheenRoughness,i.sheenColorFactor=e.sheenColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Ge{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.anisotropy==0)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.anisotropyMap){const r={index:await n.processTextureAsync(e.anisotropyMap)};n.applyTextureTransform(r,e.anisotropyMap),i.anisotropyTexture=r}i.anisotropyStrength=e.anisotropy,i.anisotropyRotation=e.anisotropyRotation,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Pe{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,s){if(!e.isMeshStandardMaterial||e.emissiveIntensity===1)return;const t=this.writer.extensionsUsed,i={};i.emissiveStrength=e.emissiveIntensity,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ke{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,s){if(!e.isMeshStandardMaterial||e.bumpScale===1&&!e.bumpMap)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.bumpMap){const r={index:await n.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};n.applyTextureTransform(r,e.bumpMap),i.bumpTexture=r}i.bumpFactor=e.bumpScale,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class He{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,s){if(!e.isInstancedMesh)return;const n=this.writer,t=e,i=new Float32Array(t.count*3),r=new Float32Array(t.count*4),o=new Float32Array(t.count*3),c=new J,l=new v,h=new ee,u=new v;for(let f=0;f<t.count;f++)t.getMatrixAt(f,c),c.decompose(l,h,u),l.toArray(i,f*3),h.toArray(r,f*4),u.toArray(o,f*3);const T={TRANSLATION:n.processAccessor(new S(i,3)),ROTATION:n.processAccessor(new S(r,4)),SCALE:n.processAccessor(new S(o,3))};t.instanceColor&&(T._COLOR_0=n.processAccessor(t.instanceColor)),s.extensions=s.extensions||{},s.extensions[this.name]={attributes:T},n.extensionsUsed[this.name]=!0,n.extensionsRequired[this.name]=!0}}H.Utils={insertKeyframe:function(a,e){const n=a.getValueSize(),t=new a.TimeBufferType(a.times.length+1),i=new a.ValueBufferType(a.values.length+n),r=a.createInterpolant(new a.ValueBufferType(n));let o;if(a.times.length===0){t[0]=e;for(let c=0;c<n;c++)i[c]=0;o=0}else if(e<a.times[0]){if(Math.abs(a.times[0]-e)<.001)return 0;t[0]=e,t.set(a.times,1),i.set(r.evaluate(e),0),i.set(a.values,n),o=0}else if(e>a.times[a.times.length-1]){if(Math.abs(a.times[a.times.length-1]-e)<.001)return a.times.length-1;t[t.length-1]=e,t.set(a.times,0),i.set(a.values,0),i.set(r.evaluate(e),a.values.length),o=t.length-1}else for(let c=0;c<a.times.length;c++){if(Math.abs(a.times[c]-e)<.001)return c;if(a.times[c]<e&&a.times[c+1]>e){t.set(a.times.slice(0,c+1),0),t[c+1]=e,t.set(a.times.slice(c+1),c+2),i.set(a.values.slice(0,(c+1)*n),0),i.set(r.evaluate(e),(c+1)*n),i.set(a.values.slice((c+1)*n),(c+2)*n),o=c+1;break}}return a.times=t,a.values=i,o},mergeMorphTargetTracks:function(a,e){const s=[],n={},t=a.tracks;for(let i=0;i<t.length;++i){let r=t[i];const o=z.parseTrackName(r.name),c=z.findNode(e,o.nodeName);if(o.propertyName!=="morphTargetInfluences"||o.propertyIndex===void 0){s.push(r);continue}if(r.createInterpolant!==r.InterpolantFactoryMethodDiscrete&&r.createInterpolant!==r.InterpolantFactoryMethodLinear){if(r.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),r=r.clone(),r.setInterpolation(Te)}const l=c.morphTargetInfluences.length,h=c.morphTargetDictionary[o.propertyIndex];if(h===void 0)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let u;if(n[c.uuid]===void 0){u=r.clone();const f=new u.ValueBufferType(l*u.times.length);for(let d=0;d<u.times.length;d++)f[d*l+h]=u.values[d];u.name=(o.nodeName||"")+".morphTargetInfluences",u.values=f,n[c.uuid]=u,s.push(u);continue}const T=r.createInterpolant(new r.ValueBufferType(1));u=n[c.uuid];for(let f=0;f<u.times.length;f++)u.values[f*l+h]=T.evaluate(u.times[f]);for(let f=0;f<r.times.length;f++){const d=this.insertKeyframe(u,r.times[f]);u.values[d*l+h]=r.values[f]}}return a.tracks=s,a},toFloat32BufferAttribute:function(a){const e=new S(new Float32Array(a.count*a.itemSize),a.itemSize,!1);if(!a.normalized&&!a.isInterleavedBufferAttribute)return e.array.set(a.array),e;for(let s=0,n=a.count;s<n;s++)for(let t=0;t<a.itemSize;t++)e.setComponent(s,t,a.getComponent(s,t));return e}};export{H as GLTFExporter};
|
|
1
|
+
import{C as $,M as J,V as v,Q as ee,B as S,R as se,a as D,S as te,N as ne,b as k,c as ie,I as re,D as oe,P as z,d as ae,e as Y,f as ce,g as ue,h as le,i as fe,L as he,j as pe,k as de,l as xe,m as ye,n as ge,o as Te}from"./style-D6eZHs3D.js";const j={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class H{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register(function(e){return new Le(e)}),this.register(function(e){return new _e(e)}),this.register(function(e){return new Oe(e)}),this.register(function(e){return new ve(e)}),this.register(function(e){return new ze(e)}),this.register(function(e){return new Be(e)}),this.register(function(e){return new Ce(e)}),this.register(function(e){return new Ue(e)}),this.register(function(e){return new Fe(e)}),this.register(function(e){return new De(e)}),this.register(function(e){return new Ge(e)}),this.register(function(e){return new Pe(e)}),this.register(function(e){return new ke(e)}),this.register(function(e){return new He(e)})}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}setTextureUtils(e){return this.textureUtils=e,this}parse(e,s,n,t){const i=new Se,r=[];for(let o=0,c=this.pluginCallbacks.length;o<c;o++)r.push(this.pluginCallbacks[o](i));i.setPlugins(r),i.setTextureUtils(this.textureUtils),i.writeAsync(e,s,t).catch(n)}parseAsync(e,s){const n=this;return new Promise(function(t,i){n.parse(e,t,i,s)})}}const g={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,CLAMP_TO_EDGE:33071,MIRRORED_REPEAT:33648,REPEAT:10497},G="KHR_mesh_quantization",R={};R[ue]=g.NEAREST;R[le]=g.NEAREST_MIPMAP_NEAREST;R[fe]=g.NEAREST_MIPMAP_LINEAR;R[he]=g.LINEAR;R[pe]=g.LINEAR_MIPMAP_NEAREST;R[de]=g.LINEAR_MIPMAP_LINEAR;R[xe]=g.CLAMP_TO_EDGE;R[ye]=g.REPEAT;R[ge]=g.MIRRORED_REPEAT;const K={scale:"scale",position:"translation",quaternion:"rotation",morphTargetInfluences:"weights"},we=new $,q=12,me=1179937895,Me=2,W=8,Ae=1313821514,Ee=5130562;function F(a,e){return a.length===e.length&&a.every(function(s,n){return s===e[n]})}function Ie(a){return new TextEncoder().encode(a).buffer}function Re(a){return F(a.elements,[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function Ne(a,e,s){const n={min:new Array(a.itemSize).fill(Number.POSITIVE_INFINITY),max:new Array(a.itemSize).fill(Number.NEGATIVE_INFINITY)};for(let t=e;t<e+s;t++)for(let i=0;i<a.itemSize;i++){let r;a.itemSize>4?r=a.array[t*a.itemSize+i]:(i===0?r=a.getX(t):i===1?r=a.getY(t):i===2?r=a.getZ(t):i===3&&(r=a.getW(t)),a.normalized===!0&&(r=k.normalize(r,a.array))),n.min[i]=Math.min(n.min[i],r),n.max[i]=Math.max(n.max[i],r)}return n}function Z(a){return Math.ceil(a/4)*4}function P(a,e=0){const s=Z(a.byteLength);if(s!==a.byteLength){const n=new Uint8Array(s);if(n.set(new Uint8Array(a)),e!==0)for(let t=a.byteLength;t<s;t++)n[t]=e;return n.buffer}return a}function X(){return typeof document>"u"&&typeof OffscreenCanvas<"u"?new OffscreenCanvas(1,1):document.createElement("canvas")}function be(a,e){if(typeof OffscreenCanvas<"u"&&a instanceof OffscreenCanvas){let s;return e==="image/jpeg"?s=.92:e==="image/webp"&&(s=.8),a.convertToBlob({type:e,quality:s})}else return new Promise(s=>a.toBlob(s,e))}class Se{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+se}},this.cache={meshes:new Map,attributes:new Map,attributesNormalized:new Map,materials:new Map,textures:new Map,images:new Map},this.textureUtils=null}setPlugins(e){this.plugins=e}setTextureUtils(e){this.textureUtils=e}async writeAsync(e,s,n={}){this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},n),this.options.animations.length>0&&(this.options.trs=!0),await this.processInputAsync(e),await Promise.all(this.pending);const t=this,i=t.buffers,r=t.json;n=t.options;const o=t.extensionsUsed,c=t.extensionsRequired,l=new Blob(i,{type:"application/octet-stream"}),h=Object.keys(o),u=Object.keys(c);if(h.length>0&&(r.extensionsUsed=h),u.length>0&&(r.extensionsRequired=u),r.buffers&&r.buffers.length>0&&(r.buffers[0].byteLength=l.size),n.binary===!0){const T=new FileReader;T.readAsArrayBuffer(l),T.onloadend=function(){const f=P(T.result),d=new DataView(new ArrayBuffer(W));d.setUint32(0,f.byteLength,!0),d.setUint32(4,Ee,!0);const x=P(Ie(JSON.stringify(r)),32),y=new DataView(new ArrayBuffer(W));y.setUint32(0,x.byteLength,!0),y.setUint32(4,Ae,!0);const M=new ArrayBuffer(q),N=new DataView(M);N.setUint32(0,me,!0),N.setUint32(4,Me,!0);const O=q+y.byteLength+x.byteLength+d.byteLength+f.byteLength;N.setUint32(8,O,!0);const p=new Blob([M,y,x,d,f],{type:"application/octet-stream"}),w=new FileReader;w.readAsArrayBuffer(p),w.onloadend=function(){s(w.result)}}}else if(r.buffers&&r.buffers.length>0){const T=new FileReader;T.readAsDataURL(l),T.onloadend=function(){const f=T.result;r.buffers[0].uri=f,s(r)}}else s(r)}serializeUserData(e,s){if(Object.keys(e.userData).length===0)return;const n=this.options,t=this.extensionsUsed;try{const i=JSON.parse(JSON.stringify(e.userData));if(n.includeCustomExtensions&&i.gltfExtensions){s.extensions===void 0&&(s.extensions={});for(const r in i.gltfExtensions)s.extensions[r]=i.gltfExtensions[r],t[r]=!0;delete i.gltfExtensions}Object.keys(i).length>0&&(s.extras=i)}catch(i){console.warn("THREE.GLTFExporter: userData of '"+e.name+"' won't be serialized because of JSON.stringify error - "+i.message)}}getUID(e,s=!1){if(this.uids.has(e)===!1){const t=new Map;t.set(!0,this.uid++),t.set(!1,this.uid++),this.uids.set(e,t)}return this.uids.get(e).get(s)}isNormalizedNormalAttribute(e){if(this.cache.attributesNormalized.has(e))return!1;const n=new v;for(let t=0,i=e.count;t<i;t++)if(Math.abs(n.fromBufferAttribute(e,t).length()-1)>5e-4)return!1;return!0}createNormalizedNormalAttribute(e){const s=this.cache;if(s.attributesNormalized.has(e))return s.attributesNormalized.get(e);const n=e.clone(),t=new v;for(let i=0,r=n.count;i<r;i++)t.fromBufferAttribute(n,i),t.x===0&&t.y===0&&t.z===0?t.setX(1):t.normalize(),n.setXYZ(i,t.x,t.y,t.z);return s.attributesNormalized.set(e,n),n}applyTextureTransform(e,s){let n=!1;const t={};(s.offset.x!==0||s.offset.y!==0)&&(t.offset=s.offset.toArray(),n=!0),s.rotation!==0&&(t.rotation=s.rotation,n=!0),(s.repeat.x!==1||s.repeat.y!==1)&&(t.scale=s.repeat.toArray(),n=!0),n&&(e.extensions=e.extensions||{},e.extensions.KHR_texture_transform=t,this.extensionsUsed.KHR_texture_transform=!0)}async buildMetalRoughTextureAsync(e,s){if(e===s)return e;function n(f){return f.colorSpace===ce?function(x){return x<.04045?x*.0773993808:Math.pow(x*.9478672986+.0521327014,2.4)}:function(x){return x}}e instanceof D&&(e=await this.decompressTextureAsync(e)),s instanceof D&&(s=await this.decompressTextureAsync(s));const t=e?e.image:null,i=s?s.image:null,r=Math.max(t?t.width:0,i?i.width:0),o=Math.max(t?t.height:0,i?i.height:0),c=X();c.width=r,c.height=o;const l=c.getContext("2d",{willReadFrequently:!0});l.fillStyle="#00ffff",l.fillRect(0,0,r,o);const h=l.getImageData(0,0,r,o);if(t){l.drawImage(t,0,0,r,o);const f=n(e),d=l.getImageData(0,0,r,o).data;for(let x=2;x<d.length;x+=4)h.data[x]=f(d[x]/256)*256}if(i){l.drawImage(i,0,0,r,o);const f=n(s),d=l.getImageData(0,0,r,o).data;for(let x=1;x<d.length;x+=4)h.data[x]=f(d[x]/256)*256}l.putImageData(h,0,0);const T=(e||s).clone();return T.source=new te(c),T.colorSpace=ne,T.channel=(e||s).channel,e&&s&&e.channel!==s.channel&&console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."),console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."),T}async decompressTextureAsync(e,s=1/0){if(this.textureUtils===null)throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.");return await this.textureUtils.decompress(e,s)}processBuffer(e){const s=this.json,n=this.buffers;return s.buffers||(s.buffers=[{byteLength:0}]),n.push(e),0}processBufferView(e,s,n,t,i){const r=this.json;r.bufferViews||(r.bufferViews=[]);let o;switch(s){case g.BYTE:case g.UNSIGNED_BYTE:o=1;break;case g.SHORT:case g.UNSIGNED_SHORT:o=2;break;default:o=4}let c=e.itemSize*o;i===g.ARRAY_BUFFER&&(c=Math.ceil(c/4)*4);const l=Z(t*c),h=new DataView(new ArrayBuffer(l));let u=0;for(let d=n;d<n+t;d++){for(let x=0;x<e.itemSize;x++){let y;e.itemSize>4?y=e.array[d*e.itemSize+x]:(x===0?y=e.getX(d):x===1?y=e.getY(d):x===2?y=e.getZ(d):x===3&&(y=e.getW(d)),e.normalized===!0&&(y=k.normalize(y,e.array))),s===g.FLOAT?h.setFloat32(u,y,!0):s===g.INT?h.setInt32(u,y,!0):s===g.UNSIGNED_INT?h.setUint32(u,y,!0):s===g.SHORT?h.setInt16(u,y,!0):s===g.UNSIGNED_SHORT?h.setUint16(u,y,!0):s===g.BYTE?h.setInt8(u,y):s===g.UNSIGNED_BYTE&&h.setUint8(u,y),u+=o}u%c!==0&&(u+=c-u%c)}const T={buffer:this.processBuffer(h.buffer),byteOffset:this.byteOffset,byteLength:l};return i!==void 0&&(T.target=i),i===g.ARRAY_BUFFER&&(T.byteStride=c),this.byteOffset+=l,r.bufferViews.push(T),{id:r.bufferViews.length-1,byteLength:0}}processBufferViewImage(e){const s=this,n=s.json;return n.bufferViews||(n.bufferViews=[]),new Promise(function(t){const i=new FileReader;i.readAsArrayBuffer(e),i.onloadend=function(){const r=P(i.result),o={buffer:s.processBuffer(r),byteOffset:s.byteOffset,byteLength:r.byteLength};s.byteOffset+=r.byteLength,t(n.bufferViews.push(o)-1)}})}processAccessor(e,s,n,t){const i=this.json,r={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"};let o;if(e.array.constructor===Float32Array)o=g.FLOAT;else if(e.array.constructor===Int32Array)o=g.INT;else if(e.array.constructor===Uint32Array)o=g.UNSIGNED_INT;else if(e.array.constructor===Int16Array)o=g.SHORT;else if(e.array.constructor===Uint16Array)o=g.UNSIGNED_SHORT;else if(e.array.constructor===Int8Array)o=g.BYTE;else if(e.array.constructor===Uint8Array)o=g.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+e.array.constructor.name);if(n===void 0&&(n=0),(t===void 0||t===1/0)&&(t=e.count),t===0)return null;const c=Ne(e,n,t);let l;s!==void 0&&(l=e===s.index?g.ELEMENT_ARRAY_BUFFER:g.ARRAY_BUFFER);const h=this.processBufferView(e,o,n,t,l),u={bufferView:h.id,byteOffset:h.byteOffset,componentType:o,count:t,max:c.max,min:c.min,type:r[e.itemSize]};return e.normalized===!0&&(u.normalized=!0),i.accessors||(i.accessors=[]),i.accessors.push(u)-1}processImage(e,s,n,t="image/png"){if(e!==null){const i=this,r=i.cache,o=i.json,c=i.options,l=i.pending;r.images.has(e)||r.images.set(e,{});const h=r.images.get(e),u=t+":flipY/"+n.toString();if(h[u]!==void 0)return h[u];o.images||(o.images=[]);const T={mimeType:t},f=X();f.width=Math.min(e.width,c.maxTextureSize),f.height=Math.min(e.height,c.maxTextureSize);const d=f.getContext("2d",{willReadFrequently:!0});if(n===!0&&(d.translate(0,f.height),d.scale(1,-1)),e.data!==void 0){s!==ie&&console.error("GLTFExporter: Only RGBAFormat is supported.",s),(e.width>c.maxTextureSize||e.height>c.maxTextureSize)&&console.warn("GLTFExporter: Image size is bigger than maxTextureSize",e);const y=new Uint8ClampedArray(e.height*e.width*4);for(let M=0;M<y.length;M+=4)y[M+0]=e.data[M+0],y[M+1]=e.data[M+1],y[M+2]=e.data[M+2],y[M+3]=e.data[M+3];d.putImageData(new ImageData(y,e.width,e.height),0,0)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas)d.drawImage(e,0,0,f.width,f.height);else throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.");c.binary===!0?l.push(be(f,t).then(y=>i.processBufferViewImage(y)).then(y=>{T.bufferView=y})):T.uri=re.getDataURL(f,t);const x=o.images.push(T)-1;return h[u]=x,x}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(e){const s=this.json;s.samplers||(s.samplers=[]);const n={magFilter:R[e.magFilter],minFilter:R[e.minFilter],wrapS:R[e.wrapS],wrapT:R[e.wrapT]};return s.samplers.push(n)-1}async processTextureAsync(e){const n=this.options,t=this.cache,i=this.json;if(t.textures.has(e))return t.textures.get(e);i.textures||(i.textures=[]),e instanceof D&&(e=await this.decompressTextureAsync(e,n.maxTextureSize));let r=e.userData.mimeType;r==="image/webp"&&(r="image/png");const o={sampler:this.processSampler(e),source:this.processImage(e.image,e.format,e.flipY,r)};e.name&&(o.name=e.name),await this._invokeAllAsync(async function(l){l.writeTexture&&await l.writeTexture(e,o)});const c=i.textures.push(o)-1;return t.textures.set(e,c),c}async processMaterialAsync(e){const s=this.cache,n=this.json;if(s.materials.has(e))return s.materials.get(e);if(e.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;n.materials||(n.materials=[]);const t={pbrMetallicRoughness:{}};e.isMeshStandardMaterial!==!0&&e.isMeshBasicMaterial!==!0&&console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");const i=e.color.toArray().concat([e.opacity]);if(F(i,[1,1,1,1])||(t.pbrMetallicRoughness.baseColorFactor=i),e.isMeshStandardMaterial?(t.pbrMetallicRoughness.metallicFactor=e.metalness,t.pbrMetallicRoughness.roughnessFactor=e.roughness):(t.pbrMetallicRoughness.metallicFactor=0,t.pbrMetallicRoughness.roughnessFactor=1),e.metalnessMap||e.roughnessMap){const o=await this.buildMetalRoughTextureAsync(e.metalnessMap,e.roughnessMap),c={index:await this.processTextureAsync(o),texCoord:o.channel};this.applyTextureTransform(c,o),t.pbrMetallicRoughness.metallicRoughnessTexture=c}if(e.map){const o={index:await this.processTextureAsync(e.map),texCoord:e.map.channel};this.applyTextureTransform(o,e.map),t.pbrMetallicRoughness.baseColorTexture=o}if(e.emissive){const o=e.emissive;if(Math.max(o.r,o.g,o.b)>0&&(t.emissiveFactor=e.emissive.toArray()),e.emissiveMap){const l={index:await this.processTextureAsync(e.emissiveMap),texCoord:e.emissiveMap.channel};this.applyTextureTransform(l,e.emissiveMap),t.emissiveTexture=l}}if(e.normalMap){const o={index:await this.processTextureAsync(e.normalMap),texCoord:e.normalMap.channel};e.normalScale&&e.normalScale.x!==1&&(o.scale=e.normalScale.x),this.applyTextureTransform(o,e.normalMap),t.normalTexture=o}if(e.aoMap){const o={index:await this.processTextureAsync(e.aoMap),texCoord:e.aoMap.channel};e.aoMapIntensity!==1&&(o.strength=e.aoMapIntensity),this.applyTextureTransform(o,e.aoMap),t.occlusionTexture=o}e.transparent?t.alphaMode="BLEND":e.alphaTest>0&&(t.alphaMode="MASK",t.alphaCutoff=e.alphaTest),e.side===oe&&(t.doubleSided=!0),e.name!==""&&(t.name=e.name),this.serializeUserData(e,t),await this._invokeAllAsync(async function(o){o.writeMaterialAsync&&await o.writeMaterialAsync(e,t)});const r=n.materials.push(t)-1;return s.materials.set(e,r),r}async processMeshAsync(e){const s=this.cache,n=this.json,t=[e.geometry.uuid];if(Array.isArray(e.material))for(let p=0,w=e.material.length;p<w;p++)t.push(e.material[p].uuid);else t.push(e.material.uuid);const i=t.join(":");if(s.meshes.has(i))return s.meshes.get(i);const r=e.geometry;let o;e.isLineSegments?o=g.LINES:e.isLineLoop?o=g.LINE_LOOP:e.isLine?o=g.LINE_STRIP:e.isPoints?o=g.POINTS:o=e.material.wireframe?g.LINES:g.TRIANGLES;const c={},l={},h=[],u=[],T={uv:"TEXCOORD_0",uv1:"TEXCOORD_1",uv2:"TEXCOORD_2",uv3:"TEXCOORD_3",color:"COLOR_0",skinWeight:"WEIGHTS_0",skinIndex:"JOINTS_0"},f=r.getAttribute("normal");f!==void 0&&!this.isNormalizedNormalAttribute(f)&&(console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."),r.setAttribute("normal",this.createNormalizedNormalAttribute(f)));let d=null;for(let p in r.attributes){if(p.slice(0,5)==="morph")continue;const w=r.attributes[p];if(p=T[p]||p.toUpperCase(),/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/.test(p)||(p="_"+p),s.attributes.has(this.getUID(w))){l[p]=s.attributes.get(this.getUID(w));continue}d=null;const m=w.array;p==="JOINTS_0"&&!(m instanceof Uint16Array)&&!(m instanceof Uint8Array)?(console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'),d=new S(new Uint16Array(m),w.itemSize,w.normalized)):(m instanceof Uint32Array||m instanceof Int32Array)&&!p.startsWith("_")&&(console.warn(`GLTFExporter: Attribute "${p}" converted to type FLOAT.`),d=H.Utils.toFloat32BufferAttribute(w));const I=this.processAccessor(d||w,r);I!==null&&(p.startsWith("_")||this.detectMeshQuantization(p,w),l[p]=I,s.attributes.set(this.getUID(w),I))}if(f!==void 0&&r.setAttribute("normal",f),Object.keys(l).length===0)return null;if(e.morphTargetInfluences!==void 0&&e.morphTargetInfluences.length>0){const p=[],w=[],A={};if(e.morphTargetDictionary!==void 0)for(const m in e.morphTargetDictionary)A[e.morphTargetDictionary[m]]=m;for(let m=0;m<e.morphTargetInfluences.length;++m){const I={};let V=!1;for(const _ in r.morphAttributes){if(_!=="position"&&_!=="normal"){V||(console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."),V=!0);continue}const b=r.morphAttributes[_][m],B=_.toUpperCase(),C=r.attributes[_];if(s.attributes.has(this.getUID(b,!0))){I[B]=s.attributes.get(this.getUID(b,!0));continue}const U=b.clone();if(!r.morphTargetsRelative)for(let E=0,Q=b.count;E<Q;E++)for(let L=0;L<b.itemSize;L++)L===0&&U.setX(E,b.getX(E)-C.getX(E)),L===1&&U.setY(E,b.getY(E)-C.getY(E)),L===2&&U.setZ(E,b.getZ(E)-C.getZ(E)),L===3&&U.setW(E,b.getW(E)-C.getW(E));I[B]=this.processAccessor(U,r),s.attributes.set(this.getUID(C,!0),I[B])}u.push(I),p.push(e.morphTargetInfluences[m]),e.morphTargetDictionary!==void 0&&w.push(A[m])}c.weights=p,w.length>0&&(c.extras={},c.extras.targetNames=w)}const x=Array.isArray(e.material);if(x&&r.groups.length===0)return null;let y=!1;if(x&&r.index===null){const p=[];for(let w=0,A=r.attributes.position.count;w<A;w++)p[w]=w;r.setIndex(p),y=!0}const M=x?e.material:[e.material],N=x?r.groups:[{materialIndex:0,start:void 0,count:void 0}];for(let p=0,w=N.length;p<w;p++){const A={mode:o,attributes:l};if(this.serializeUserData(r,A),u.length>0&&(A.targets=u),r.index!==null){let I=this.getUID(r.index);(N[p].start!==void 0||N[p].count!==void 0)&&(I+=":"+N[p].start+":"+N[p].count),s.attributes.has(I)?A.indices=s.attributes.get(I):(A.indices=this.processAccessor(r.index,r,N[p].start,N[p].count),s.attributes.set(I,A.indices)),A.indices===null&&delete A.indices}const m=await this.processMaterialAsync(M[N[p].materialIndex]);m!==null&&(A.material=m),h.push(A)}y===!0&&r.setIndex(null),c.primitives=h,n.meshes||(n.meshes=[]),await this._invokeAllAsync(function(p){p.writeMesh&&p.writeMesh(e,c)});const O=n.meshes.push(c)-1;return s.meshes.set(i,O),O}detectMeshQuantization(e,s){if(this.extensionsUsed[G])return;let n;switch(s.array.constructor){case Int8Array:n="byte";break;case Uint8Array:n="unsigned byte";break;case Int16Array:n="short";break;case Uint16Array:n="unsigned short";break;default:return}s.normalized&&(n+=" normalized");const t=e.split("_",1)[0];j[t]&&j[t].includes(n)&&(this.extensionsUsed[G]=!0,this.extensionsRequired[G]=!0)}processCamera(e){const s=this.json;s.cameras||(s.cameras=[]);const n=e.isOrthographicCamera,t={type:n?"orthographic":"perspective"};return n?t.orthographic={xmag:e.right*2,ymag:e.top*2,zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near}:t.perspective={aspectRatio:e.aspect,yfov:k.degToRad(e.fov),zfar:e.far<=0?.001:e.far,znear:e.near<0?0:e.near},e.name!==""&&(t.name=e.type),s.cameras.push(t)-1}processAnimation(e,s){const n=this.json,t=this.nodeMap;n.animations||(n.animations=[]),e=H.Utils.mergeMorphTargetTracks(e.clone(),s);const i=e.tracks,r=[],o=[];for(let l=0;l<i.length;++l){const h=i[l],u=z.parseTrackName(h.name);let T=z.findNode(s,u.nodeName);const f=K[u.propertyName];if(u.objectName==="bones"&&(T.isSkinnedMesh===!0?T=T.skeleton.getBoneByName(u.objectIndex):T=void 0),!T||!f){console.warn('THREE.GLTFExporter: Could not export animation track "%s".',h.name);continue}const d=1;let x=h.values.length/h.times.length;f===K.morphTargetInfluences&&(x/=T.morphTargetInfluences.length);let y;h.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline===!0?(y="CUBICSPLINE",x/=3):h.getInterpolation()===ae?y="STEP":y="LINEAR",o.push({input:this.processAccessor(new S(h.times,d)),output:this.processAccessor(new S(h.values,x)),interpolation:y}),r.push({sampler:o.length-1,target:{node:t.get(T),path:f}})}const c={name:e.name||"clip_"+n.animations.length,samplers:o,channels:r};return this.serializeUserData(e,c),n.animations.push(c),n.animations.length-1}processSkin(e){const s=this.json,n=this.nodeMap,t=s.nodes[n.get(e)],i=e.skeleton;if(i===void 0)return null;const r=e.skeleton.bones[0];if(r===void 0)return null;const o=[],c=new Float32Array(i.bones.length*16),l=new J;for(let u=0;u<i.bones.length;++u)o.push(n.get(i.bones[u])),l.copy(i.boneInverses[u]),l.multiply(e.bindMatrix).toArray(c,u*16);return s.skins===void 0&&(s.skins=[]),s.skins.push({inverseBindMatrices:this.processAccessor(new S(c,16)),joints:o,skeleton:n.get(r)}),t.skin=s.skins.length-1}async processNodeAsync(e){const s=this.json,n=this.options,t=this.nodeMap;s.nodes||(s.nodes=[]);const i={};if(n.trs){const o=e.quaternion.toArray(),c=e.position.toArray(),l=e.scale.toArray();F(o,[0,0,0,1])||(i.rotation=o),F(c,[0,0,0])||(i.translation=c),F(l,[1,1,1])||(i.scale=l)}else e.matrixAutoUpdate&&e.updateMatrix(),Re(e.matrix)===!1&&(i.matrix=e.matrix.elements);if(e.name!==""&&(i.name=String(e.name)),this.serializeUserData(e,i),e.isMesh||e.isLine||e.isPoints){const o=await this.processMeshAsync(e);o!==null&&(i.mesh=o)}else e.isCamera&&(i.camera=this.processCamera(e));e.isSkinnedMesh&&this.skins.push(e);const r=s.nodes.push(i)-1;if(t.set(e,r),e.children.length>0){const o=[];for(let c=0,l=e.children.length;c<l;c++){const h=e.children[c];if(h.visible||n.onlyVisible===!1){const u=await this.processNodeAsync(h);u!==null&&o.push(u)}}o.length>0&&(i.children=o)}return await this._invokeAllAsync(function(o){o.writeNode&&o.writeNode(e,i)}),r}async processSceneAsync(e){const s=this.json,n=this.options;s.scenes||(s.scenes=[],s.scene=0);const t={};e.name!==""&&(t.name=e.name),s.scenes.push(t);const i=[];for(let r=0,o=e.children.length;r<o;r++){const c=e.children[r];if(c.visible||n.onlyVisible===!1){const l=await this.processNodeAsync(c);l!==null&&i.push(l)}}i.length>0&&(t.nodes=i),this.serializeUserData(e,t)}async processObjectsAsync(e){const s=new Y;s.name="AuxScene";for(let n=0;n<e.length;n++)s.children.push(e[n]);await this.processSceneAsync(s)}async processInputAsync(e){const s=this.options;e=e instanceof Array?e:[e],await this._invokeAllAsync(function(t){t.beforeParse&&t.beforeParse(e)});const n=[];for(let t=0;t<e.length;t++)e[t]instanceof Y?await this.processSceneAsync(e[t]):n.push(e[t]);n.length>0&&await this.processObjectsAsync(n);for(let t=0;t<this.skins.length;++t)this.processSkin(this.skins[t]);for(let t=0;t<s.animations.length;++t)this.processAnimation(s.animations[t],e[0]);await this._invokeAllAsync(function(t){t.afterParse&&t.afterParse(e)})}async _invokeAllAsync(e){for(let s=0,n=this.plugins.length;s<n;s++)await e(this.plugins[s])}}class Le{constructor(e){this.writer=e,this.name="KHR_lights_punctual"}writeNode(e,s){if(!e.isLight)return;if(!e.isDirectionalLight&&!e.isPointLight&&!e.isSpotLight){console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.",e);return}const n=this.writer,t=n.json,i=n.extensionsUsed,r={};e.name&&(r.name=e.name),r.color=e.color.toArray(),r.intensity=e.intensity,e.isDirectionalLight?r.type="directional":e.isPointLight?(r.type="point",e.distance>0&&(r.range=e.distance)):e.isSpotLight&&(r.type="spot",e.distance>0&&(r.range=e.distance),r.spot={},r.spot.innerConeAngle=(1-e.penumbra)*e.angle,r.spot.outerConeAngle=e.angle),e.decay!==void 0&&e.decay!==2&&console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."),e.target&&(e.target.parent!==e||e.target.position.x!==0||e.target.position.y!==0||e.target.position.z!==-1)&&console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."),i[this.name]||(t.extensions=t.extensions||{},t.extensions[this.name]={lights:[]},i[this.name]=!0);const o=t.extensions[this.name].lights;o.push(r),s.extensions=s.extensions||{},s.extensions[this.name]={light:o.length-1}}}class _e{constructor(e){this.writer=e,this.name="KHR_materials_unlit"}async writeMaterialAsync(e,s){if(!e.isMeshBasicMaterial)return;const t=this.writer.extensionsUsed;s.extensions=s.extensions||{},s.extensions[this.name]={},t[this.name]=!0,s.pbrMetallicRoughness.metallicFactor=0,s.pbrMetallicRoughness.roughnessFactor=.9}}class Ce{constructor(e){this.writer=e,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.clearcoat===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.clearcoatFactor=e.clearcoat,e.clearcoatMap){const r={index:await n.processTextureAsync(e.clearcoatMap),texCoord:e.clearcoatMap.channel};n.applyTextureTransform(r,e.clearcoatMap),i.clearcoatTexture=r}if(i.clearcoatRoughnessFactor=e.clearcoatRoughness,e.clearcoatRoughnessMap){const r={index:await n.processTextureAsync(e.clearcoatRoughnessMap),texCoord:e.clearcoatRoughnessMap.channel};n.applyTextureTransform(r,e.clearcoatRoughnessMap),i.clearcoatRoughnessTexture=r}if(e.clearcoatNormalMap){const r={index:await n.processTextureAsync(e.clearcoatNormalMap),texCoord:e.clearcoatNormalMap.channel};e.clearcoatNormalScale.x!==1&&(r.scale=e.clearcoatNormalScale.x),n.applyTextureTransform(r,e.clearcoatNormalMap),i.clearcoatNormalTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Ue{constructor(e){this.writer=e,this.name="KHR_materials_dispersion"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.dispersion===0)return;const t=this.writer.extensionsUsed,i={};i.dispersion=e.dispersion,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Fe{constructor(e){this.writer=e,this.name="KHR_materials_iridescence"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.iridescence===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.iridescenceFactor=e.iridescence,e.iridescenceMap){const r={index:await n.processTextureAsync(e.iridescenceMap),texCoord:e.iridescenceMap.channel};n.applyTextureTransform(r,e.iridescenceMap),i.iridescenceTexture=r}if(i.iridescenceIor=e.iridescenceIOR,i.iridescenceThicknessMinimum=e.iridescenceThicknessRange[0],i.iridescenceThicknessMaximum=e.iridescenceThicknessRange[1],e.iridescenceThicknessMap){const r={index:await n.processTextureAsync(e.iridescenceThicknessMap),texCoord:e.iridescenceThicknessMap.channel};n.applyTextureTransform(r,e.iridescenceThicknessMap),i.iridescenceThicknessTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Oe{constructor(e){this.writer=e,this.name="KHR_materials_transmission"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.transmissionFactor=e.transmission,e.transmissionMap){const r={index:await n.processTextureAsync(e.transmissionMap),texCoord:e.transmissionMap.channel};n.applyTextureTransform(r,e.transmissionMap),i.transmissionTexture=r}s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ve{constructor(e){this.writer=e,this.name="KHR_materials_volume"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.transmission===0)return;const n=this.writer,t=n.extensionsUsed,i={};if(i.thicknessFactor=e.thickness,e.thicknessMap){const r={index:await n.processTextureAsync(e.thicknessMap),texCoord:e.thicknessMap.channel};n.applyTextureTransform(r,e.thicknessMap),i.thicknessTexture=r}e.attenuationDistance!==1/0&&(i.attenuationDistance=e.attenuationDistance),i.attenuationColor=e.attenuationColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ze{constructor(e){this.writer=e,this.name="KHR_materials_ior"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.ior===1.5)return;const t=this.writer.extensionsUsed,i={};i.ior=e.ior,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Be{constructor(e){this.writer=e,this.name="KHR_materials_specular"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.specularIntensity===1&&e.specularColor.equals(we)&&!e.specularIntensityMap&&!e.specularColorMap)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.specularIntensityMap){const r={index:await n.processTextureAsync(e.specularIntensityMap),texCoord:e.specularIntensityMap.channel};n.applyTextureTransform(r,e.specularIntensityMap),i.specularTexture=r}if(e.specularColorMap){const r={index:await n.processTextureAsync(e.specularColorMap),texCoord:e.specularColorMap.channel};n.applyTextureTransform(r,e.specularColorMap),i.specularColorTexture=r}i.specularFactor=e.specularIntensity,i.specularColorFactor=e.specularColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class De{constructor(e){this.writer=e,this.name="KHR_materials_sheen"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.sheen==0)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.sheenRoughnessMap){const r={index:await n.processTextureAsync(e.sheenRoughnessMap),texCoord:e.sheenRoughnessMap.channel};n.applyTextureTransform(r,e.sheenRoughnessMap),i.sheenRoughnessTexture=r}if(e.sheenColorMap){const r={index:await n.processTextureAsync(e.sheenColorMap),texCoord:e.sheenColorMap.channel};n.applyTextureTransform(r,e.sheenColorMap),i.sheenColorTexture=r}i.sheenRoughnessFactor=e.sheenRoughness,i.sheenColorFactor=e.sheenColor.toArray(),s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Ge{constructor(e){this.writer=e,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(e,s){if(!e.isMeshPhysicalMaterial||e.anisotropy==0)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.anisotropyMap){const r={index:await n.processTextureAsync(e.anisotropyMap)};n.applyTextureTransform(r,e.anisotropyMap),i.anisotropyTexture=r}i.anisotropyStrength=e.anisotropy,i.anisotropyRotation=e.anisotropyRotation,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class Pe{constructor(e){this.writer=e,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(e,s){if(!e.isMeshStandardMaterial||e.emissiveIntensity===1)return;const t=this.writer.extensionsUsed,i={};i.emissiveStrength=e.emissiveIntensity,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class ke{constructor(e){this.writer=e,this.name="EXT_materials_bump"}async writeMaterialAsync(e,s){if(!e.isMeshStandardMaterial||e.bumpScale===1&&!e.bumpMap)return;const n=this.writer,t=n.extensionsUsed,i={};if(e.bumpMap){const r={index:await n.processTextureAsync(e.bumpMap),texCoord:e.bumpMap.channel};n.applyTextureTransform(r,e.bumpMap),i.bumpTexture=r}i.bumpFactor=e.bumpScale,s.extensions=s.extensions||{},s.extensions[this.name]=i,t[this.name]=!0}}class He{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,s){if(!e.isInstancedMesh)return;const n=this.writer,t=e,i=new Float32Array(t.count*3),r=new Float32Array(t.count*4),o=new Float32Array(t.count*3),c=new J,l=new v,h=new ee,u=new v;for(let f=0;f<t.count;f++)t.getMatrixAt(f,c),c.decompose(l,h,u),l.toArray(i,f*3),h.toArray(r,f*4),u.toArray(o,f*3);const T={TRANSLATION:n.processAccessor(new S(i,3)),ROTATION:n.processAccessor(new S(r,4)),SCALE:n.processAccessor(new S(o,3))};t.instanceColor&&(T._COLOR_0=n.processAccessor(t.instanceColor)),s.extensions=s.extensions||{},s.extensions[this.name]={attributes:T},n.extensionsUsed[this.name]=!0,n.extensionsRequired[this.name]=!0}}H.Utils={insertKeyframe:function(a,e){const n=a.getValueSize(),t=new a.TimeBufferType(a.times.length+1),i=new a.ValueBufferType(a.values.length+n),r=a.createInterpolant(new a.ValueBufferType(n));let o;if(a.times.length===0){t[0]=e;for(let c=0;c<n;c++)i[c]=0;o=0}else if(e<a.times[0]){if(Math.abs(a.times[0]-e)<.001)return 0;t[0]=e,t.set(a.times,1),i.set(r.evaluate(e),0),i.set(a.values,n),o=0}else if(e>a.times[a.times.length-1]){if(Math.abs(a.times[a.times.length-1]-e)<.001)return a.times.length-1;t[t.length-1]=e,t.set(a.times,0),i.set(a.values,0),i.set(r.evaluate(e),a.values.length),o=t.length-1}else for(let c=0;c<a.times.length;c++){if(Math.abs(a.times[c]-e)<.001)return c;if(a.times[c]<e&&a.times[c+1]>e){t.set(a.times.slice(0,c+1),0),t[c+1]=e,t.set(a.times.slice(c+1),c+2),i.set(a.values.slice(0,(c+1)*n),0),i.set(r.evaluate(e),(c+1)*n),i.set(a.values.slice((c+1)*n),(c+2)*n),o=c+1;break}}return a.times=t,a.values=i,o},mergeMorphTargetTracks:function(a,e){const s=[],n={},t=a.tracks;for(let i=0;i<t.length;++i){let r=t[i];const o=z.parseTrackName(r.name),c=z.findNode(e,o.nodeName);if(o.propertyName!=="morphTargetInfluences"||o.propertyIndex===void 0){s.push(r);continue}if(r.createInterpolant!==r.InterpolantFactoryMethodDiscrete&&r.createInterpolant!==r.InterpolantFactoryMethodLinear){if(r.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline)throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.");console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."),r=r.clone(),r.setInterpolation(Te)}const l=c.morphTargetInfluences.length,h=c.morphTargetDictionary[o.propertyIndex];if(h===void 0)throw new Error("THREE.GLTFExporter: Morph target name not found: "+o.propertyIndex);let u;if(n[c.uuid]===void 0){u=r.clone();const f=new u.ValueBufferType(l*u.times.length);for(let d=0;d<u.times.length;d++)f[d*l+h]=u.values[d];u.name=(o.nodeName||"")+".morphTargetInfluences",u.values=f,n[c.uuid]=u,s.push(u);continue}const T=r.createInterpolant(new r.ValueBufferType(1));u=n[c.uuid];for(let f=0;f<u.times.length;f++)u.values[f*l+h]=T.evaluate(u.times[f]);for(let f=0;f<r.times.length;f++){const d=this.insertKeyframe(u,r.times[f]);u.values[d*l+h]=r.values[f]}}return a.tracks=s,a},toFloat32BufferAttribute:function(a){const e=new S(new Float32Array(a.count*a.itemSize),a.itemSize,!1);if(!a.normalized&&!a.isInterleavedBufferAttribute)return e.array.set(a.array),e;for(let s=0,n=a.count;s<n;s++)for(let t=0;t<a.itemSize;t++)e.setComponent(s,t,a.getComponent(s,t));return e}};export{H as GLTFExporter};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{G as ae,b as P,p as oe,V as y,W as he,O as we,e as fe,C as be,q as $,r as ye,A as Me,M as ne,g as ve,L as re,s as xe,t as Le,u as Ze}from"./style-D6eZHs3D.js";import{m as Se,D as De,i as We,c as Be}from"./presets-jXE0t1fU.js";const A=e=>document.getElementById(e),se=A("comparison-status"),Q=A("atlas"),w=A("part"),X=A("yaw"),V=A("pitch"),z=A("zoom"),D=A("layers"),F=A("spacing"),M=A("explode"),Y=A("clay"),Ke=document.querySelector(".compare-results"),le=new URLSearchParams(location.search),E=le.get("session"),O=E&&/^[a-f0-9-]{36}$/.test(E)?"./__stack3_project/"+E:void 0;let L,v=0,N,ge,k,R=[],Ie,U=1;const _=new y;let Ce=[],T=0;const ee="top,left,front,rear",W={layers:De,resolution:144},q=Se.tank,ce="Future Tank · hull material passes",S={source:new URL(""+new URL("hull-4view-BPPqJYUz.png",import.meta.url).href,import.meta.url),clay:new URL(""+new URL("hull-clay-4view-3Cu-4Hvr.png",import.meta.url).href,import.meta.url),depth:new URL(""+new URL("hull-depth-4view-DCOdT5ev.png",import.meta.url).href,import.meta.url),baseColor:new URL(""+new URL("hull-base-color-4view-DrQmdT3h.png",import.meta.url).href,import.meta.url),normal:new URL(""+new URL("hull-normal-4view-CvLaFITy.png",import.meta.url).href,import.meta.url),calibration:new URL("data:application/json;base64,ewogICJzb3VyY2VBdGxhcyI6ICJodWxsLTR2aWV3LnBuZyIsCiAgImdlb21ldHJ5IjogInN0YWNrMyByZWd1bGFyaXplZCB2aXN1YWwgaHVsbCBmcm9tIHRoZSBSR0IgYXRsYXMgc2lsaG91ZXR0ZXMsIHdpdGggdGhlIHR1cm50YWJsZSBhbmQgbGFyZ2UgaGF0Y2ggcmVsaWVmIGd1aWRlZCBieSB2aXNpYmxlIHNvdXJjZSBnZW9tZXRyeSIsCiAgImRpbWVuc2lvbnMiOiBbCiAgICAxODc0LAogICAgNjkyCiAgXSwKICAibGF5b3V0IjogWwogICAgInRvcCIsCiAgICAibGVmdCIsCiAgICAiZnJvbnQiLAogICAgInJlYXIiCiAgXSwKICAicGl4ZWxzUGVyVW5pdCI6IDIwMCwKICAiZ3JvdW5kWSI6IDQ0MCwKICAiY2xheSI6IHsKICAgICJmaWxlIjogImh1bGwtY2xheS00dmlldy5wbmciLAogICAgImJhY2tncm91bmQiOiAidHJhbnNwYXJlbnQiCiAgfSwKICAiZGVwdGgiOiB7CiAgICAiZmlsZSI6ICJodWxsLWRlcHRoLTR2aWV3LnBuZyIsCiAgICAiZW5jb2RpbmciOiAiMTYtYml0IHVuc2lnbmVkIGdyYXlzY2FsZSwgbGluZWFyIGludmVyc2UgY2FtZXJhIGRpc3RhbmNlIiwKICAgICJiYWNrZ3JvdW5kIjogMCwKICAgICJ2YWxpZFJhbmdlIjogWwogICAgICAxLAogICAgICA2NTUzNQogICAgXSwKICAgICJkZWNvZGUiOiAiZGlzdGFuY2UgPSBuZWFyICsgKGZhciAtIG5lYXIpICogKDY1NTM1IC0gdmFsdWUpIC8gNjU1MzQiLAogICAgInVuaXRzIjogInN0YWNrMyBzY2VuZSB1bml0cyIsCiAgICAicGl4ZWxDZW50ZXJPZmZzZXQiOiAwLjUKICB9LAogICJ2aWV3cyI6IHsKICAgICJ0b3AiOiB7CiAgICAgICJyZWN0IjogWwogICAgICAgIDAsCiAgICAgICAgMCwKICAgICAgICAzOTYsCiAgICAgICAgNjkyCiAgICAgIF0sCiAgICAgICJhbmNob3IiOiBbCiAgICAgICAgMTk5LAogICAgICAgIDM0NgogICAgICBdLAogICAgICAib3JpZ2luIjogWwogICAgICAgIDAsCiAgICAgICAgMS4wNCwKICAgICAgICAwCiAgICAgIF0sCiAgICAgICJyaWdodCI6IFsKICAgICAgICAtMSwKICAgICAgICAwLAogICAgICAgIDAKICAgICAgXSwKICAgICAgInVwIjogWwogICAgICAgIDAsCiAgICAgICAgMCwKICAgICAgICAxCiAgICAgIF0sCiAgICAgICJmb3J3YXJkIjogWwogICAgICAgIDAsCiAgICAgICAgLTEsCiAgICAgICAgMAogICAgICBdLAogICAgICAibmVhciI6IDAsCiAgICAgICJmYXIiOiAxLjE0CiAgICB9LAogICAgImxlZnQiOiB7CiAgICAgICJyZWN0IjogWwogICAgICAgIDM5NiwKICAgICAgICAwLAogICAgICAgIDY4OCwKICAgICAgICA2OTIKICAgICAgXSwKICAgICAgImFuY2hvciI6IFsKICAgICAgICA3NDAsCiAgICAgICAgNDQwCiAgICAgIF0sCiAgICAgICJvcmlnaW4iOiBbCiAgICAgICAgLTAuOTQ1LAogICAgICAgIDAsCiAgICAgICAgMAogICAgICBdLAogICAgICAicmlnaHQiOiBbCiAgICAgICAgMCwKICAgICAgICAwLAogICAgICAgIDEKICAgICAgXSwKICAgICAgInVwIjogWwogICAgICAgIDAsCiAgICAgICAgMSwKICAgICAgICAwCiAgICAgIF0sCiAgICAgICJmb3J3YXJkIjogWwogICAgICAgIDEsCiAgICAgICAgMCwKICAgICAgICAwCiAgICAgIF0sCiAgICAgICJuZWFyIjogMCwKICAgICAgImZhciI6IDEuODkKICAgIH0sCiAgICAiZnJvbnQiOiB7CiAgICAgICJyZWN0IjogWwogICAgICAgIDEwODQsCiAgICAgICAgMCwKICAgICAgICAzOTQsCiAgICAgICAgNjkyCiAgICAgIF0sCiAgICAgICJhbmNob3IiOiBbCiAgICAgICAgMTI4MSwKICAgICAgICA0NDAKICAgICAgXSwKICAgICAgIm9yaWdpbiI6IFsKICAgICAgICAwLAogICAgICAgIDAsCiAgICAgICAgLTEuNjgwMDAwMDAwMDAwMDAwMgogICAgICBdLAogICAgICAicmlnaHQiOiBbCiAgICAgICAgLTEsCiAgICAgICAgMCwKICAgICAgICAwCiAgICAgIF0sCiAgICAgICJ1cCI6IFsKICAgICAgICAwLAogICAgICAgIDEsCiAgICAgICAgMAogICAgICBdLAogICAgICAiZm9yd2FyZCI6IFsKICAgICAgICAwLAogICAgICAgIDAsCiAgICAgICAgMQogICAgICBdLAogICAgICAibmVhciI6IDAsCiAgICAgICJmYXIiOiAzLjM2MDAwMDAwMDAwMDAwMDMKICAgIH0sCiAgICAicmVhciI6IHsKICAgICAgInJlY3QiOiBbCiAgICAgICAgMTQ3OCwKICAgICAgICAwLAogICAgICAgIDM5NiwKICAgICAgICA2OTIKICAgICAgXSwKICAgICAgImFuY2hvciI6IFsKICAgICAgICAxNjc1LAogICAgICAgIDQ0MAogICAgICBdLAogICAgICAib3JpZ2luIjogWwogICAgICAgIDAsCiAgICAgICAgMCwKICAgICAgICAxLjY4MDAwMDAwMDAwMDAwMDIKICAgICAgXSwKICAgICAgInJpZ2h0IjogWwogICAgICAgIDEsCiAgICAgICAgMCwKICAgICAgICAwCiAgICAgIF0sCiAgICAgICJ1cCI6IFsKICAgICAgICAwLAogICAgICAgIDEsCiAgICAgICAgMAogICAgICBdLAogICAgICAiZm9yd2FyZCI6IFsKICAgICAgICAwLAogICAgICAgIDAsCiAgICAgICAgLTEKICAgICAgXSwKICAgICAgIm5lYXIiOiAwLAogICAgICAiZmFyIjogMy4zNjAwMDAwMDAwMDAwMDAzCiAgICB9CiAgfSwKICAiYmFzZUNvbG9yIjogewogICAgImZpbGUiOiAiaHVsbC1iYXNlLWNvbG9yLTR2aWV3LnBuZyIsCiAgICAiZW5jb2RpbmciOiAiUkdCQTggc1JHQiIsCiAgICAic291cmNlIjogImdlbmVyYXRlZCBtYXRlcmlhbCBwYXNzIHJlZ2lzdGVyZWQgcGVyIHZpZXcgdG8gdGhlIENsYXkgc2lsaG91ZXR0ZXMiCiAgfSwKICAibm9ybWFsIjogewogICAgImZpbGUiOiAiaHVsbC1ub3JtYWwtNHZpZXcucG5nIiwKICAgICJlbmNvZGluZyI6ICJSR0JBOCBsaW5lYXIgZGF0YSIsCiAgICAic3BhY2UiOiAidmlldyIsCiAgICAiYXhlcyI6IHsKICAgICAgInJlZCI6ICIrWCBpbWFnZSByaWdodCIsCiAgICAgICJncmVlbiI6ICIrWSBpbWFnZSB1cCIsCiAgICAgICJibHVlIjogIitaIHRvd2FyZCB0aGUgY2FtZXJhIgogICAgfSwKICAgICJkZWNvZGUiOiAibm9ybWFsID0gbm9ybWFsaXplKDIgKiBSR0IgLyAyNTUgLSAxKSIsCiAgICAiYmFja2dyb3VuZCI6ICJhbHBoYSAwIgogIH0sCiAgInNpemUiOiBbCiAgICAxLjY5LAogICAgMy4xNiwKICAgIDAuOTQKICBdCn0K",import.meta.url)},Ae=["Armored tank · full (assembled)",...q.map(e=>"Armored tank · "+e.name.toLowerCase()),ce],B=["Voxel surface","Marching Cubes","Finer grid","RGB · nearest","RGB · linear","RGB + ID","RGB + ID + depth"];function Z(e,s=!1){se.value=e,se.dataset.error=String(s)}function Ne(){const e=new he({antialias:!0}),s=Math.min(devicePixelRatio,2),t=new we(-1,1,1,-1,.01,50),a=new fe;a.background=new be("#121923");const n=new $({color:"#b4bac3",roughness:.85}),o=new ye("#fff2e5",2.6);o.position.set(3,6,-4),a.add(o,new Me("#b6c9e4",1.5));let r=0,i=0;return{gray:n,draw(g,l,C){const c=Math.round(l.clientWidth*s),d=Math.round(l.clientHeight*s);if(!c||!d)return;const b=c/d,I=U/Math.min(1,b)/Number(z.value);t.left=-I*b,t.right=I*b,t.top=I,t.bottom=-I;const p=P.degToRad(Number(X.value)),u=P.degToRad(Number(V.value)),m=Math.max(8,U*4);t.far=m+U*3,t.position.set(Math.sin(p)*Math.cos(u)*m,Math.sin(u)*m,-Math.cos(p)*Math.cos(u)*m).add(_),t.lookAt(_),t.updateProjectionMatrix(),(c!==r||d!==i)&&(e.setSize(c,d,!1),r=c,i=d),(l.width!==c||l.height!==d)&&(l.width=c,l.height=d),a.add(g),e.render(a,t),C.drawImage(e.domElement,0,0),a.remove(g)}}}function je(e,s){const t=new $({map:e.map,roughness:.82});if(e.dispose(),!s)return t;const a=new Le(s.data,s.width,s.height);return a.minFilter=a.magFilter=re,a.needsUpdate=!0,t.normalMap=a,t.normalMapType=Ze,t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("#include <normal_fragment_maps>",`
|
|
2
|
+
vec3 geometricNormal = normal;
|
|
3
|
+
#include <normal_fragment_maps>
|
|
4
|
+
float coverage = texture2D(normalMap, vNormalMapUv).a;
|
|
5
|
+
normal = normalize(mix(geometricNormal, normal, coverage));
|
|
6
|
+
`)},t}function Fe(e,s,t){const a=s.getContext("2d",{alpha:!1});if(!a)throw new Error("Could not create a thumbnail surface.");const n=We(e.parts.map(I=>I.asset),e.parts),o=e.parts.flatMap(I=>I.mounts),r=e.parts.flatMap(I=>I.mounts.map(()=>I.normalMap)),i=Be(n),g=e.nearest?ve:re,l=[],C=[];for(const[I,{asset:p}]of n.entries()){const u=i.children[I],m=o[I].matrix;if(m&&(u.matrix.fromArray(m),u.matrixAutoUpdate=!1,u.matrixWorldNeedsUpdate=!0),p.target==="stack"){C.push({object:u,asset:p});continue}const h=u,f=h.material,x=e.lit?je(f,r[I]):f;x.map&&(x.map.minFilter=x.map.magFilter=g,x.map.needsUpdate=!0);const te=!e.geometryOnly&&p.frontAccents,G=te?xe(te):void 0;G&&(G.material.alphaTest=.4,h.add(G)),l.push({mesh:h,textured:x,accent:G})}const c=i.children.map(I=>(I.matrixAutoUpdate&&I.updateMatrix(),I.matrixAutoUpdate=!1,I.matrix.clone()));let d=1,b=0;return{surface:s,isStack:C.length>0,draw(){const I=M.valueAsNumber/100;if(I!==b){for(const[m,h]of i.children.entries()){const f=Ce[m];h.matrix.copy(c[m]),h.matrix.elements[12]+=f.x*I,h.matrix.elements[13]+=f.y*I,h.matrix.elements[14]+=f.z*I,h.matrixWorldNeedsUpdate=!0}b=I}const p=F.valueAsNumber;if(C.length&&p!==d){for(const{object:m,asset:h}of C)for(const[f,x]of m.children.entries())x.position.y=((f+.5)*h.spacing-h.pivot[2])*p;d=p}const u=e.geometryOnly||Y.getAttribute("aria-pressed")==="true";for(const{mesh:m,textured:h,accent:f}of l)m.material=u?t.gray:h,f&&(f.visible=!u);t.draw(i,s,a)},dispose(){for(const{object:I}of C){const p=I.children;p[0]?.geometry.dispose();for(const u of p){const m=u.material;m.map?.dispose(),m.dispose()}}for(const{mesh:I,textured:p,accent:u}of l){if(I.geometry.dispose(),p.map?.dispose(),p instanceof $&&p.normalMap?.dispose(),p.dispose(),!u)continue;u.geometry.dispose();const m=u.material;m.map?.dispose(),m.dispose()}}}}function Oe(e){const s=r=>e.map(i=>({name:i.name,mounts:i.mounts,asset:typeof r=="number"?i.meshes[r]:i[r],grid:r==="voxel"||r==="marching"?i.coarseGrid:i.fullGrid})),t=s(0),a=e.every(r=>r.fullGrid.every((i,g)=>i===r.coarseGrid[g])),n=[{title:"RGB only",detail:"Visual hull and RGB projection",parts:t},{title:"RGB + ID",detail:"Keeps accent colors on visible source-facing surfaces",parts:s(1)},{title:"RGB + ID + depth",detail:"Rebuilds the surface with smoother depth transitions",parts:s(2)}],o=[{title:"Sprite Stack",detail:"Spacing changes the distance between these horizontal slices.",parts:s("stack")},{title:B[0],detail:"Exposed faces of the occupied cells.",parts:s("voxel"),geometryOnly:!0},{title:B[1],detail:"Interpolated surface from the same occupied cells.",parts:s("marching"),geometryOnly:!0},{title:B[2],detail:a?"Only one occupied grid was available at these settings.":"Marching Cubes rebuilt with the full sampling grid.",parts:t,geometryOnly:!0},{title:B[3],detail:"Projects the atlas onto that mesh, using the closest texel.",parts:t,nearest:!0},{title:B[4],detail:"Blends nearby texels on the same textured mesh.",parts:t},n[1],n[2]];if(e.some(r=>r.mapped)){const r=e.map(l=>({name:l.name,mounts:l.mounts,asset:l.mapped?.mesh??l.meshes[0],grid:l.mapped?.grid??l.fullGrid})),i=r.map((l,C)=>({...l,normalMap:e[C].mapped?.normalMap})),g=r.map((l,C)=>({...l,asset:e[C].mapped?.silhouetteMesh??l.asset}));o.unshift({title:"Clay Silhouette Only",detail:"Uses the same calibrated Clay views, grid, and lighting.",parts:g,geometryOnly:!0},{title:"Clay + Depth Map",detail:"Uses the 16-bit depth pass to carve the registered Clay silhouettes.",parts:r,geometryOnly:!0},{title:"Depth + Base Color",detail:"Projects the generated color pass onto the depth-carved mesh.",parts:r,lit:!0},{title:"Depth + Base Color + Normal",detail:"Uses the view-space normal pass for per-pixel lighting on the same mesh.",parts:i,lit:!0})}return o}function Re(e,s){const t=document.createElement("figure"),a=document.createElement("canvas");a.className="model",a.setAttribute("role","img"),a.setAttribute("aria-label",e.title),t.append(a);const n=document.createElement("figcaption"),o=document.createElement("small"),r=e.parts.map(({name:l,grid:C})=>(l?l+" ":"")+C.join(" × ")).join(" · "),i=e.parts.reduce((l,{asset:C,mounts:c})=>l+(C.target==="stack"?C.layers:C.indices.length/3)*c.length,0),g=e.parts[0].asset.target==="stack"?" slices":" triangles";o.textContent=r+" cells · "+i.toLocaleString()+g,n.append(o),t.append(n),s.append(t),R.push(Fe(e,a,Ie)),ue.observe(a)}function Je(e){const s=document.createElement("section");s.className="depth-fit";const t=document.createElement("h2");t.textContent="Depth Fit",s.append(t);const a=c=>c===null?"—":c.toFixed(3),n=document.createElement("strong");n.textContent=a(e.baselineMae)+" → "+a(e.carvedMae)+" units",s.append(n);const o=document.createElement("p"),r=e.baselineMae&&e.carvedMae!==null?100*(e.carvedMae/e.baselineMae-1):null;o.textContent="Mean absolute distance error against the supplied depth map"+(r===null?".":" · "+(r>0?"+":"−")+Math.abs(r).toFixed(1)+"%"),s.append(o);const i=document.createElement("table");i.setAttribute("aria-label","Mean absolute depth error by camera");const g=i.createTHead().insertRow();for(const c of["View","Clay only","+ Depth"]){const d=document.createElement("th");d.scope="col",d.textContent=c,g.append(d)}const l=i.createTBody();for(const c of e.byView){const d=l.insertRow();for(const b of[c.view.toUpperCase(),a(c.baselineMae),a(c.carvedMae)])d.insertCell().textContent=b}s.append(i);const C=document.createElement("p");return C.textContent=e.sharedPixels.toLocaleString()+" shared visible pixels · "+(100*e.sharedPixels/Math.max(1,e.referencePixels)).toFixed(1)+"% of reference",s.append(C),s}function Ge(e){for(const n of R)ue.unobserve(n.surface),n.dispose();R=[];const s=Oe(e.parts),t=e.parts.find(n=>n.mapped)?.mapped?.fit,a=document.createDocumentFragment();for(const n of s){const o=document.createElement("section"),r=document.createElement("h2"),i=document.createElement("p");r.textContent=n.title,i.textContent=n.detail,o.append(r),Re(n,o),o.append(i),a.append(o),t&&n.title==="Clay + Depth Map"&&a.append(Je(t))}Ke.replaceChildren(a),J()}function J(){T||(T=requestAnimationFrame(()=>{T=0,A("yaw-value").textContent=X.value+"°",A("pitch-value").textContent=V.value+"°",A("zoom-value").textContent=z.value+"×",A("explode-value").textContent=M.value+"%",R.forEach(e=>e.draw())}))}function me(){return window.clearTimeout(ge),N?.terminate(),N=void 0,++v}function de(e,s,t){const a=new Worker(new URL(""+new URL("compare.worker-CgJq-znx.js",import.meta.url).href,import.meta.url),{type:"module"});N=a,a.onerror=()=>{a.terminate(),t===v&&(N=void 0,Z("The comparison worker could not start.",!0))},a.onmessage=({data:n})=>{if(a.terminate(),t===v){if(N=void 0,"error"in n){Z(n.error,!0);return}try{Ue(n,s)}catch(o){Z(o instanceof Error?o.message:String(o),!0)}}},a.postMessage(e)}function K(e,s){const t=me();k=void 0,D.disabled=!0,F.disabled=!0,M.disabled=!0,Z("Building comparison from "+s+"…"),A("comparison-warnings").replaceChildren(),e().then(a=>{if(t!==v)return;k={job:a,name:s};const n="parts"in a?a.parts.map(r=>r.settings):[a.settings],o=n[0].layers??W.layers;D.value=String(o),A("layers-value").textContent=n.every(r=>(r.layers??W.layers)===o)?String(o):"Per part",D.disabled=!1,de(a,s,t)}).catch(a=>{t===v&&Z(String(a),!0)})}function Ye(e){return e.flatMap(s=>{const{size:[t,a,n],pivot:o}=s.meshes[0],r=new oe(new y(-t/2,-o[2],-a/2),new y(t/2,n-o[2],a/2));return s.mounts.map(({position:[i,g,l],scale:C=1,matrix:c})=>{const d=c?new ne().fromArray(c):new ne().makeScale(C,C,C).setPosition(i,l,-g);return r.clone().applyMatrix4(d)})})}function Ee(e,s){const t=e.map(i=>i.getSize(new y)),a=t.reduce((i,g,l)=>g.x*g.z>t[i].x*t[i].z?l:i,0),n=e[a].getCenter(new y),o=t[a],r=Math.max(s.x,s.y,s.z)*.12;return e.map((i,g)=>{if(g===a)return new y;const l=i.getCenter(new y).sub(n),C=l.y>o.y*.18;l.y=0;const c=Math.hypot(l.x/o.x,l.z/o.z);return c>.16?l.normalize().multiplyScalar(r):l.set(0,0,0),(C||c<=.16)&&(l.y=r),l})}function Ue(e,s){Ie??=Ne();const t=Ye(e.parts),a=t.reduce((r,i)=>r.union(i),new oe),n=a.getSize(new y);U=n.length()*.53,a.getCenter(_),Ce=Ee(t,n),M.disabled=t.length<2,M.disabled&&(M.value=M.defaultValue),A("comparison-warnings").replaceChildren(...e.warnings.map(r=>{const i=document.createElement("li");return i.textContent=r,i})),Ge(e),F.disabled=!1;const o=e.parts.length>1?" "+e.parts.length+" atlases reconstructed separately.":"";Z(s+" · Comparison ready."+o+" Camera settings are shared.")}function pe(){const e=L?.nodes.filter(n=>n.atlasId)??[],s=document.createElement("optgroup");s.label="Built-in atlases",s.append(...Ae.map((n,o)=>new Option(n,"sample:"+o)));const t=document.createElement("optgroup");t.label=L?.name??"Project",t.append(...e.map(n=>new Option(n.name,n.id))),e.length>1&&t.append(new Option("Project · full (assembled)","project:assembly"));const a=e.length?[t,s]:[s];w.replaceChildren(...a)}function ke(e){const s=new ae,t=new Map(e.map(n=>{const o=new ae;return o.position.set(...n.position),o.rotation.set(...n.rotation.map(P.degToRad)),o.scale.set(...n.scale),o.visible=n.visible,[n.id,o]}));for(const n of e)((n.parentId?t.get(n.parentId):void 0)??s).add(t.get(n.id));s.updateMatrixWorld(!0);const a=new Set;return s.traverseVisible(n=>a.add(n)),e.flatMap(n=>{const o=t.get(n.id);return n.atlasId&&a.has(o)?[{node:n,matrix:o.matrixWorld.toArray()}]:[]})}async function ie(e){const s=O+"/atlas/"+encodeURIComponent(e.id),t=await fetch(s);if(!t.ok)throw new Error("Could not load the project atlas.");return{file:await t.blob(),layout:e.layout}}async function Xe(){async function e(i){const g=await fetch(i);if(!g.ok)throw new Error("Could not load the hull material passes.");return g}const[s,t,a,n,o,r]=await Promise.all([e(S.source).then(i=>i.blob()),e(S.clay).then(i=>i.blob()),e(S.depth).then(i=>i.blob()),e(S.baseColor).then(i=>i.blob()),e(S.normal).then(i=>i.blob()),e(S.calibration).then(i=>i.json())]);return{file:s,layout:ee,settings:{...W,size:r.size},maps:{clay:t,depth:a,baseColor:n,normal:o,calibration:r}}}function j(){if(w.value.startsWith("sample:")){const t=Number(w.value.slice(7)),a=Ae[t];if(!a)return;if(a===ce){K(Xe,a);return}K(async()=>{async function n(r){const i=await fetch(r);if(!i.ok)throw new Error("Could not load the built-in atlas.");return{file:await i.blob(),layout:ee}}if(t===0)return{parts:await Promise.all(q.map(async({name:i,url:g,size:l,mounts:C})=>({...await n(g),name:i,mounts:C,settings:{...W,size:l,height:l?.[2]}})))};const o=q[t-1].url;return{...await n(o),settings:W}},a);return}if(w.value==="project:assembly"&&L&&O){const t=L;K(async()=>{const a=ke(t.nodes);if(!a.length)throw new Error("No visible atlas parts in the project.");const n=new Map;return{parts:await Promise.all(a.map(async({node:r,matrix:i})=>{const g=t.atlases.find(l=>l.id===r.atlasId);if(!g)throw new Error("Missing atlas for "+r.name);return n.has(g.id)||n.set(g.id,ie(g)),{...await n.get(g.id),name:r.name,mounts:[{name:r.name,position:[0,0,0],matrix:i}],settings:r.settings}}))}},t.name+" · full (assembled)");return}const e=L?.nodes.find(t=>t.id===w.value),s=L?.atlases.find(t=>t.id===e?.atlasId);!O||!e||!s||K(async()=>({...await ie(s),settings:e.settings}),e.name)}Q.addEventListener("change",()=>{const e=Q.files?.[0];e&&(w.selectedIndex=-1,K(async()=>({file:e,layout:ee,settings:W}),e.name))});w.addEventListener("change",()=>{Q.value="",j()});D.addEventListener("input",()=>{if(!k)return;const{job:e,name:s}=k,t=D.valueAsNumber;if(!D.validity.valid||!Number.isFinite(t))return;const a=me();A("layers-value").textContent=String(t),Z("Rebuilding "+s+" at "+t+" layers…");const n="parts"in e?{parts:e.parts.map(o=>({...o,settings:{...o.settings,layers:t}}))}:{...e,settings:{...e.settings,layers:t}};ge=window.setTimeout(()=>de(n,s,a),85)});F.addEventListener("input",()=>{A("spacing-value").textContent=F.valueAsNumber.toFixed(2)+"×",R.find(e=>e.isStack)?.draw()});for(const e of[X,V,z,M])e.addEventListener("input",J);Y.addEventListener("click",()=>{Y.setAttribute("aria-pressed",String(Y.getAttribute("aria-pressed")!=="true")),J()});A("reset").addEventListener("click",()=>{for(const e of[X,V,z])e.value=e.defaultValue;J()});const ue=new ResizeObserver(J);pe();const H=le.get("sample");H!==null&&[...w.options].some(e=>e.value==="sample:"+H)&&(w.value="sample:"+H,j());if(O){const e=A("back");e.href="./project.html?session="+E+"&playground=1",e.textContent="Playground",fetch(O+"/state").then(async s=>{if(!s.ok)throw new Error("Could not read the project.");L=await s.json();const t=w.value;pe(),v?w.value=t:([...w.options].some(a=>a.value==="project:assembly")&&(w.value="project:assembly"),j())}).catch(()=>{v||j()})}else v||j();
|