Spaces:
Running
Running
File size: 13,473 Bytes
7c9b0f5 c7c8c1d e8b4797 c7c8c1d 8c64c02 c7c8c1d caacb2c 7c9b0f5 a63bcf2 7c9b0f5 4081c62 7c9b0f5 df5ca69 7c9b0f5 c88c94a 7c9b0f5 4081c62 c88c94a 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 df5ca69 5e521fc 7c9b0f5 4081c62 7c9b0f5 4081c62 7c9b0f5 c88c94a 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 7fccc8c 7c9b0f5 df5ca69 7c9b0f5 236a054 7c9b0f5 b42c09b 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 df5ca69 7c9b0f5 df5ca69 b6a8b79 | 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 | let pc;
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 hexToRgbaArray(hex) {
try {
hex = hex.replace("#", "");
if (hex.length === 6) hex += "FF";
if (hex.length !== 8) return [1, 1, 1, 1];
const num = parseInt(hex, 16);
return [
((num >> 24) & 0xFF) / 255,
((num >> 16) & 0xFF) / 255,
((num >> 8) & 0xFF) / 255,
(num & 0xFF) / 255
];
} catch (e) {
alert("hexToRgbaArray error: " + e);
return [1, 1, 1, 1];
}
}
export async function initializeViewer(config, instanceId) {
alert("initializeViewer: start");
if (viewerInitialized) {
alert("Already initialized!");
return;
}
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
const isMobile = isIOS || /Android/i.test(navigator.userAgent);
try {
// Parse config
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 progressIndicator= document.getElementById('progress-indicator-' + 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);
// Apply background color from config if present
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 });
// --- Mouse wheel suppression
canvas.addEventListener('wheel', (e) => {
e.preventDefault(); // Only block page scroll if mouse is over viewer
}, { passive: false });
if (progressDialog) progressDialog.style.display = 'block';
alert("Canvas created. Loading PlayCanvas...");
if (!pc) {
pc = await import("https://cdn.jsdelivr.net/npm/playcanvas@latest/+esm");
window.pc = pc;
alert("PlayCanvas imported.");
}
// Create app and graphics device
let device;
try {
device = await pc.createGraphicsDevice(canvas, {
deviceTypes: ["webgl2", "webgl1"],
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
});
device.maxPixelRatio = Math.min(window.devicePixelRatio, 2);
alert("Graphics device created.");
} catch (e) {
alert("Graphics device error: " + e);
throw e;
}
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);
alert("App created.");
// Resizing
resizeObserver = new ResizeObserver(entries => {
entries.forEach(entry => {
try {
app.resizeCanvas(entry.contentRect.width, entry.contentRect.height);
} catch (e) { alert("resizeCanvas error: " + e); }
});
});
resizeObserver.observe(viewerContainer);
window.addEventListener('resize', () => {
try {
app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
} catch (e) { alert("resizeCanvas error: " + e); }
});
app.on('destroy', () => resizeObserver.disconnect());
// Prepare asset loading (SOGS as 'gsplat')
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]);
// Individual asset error listeners
assets.sogs.on('error', (err) => { alert("SOGS asset error: " + err); });
assets.orbit.on('error', (err) => { alert("Orbit-camera.js asset error: " + err); });
if (assets.glb) assets.glb.on('error', (err) => { alert("GLB asset error: " + err); });
assets.sogs.ready(() => { alert("SOGS asset ready."); });
assets.orbit.ready(() => { alert("orbit-camera.js asset ready."); });
if (assets.glb) assets.glb.ready(() => { alert("GLB asset ready."); });
const loader = new pc.AssetListLoader(Object.values(assets), app.assets);
loader.on('error', (err) => { alert("Asset loader error: " + err); });
loader.load(() => {
alert("All assets loaded. Starting app...");
try {
app.start();
} catch (e) {
alert("app.start() error: " + e);
throw e;
}
if (progressDialog) progressDialog.style.display = 'none';
// Add SOGS model
try {
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);
alert("Model entity added!");
} catch (e) {
alert("Model entity error: " + e);
throw e;
}
// Add the GLB entity if provided
try {
if (assets.glb && assets.glb.resource && assets.glb.resource.instantiateRenderEntity) {
const glbEntity = assets.glb.resource.instantiateRenderEntity();
app.root.addChild(glbEntity);
alert("GLB entity added.");
}
} catch (e) {
alert("GLB entity error: " + e);
}
// CAMERA
try {
cameraEntity = new pc.Entity('camera');
// Support background color
let bg = [1, 1, 1, 1];
if (canvasBg && /^#?[0-9a-f]{6,8}$/i.test(canvasBg.replace("#", ""))) {
bg = hexToRgbaArray(canvasBg);
}
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');
// Pass all attributes to Orbit Camera 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);
alert("Camera added.");
} catch (e) {
alert("Camera error: " + e);
}
try {
app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight);
alert("resizeCanvas called.");
} catch (e) {
alert("resizeCanvas error: " + e);
}
try {
app.once('update', () => resetViewerCamera());
alert("resetViewerCamera scheduled.");
} catch (e) {
alert("resetViewerCamera schedule error: " + e);
}
// 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
});
alert("Tooltips loaded.");
}).catch(e => { alert("Tooltips module error: " + e); });
}
} catch (e) {
alert("Tooltips try-catch error: " + e);
}
viewerInitialized = true;
alert("Viewer initialized success!");
});
alert("Asset loader started.");
} catch (e) {
alert("Main try-catch error: " + e);
throw e;
}
}
// Resets the viewer camera (as in your PLY example)
export function resetViewerCamera() {
alert("resetViewerCamera called.");
try {
if (!cameraEntity || !modelEntity || !app) {
alert("resetViewerCamera: cameraEntity/modelEntity/app not ready");
return;
}
const orbitCam = cameraEntity.script.orbitCamera;
if (!orbitCam) {
alert("resetViewerCamera: orbitCam missing");
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();
alert("resetViewerCamera: success");
} catch (e) {
alert("resetViewerCamera: error: " + e);
}
}
|