-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviewer3d.js
More file actions
207 lines (171 loc) · 5.95 KB
/
Copy pathviewer3d.js
File metadata and controls
207 lines (171 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import * as THREE from "three";
import { MTLLoader } from "three/addons/loaders/MTLLoader.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { OBJLoader } from "three/addons/loaders/OBJLoader.js";
const stageRegistry = new WeakMap();
function createViewer(stage) {
if (!stage || stageRegistry.has(stage)) {
return stageRegistry.get(stage);
}
const fallback = stage.querySelector("[data-model-fallback]");
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0x0f1115, 1);
renderer.domElement.setAttribute("aria-label", stage.dataset.modelAlt || "3D model preview");
renderer.domElement.style.touchAction = "none";
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0f1115);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 2000);
camera.position.set(0, 1.1, 4.8);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.enablePan = false;
controls.enableZoom = true;
controls.rotateSpeed = 0.9;
controls.zoomSpeed = 0.9;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.9;
controls.minDistance = 1.2;
controls.maxDistance = 18;
controls.addEventListener("start", () => {
renderer.domElement.style.cursor = "grabbing";
});
controls.addEventListener("end", () => {
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.style.cursor = "grab";
const ambientLight = new THREE.HemisphereLight(0xe8edf7, 0x0f1115, 1.55);
scene.add(ambientLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.35);
keyLight.position.set(4, 6, 5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x8cb3ff, 1.2);
rimLight.position.set(-5, 3, -4);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.CircleGeometry(3.8, 64),
new THREE.ShadowMaterial({ color: 0x000000, opacity: 0.22 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.9;
scene.add(floor);
let modelRoot = null;
const fitCameraToObject = (object) => {
const box = new THREE.Box3().setFromObject(object);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z) || 1;
const distance = maxSize * 2.15;
controls.target.copy(center);
camera.position.set(center.x + distance * 0.9, center.y + maxSize * 0.35, center.z + distance);
camera.near = Math.max(maxSize / 100, 0.01);
camera.far = Math.max(maxSize * 20, 100);
camera.updateProjectionMatrix();
controls.update();
};
const setFallback = (title, detail) => {
if (!fallback) {
return;
}
fallback.hidden = false;
const titleNode = fallback.querySelector("p");
const detailNode = fallback.querySelector("span");
if (titleNode) {
titleNode.textContent = title;
}
if (detailNode) {
detailNode.textContent = detail;
}
};
const hideFallback = () => {
if (fallback) {
fallback.hidden = true;
}
};
const loadModel = async () => {
const src = stage.dataset.modelSrc;
const modelName = stage.dataset.modelName || "OBJ Preview";
if (!src) {
setFallback("OBJ preview", "Falta data-model-src.");
return;
}
const objLoader = new OBJLoader();
const mtlLoader = new MTLLoader();
const lastSlashIndex = src.lastIndexOf("/");
const assetPath = lastSlashIndex >= 0 ? src.slice(0, lastSlashIndex + 1) : "";
const fileName = lastSlashIndex >= 0 ? src.slice(lastSlashIndex + 1) : src;
const mtlSrc = `${assetPath}${fileName.replace(/\.obj$/i, ".mtl")}`;
objLoader.setPath(assetPath);
mtlLoader.setPath(assetPath);
mtlLoader.setResourcePath(assetPath);
try {
const materials = await mtlLoader.loadAsync(mtlSrc);
materials.preload();
objLoader.setMaterials(materials);
} catch (error) {
// Fallback to plain OBJ materials when no matching MTL exists.
}
try {
const object = await objLoader.loadAsync(fileName);
object.traverse((child) => {
if (!child.isMesh) {
return;
}
child.castShadow = false;
child.receiveShadow = false;
child.material.side = THREE.FrontSide;
if (!child.material) {
child.material = new THREE.MeshStandardMaterial({
color: 0xdbe8f7,
metalness: 0.5,
roughness: 0.42
});
}
});
modelRoot = object;
scene.add(object);
fitCameraToObject(object);
hideFallback();
} catch (error) {
setFallback(modelName, `No pude cargar ${src}.`);
}
};
const resize = () => {
const width = Math.max(stage.clientWidth, 1);
const height = Math.max(stage.clientHeight, 1);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
};
const observer = new ResizeObserver(resize);
observer.observe(stage);
resize();
loadModel();
const state = { renderer, scene, camera, controls, observer, get modelRoot() { return modelRoot; } };
stageRegistry.set(stage, state);
return state;
}
function initializeModelStages(root = document) {
const stages = root.matches?.("[data-model-stage]")
? [root]
: Array.from(root.querySelectorAll("[data-model-stage]"));
stages.forEach((stage) => {
createViewer(stage);
});
}
function animate() {
document.querySelectorAll("[data-model-stage]").forEach((stage) => {
const state = stageRegistry.get(stage);
if (!state) {
return;
}
state.controls.update();
state.renderer.render(state.scene, state.camera);
});
requestAnimationFrame(animate);
}
window.initializeModelStages = initializeModelStages;
initializeModelStages();
requestAnimationFrame(animate);