Spaces:
Running
Running
| // viewer.js | |
| // ============================== | |
| 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 sogsUrl, glbUrl, canvasBg; | |
| function getDeviceTypes() { | |
| const ua = navigator.userAgent; | |
| if (/iPad|iPhone|iPod/.test(ua) || (ua.includes("Macintosh") && "ontouchend" in document)) { | |
| return ['webgl2', 'webgl1']; // Try both on iOS | |
| } | |
| return ['webgl2', 'webgl1']; | |
| } | |
| export async function initializeViewer(config, instanceId) { | |
| try { | |
| alert("initializeViewer: start"); | |
| if (viewerInitialized) return; | |
| const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent); | |
| const isMobile = isIOS || /Android/i.test(navigator.userAgent); | |
| // Parse config fields | |
| sogsUrl = config.sogs_json_url; | |
| glbUrl = config.glb_url; | |
| canvasBg = config.canvas_background || "#ffffff"; | |
| 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; | |
| 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'); | |
| viewerContainer.insertBefore(canvas, progressDialog); | |
| canvas.style.background = canvasBg; | |
| 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 }); | |
| progressDialog.style.display = 'block'; | |
| alert("Canvas created. Loading PlayCanvas..."); | |
| // 1. Import PlayCanvas | |
| const pcMod = await import("https://cdn.jsdelivr.net/npm/playcanvas@2.8.0/+esm"); | |
| alert("PlayCanvas imported."); | |
| window.pc = pcMod; // ensures global for script-based scripts | |
| // 2. Now all use window.pc from here | |
| const pc = window.pc; | |
| // 3. Graphics Device | |
| const gfxOptions = { | |
| deviceTypes: getDeviceTypes(), | |
| glslangUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/glslang/glslang.js", | |
| twgslUrl: "https://mikafil-viewer-sgos.static.hf.space/static/lib/twgsl/twgsl.js", | |
| antialias: false | |
| }; | |
| const device = await pc.createGraphicsDevice(canvas, gfxOptions); | |
| device.maxPixelRatio = Math.min(window.devicePixelRatio, 2); | |
| alert("Graphics device created."); | |
| // 4. App creation (Application, not AppBase for max compatibility) | |
| app = new pc.Application(canvas, { | |
| graphicsDevice: device, | |
| mouse: new pc.Mouse(canvas), | |
| touch: new pc.TouchDevice(canvas), | |
| componentSystems: [ | |
| pc.RenderComponentSystem, | |
| pc.CameraComponentSystem, | |
| pc.LightComponentSystem, | |
| pc.ScriptComponentSystem, | |
| pc.GSplatComponentSystem, | |
| pc.CollisionComponentSystem, | |
| pc.RigidbodyComponentSystem | |
| ], | |
| resourceHandlers: [ | |
| pc.TextureHandler, | |
| pc.ContainerHandler, | |
| pc.ScriptHandler, | |
| pc.GSplatHandler | |
| ] | |
| }); | |
| alert("App created."); | |
| app.setCanvasFillMode(pc.FILLMODE_NONE); | |
| app.setCanvasResolution(pc.RESOLUTION_AUTO); | |
| // Resize observer logic | |
| 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()); | |
| // Asset loading | |
| const assets = { | |
| sogs: new pc.Asset('gsplat', 'gsplat', { url: sogsUrl }), | |
| orbit: new pc.Asset('script', 'script', { url: "https://mikafil-viewer-sgos.static.hf.space/orbit-camera.js" }), | |
| glb: new pc.Asset('glb', 'container', { url: glbUrl }), | |
| }; | |
| for (const key in assets) app.assets.add(assets[key]); | |
| const assetList = Object.values(assets).filter(asset => asset.url); | |
| const assetListLoader = new pc.AssetListLoader(assetList, app.assets); | |
| assetListLoader.load(() => { | |
| alert("Asset loader started."); | |
| if (!assets.sogs.resource) { | |
| alert("SOGS asset failed to load."); | |
| return; | |
| } | |
| modelEntity = new pc.Entity('model'); | |
| modelEntity.addComponent('gsplat', { asset: assets.sogs }); | |
| modelEntity.setLocalPosition(modelX, modelY, modelZ); | |
| modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ); | |
| modelEntity.setLocalScale(modelScale, modelScale, modelScale); | |
| app.root.addChild(modelEntity); | |
| if (!assets.orbit.resource) { | |
| alert("orbit-camera.js asset failed to load!"); | |
| return; | |
| } | |
| alert("orbit-camera.js asset ready."); | |
| if (assets.glb && assets.glb.resource && assets.glb.resource.instantiateRenderEntity) { | |
| const glbEntity = assets.glb.resource.instantiateRenderEntity(); | |
| app.root.addChild(glbEntity); | |
| alert("GLB asset ready."); | |
| } else { | |
| alert("GLB not provided or failed to load."); | |
| } | |
| cameraEntity = new pc.Entity('camera'); | |
| // Parse and apply background color | |
| let bg = [1, 1, 1, 1]; | |
| if (canvasBg && /^#?[0-9a-f]{6,8}$/i.test(canvasBg.replace("#", ""))) { | |
| let hex = canvasBg.replace("#", ""); | |
| if (hex.length === 6) hex += "FF"; | |
| const num = parseInt(hex, 16); | |
| bg = [ | |
| ((num >> 24) & 0xFF) / 255, | |
| ((num >> 16) & 0xFF) / 255, | |
| ((num >> 8) & 0xFF) / 255, | |
| (num & 0xFF) / 255 | |
| ]; | |
| } | |
| cameraEntity.addComponent('camera', { clearColor: new pc.Color(bg[0], bg[1], bg[2], bg[3]) }); | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelEntity.getPosition()); | |
| cameraEntity.addComponent('script'); | |
| 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); | |
| app.setCanvasFillMode(pc.FILLMODE_NONE); | |
| app.setCanvasResolution(pc.RESOLUTION_AUTO); | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| app.once('update', () => resetViewerCamera()); | |
| // Tooltips support (optional) | |
| try { | |
| if (config.tooltips_url) { | |
| import('https://mikafil-viewer-sgos.static.hf.space/tooltips.js').then(tooltipsModule => { | |
| tooltipsModule.initializeTooltips({ | |
| app, | |
| cameraEntity, | |
| modelEntity, | |
| tooltipsUrl: config.tooltips_url, | |
| defaultVisible: !!config.showTooltipsDefault, | |
| moveDuration: config.tooltipMoveDuration || 0.6 | |
| }); | |
| }).catch(e => { | |
| alert("Tooltips import failed: " + e); | |
| }); | |
| } | |
| } catch (e) { | |
| alert("Tooltips error: " + e); | |
| } | |
| progressDialog.style.display = 'none'; | |
| alert("App finished initializing. (Last alert)"); | |
| viewerInitialized = true; | |
| }); | |
| } catch (e) { | |
| alert("viewer.js error: " + e); | |
| } | |
| } | |
| export function resetViewerCamera() { | |
| try { | |
| if (!cameraEntity || !modelEntity || !app) return; | |
| const orbitCam = cameraEntity.script.orbitCamera; | |
| if (!orbitCam) return; | |
| const modelPos = modelEntity.getPosition(); | |
| const tempEnt = new window.pc.Entity(); | |
| tempEnt.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| tempEnt.lookAt(modelPos); | |
| const dist = new window.pc.Vec3().sub2( | |
| new window.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 window.pc.Vec3(); | |
| rot.transformVector(window.pc.Vec3.FORWARD, fwd); | |
| const yaw = Math.atan2(-fwd.x, -fwd.z) * window.pc.math.RAD_TO_DEG; | |
| const yawQuat = new window.pc.Quat().setFromEulerAngles(0, -yaw, 0); | |
| const rotNoYaw = new window.pc.Quat().mul2(yawQuat, rot); | |
| const fNoYaw = new window.pc.Vec3(); | |
| rotNoYaw.transformVector(window.pc.Vec3.FORWARD, fNoYaw); | |
| const pitch = Math.atan2(fNoYaw.y, -fNoYaw.z) * window.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) { | |
| alert("resetViewerCamera error: " + e); | |
| } | |
| } | |