Spaces:
Running
Running
| // viewer.js | |
| // ============================== | |
| let pc; // PlayCanvas module (will be loaded dynamically) | |
| export let app = null; | |
| let cameraEntity = null; | |
| let modelEntity = null; | |
| let viewerInitialized = false; | |
| let resizeObserver = null; | |
| let chosenCameraX, chosenCameraY, chosenCameraZ; | |
| let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minPivotY, minY; | |
| let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ; | |
| let plyUrl, glbUrl; | |
| export async function initializeViewer(config, instanceId) { | |
| if (viewerInitialized) return; | |
| // Device detection | |
| const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; | |
| const isMobile = isIOS || /Android/i.test(navigator.userAgent); | |
| // 1. Read config | |
| plyUrl = config.ply_url; | |
| glbUrl = config.glb_url; | |
| minZoom = parseFloat(config.minZoom || "1"); | |
| maxZoom = parseFloat(config.maxZoom || "20"); | |
| minAngle = parseFloat(config.minAngle || "-45"); | |
| maxAngle = parseFloat(config.maxAngle || "90"); | |
| minAzimuth = (config.minAzimuth !== undefined) ? parseFloat(config.minAzimuth) : -360; | |
| maxAzimuth = (config.maxAzimuth !== undefined) ? parseFloat(config.maxAzimuth) : 360; | |
| minPivotY = parseFloat(config.minPivotY || "0"); | |
| minY = (config.minY !== undefined) ? parseFloat(config.minY) : 0; | |
| modelX = (config.modelX !== undefined) ? parseFloat(config.modelX) : 0; | |
| modelY = (config.modelY !== undefined) ? parseFloat(config.modelY) : 0; | |
| modelZ = (config.modelZ !== undefined) ? parseFloat(config.modelZ) : 0; | |
| modelScale = (config.modelScale !== undefined) ? parseFloat(config.modelScale) : 1; | |
| modelRotationX = (config.modelRotationX !== undefined) ? parseFloat(config.modelRotationX) : 0; | |
| modelRotationY = (config.modelRotationY !== undefined) ? parseFloat(config.modelRotationY) : 0; | |
| modelRotationZ = (config.modelRotationZ !== undefined) ? parseFloat(config.modelRotationZ) : 0; | |
| const cameraX = (config.cameraX !== undefined) ? parseFloat(config.cameraX) : 0; | |
| const cameraY = (config.cameraY !== undefined) ? parseFloat(config.cameraY) : 2; | |
| const cameraZ = (config.cameraZ !== undefined) ? parseFloat(config.cameraZ) : 5; | |
| const cameraXPhone = (config.cameraXPhone !== undefined) ? parseFloat(config.cameraXPhone) : cameraX; | |
| const cameraYPhone = (config.cameraYPhone !== undefined) ? parseFloat(config.cameraYPhone) : cameraY; | |
| const cameraZPhone = (config.cameraZPhone !== undefined) ? parseFloat(config.cameraZPhone) : (cameraZ * 1.5); | |
| chosenCameraX = isMobile ? cameraXPhone : cameraX; | |
| chosenCameraY = isMobile ? cameraYPhone : cameraY; | |
| chosenCameraZ = isMobile ? cameraZPhone : cameraZ; | |
| // 2. Grab DOM | |
| const canvasId = 'canvas-' + instanceId; | |
| const progressDialog = document.getElementById('progress-dialog-' + instanceId); | |
| const progressIndicator = document.getElementById('progress-indicator-' + instanceId); | |
| const viewerContainer = document.getElementById('viewer-container-' + instanceId); | |
| // 3. Create <canvas> | |
| let oldCanvas = document.getElementById(canvasId); | |
| if (oldCanvas) oldCanvas.remove(); | |
| const canvas = document.createElement('canvas'); | |
| canvas.id = canvasId; | |
| canvas.className = 'ply-canvas'; | |
| canvas.style.zIndex = "1"; | |
| canvas.style.width = "100%"; | |
| canvas.style.height = "100%"; | |
| canvas.setAttribute('tabindex', '0'); | |
| viewerContainer.insertBefore(canvas, progressDialog); | |
| // Remove touch-action/pointer-events from overlays if present (to not block iOS events) | |
| // (This is safe as overlays/panels should not interfere with viewer canvas input) | |
| if (viewerContainer.style.touchAction) viewerContainer.style.touchAction = ""; | |
| if (viewerContainer.style.pointerEvents) viewerContainer.style.pointerEvents = ""; | |
| if (canvas.style.pointerEvents) canvas.style.pointerEvents = ""; | |
| // Prevent iOS Safari zoom gesture conflicts | |
| 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', function(e) { | |
| if (e.touches.length > 1) e.preventDefault(); | |
| }, { passive: false }); | |
| // 4. Wheel/zoom listener (desktop) | |
| canvas.addEventListener('wheel', e => { | |
| if (cameraEntity && cameraEntity.script && cameraEntity.script.orbitCamera) { | |
| const orbitCam = cameraEntity.script.orbitCamera; | |
| const sens = (cameraEntity.script.orbitCameraInputMouse?.distanceSensitivity) || 0.4; | |
| if (cameraEntity.camera.projection === pc.PROJECTION_PERSPECTIVE) { | |
| orbitCam.distance -= e.deltaY * 0.01 * sens * (orbitCam.distance * 0.1); | |
| } else { | |
| orbitCam.orthoHeight -= e.deltaY * 0.01 * sens * (orbitCam.orthoHeight * 0.1); | |
| } | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| } | |
| }, { passive: false }); | |
| // Show loading | |
| progressDialog.style.display = 'block'; | |
| // 5. Import PlayCanvas if not present | |
| if (!pc) { | |
| pc = await import("https://esm.run/playcanvas"); | |
| window.pc = pc; | |
| } | |
| // 6. Setup device & app | |
| const device = await pc.createGraphicsDevice(canvas, { | |
| deviceTypes: ["webgl2"], | |
| 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; | |
| // Attach input to document.body (not canvas) for iOS and match PlayCanvas example! | |
| opts.mouse = new pc.Mouse(document.body); | |
| opts.touch = new pc.TouchDevice(document.body); | |
| 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); | |
| // Attach ResizeObserver to keep canvas in sync with container size | |
| resizeObserver = new ResizeObserver(entries => { | |
| for (const entry of entries) { | |
| const { width, height } = entry.contentRect; | |
| if (app) { | |
| app.resizeCanvas(width, height); | |
| } | |
| } | |
| }); | |
| resizeObserver.observe(viewerContainer); | |
| window.addEventListener('resize', () => { | |
| if (app) app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| }); | |
| app.on('destroy', () => { | |
| if (resizeObserver) resizeObserver.disconnect(); | |
| resizeObserver = null; | |
| }); | |
| // --- iOS-specific fix: robust binary loader for PLY --- | |
| // If window.PLY_FORCE_ARRAYBUFFER is set, override asset loader for PLY | |
| if (window.PLY_FORCE_ARRAYBUFFER) { | |
| const origRequest = pc.Http.request; | |
| pc.Http.request = function(options) { | |
| if (options && options.url && (options.url.endsWith('.ply') || options.responseType === 'gsplat')) { | |
| options.responseType = 'arraybuffer'; | |
| } | |
| return origRequest.call(this, options); | |
| }; | |
| } | |
| // 7. Asset loading (progress bar) | |
| const assets = { | |
| model: new pc.Asset('gsplat', 'gsplat', { url: plyUrl }), | |
| orbit: new pc.Asset('script', 'script', { url: "https://mikafil-viewer-gs.static.hf.space/orbit-camera.js" }), | |
| galerie: new pc.Asset('galerie', 'container', { url: glbUrl }), | |
| hdr: new pc.Asset('hdr', 'texture', { | |
| url: "https://huggingface.co/datasets/bilca/ply_files/resolve/main/galeries/blanc.png" | |
| }, { type: pc.TEXTURETYPE_RGBP, mipmaps: false }) | |
| }; | |
| let lastProg = 0; | |
| assets.model.on('load', () => { progressDialog.style.display = 'none'; }); | |
| assets.model.on('error', err => { | |
| progressDialog.innerHTML = `<p style="color: red">Error loading model: ${err}</p>`; | |
| }); | |
| const progCheck = setInterval(() => { | |
| if (assets.model.resource) { | |
| progressIndicator.value = 100; | |
| clearInterval(progCheck); | |
| progressDialog.style.display = 'none'; | |
| } else if (assets.model.loading) { | |
| lastProg = Math.min(lastProg + 2, 90); | |
| progressIndicator.value = lastProg; | |
| } | |
| }, 100); | |
| // Wait for PlayCanvas app and input to be ready, then load assets | |
| const loader = new pc.AssetListLoader(Object.values(assets), app.assets); | |
| loader.load(async () => { | |
| app.start(); | |
| app.scene.envAtlas = assets.hdr.resource; | |
| // Main model entity | |
| modelEntity = new pc.Entity('model'); | |
| modelEntity.addComponent('gsplat', { asset: assets.model }); | |
| modelEntity.setLocalPosition(modelX, modelY, modelZ); | |
| modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ); | |
| modelEntity.setLocalScale(modelScale, modelScale, modelScale); | |
| app.root.addChild(modelEntity); | |
| // Light | |
| const dirLight = new pc.Entity('Cascaded Light'); | |
| dirLight.addComponent('light', { | |
| type: 'directional', | |
| color: pc.Color.WHITE, | |
| shadowBias: 0.3, | |
| normalOffsetBias: 0.2, | |
| intensity: 1.0, | |
| soft: true, | |
| shadowResolution: 4096, | |
| penumbraSize: 7, | |
| penumbraFalloff: 1.5, | |
| shadowSamples: 128, | |
| shadowBlockerSamples: 16, | |
| castShadows: true, | |
| shadowType: pc.SHADOW_PCSS_32F, | |
| shadowDistance: 1000 | |
| }); | |
| dirLight.setLocalEulerAngles(0, 0, 0); | |
| app.root.addChild(dirLight); | |
| // Gallery GLB (optional) | |
| if (assets.galerie && assets.galerie.resource && assets.galerie.resource.instantiateRenderEntity) { | |
| const galleryEntity = assets.galerie.resource.instantiateRenderEntity(); | |
| app.root.addChild(galleryEntity); | |
| } | |
| // Camera setup | |
| cameraEntity = new pc.Entity('camera'); | |
| cameraEntity.addComponent('camera', { | |
| clearColor: config.canvas_background | |
| ? new pc.Color( | |
| parseInt(config.canvas_background.substr(1, 2), 16) / 255, | |
| parseInt(config.canvas_background.substr(3, 2), 16) / 255, | |
| parseInt(config.canvas_background.substr(5, 2), 16) / 255, | |
| 1 | |
| ) | |
| : new pc.Color(0.2, 0.2, 0.2, 1) | |
| }); | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelEntity.getPosition()); | |
| cameraEntity.addComponent('script'); | |
| cameraEntity.script.create('orbitCamera', { | |
| attributes: { | |
| inertiaFactor: 0.2, | |
| focusEntity: modelEntity, | |
| distanceMax: maxZoom, | |
| distanceMin: minZoom, | |
| pitchAngleMax: maxAngle, | |
| pitchAngleMin: minAngle, | |
| yawAngleMax: maxAzimuth, | |
| yawAngleMin: minAzimuth, | |
| minPivotY: minPivotY, | |
| minY: minY, | |
| frameOnStart: false | |
| } | |
| }); | |
| cameraEntity.script.create('orbitCameraInputMouse', { | |
| attributes: { | |
| orbitSensitivity: isMobile ? 0.6 : 0.3, | |
| distanceSensitivity: isMobile ? 0.5 : 0.4 | |
| } | |
| }); | |
| cameraEntity.script.create('orbitCameraInputTouch', { | |
| attributes: { | |
| orbitSensitivity: 0.6, | |
| distanceSensitivity: 0.5 | |
| } | |
| }); | |
| app.root.addChild(cameraEntity); | |
| // On first update, reset camera to proper config | |
| app.once('update', () => { resetViewerCamera(); }); | |
| // Clamp Y so camera never goes below floor | |
| app.on('update', dt => { | |
| if (cameraEntity) { | |
| const pos = cameraEntity.getPosition(); | |
| if (pos.y < minY) cameraEntity.setPosition(pos.x, minY, pos.z); | |
| } | |
| }); | |
| // Final resize | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| // Tooltips | |
| if (config.tooltips_url) { | |
| try { | |
| const tooltipsModule = await import('./tooltips.js'); | |
| await tooltipsModule.initializeTooltips({ | |
| app, | |
| cameraEntity, | |
| modelEntity, | |
| tooltipsUrl: config.tooltips_url, | |
| defaultVisible: !!config.showTooltipsDefault, | |
| moveDuration: config.tooltipMoveDuration || 0.6 | |
| }); | |
| } catch (e) {/* Fail quietly */} | |
| } | |
| // Ready! | |
| viewerInitialized = true; | |
| }); | |
| } | |
| 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) {/* Fail quietly */} | |
| } | |
| export function cleanupViewer() { | |
| if (app) { | |
| try { | |
| app.destroy(); | |
| } catch {} | |
| app = null; | |
| } | |
| cameraEntity = null; | |
| modelEntity = null; | |
| viewerInitialized = false; | |
| if (resizeObserver) { | |
| resizeObserver.disconnect(); | |
| resizeObserver = null; | |
| } | |
| } | |