Spaces:
Running
Running
File size: 19,356 Bytes
544434e abca371 dc409ad abca371 2df87ba c7c8c1d 8fe43ef 0e6816a dc409ad 8fe43ef c7c8c1d abca371 16f55ef f97559f cc8e895 aa04c11 10668a0 abca371 0e6816a dc409ad 0e6816a abca371 b6b57ef abca371 b6b57ef abca371 c7c8c1d abca371 b81d6ba abca371 7f9d62c abca371 5ca7928 abca371 5ca7928 5d6ec8d abca371 a2597c7 abca371 dc409ad 7a47044 5997e11 9fa27bc 41009a2 253d9fc cb1ca43 5ca7928 34139b2 fd176ec 34139b2 fd176ec 5ca7928 abca371 fd176ec 1a8d2be abca371 5ca7928 abca371 5ca7928 abca371 5ca7928 5d6ec8d 4e60b08 5ca7928 abca371 5ca7928 253d9fc abca371 42f656d abca371 42f656d abca371 6f9b0cf 6afa911 41e1429 6f9b0cf f817dc2 6f9b0cf fd5397f 4457ba9 30b323c 24f8767 fd5397f 06448c9 1be684b 6f9b0cf 41e1429 6f9b0cf abca371 5ca7928 abca371 66c6f7d abca371 5ca7928 253d9fc 5ca7928 abca371 9fa27bc 7f9d62c 4af1760 abca371 0e6816a abca371 0e6816a 9fa27bc 16652e2 abca371 7f9d62c abca371 5ca7928 abca371 7f9d62c abca371 7f9d62c abca371 7f9d62c abca371 2f3089c | 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | // viewer.js
// ----- Helper to load image textures into PlayCanvas -----
async function loadImageAsTexture(url, app) {
return new Promise((resolve, reject) => {
const img = new window.Image();
img.crossOrigin = "anonymous";
img.onload = function() {
const tex = new pc.Texture(app.graphicsDevice, {
width: img.width,
height: img.height,
format: pc.PIXELFORMAT_R8_G8_B8_A8,
});
tex.setSource(img);
resolve(tex);
};
img.onerror = reject;
img.src = url;
});
}
// ----- Global handles -----
let pc;
export let app = null;
let cameraEntity = null;
let modelEntity = null;
let tubeEntity = null;
let filtreEntity = null;
let viewerInitialized = false;
let resizeObserver = null;
// Materials (for real-time switching)
let matTransparent = null;
let matOpaque = null;
let tubeTransparent = null;
let tubeOpaque = null;
// Configurable globals
let chosenCameraX, chosenCameraY, chosenCameraZ;
let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minPivotY, minY;
let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ;
let glbUrl, glbUrl2, glbUrl3;
// ----- Utility: Recursive scene traversal -----
function traverse(entity, callback) {
callback(entity);
if (entity.children) {
entity.children.forEach(child => traverse(child, callback));
}
}
// ----- Main Viewer Initialization -----
export async function initializeViewer(config, instanceId) {
if (viewerInitialized) return; // Prevent double-init
// ----- Config setup -----
glbUrl = config.glb_url;
glbUrl2 = config.glb_url_2;
glbUrl3 = config.glb_url_3;
minZoom = 0.5; maxZoom = 1;
minAngle = -Infinity; maxAngle = Infinity;
minAzimuth = -Infinity; maxAzimuth = Infinity;
minPivotY = 0; minY = -10;
modelX = modelY = modelZ = 0;
modelScale = 1;
modelRotationX = modelRotationY = modelRotationZ = 0;
// Camera setup for desktop/mobile
chosenCameraX = chosenCameraY = 0;
chosenCameraZ = 1;
// ----- DOM: Canvas and progress -----
const canvasId = 'canvas-' + instanceId;
const progressDialog = document.getElementById('progress-dialog-' + instanceId);
const viewerContainer = document.getElementById('viewer-container-' + instanceId);
let oldCanvas = document.getElementById(canvasId);
if (oldCanvas) oldCanvas.remove();
const canvas = document.createElement('canvas');
canvas.id = canvasId;
canvas.className = 'ply-canvas';
canvas.style.width = "100%";
canvas.style.height = "100%";
canvas.setAttribute('tabindex', '0');
if (progressDialog) {
viewerContainer.insertBefore(canvas, progressDialog);
} else {
viewerContainer.appendChild(canvas);
}
// Touch and scroll safety
canvas.style.touchAction = "none";
canvas.style.webkitTouchCallout = "none";
canvas.addEventListener('gesturestart', e => e.preventDefault());
canvas.addEventListener('gesturechange', e => e.preventDefault());
canvas.addEventListener('gestureend', e => e.preventDefault());
canvas.addEventListener('dblclick', e => e.preventDefault());
canvas.addEventListener('touchstart', e => { if (e.touches.length > 1) e.preventDefault(); }, { passive: false });
canvas.addEventListener('wheel', e => e.preventDefault(), { passive: false });
if (progressDialog) progressDialog.style.display = 'block';
// ----- Load PlayCanvas -----
if (!pc) {
pc = await import("https://esm.run/playcanvas");
window.pc = pc;
}
// ----- PlayCanvas App Setup -----
const device = await pc.createGraphicsDevice(canvas, {
deviceTypes: ["webgl2", "webgl1"],
glslangUrl: "https://playcanvas.vercel.app/static/lib/glslang/glslang.js",
twgslUrl: "https://playcanvas.vercel.app/static/lib/twgsl/twgsl.js",
antialias: false
});
device.maxPixelRatio = Math.min(window.devicePixelRatio, 2);
const opts = new pc.AppOptions();
opts.graphicsDevice = device;
opts.mouse = new pc.Mouse(canvas);
opts.touch = new pc.TouchDevice(canvas);
opts.componentSystems = [
pc.RenderComponentSystem, pc.CameraComponentSystem,
pc.LightComponentSystem, pc.ScriptComponentSystem,
pc.GSplatComponentSystem, pc.CollisionComponentSystem,
pc.RigidbodyComponentSystem
];
opts.resourceHandlers = [
pc.TextureHandler, pc.ContainerHandler,
pc.ScriptHandler, pc.GSplatHandler
];
app = new pc.Application(canvas, opts);
app.setCanvasFillMode(pc.FILLMODE_NONE);
app.setCanvasResolution(pc.RESOLUTION_AUTO);
// Canvas responsive resize
resizeObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
app.resizeCanvas(entry.contentRect.width, entry.contentRect.height);
});
});
resizeObserver.observe(viewerContainer);
window.addEventListener('resize', () => app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight));
app.on('destroy', () => resizeObserver.disconnect());
// ----- Load all images as Textures (async, safe for CORS) -----
// All of these can fail (network, CORS), so wrap with try/catch if needed.
const hdrTex = await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/hdr/ciel_nuageux_1k.png', app);
const emitTex = await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/textures/emit_map_1k.png', app);
const opTex = await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/textures/op_map_1k.png', app);
const thicknessTex= await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/textures/thickness_map_1k.png', app);
const bgTex = await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/images/banniere_earcare.png', app);
const opTubetex = await loadImageAsTexture('https://huggingface.co/datasets/MikaFil/3D_models/resolve/main/EARCARE/textures/op_mask_tube.png', app);
// ----- GLB asset definition -----
const assets = {
orbit: new pc.Asset('script', 'script', { url: "https://mikafil-visualiseur-EARCARE.static.hf.space/orbit-camera.js" }),
model: new pc.Asset('model_glb', 'container', { url: glbUrl }),
tube: new pc.Asset('tube_glb', 'container', { url: glbUrl2 }),
filtre: new pc.Asset('filtre_glb', 'container', { url: glbUrl3 }),
};
for (const key in assets) app.assets.add(assets[key]);
// ----- Environment / Skybox -----
app.scene.envAtlas = hdrTex;
app.scene.skyboxRotation = new pc.Quat().setFromEulerAngles(0, -90, 0);
app.scene.skyboxIntensity = 4;
app.scene.skyboxMip = 0;
// ----- Load GLBs -----
const loader = new pc.AssetListLoader(Object.values(assets), app.assets);
loader.load(() => {
app.start();
if (progressDialog) progressDialog.style.display = 'none';
// Reorder depth layer for transmission
const depthLayer = app.scene.layers.getLayerById(pc.LAYERID_DEPTH);
app.scene.layers.remove(depthLayer);
app.scene.layers.insertOpaque(depthLayer, 2);
// Instantiate GLB entities
modelEntity = assets.model.resource.instantiateRenderEntity();
tubeEntity = assets.tube.resource.instantiateRenderEntity();
filtreEntity = assets.filtre.resource.instantiateRenderEntity();
app.root.addChild(modelEntity);
app.root.addChild(tubeEntity);
app.root.addChild(filtreEntity);
// ----- Materials Setup -----
// Transparent material (main model)
matTransparent = new pc.StandardMaterial();
matTransparent.blendType = pc.BLEND_NORMAL;
matTransparent.diffuse = new pc.Color(1, 1, 1);
matTransparent.specular = new pc.Color(0.01, 0.01, 0.01);
matTransparent.gloss = 1;
matTransparent.metalness = 0;
matTransparent.useMetalness = true;
matTransparent.useDynamicRefraction = true;
matTransparent.depthWrite = true;
matTransparent.refraction = 0.8;
matTransparent.refractionIndex = 1;
matTransparent.thickness = 0.02;
matTransparent.thicknessMap = thicknessTex;
matTransparent.opacityMap = opTex;
matTransparent.opacityMapChannel = "r";
matTransparent.opacity = 0.97;
matTransparent.emissive = new pc.Color(1, 1, 1);
matTransparent.emissiveMap = emitTex;
matTransparent.emissiveIntensity = 0.1;
matTransparent.update();
// Opaque material (main model)
matOpaque = new pc.StandardMaterial();
matOpaque.blendType = pc.BLEND_NORMAL;
matOpaque.diffuse = new pc.Color(0.7, 0.05, 0.05);
matOpaque.specular = new pc.Color(0.01, 0.01, 0.01);
matOpaque.specularityFactor = 1;
matOpaque.gloss = 1;
matOpaque.metalness = 0;
matOpaque.opacityMap = opTex;
matOpaque.opacityMapChannel = "r";
matOpaque.opacity = 1;
matOpaque.emissive = new pc.Color(0.372, 0.03, 0.003);
matOpaque.emissiveMap = emitTex;
matOpaque.emissiveIntensity = 2;
matOpaque.update();
// Transparent material (tube)
tubeTransparent = new pc.StandardMaterial();
tubeTransparent.diffuse = new pc.Color(1, 1, 1);
tubeTransparent.blendType = pc.BLEND_NORMAL;
tubeTransparent.opacityMap = opTubetex;
tubeTransparent.opacityMapChannel = "r";
tubeTransparent.opacity = 0.03;
tubeTransparent.depthTest = false;
tubeTransparent.depthWrite = false;
tubeTransparent.useMetalness = true;
tubeTransparent.useDynamicRefraction = true;
tubeTransparent.thickness = 4;
tubeTransparent.update();
// Opaque material (tube)
tubeOpaque = new pc.StandardMaterial();
tubeOpaque.diffuse = new pc.Color(1, 1, 1);
tubeOpaque.opacity = 0.9;
tubeOpaque.update();
// ----- Assign materials to meshes -----
traverse(modelEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = matOpaque;
}
}
});
traverse(tubeEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = tubeOpaque;
}
}
});
// ----- Modification du material "transparent" du filtre
/*traverse(filtreEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
if (mi.material && mi.material.name === "transparant") {
// Ici tu as ton matériau
const mat = mi.material;
mat.opacity = 0.01;
mat.blendType = pc.BLEND_NONE;
mat.depthTest = false;
mat.depthWrite = false;
mat.useMetalness = true;
mat.useDynamicRefraction = true;
mat.thickness = 1;
//mat.specular = new pc.Color(0.01, 0.01, 0.01);
mat.gloss = 1;
mat.glossInvert = true;
mat.metalness = 0;
mat.update();
}
}
}
});*/
// ----- Model, Tube, Filtre transforms -----
modelEntity.setPosition(modelX, modelY, modelZ);
modelEntity.setLocalScale(modelScale, modelScale, modelScale);
modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
tubeEntity.setPosition(modelX, modelY, modelZ);
tubeEntity.setLocalScale(modelScale, modelScale, modelScale);
tubeEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
filtreEntity.setPosition(modelX, modelY, modelZ);
filtreEntity.setLocalScale(modelScale, modelScale, modelScale);
filtreEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ);
// ----- Camera + Orbit Controls -----
cameraEntity = new pc.Entity('camera');
cameraEntity.addComponent('camera', {
clearColor: new pc.Color(0.8, 0.8, 0.8, 1),
toneMapping: pc.TONEMAP_NEUTRAL
});
cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
cameraEntity.lookAt(modelEntity.getPosition());
cameraEntity.addComponent('script');
// KHR_materials_transmission support
cameraEntity.camera.requestSceneColorMap(true);
cameraEntity.script.create('orbitCamera', {
attributes: {
focusEntity: modelEntity,
inertiaFactor: 0.2,
distanceMax: maxZoom,
distanceMin: minZoom,
pitchAngleMax: maxAngle,
pitchAngleMin: minAngle,
yawAngleMax: maxAzimuth,
yawAngleMin: minAzimuth,
minY: minY,
frameOnStart: false
}
});
cameraEntity.script.create('orbitCameraInputMouse');
cameraEntity.script.create('orbitCameraInputTouch');
app.root.addChild(cameraEntity);
// Remove Skybox layer from camera
const skyboxLayer = app.scene.layers.getLayerByName("Skybox");
if (skyboxLayer) {
const camLayers = cameraEntity.camera.layers.slice();
const idx = camLayers.indexOf(skyboxLayer.id);
if (idx !== -1) {
camLayers.splice(idx, 1);
cameraEntity.camera.layers = camLayers;
}
}
/*
// ----- Camera-attached background plane -----
const bgPlane = new pc.Entity("Plane");
bgPlane.addComponent("model", { type: "plane" });
bgPlane.setLocalPosition(0, 0, -10);
bgPlane.setLocalScale(11, 1, 5.5);
bgPlane.setLocalEulerAngles(90, 0, 0);
// Simple material for the banner
const mat = new pc.StandardMaterial();
mat.diffuse = new pc.Color(1, 1, 1);
mat.diffuseMap = bgTex;
mat.emissive = new pc.Color(1, 1, 1);
mat.emissiveMap = bgTex;
mat.emissiveIntensity = 1;
mat.useLighting = false;
mat.update();
bgPlane.model.material = mat;
cameraEntity.addChild(bgPlane);
*/
// ----- Lighting -----
const light = new pc.Entity("mainLight");
light.addComponent('light', {
type: "directional",
color: new pc.Color(1, 1, 1),
intensity: 1,
});
light.setPosition(1, 1, -1);
light.lookAt(0, 0, 0);
app.root.addChild(light);
app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
app.once('update', () => resetViewerCamera());
// ----- Optional: Tooltips -----
try {
if (config.tooltips_url) {
import('./tooltips.js').then(tooltipsModule => {
tooltipsModule.initializeTooltips({
app,
cameraEntity,
modelEntity,
tooltipsUrl: config.tooltips_url,
defaultVisible: !!config.showTooltipsDefault,
moveDuration: config.tooltipMoveDuration || 0.6
});
}).catch(e => { /* fail silently */ });
}
} catch (e) { /* fail silently */ }
viewerInitialized = true;
});
}
// ----- Camera Utility: Resets camera to default view -----
export function resetViewerCamera() {
try {
if (!cameraEntity || !modelEntity || !app) return;
const orbitCam = cameraEntity.script.orbitCamera;
if (!orbitCam) return;
const modelPos = modelEntity.getPosition();
const tempEnt = new pc.Entity();
tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
tempEnt.lookAt(modelPos);
const dist = new pc.Vec3().sub2(
new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ),
modelPos
).length();
cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ);
cameraEntity.lookAt(modelPos);
orbitCam.pivotPoint = modelPos.clone();
orbitCam._targetDistance = dist;
orbitCam._distance = dist;
const rot = tempEnt.getRotation();
const fwd = new pc.Vec3();
rot.transformVector(pc.Vec3.FORWARD, fwd);
const yaw = Math.atan2(-fwd.x, -fwd.z) * pc.math.RAD_TO_DEG;
const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0);
const rotNoYaw = new pc.Quat().mul2(yawQuat, rot);
const fNoYaw = new pc.Vec3();
rotNoYaw.transformVector(pc.Vec3.FORWARD, fNoYaw);
const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG;
orbitCam._targetYaw = yaw;
orbitCam._yaw = yaw;
orbitCam._targetPitch = pitch;
orbitCam._pitch = pitch;
if (orbitCam._updatePosition) orbitCam._updatePosition();
tempEnt.destroy();
} catch (e) {
// Silent fail
}
}
/**
* Change the main model's diffuse color in real time.
* r,g,b are floats [0,1]. This is a reusable function for new colors.
*/
export function changeColor(dr, dg, db, er, eg, eb, ei, op, boolTrans) {
if (boolTrans) {
if (!matTransparent) return;
matTransparent.diffuse.set(dr, dg, db);
matTransparent.emissive.set(er, eg, eb);
matTransparent.emissiveIntensity = ei;
matTransparent.opacity = op;
matTransparent.update();
tubeTransparent.diffuse.set(dr, dg, db);
tubeTransparent.update();
traverse(modelEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = matTransparent;
}
}
});
traverse(tubeEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = tubeTransparent;
}
}
});
} else {
if (!matOpaque) return;
matOpaque.diffuse.set(dr, dg, db);
matOpaque.emissive.set(er, eg, eb);
matOpaque.emissiveIntensity = ei;
matOpaque.update();
traverse(modelEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = matOpaque;
}
}
});
traverse(tubeEntity, node => {
if (node.render && node.render.meshInstances) {
for (let mi of node.render.meshInstances) {
mi.material = tubeOpaque;
}
}
});
}
}
|