Spaces:
Running
Running
| // ============================== | |
| // viewer.js | |
| // ============================== | |
| let pc; // will hold the PlayCanvas module once imported | |
| export let app = null; | |
| let cameraEntity = null; | |
| let modelEntity = null; | |
| let viewerInitialized = false; | |
| let chosenCameraX, chosenCameraY, chosenCameraZ; | |
| let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minPivotY, minY; | |
| let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ; | |
| let plyUrl, glbUrl; | |
| /** | |
| * initializeViewer(config, instanceId) | |
| * | |
| * - Dynamically imports PlayCanvas (once). | |
| * - Creates a new <canvas id="canvas-<instanceId>"> inside the viewer container. | |
| * - Sets up lights, model loading, camera + orbit controls, HDR, etc. | |
| * - Exposes app, cameraEntity, modelEntity, so that interface.js can resize or reset. | |
| * - Imports & initializes info-points from points.js. | |
| */ | |
| export async function initializeViewer(config, instanceId) { | |
| if (viewerInitialized) return; | |
| // Detect device type again (for camera coordinates & input sensitivity) | |
| const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; | |
| const isMobile = isIOS || /Android/i.test(navigator.userAgent); | |
| // βββ 1. Read all relevant config values βββββββββββββββββββββββββββββββββββββββ | |
| 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 elements inside interface.jsβs container βββββββββββββββββββββ | |
| const canvasId = 'canvas-' + instanceId; | |
| const progressDialog = document.getElementById('progress-dialog-' + instanceId); | |
| const progressIndicator = document.getElementById('progress-indicator-' + instanceId); | |
| const viewerContainerElem = document.getElementById('viewer-container-' + instanceId); | |
| // βββ 3. Create a fresh <canvas> (removing any old one) ββββββββββββββββββββββββ | |
| let oldCanvas = document.getElementById(canvasId); | |
| if (oldCanvas) { | |
| oldCanvas.remove(); | |
| } | |
| const newCanvas = document.createElement('canvas'); | |
| newCanvas.id = canvasId; | |
| newCanvas.className = 'ply-canvas'; | |
| newCanvas.style.zIndex = "1"; | |
| viewerContainerElem.insertBefore(newCanvas, progressDialog); | |
| const canvas = newCanvas; | |
| // βββ 4. Add mouseβwheel listener for zoom adjustments ββββββββββββββββββββββββ | |
| canvas.addEventListener('wheel', function(e) { | |
| if (cameraEntity && cameraEntity.script && cameraEntity.script.orbitCamera) { | |
| const orbitCam = cameraEntity.script.orbitCamera; | |
| const sensitivity = (cameraEntity.script.orbitCameraInputMouse && cameraEntity.script.orbitCameraInputMouse.distanceSensitivity) || 0.4; | |
| if (cameraEntity.camera.projection === pc.PROJECTION_PERSPECTIVE) { | |
| orbitCam.distance -= e.deltaY * 0.01 * sensitivity * (orbitCam.distance * 0.1); | |
| } else { | |
| orbitCam.orthoHeight -= e.deltaY * 0.01 * sensitivity * (orbitCam.orthoHeight * 0.1); | |
| } | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| } | |
| }, { passive: false }); | |
| progressDialog.style.display = 'block'; | |
| // βββ 5. Import PlayCanvas (only once) βββββββββββββββββββββββββββββββββββββββββ | |
| if (!pc) { | |
| pc = await import("https://esm.run/playcanvas"); | |
| window.pc = pc; | |
| } | |
| try { | |
| // βββ 6. Create a GraphicsDevice + AppOptions ββββββββββββββββββββββββββββββββ | |
| const deviceType = "webgl2"; | |
| const gfxOptions = { | |
| deviceTypes: [deviceType], | |
| glslangUrl: "https://playcanvas.vercel.app/static/lib/glslang/glslang.js", | |
| twgslUrl: "https://playcanvas.vercel.app/static/lib/twgsl/twgsl.js", | |
| antialias: false | |
| }; | |
| const device = await pc.createGraphicsDevice(canvas, gfxOptions); | |
| device.maxPixelRatio = Math.min(window.devicePixelRatio, 2); | |
| const createOptions = new pc.AppOptions(); | |
| createOptions.graphicsDevice = device; | |
| createOptions.mouse = new pc.Mouse(canvas); | |
| createOptions.touch = new pc.TouchDevice(canvas); | |
| // βββ ADD: include physics systems for collision-based picking βββββββββββββββ | |
| createOptions.componentSystems = [ | |
| pc.RenderComponentSystem, | |
| pc.CameraComponentSystem, | |
| pc.LightComponentSystem, | |
| pc.ScriptComponentSystem, | |
| pc.GSplatComponentSystem, | |
| pc.CollisionComponentSystem, | |
| pc.RigidbodyComponentSystem | |
| ]; | |
| createOptions.resourceHandlers = [ | |
| pc.TextureHandler, | |
| pc.ContainerHandler, | |
| pc.ScriptHandler, | |
| pc.GSplatHandler | |
| ]; | |
| // βββ REPLACED: use pc.Application (instead of deprecated / removed AppBase) ββ | |
| app = new pc.Application(canvas, createOptions); | |
| // βββ LISTEN for fullscreen-exit from interface.js to resize the canvas βββββββ | |
| window.addEventListener('viewerFullscreenExit', () => { | |
| if (app && canvas && viewerContainerElem) { | |
| const vcw = viewerContainerElem.clientWidth; | |
| const vch = viewerContainerElem.clientHeight; | |
| app.resizeCanvas(vcw, vch); | |
| } | |
| }); | |
| // Configure application | |
| app.setCanvasFillMode(pc.FILLMODE_NONE); | |
| app.setCanvasResolution(pc.RESOLUTION_AUTO); | |
| app.scene.exposure = 0.5; | |
| app.scene.toneMapping = pc.TONEMAP_ACES; | |
| // βββ NEW: Observe viewerContainer size changes to guarantee we resize at final dims βββ | |
| const ro = new ResizeObserver(entries => { | |
| for (const entry of entries) { | |
| const { width, height } = entry.contentRect; | |
| if (app) { | |
| app.resizeCanvas(width, height); | |
| } | |
| } | |
| }); | |
| ro.observe(viewerContainerElem); | |
| // βββ 7. Handle windowβresize for the PlayCanvas canvas βββββββββββββββββββββ | |
| const resizeCanvas = () => { | |
| if (app) { | |
| if (document.fullscreenElement === viewerContainerElem) { | |
| app.resizeCanvas(window.innerWidth, window.innerHeight); | |
| } else { | |
| const cw = canvas.clientWidth; | |
| const ch = canvas.clientHeight; | |
| app.resizeCanvas(cw, ch); | |
| } | |
| } | |
| }; | |
| window.addEventListener('resize', resizeCanvas); | |
| app.on('destroy', () => { | |
| window.removeEventListener('resize', resizeCanvas); | |
| ro.disconnect(); | |
| }); | |
| // βββ 8. Declare assets: PLY + orbitβcamera.js + GLB + HDR βββββββββββββββββββ | |
| const assets = { | |
| model: new pc.Asset('gsplat', 'gsplat', { url: plyUrl }), | |
| orbit: new pc.Asset('script', 'script', { url: "https://bilca-visionneur-play-canva-2.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 } | |
| ) | |
| }; | |
| const assetListLoader = new pc.AssetListLoader(Object.values(assets), app.assets); | |
| let lastProgress = 0; | |
| assets.model.on('load', () => { | |
| progressDialog.style.display = 'none'; | |
| }); | |
| assets.model.on('error', (err) => { | |
| console.error("Error loading PLY file:", err); | |
| progressDialog.innerHTML = `<p style="color: red">Error loading model: ${err}</p>`; | |
| }); | |
| const checkProgress = () => { | |
| if (assets.model.resource) { | |
| progressIndicator.value = 100; | |
| clearInterval(progressChecker); | |
| progressDialog.style.display = 'none'; | |
| } else if (assets.model.loading) { | |
| lastProgress += 2; | |
| if (lastProgress > 90) lastProgress = 90; | |
| progressIndicator.value = lastProgress; | |
| } | |
| }; | |
| const progressChecker = setInterval(checkProgress, 100); | |
| // βββ 9. Once assets are loaded, build the scene ββββββββββββββββββββββββββββ | |
| assetListLoader.load(async () => { | |
| app.start(); | |
| app.scene.envAtlas = assets.hdr.resource; | |
| // 9a. Create & position the model | |
| 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); | |
| // 9b. Add a directional 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 | |
| }); | |
| app.root.addChild(dirLight); | |
| dirLight.setLocalEulerAngles(0, 0, 0); | |
| // 9c. Instantiate the GLB βgalleryβ if any | |
| const galleryEntity = assets.galerie.resource.instantiateRenderEntity(); | |
| app.root.addChild(galleryEntity); | |
| // 9d. Create & configure the camera + orbitβcamera scripts | |
| cameraEntity = new pc.Entity('camera'); | |
| cameraEntity.addComponent('camera', { | |
| clearColor: config.canvas_background | |
| ? parseInt(config.canvas_background.substr(1, 2), 16) / 255 | |
| : 0, | |
| toneMapping: pc.TONEMAP_ACES | |
| }); | |
| // *** Set initial position/orientation from config immediately *** | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelEntity.getPosition()); | |
| // Warn if camera is very far | |
| const distanceCheck = new pc.Vec3().sub2( | |
| cameraEntity.getPosition(), | |
| modelEntity.getPosition() | |
| ).length(); | |
| if (distanceCheck > 100) { | |
| console.warn("Warning: Camera is far from model; it might not be visible"); | |
| } | |
| 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, | |
| frameOnStart: false | |
| } | |
| }); | |
| cameraEntity.script.create('orbitCameraInputMouse', { | |
| attributes: { | |
| orbitSensitivity: isMobile ? 0.6 : 0.3, | |
| distanceSensitivity: isMobile ? 0.5 : 0.4 | |
| } | |
| }); | |
| // Disable default onMouseWheel in orbitCameraInputMouse so we handle it ourselves | |
| if (cameraEntity.script.orbitCameraInputMouse) { | |
| cameraEntity.script.orbitCameraInputMouse.onMouseWheel = function() {}; | |
| } | |
| cameraEntity.script.create('orbitCameraInputTouch', { | |
| attributes: { | |
| orbitSensitivity: 0.6, | |
| distanceSensitivity: 0.5 | |
| } | |
| }); | |
| app.root.addChild(cameraEntity); | |
| // βββ NEW: Ensure camera is reset on the first frame βββββββββββββββββββββββ | |
| app.once('update', function() { | |
| // Call existing resetViewerCamera() so that pivot, yaw/pitch, and distance get | |
| // recalculated correctly before the first render. | |
| resetViewerCamera(); | |
| }); | |
| // 9e. Constrain cameraβs Y so it never dips below minY | |
| app.on('update', function(dt) { | |
| if (cameraEntity) { | |
| const pos = cameraEntity.getPosition(); | |
| if (pos.y < minY) { | |
| cameraEntity.setPosition(pos.x, minY, pos.z); | |
| } | |
| } | |
| }); | |
| // 9f. Resize canvas one last time to fit container | |
| const initialW = viewerContainerElem.clientWidth; | |
| const initialH = viewerContainerElem.clientHeight; | |
| app.resizeCanvas(initialW, initialH); | |
| // βββ NEW: Load & initialize the info-points module ββββββββββββββββββββββ | |
| try { | |
| const pointsModule = await import('./points.js'); | |
| pointsModule.initializePoints({ | |
| app, | |
| cameraEntity, | |
| modelEntity, | |
| pointsUrl: config.points_url, | |
| defaultVisible: !!config.showPointsDefault, | |
| moveDuration: config.pointMoveDuration || 0.6 // optional smoothβmove duration | |
| }); | |
| } catch (e) { | |
| console.error("Error loading points.js:", e); | |
| } | |
| progressDialog.style.display = 'none'; | |
| viewerInitialized = true; | |
| }); | |
| } catch (error) { | |
| console.error("Error initializing PlayCanvas viewer:", error); | |
| progressDialog.innerHTML = `<p style="color: red">Error loading viewer: ${error.message}</p>`; | |
| } | |
| } | |
| /** | |
| * resetViewerCamera() | |
| * | |
| * Reβcenters the camera on the model, using the chosenCameraXYZ from config. | |
| * Exactly the same math as in the old index.jsβs resetCamera(). | |
| */ | |
| export function resetViewerCamera() { | |
| try { | |
| if (!cameraEntity || !modelEntity || !app) return; | |
| const orbitCam = cameraEntity.script.orbitCamera; | |
| if (!orbitCam) return; | |
| const modelPos = modelEntity.getPosition(); | |
| // Create a temporary entity at chosenCameraX,Y,Z to compute yaw/pitch | |
| const tempEntity = new pc.Entity(); | |
| tempEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| tempEntity.lookAt(modelPos); | |
| // Compute distance | |
| const distance = new pc.Vec3().sub2( | |
| new pc.Vec3(chosenCameraX, chosenCameraY, chosenCameraZ), | |
| modelPos | |
| ).length(); | |
| // Reposition camera | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelPos); | |
| orbitCam.pivotPoint = new pc.Vec3(modelPos.x, modelPos.y, modelPos.z); | |
| orbitCam._targetDistance = distance; | |
| orbitCam._distance = distance; | |
| // Compute yaw & pitch from the βtempEntityβ | |
| const rotation = tempEntity.getRotation(); | |
| const tempForward = new pc.Vec3(); | |
| rotation.transformVector(pc.Vec3.FORWARD, tempForward); | |
| const yaw = Math.atan2(-tempForward.x, -tempForward.z) * pc.math.RAD_TO_DEG; | |
| const yawQuat = new pc.Quat().setFromEulerAngles(0, -yaw, 0); | |
| const rotWithoutYaw = new pc.Quat().mul2(yawQuat, rotation); | |
| const forwardWithoutYaw = new pc.Vec3(); | |
| rotWithoutYaw.transformVector(pc.Vec3.FORWARD, forwardWithoutYaw); | |
| const pitch = Math.atan2(forwardWithoutYaw.y, -forwardWithoutYaw.z) * pc.math.RAD_TO_DEG; | |
| orbitCam._targetYaw = yaw; | |
| orbitCam._yaw = yaw; | |
| orbitCam._targetPitch = pitch; | |
| orbitCam._pitch = pitch; | |
| if (typeof orbitCam._updatePosition === 'function') { | |
| orbitCam._updatePosition(); | |
| } | |
| tempEntity.destroy(); | |
| } catch (error) { | |
| console.error("Error resetting camera:", error); | |
| } | |
| } | |
| /** | |
| * cleanupViewer() | |
| * | |
| * Destroys the PlayCanvas `app` (if it exists) and clears references. Called when the user clicks βXβ. | |
| */ | |
| export function cleanupViewer() { | |
| if (app) { | |
| try { | |
| app.destroy(); | |
| } catch (e) { | |
| console.error("Error destroying PlayCanvas app:", e); | |
| } | |
| app = null; | |
| } | |
| cameraEntity = null; | |
| modelEntity = null; | |
| viewerInitialized = false; | |
| } | |