Spaces:
Running
Running
| // viewer_pr_env.js | |
| // ============================== | |
| // Version intégrant le contrôleur caméra en local (pas de <script src=...>) | |
| // + Fix "sortie du monde" : clamp dans la worldAabb et pas de culling de boîtes quasi-globales | |
| // + Logs détaillés | |
| /* ------------------------------------------- | |
| Utils communs | |
| -------------------------------------------- */ | |
| // (Conservé pour compat, même si .sog n'en a pas besoin) | |
| 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; | |
| }); | |
| } | |
| // Patch global Image -> force CORS | |
| (function () { | |
| const OriginalImage = window.Image; | |
| window.Image = function (...args) { | |
| const img = new OriginalImage(...args); | |
| img.crossOrigin = "anonymous"; | |
| return img; | |
| }; | |
| })(); | |
| function hexToRgbaArray(hex) { | |
| try { | |
| hex = String(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) { | |
| console.warn("hexToRgbaArray error:", e); | |
| return [1, 1, 1, 1]; | |
| } | |
| } | |
| // Parcours récursif d'une hiérarchie d'entités | |
| function traverse(entity, callback) { | |
| callback(entity); | |
| if (entity.children) { | |
| entity.children.forEach((child) => traverse(child, callback)); | |
| } | |
| } | |
| // Helpers math pour le script caméra | |
| function vAdd(a,b){ return new pc.Vec3(a.x+b.x,a.y+b.y,a.z+b.z); } | |
| function vSub(a,b){ return new pc.Vec3(a.x-b.x,a.y-b.y,a.z-b.z); } | |
| function vScale(v,s){ return new pc.Vec3(v.x*s,v.y*s,v.z*s); } | |
| function vLen(v){ return Math.sqrt(v.x*v.x+v.y*v.y+v.z*v.z); } | |
| function vDot(a,b){ return a.x*b.x+a.y*b.y+a.z*b.z; } | |
| function clamp(v,a,b){ return Math.max(a, Math.min(b,v)); } | |
| /* ------------------------------------------- | |
| Scripts caméra intégrés (ex-ctrl_camera_pr_env.js) | |
| — collisions capsule vs AABBs + cage monde | |
| -------------------------------------------- */ | |
| function registerFreeCamScripts() { | |
| if (window.__PLY_FREECAM_REG__) return; | |
| window.__PLY_FREECAM_REG__ = true; | |
| // ctrl_camera_pr_env.js — corrigé | |
| var FreeCamera = pc.createScript('orbitCamera'); // garder le nom public pour compat viewer | |
| // ======================== Attributs =========================== | |
| // Look | |
| FreeCamera.attributes.add('inertiaFactor', { type: 'number', default: 0.10, title: 'Inertia (rotation)' }); | |
| FreeCamera.attributes.add('pitchAngleMin', { type: 'number', default: -89, title: 'Pitch Min (deg)' }); | |
| FreeCamera.attributes.add('pitchAngleMax', { type: 'number', default: 89, title: 'Pitch Max (deg)' }); | |
| // Sol mini (filet de sécurité) | |
| FreeCamera.attributes.add('minY', { type: 'number', default: -10, title: 'Minimum camera Y' }); | |
| // Vitesse (m/s) | |
| FreeCamera.attributes.add('moveSpeed', { type: 'number', default: 2.0, title: 'Move Speed' }); | |
| FreeCamera.attributes.add('strafeSpeed', { type: 'number', default: 2.0, title: 'Strafe Speed' }); | |
| FreeCamera.attributes.add('dollySpeed', { type: 'number', default: 2.0, title: 'Mouse/Pinch Dolly Speed' }); | |
| // Capsule caméra | |
| FreeCamera.attributes.add('capsuleRadius', { type: 'number', default: 0.30, title: 'Capsule Radius (m)' }); | |
| FreeCamera.attributes.add('capsuleHeight', { type: 'number', default: 1.60, title: 'Capsule Height (m) — yeux à ~0.9m au-dessus du centre' }); | |
| FreeCamera.attributes.add('collisionEps', { type: 'number', default: 0.0005, title: 'Collision Epsilon' }); | |
| // Mouvement "swept" | |
| FreeCamera.attributes.add('maxStepDistance', { type: 'number', default: 0.10, title: 'Max step distance (swept move)' }); // réduit (anti-tunnel) | |
| FreeCamera.attributes.add('maxResolveIters', { type: 'number', default: 8, title: 'Max resolve iterations per step' }); | |
| // Escaliers | |
| FreeCamera.attributes.add('stepHeight', { type: 'number', default: 0.35, title: 'Max step-up height (m)' }); | |
| FreeCamera.attributes.add('stepAhead', { type: 'number', default: 0.20, title: 'Probe distance ahead for step (m)' }); | |
| FreeCamera.attributes.add('snapDownMax', { type: 'number', default: 0.60, title: 'Max snap-down (m)' }); | |
| FreeCamera.attributes.add('enableGroundSnap', { type: 'boolean', default: true, title: 'Enable ground snap' }); | |
| // AABBs (construction "indoor-safe") | |
| FreeCamera.attributes.add('inflateBias', { type: 'number', default: 0.0, title: 'Extra inflate AABB (m)' }); | |
| FreeCamera.attributes.add('mergeGap', { type: 'number', default: 0.0, title: 'Merge AABBs gap (0: chevauchement réel seulement)' }); | |
| FreeCamera.attributes.add('globalCullFrac',{ type: 'number', default: 0.0, title: 'Cull near-global AABBs (désactivé)' }); // désactivé | |
| // BBox globale optionnelle (filet additionnel) | |
| FreeCamera.attributes.add('Xmin', { type: 'number', default: -Infinity, title: 'BBox Xmin' }); | |
| FreeCamera.attributes.add('Xmax', { type: 'number', default: Infinity, title: 'BBox Xmax' }); | |
| FreeCamera.attributes.add('Ymin', { type: 'number', default: -Infinity, title: 'BBox Ymin' }); | |
| FreeCamera.attributes.add('Ymax', { type: 'number', default: Infinity, title: 'BBox Ymax' }); | |
| FreeCamera.attributes.add('Zmin', { type: 'number', default: -Infinity, title: 'BBox Zmin' }); | |
| FreeCamera.attributes.add('Zmax', { type: 'number', default: Infinity, title: 'BBox Zmax' }); | |
| // Compat (pour le viewer) | |
| FreeCamera.attributes.add('focusEntity', { type: 'entity', title: 'Collision Root (ENV GLB)' }); | |
| FreeCamera.attributes.add('frameOnStart', { type: 'boolean', default: false, title: 'Compat: Frame on Start (unused)' }); | |
| FreeCamera.attributes.add('yawAngleMin', { type: 'number', default: -360, title: 'Compat: Yaw Min (unused)' }); | |
| FreeCamera.attributes.add('yawAngleMax', { type: 'number', default: 360, title: 'Compat: Yaw Max (unused)' }); | |
| FreeCamera.attributes.add('distanceMin', { type: 'number', default: 0.1, title: 'Compat: Distance Min (unused)' }); | |
| // ======================== Capsule util =========================== | |
| function capsuleSegment(p, height, radius) { | |
| var seg = Math.max(0, height - 2*radius); | |
| var half = seg * 0.5; | |
| return { a: new pc.Vec3(p.x, p.y - half, p.z), b: new pc.Vec3(p.x, p.y + half, p.z), len: seg }; | |
| } | |
| function capsuleVsAabbPenetration(center, height, radius, aabb, outPush) { | |
| var seg = capsuleSegment(center, height, radius); | |
| var pts = [seg.a, seg.b, new pc.Vec3((seg.a.x+seg.b.x)/2,(seg.a.y+seg.b.y)/2,(seg.a.z+seg.b.z)/2)]; | |
| var amin = aabb.getMin(); | |
| var amax = aabb.getMax(); | |
| var eps = 1e-9; | |
| var bestPen = 0; | |
| var bestPush = null; | |
| for (var i=0;i<pts.length;i++){ | |
| var p = pts[i]; | |
| var cx = clamp(p.x, amin.x, amax.x); | |
| var cy = clamp(p.y, amin.y, amax.y); | |
| var cz = clamp(p.z, amin.z, amax.z); | |
| var dx = p.x - cx, dy = p.y - cy, dz = p.z - cz; | |
| var d2 = dx*dx + dy*dy + dz*dz; | |
| var d = Math.sqrt(Math.max(d2, eps)); | |
| var pen = radius - d; | |
| if (pen > bestPen) { | |
| if (d > 1e-6) { | |
| bestPush = new pc.Vec3(dx/d * pen, dy/d * pen, dz/d * pen); | |
| } else { | |
| var ex = Math.min(Math.abs(p.x - amin.x), Math.abs(amax.x - p.x)); | |
| var ey = Math.min(Math.abs(p.y - amin.y), Math.abs(amax.y - p.y)); | |
| var ez = Math.min(Math.abs(p.z - amin.z), Math.abs(amax.z - p.z)); | |
| if (ex <= ey && ex <= ez) bestPush = new pc.Vec3((Math.abs(p.x - amin.x) < Math.abs(amax.x - p.x) ? -1:1)*pen,0,0); | |
| else if (ey <= ex && ey <= ez) bestPush = new pc.Vec3(0,(Math.abs(p.y - amin.y) < Math.abs(amax.y - p.y) ? -1:1)*pen,0); | |
| else bestPush = new pc.Vec3(0,0,(Math.abs(p.z - amin.z) < Math.abs(amax.z - p.z) ? -1:1)*pen); | |
| } | |
| bestPen = pen; | |
| } | |
| } | |
| if (bestPen > 0 && outPush) outPush.copy(bestPush); | |
| return bestPen; | |
| } | |
| // ======================== Getters pitch/yaw =========================== | |
| Object.defineProperty(FreeCamera.prototype, 'pitch', { | |
| get: function () { return this._targetPitch; }, | |
| set: function (v) { this._targetPitch = pc.math.clamp(v, this.pitchAngleMin, this.pitchAngleMax); } | |
| }); | |
| Object.defineProperty(FreeCamera.prototype, 'yaw', { | |
| get: function () { return this._targetYaw; }, | |
| set: function (v) { this._targetYaw = v; } | |
| }); | |
| // ======================== Init =========================== | |
| FreeCamera.prototype.initialize = function () { | |
| var q = this.entity.getRotation(); | |
| var f = new pc.Vec3(); q.transformVector(pc.Vec3.FORWARD, f); | |
| this._yaw = Math.atan2(f.x, f.z) * pc.math.RAD_TO_DEG; | |
| var yawQuat = new pc.Quat().setFromEulerAngles(0, -this._yaw, 0); | |
| var noYawQ = new pc.Quat().mul2(yawQuat, q); | |
| var fNoYaw = new pc.Vec3(); noYawQ.transformVector(pc.Vec3.FORWARD, fNoYaw); | |
| this._pitch = pc.math.clamp(Math.atan2(-fNoYaw.y, -fNoYaw.z) * pc.math.RAD_TO_DEG, this.pitchAngleMin, this.pitchAngleMax); | |
| this._targetYaw = this._yaw; | |
| this._targetPitch = this._pitch; | |
| this.entity.setLocalEulerAngles(this._pitch, this._yaw, 0); | |
| this.app.systems.script.app.freeCamState = this.app.systems.script.app.freeCamState || {}; | |
| this.state = this.app.systems.script.app.freeCamState; | |
| // Colliders + cage monde | |
| this._buildAabbsFromFocus(); | |
| var p0 = this.entity.getPosition().clone(); | |
| var p1 = this._resolveCapsuleCollisions(p0, this.maxResolveIters); | |
| if (vLen(vSub(p1,p0)) > this.capsuleRadius * 0.25) { | |
| var dir = vSub(p1,p0); var L = vLen(dir)||1; | |
| p1 = vAdd(p0, vScale(dir, (this.capsuleRadius*0.25)/L)); | |
| } | |
| this._clampBBoxMinY(p1); | |
| p1 = this._clampInsideWorld(p1); // <<< clamp dans la cage | |
| this.entity.setPosition(p1); | |
| var self = this; | |
| this._onResize = function(){ self._checkAspectRatio(); }; | |
| window.addEventListener('resize', this._onResize, false); | |
| this._checkAspectRatio(); | |
| console.log('[FREE-CAM:init] pos=', p1); | |
| }; | |
| FreeCamera.prototype.update = function (dt) { | |
| var t = this.inertiaFactor === 0 ? 1 : Math.min(dt / this.inertiaFactor, 1); | |
| this._yaw = pc.math.lerp(this._yaw, this._targetYaw, t); | |
| this._pitch = pc.math.lerp(this._pitch, this._targetPitch, t); | |
| this.entity.setLocalEulerAngles(this._pitch, this._yaw, 0); | |
| var pos = this.entity.getPosition().clone(); | |
| pos = this._resolveCapsuleCollisions(pos, this.maxResolveIters); | |
| this._clampBBoxMinY(pos); | |
| pos = this._clampInsideWorld(pos); // <<< clamp dans la cage à chaque frame | |
| this.entity.setPosition(pos); | |
| }; | |
| FreeCamera.prototype._checkAspectRatio = function () { | |
| var gd = this.app.graphicsDevice; | |
| if (!gd) return; | |
| this.entity.camera.horizontalFov = (gd.height > gd.width); | |
| }; | |
| // ======================== Build colliders =========================== | |
| FreeCamera.prototype._buildAabbsFromFocus = function () { | |
| this._colliders = []; | |
| this._worldAabb = null; | |
| this._useCollision = false; | |
| this._containMin = null; | |
| this._containMax = null; | |
| var root = this.focusEntity; | |
| if (!root) { | |
| console.warn('[FREE-CAM] focusEntity manquant — pas de collisions.'); | |
| return; | |
| } | |
| // Collecte des AABBs de mesh | |
| var boxes = []; | |
| var stack = [root]; | |
| while (stack.length) { | |
| var e = stack.pop(); | |
| var rc = e.render; | |
| if (rc && rc.meshInstances && rc.meshInstances.length) { | |
| for (var i=0;i<rc.meshInstances.length;i++){ | |
| var bb = rc.meshInstances[i].aabb; | |
| boxes.push(new pc.BoundingBox(bb.center.clone(), bb.halfExtents.clone())); | |
| } | |
| } | |
| var ch = e.children; | |
| if (ch && ch.length) for (var j=0;j<ch.length;j++) stack.push(ch[j]); | |
| } | |
| if (boxes.length === 0) { | |
| console.warn('[FREE-CAM] Aucun meshInstance sous focusEntity — pas de collisions.'); | |
| return; | |
| } | |
| // Monde | |
| var world = boxes[0].clone(); | |
| for (var k=1;k<boxes.length;k++) world.add(boxes[k]); | |
| // Désactiver tout culling des quasi-globales : on garde tout | |
| var filtered = boxes; | |
| // Merge strict | |
| var merged = filtered; | |
| // Petit gonflage optionnel | |
| var inflate = Math.max(0, this.inflateBias||0); | |
| for (var n=0;n<merged.length;n++){ | |
| merged[n].halfExtents.add(new pc.Vec3(inflate, inflate, inflate)); | |
| } | |
| // Enregistrer | |
| if (merged.length>0) { | |
| for (var t=0;t<merged.length;t++) this._colliders.push({ aabb: merged[t] }); | |
| this._worldAabb = world; | |
| this._useCollision = true; | |
| // Cage monde : world min/max moins le rayon pour éviter le clipping | |
| var R = Math.max(0, this.capsuleRadius || 0.3); | |
| var wmin = world.getMin().clone().add(new pc.Vec3(R, R, R)); | |
| var wmax = world.getMax().clone().sub(new pc.Vec3(R, R, R)); | |
| this._containMin = wmin; | |
| this._containMax = wmax; | |
| } | |
| console.log('[FREE-CAM] colliders=', this._colliders.length, '(raw=', boxes.length, ')'); | |
| if (this._worldAabb) { | |
| console.log('[FREE-CAM] worldAabb min=', this._worldAabb.getMin(), 'max=', this._worldAabb.getMax()); | |
| console.log('[FREE-CAM] contain box min=', this._containMin, 'max=', this._containMax); | |
| } | |
| }; | |
| FreeCamera.prototype._mergeAabbs = function (boxes, gap) { | |
| if (!boxes || boxes.length<=1) return boxes.slice(); | |
| var out = boxes.slice(); | |
| var tol = Math.max(0, gap||0); | |
| var changed = true; | |
| function overlap(a,b,t){ | |
| var amin=a.getMin(), amax=a.getMax(); | |
| var bmin=b.getMin(), bmax=b.getMax(); | |
| return !( | |
| amax.x < bmin.x - t || amin.x > bmax.x + t || | |
| amax.y < bmin.y - t || amin.y > bmax.y + t || | |
| amax.z < bmin.z - t || amin.z > bmax.z + t | |
| ); | |
| } | |
| while (changed){ | |
| changed=false; | |
| var next=[], used=new Array(out.length).fill(false); | |
| for (var i=0;i<out.length;i++){ | |
| if (used[i]) continue; | |
| var acc = out[i]; | |
| for (var j=i+1;j<out.length;j++){ | |
| if (used[j]) continue; | |
| if (overlap(acc,out[j],tol)){ | |
| var aMin=acc.getMin(), aMax=acc.getMax(); | |
| var bMin=out[j].getMin(), bMax=out[j].getMax(); | |
| var nMin=new pc.Vec3(Math.min(aMin.x,bMin.x), Math.min(aMin.y,bMin.y), Math.min(aMin.z,bMin.z)); | |
| var nMax=new pc.Vec3(Math.max(aMax.x,bMax.x), Math.max(aMax.y,bMax.y), Math.max(aMax.z,bMax.z)); | |
| var c=nMin.clone().add(nMax).mulScalar(0.5); | |
| var h=new pc.Vec3(Math.abs(nMax.x-c.x), Math.abs(nMax.y-c.y), Math.abs(nMax.z-c.z)); | |
| acc = new pc.BoundingBox(c,h); | |
| used[j]=true; changed=true; | |
| } | |
| } | |
| used[i]=true; next.push(acc); | |
| } | |
| out=next; | |
| } | |
| return out; | |
| }; | |
| // ======================== BBox globale + minY =========================== | |
| FreeCamera.prototype._bboxEnabled = function () { | |
| return (this.Xmin < this.Xmax) && (this.Ymin < this.Ymax) && (this.Zmin < this.Zmax); | |
| }; | |
| FreeCamera.prototype._clampBBoxMinY = function (p) { | |
| if (p.y < this.minY) p.y = this.minY; | |
| if (!this._bboxEnabled()) return; | |
| p.x = clamp(p.x, this.Xmin, this.Xmax); | |
| p.y = clamp(p.y, Math.max(this.Ymin, this.minY), this.Ymax); | |
| p.z = clamp(p.z, this.Zmin, this.Zmax); | |
| }; | |
| // >>> Cage monde : clamp interne <<< | |
| FreeCamera.prototype._clampInsideWorld = function(p){ | |
| if (!this._containMin || !this._containMax) return p; | |
| p.x = Math.max(this._containMin.x, Math.min(this._containMax.x, p.x)); | |
| p.y = Math.max(Math.max(this._containMin.y, this.minY), Math.min(this._containMax.y, p.y)); | |
| p.z = Math.max(this._containMin.z, Math.min(this._containMax.z, p.z)); | |
| return p; | |
| }; | |
| FreeCamera.prototype._isOutsideWorld = function(p){ | |
| if (!this._containMin || !this._containMax) return false; | |
| return (p.x < this._containMin.x || p.x > this._containMax.x || | |
| p.y < Math.max(this._containMin.y, this.minY) || p.y > this._containMax.y || | |
| p.z < this._containMin.z || p.z > this._containMax.z); | |
| }; | |
| // ======================== Capsule vs AABBs : resolve =========================== | |
| FreeCamera.prototype._resolveCapsuleCollisions = function (pos, maxIters) { | |
| if (!this._useCollision) return pos.clone(); | |
| var p = pos.clone(); | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); | |
| var eps = Math.max(1e-7, this.collisionEps); | |
| if (!this._colliders || this._colliders.length===0) return p; | |
| var iters = Math.max(1, maxIters||1); | |
| for (var iter=0; iter<iters; iter++){ | |
| var moved = false; | |
| for (var i=0;i<this._colliders.length;i++){ | |
| var aabb = this._colliders[i].aabb; | |
| var push = new pc.Vec3(); | |
| var pen = capsuleVsAabbPenetration(p, H, R, aabb, push); | |
| if (pen > eps) { | |
| p.add(push); | |
| moved = true; | |
| } | |
| } | |
| if (!moved) break; | |
| } | |
| return p; | |
| }; | |
| // ======================== Mvt principal : swept + step + snap =========================== | |
| FreeCamera.prototype._moveSwept = function (from, delta) { | |
| if (!this._useCollision) return vAdd(from, delta); | |
| var maxStep = Math.max(0.01, this.maxStepDistance||0.1); | |
| var dist = vLen(delta); | |
| if (dist <= maxStep) return this._moveStep(from, delta); | |
| var steps = Math.ceil(dist / maxStep); | |
| var step = vScale(delta, 1/steps); | |
| var cur = from.clone(); | |
| for (var i=0;i<steps;i++) cur = this._moveStep(cur, step); | |
| return cur; | |
| }; | |
| FreeCamera.prototype._moveStep = function (from, delta) { | |
| var target = vAdd(from, delta); | |
| var after = this._resolveCapsuleCollisions(target, this.maxResolveIters); | |
| var collided = (vLen(vSub(after, target)) > 0); | |
| if (!collided) { | |
| if (this.enableGroundSnap) after = this._snapDown(after); | |
| after = this._clampInsideWorld(after); // <<< clamp | |
| return after; | |
| } | |
| var n = this._estimateNormal(after); | |
| if (n) { | |
| var desire = delta.clone(); | |
| var slide = vSub(desire, vScale(n, vDot(desire, n))); | |
| var slideTarget = vAdd(from, slide); | |
| var slideAfter = this._resolveCapsuleCollisions(slideTarget, this.maxResolveIters); | |
| // Step-up si slide insuffisant | |
| if (vLen(vSub(slideAfter, slideTarget)) > 0) { | |
| var stepped = this._tryStepUp(from, desire); | |
| if (stepped) { | |
| if (this.enableGroundSnap) stepped = this._snapDown(stepped); | |
| stepped = this._clampInsideWorld(stepped); // <<< clamp | |
| return stepped; | |
| } | |
| } | |
| if (this.enableGroundSnap) slideAfter = this._snapDown(slideAfter); | |
| slideAfter = this._clampInsideWorld(slideAfter); // <<< clamp | |
| return slideAfter; | |
| } | |
| if (this.enableGroundSnap) after = this._snapDown(after); | |
| after = this._clampInsideWorld(after); // <<< clamp | |
| return after; | |
| }; | |
| // Normale approx via micro-probes | |
| FreeCamera.prototype._estimateNormal = function (p) { | |
| if (!this._colliders) return null; | |
| var probe = 0.02; | |
| var base = this._resolveCapsuleCollisions(p, this.maxResolveIters); | |
| var nx = this._resolveCapsuleCollisions(new pc.Vec3(p.x+probe,p.y,p.z), this.maxResolveIters); | |
| var px = this._resolveCapsuleCollisions(new pc.Vec3(p.x-probe,p.y,p.z), this.maxResolveIters); | |
| var ny = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y+probe,p.z), this.maxResolveIters); | |
| var py = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y-probe,p.z), this.maxResolveIters); | |
| var nz = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y,p.z+probe), this.maxResolveIters); | |
| var pz = this._resolveCapsuleCollisions(new pc.Vec3(p.x,p.y,p.z-probe), this.maxResolveIters); | |
| function d(a,b){ return vLen(vSub(a,b)); } | |
| var dx = d(nx,base) - d(px,base); | |
| var dy = d(ny,base) - d(py,base); | |
| var dz = d(nz,base) - d(pz,base); | |
| var n = new pc.Vec3(dx,dy,dz); | |
| var L = vLen(n); | |
| if (L < 1e-5) return null; | |
| return vScale(n, 1/L); | |
| }; | |
| // Step-up : monter une marche (jusqu'à stepHeight) | |
| FreeCamera.prototype._tryStepUp = function (from, wishDelta) { | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); | |
| var maxH = Math.max(0, this.stepHeight || 0.35); | |
| var ahead = Math.max(0.05, this.stepAhead || 0.20); | |
| var horiz = new pc.Vec3(wishDelta.x, 0, wishDelta.z); | |
| var hLen = vLen(horiz); | |
| if (hLen < 1e-6) return null; | |
| horiz = vScale(horiz, 1/hLen); | |
| var probe = vAdd(from, vScale(horiz, Math.min(hLen, ahead))); | |
| var trials = 3; | |
| for (var i=1;i<=trials;i++){ | |
| var up = maxH * (i/trials); | |
| var raised = new pc.Vec3(probe.x, probe.y + up, probe.z); | |
| raised = this._resolveCapsuleCollisions(raised, this.maxResolveIters); | |
| var stepped = this._resolveCapsuleCollisions(vAdd(raised, wishDelta), this.maxResolveIters); | |
| if (vLen(vSub(stepped, raised)) > 0.02) return stepped; | |
| } | |
| return null; | |
| }; | |
| // Snap-down : redéposer sur le sol si on flotte un peu (descente d'escalier) | |
| FreeCamera.prototype._snapDown = function (p) { | |
| var R = Math.max(0, this.capsuleRadius); | |
| var H = Math.max(2*R, this.capsuleHeight); | |
| var maxDown = Math.max(0, this.snapDownMax || 0.6); | |
| var steps = 4; | |
| var step = maxDown / steps; | |
| var cur = p.clone(); | |
| for (var i=0;i<steps;i++){ | |
| var down = new pc.Vec3(cur.x, cur.y - step, cur.z); | |
| var resolved = this._resolveCapsuleCollisions(down, this.maxResolveIters); | |
| if (vLen(vSub(resolved, down)) > 0) { | |
| return this._resolveCapsuleCollisions(new pc.Vec3(resolved.x, resolved.y + 0.01, resolved.z), this.maxResolveIters); | |
| } | |
| cur.copy(down); | |
| } | |
| return p; | |
| }; | |
| // ===================== INPUT SOURIS ===================== | |
| var FreeCameraInputMouse = pc.createScript('orbitCameraInputMouse'); | |
| FreeCameraInputMouse.attributes.add('lookSensitivity', { type: 'number', default: 0.28, title: 'Look Sensitivity' }); | |
| FreeCameraInputMouse.attributes.add('wheelSensitivity',{ type: 'number', default: 0.8, title: 'Wheel Sensitivity (anti-tunnel)' }); | |
| FreeCameraInputMouse.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.last = new pc.Vec2(); | |
| this.isLooking = false; | |
| if (this.app.mouse) { | |
| this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEUP, this.onMouseUp, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this); | |
| this.app.mouse.on(pc.EVENT_MOUSEWHEEL, this.onMouseWheel, this); | |
| this.app.mouse.disableContextMenu(); | |
| } | |
| var self = this; | |
| this._onOut = function(){ self.isLooking = false; }; | |
| window.addEventListener('mouseout', this._onOut, false); | |
| this.on('destroy', () => { | |
| if (this.app.mouse) { | |
| this.app.mouse.off(pc.EVENT_MOUSEDOWN, this.onMouseDown, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEUP, this.onMouseUp, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEMOVE, this.onMouseMove, this); | |
| this.app.mouse.off(pc.EVENT_MOUSEWHEEL, this.onMouseWheel, this); | |
| } | |
| window.removeEventListener('mouseout', this._onOut, false); | |
| }); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseDown = function (e) { | |
| this.isLooking = true; | |
| this.last.set(e.x, e.y); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseUp = function () { | |
| this.isLooking = false; | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseMove = function (e) { | |
| if (!this.isLooking || !this.freeCam) return; | |
| var sens = this.lookSensitivity; | |
| this.freeCam.yaw = this.freeCam.yaw - e.dx * sens; | |
| this.freeCam.pitch = this.freeCam.pitch - e.dy * sens; | |
| this.last.set(e.x, e.y); | |
| }; | |
| FreeCameraInputMouse.prototype.onMouseWheel = function (e) { | |
| if (!this.freeCam) return; | |
| var cam = this.entity; | |
| var move = -e.wheelDelta * this.wheelSensitivity * this.freeCam.dollySpeed * 0.05; | |
| var fwd = cam.forward.clone(); if (fwd.lengthSq()>1e-8) fwd.normalize(); | |
| var from = cam.getPosition().clone(); | |
| var to = from.clone().add(fwd.mulScalar(move)); | |
| var next = this.freeCam._moveSwept(from, to.sub(from)); | |
| this.freeCam._clampBBoxMinY(next); | |
| next = this.freeCam._clampInsideWorld(next); | |
| cam.setPosition(next); | |
| e.event.preventDefault(); | |
| }; | |
| // ===================== INPUT TOUCH ===================== | |
| var FreeCameraInputTouch = pc.createScript('orbitCameraInputTouch'); | |
| FreeCameraInputTouch.attributes.add('lookSensitivity', { type: 'number', default: 0.5, title: 'Look Sensitivity' }); | |
| FreeCameraInputTouch.attributes.add('pinchDollyFactor', { type: 'number', default: 0.02, title: 'Pinch Dolly Factor' }); | |
| FreeCameraInputTouch.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.last = new pc.Vec2(); | |
| this.isLooking = false; | |
| this.lastPinch = 0; | |
| if (this.app.touch) { | |
| this.app.touch.on(pc.EVENT_TOUCHSTART, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHEND, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHCANCEL, this.onTouchStartEndCancel, this); | |
| this.app.touch.on(pc.EVENT_TOUCHMOVE, this.onTouchMove, this); | |
| } | |
| this.on('destroy', () => { | |
| if (this.app.touch) { | |
| this.app.touch.off(pc.EVENT_TOUCHSTART, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHEND, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHCANCEL, this.onTouchStartEndCancel, this); | |
| this.app.touch.off(pc.EVENT_TOUCHMOVE, this.onTouchMove, this); | |
| } | |
| }); | |
| }; | |
| FreeCameraInputTouch.prototype.onTouchStartEndCancel = function (e) { | |
| var t = e.touches; | |
| if (t.length === 1) { | |
| this.isLooking = (e.event.type === 'touchstart'); | |
| this.last.set(t[0].x, t[0].y); | |
| } else if (t.length === 2) { | |
| var dx = t[0].x - t[1].x, dy = t[0].y - t[1].y; | |
| this.lastPinch = Math.sqrt(dx*dx + dy*dy); | |
| } else { | |
| this.isLooking = false; | |
| } | |
| }; | |
| FreeCameraInputTouch.prototype.onTouchMove = function (e) { | |
| var t = e.touches; | |
| if (!this.freeCam) return; | |
| if (t.length === 1 && this.isLooking) { | |
| var s = this.lookSensitivity; | |
| var dx = t[0].x - this.last.x, dy = t[0].y - this.last.y; | |
| this.freeCam.yaw = this.freeCam.yaw - dx * s; | |
| this.freeCam.pitch = this.freeCam.pitch - dy * s; | |
| this.last.set(t[0].x, t[0].y); | |
| } else if (t.length === 2) { | |
| var dx = t[0].x - t[1].x, dy = t[0].y - t[1].y; | |
| var dist = Math.sqrt(dx*dx + dy*dy); | |
| var delta = dist - this.lastPinch; this.lastPinch = dist; | |
| var cam = this.entity; | |
| var fwd = cam.forward.clone(); if (fwd.lengthSq()>1e-8) fwd.normalize(); | |
| var from = cam.getPosition().clone(); | |
| var to = from.clone().add(fwd.mulScalar(delta * this.pinchDollyFactor * this.freeCam.dollySpeed)); | |
| var next = this.freeCam._moveSwept(from, to.sub(from)); | |
| this.freeCam._clampBBoxMinY(next); | |
| next = this.freeCam._clampInsideWorld(next); | |
| cam.setPosition(next); | |
| } | |
| }; | |
| // ===================== INPUT CLAVIER ===================== | |
| var FreeCameraInputKeyboard = pc.createScript('orbitCameraInputKeyboard'); | |
| FreeCameraInputKeyboard.attributes.add('acceleration', { type: 'number', default: 1.0, title: 'Accel (unused, future)' }); | |
| FreeCameraInputKeyboard.prototype.initialize = function () { | |
| this.freeCam = this.entity.script.orbitCamera; | |
| this.kb = this.app.keyboard || null; | |
| }; | |
| FreeCameraInputKeyboard.prototype.update = function (dt) { | |
| if (!this.freeCam || !this.kb) return; | |
| var fwd = (this.kb.isPressed(pc.KEY_UP) || this.kb.isPressed(pc.KEY_Z) || this.kb.isPressed(pc.KEY_W)) ? 1 : | |
| (this.kb.isPressed(pc.KEY_DOWN) || this.kb.isPressed(pc.KEY_S)) ? -1 : 0; | |
| var strf = (this.kb.isPressed(pc.KEY_RIGHT) || this.kb.isPressed(pc.KEY_D)) ? 1 : | |
| (this.kb.isPressed(pc.KEY_LEFT) || this.kb.isPressed(pc.KEY_Q) || this.kb.isPressed(pc.KEY_A)) ? -1 : 0; | |
| if (fwd !== 0 || strf !== 0) { | |
| var cam = this.entity; | |
| var from = cam.getPosition().clone(); | |
| var forward = cam.forward.clone(); if (forward.lengthSq()>1e-8) forward.normalize(); | |
| var right = cam.right.clone(); if (right.lengthSq()>1e-8) right.normalize(); | |
| var delta = new pc.Vec3() | |
| .add(forward.mulScalar(fwd * this.freeCam.moveSpeed * dt)) | |
| .add(right .mulScalar(strf * this.freeCam.strafeSpeed * dt)); | |
| var next = this.freeCam._moveSwept(from, delta); | |
| this.freeCam._clampBBoxMinY(next); | |
| next = this.freeCam._clampInsideWorld(next); | |
| cam.setPosition(next); | |
| } | |
| var shift = this.kb.isPressed(pc.KEY_SHIFT); | |
| if (shift) { | |
| var yawDir = (this.kb.isPressed(pc.KEY_LEFT) ? 1 : 0) - (this.kb.isPressed(pc.KEY_RIGHT) ? 1 : 0); | |
| var pitchDir = (this.kb.isPressed(pc.KEY_UP) ? 1 : 0) - (this.kb.isPressed(pc.KEY_DOWN) ? 1 : 0); | |
| var yawSpeed = 120, pitchSpeed = 90; | |
| if (yawDir !== 0) this.freeCam.yaw = this.freeCam.yaw + yawDir * yawSpeed * dt; | |
| if (pitchDir !== 0) this.freeCam.pitch = this.freeCam.pitch + pitchDir * pitchSpeed * dt; | |
| } | |
| }; | |
| } | |
| /* ------------------------------------------- | |
| State (par module = par instance importée) | |
| -------------------------------------------- */ | |
| let pc; | |
| export let app = null; | |
| let cameraEntity = null; | |
| let modelEntity = null; | |
| let envEntity = null; // <<< GLB instancié (focusEntity collisions) | |
| let viewerInitialized = false; | |
| let resizeObserver = null; | |
| let resizeTimeout = null; | |
| // paramètres courants de l'instance | |
| let chosenCameraX, chosenCameraY, chosenCameraZ; | |
| let minZoom, maxZoom, minAngle, maxAngle, minAzimuth, maxAzimuth, minY; | |
| let modelX, modelY, modelZ, modelScale, modelRotationX, modelRotationY, modelRotationZ; | |
| let presentoirScaleX, presentoirScaleY, presentoirScaleZ; | |
| let sogUrl, glbUrl, presentoirUrl; | |
| let color_bg_hex, color_bg, espace_expo_bool; | |
| // perf dynamique | |
| let maxDevicePixelRatio = 1.75; // plafond par défaut (configurable) | |
| let interactDpr = 1.0; // DPR pendant interaction | |
| let idleRestoreDelay = 350; // ms avant de restaurer le DPR | |
| let idleTimer = null; | |
| /* ------------------------------------------- | |
| Initialisation | |
| -------------------------------------------- */ | |
| export async function initializeViewer(config, instanceId) { | |
| if (viewerInitialized) return; | |
| const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent); | |
| const isMobile = isIOS || /Android/i.test(navigator.userAgent); | |
| console.log(`[VIEWER] A: initializeViewer begin`, { instanceId }); | |
| // --- Configuration --- | |
| sogUrl = config.sog_url || config.sogs_json_url; | |
| glbUrl = config.glb_url ?? "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb"; | |
| presentoirUrl = config.presentoir_url ?? "https://huggingface.co/datasets/MikaFil/viewer_gs/resolve/main/ressources/espace_expo/sol_blanc_2.glb"; | |
| minZoom = parseFloat(config.minZoom || "1"); | |
| maxZoom = parseFloat(config.maxZoom || "20"); | |
| minAngle = parseFloat(config.minAngle || "-2000"); | |
| maxAngle = parseFloat(config.maxAngle || "2000"); | |
| minAzimuth = config.minAzimuth !== undefined ? parseFloat(config.minAzimuth) : -360; | |
| maxAzimuth = config.maxAzimuth !== undefined ? parseFloat(config.maxAzimuth) : 360; | |
| 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; | |
| presentoirScaleX = config.presentoirScaleX !== undefined ? parseFloat(config.presentoirScaleX) : 0; | |
| presentoirScaleY = config.presentoirScaleY !== undefined ? parseFloat(config.presentoirScaleY) : 0; | |
| presentoirScaleZ = config.presentoirScaleZ !== undefined ? parseFloat(config.presentoirScaleZ) : 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; | |
| color_bg_hex = config.canvas_background !== undefined ? config.canvas_background : "#FFFFFF"; | |
| espace_expo_bool = config.espace_expo_bool !== undefined ? config.espace_expo_bool : false; | |
| color_bg = hexToRgbaArray(color_bg_hex); | |
| chosenCameraX = isMobile ? cameraXPhone : cameraX; | |
| chosenCameraY = isMobile ? cameraYPhone : cameraY; | |
| chosenCameraZ = isMobile ? cameraZPhone : cameraZ; | |
| // Options perf configurables | |
| if (config.maxDevicePixelRatio !== undefined) { | |
| maxDevicePixelRatio = Math.max(0.75, parseFloat(config.maxDevicePixelRatio) || maxDevicePixelRatio); | |
| } | |
| if (config.interactionPixelRatio !== undefined) { | |
| interactDpr = Math.max(0.75, parseFloat(config.interactionPixelRatio) || interactDpr); | |
| } | |
| if (config.idleRestoreDelayMs !== undefined) { | |
| idleRestoreDelay = Math.max(120, parseInt(config.idleRestoreDelayMs, 10) || idleRestoreDelay); | |
| } | |
| // --- Prépare le canvas unique à cette instance --- | |
| const canvasId = "canvas-" + instanceId; | |
| const progressDialog = document.getElementById("progress-dialog-" + instanceId); | |
| const viewerContainer = document.getElementById("viewer-container-" + instanceId); | |
| const old = document.getElementById(canvasId); | |
| if (old) old.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); | |
| // interactions de base | |
| 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 } | |
| ); | |
| // Bloque le scroll page uniquement quand le pointeur est sur le canvas | |
| const scrollKeys = new Set([ | |
| "ArrowUp","ArrowDown","ArrowLeft","ArrowRight", | |
| "PageUp","PageDown","Home","End"," ","Space","Spacebar" | |
| ]); | |
| let isPointerOverCanvas = false; | |
| const focusCanvas = () => canvas.focus({ preventScroll: true }); | |
| const onPointerEnter = () => { isPointerOverCanvas = true; focusCanvas(); }; | |
| const onPointerLeave = () => { isPointerOverCanvas = false; if (document.activeElement === canvas) canvas.blur(); }; | |
| const onCanvasBlur = () => { isPointerOverCanvas = false; }; | |
| canvas.addEventListener("pointerenter", onPointerEnter); | |
| canvas.addEventListener("pointerleave", onPointerLeave); | |
| canvas.addEventListener("mouseenter", onPointerEnter); | |
| canvas.addEventListener("mouseleave", onPointerLeave); | |
| canvas.addEventListener("mousedown", focusCanvas); | |
| canvas.addEventListener("touchstart", () => { focusCanvas(); }, { passive: false }); | |
| canvas.addEventListener("blur", onCanvasBlur); | |
| const onKeyDownCapture = (e) => { | |
| if (!isPointerOverCanvas) return; | |
| if (scrollKeys.has(e.key) || scrollKeys.has(e.code)) e.preventDefault(); | |
| }; | |
| window.addEventListener("keydown", onKeyDownCapture, true); | |
| progressDialog.style.display = "block"; | |
| // --- Charge PlayCanvas lib ESM (une par module/instance) --- | |
| if (!pc) { | |
| pc = await import("https://esm.run/playcanvas"); | |
| window.pc = pc; // debug | |
| } | |
| console.log('[VIEWER] PlayCanvas ESM chargé:', !!pc); | |
| // --- Crée l'Application --- | |
| 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 || 1, maxDevicePixelRatio); | |
| const opts = new pc.AppOptions(); | |
| opts.graphicsDevice = device; | |
| opts.mouse = new pc.Mouse(canvas); | |
| opts.touch = new pc.TouchDevice(canvas); | |
| opts.keyboard = new pc.Keyboard(canvas); | |
| opts.componentSystems = [ | |
| pc.RenderComponentSystem, | |
| pc.CameraComponentSystem, | |
| pc.LightComponentSystem, | |
| pc.ScriptComponentSystem, | |
| pc.GSplatComponentSystem, | |
| pc.CollisionComponentSystem, | |
| pc.RigidbodyComponentSystem | |
| ]; | |
| // GSplatHandler gère nativement les .sog | |
| 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); | |
| // --- Debounce resize (moins de rafales) --- | |
| resizeObserver = new ResizeObserver((entries) => { | |
| if (!entries || !entries.length) return; | |
| if (resizeTimeout) clearTimeout(resizeTimeout); | |
| resizeTimeout = setTimeout(() => { | |
| app.resizeCanvas(entries[0].contentRect.width, entries[0].contentRect.height); | |
| }, 60); | |
| }); | |
| resizeObserver.observe(viewerContainer); | |
| window.addEventListener("resize", () => { | |
| if (resizeTimeout) clearTimeout(resizeTimeout); | |
| resizeTimeout = setTimeout(() => { | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| }, 60); | |
| }); | |
| app.on("destroy", () => { | |
| try { resizeObserver.disconnect(); } catch {} | |
| if (opts.keyboard && opts.keyboard.detach) opts.keyboard.detach(); | |
| window.removeEventListener("keydown", onKeyDownCapture, true); | |
| canvas.removeEventListener("pointerenter", onPointerEnter); | |
| canvas.removeEventListener("pointerleave", onPointerLeave); | |
| canvas.removeEventListener("mouseenter", onPointerEnter); | |
| canvas.removeEventListener("mouseleave", onPointerLeave); | |
| canvas.removeEventListener("mousedown", focusCanvas); | |
| canvas.removeEventListener("touchstart", focusCanvas); | |
| canvas.removeEventListener("blur", onCanvasBlur); | |
| }); | |
| // --- Enregistre et charge les assets en 1 phase pour SOG + GLB (focusEntity prêt avant la caméra) --- | |
| const sogAsset = new pc.Asset("gsplat", "gsplat", { url: sogUrl }); | |
| const glbAsset = new pc.Asset("glb", "container", { url: glbUrl }); | |
| app.assets.add(sogAsset); | |
| app.assets.add(glbAsset); | |
| // >>> Scripts caméra en local (aucune requête réseau) <<< | |
| registerFreeCamScripts(); | |
| // ---------- CHARGEMENT SOG + GLB AVANT CREATION CAMERA ---------- | |
| await new Promise((resolve, reject) => { | |
| const loader = new pc.AssetListLoader([sogAsset, glbAsset], app.assets); | |
| loader.load(() => resolve()); | |
| loader.on('error', (e)=>{ console.error('[VIEWER] Asset load error:', e); reject(e); }); | |
| }); | |
| app.start(); // démarre l'update loop dès que possible | |
| progressDialog.style.display = "none"; | |
| console.log("[VIEWER] app.start OK — assets chargés"); | |
| // --- Modèle principal (GSplat via .sog) --- | |
| modelEntity = new pc.Entity("model"); | |
| modelEntity.addComponent("gsplat", { asset: sogAsset }); | |
| modelEntity.setLocalPosition(modelX, modelY, modelZ); | |
| modelEntity.setLocalEulerAngles(modelRotationX, modelRotationY, modelRotationZ); | |
| modelEntity.setLocalScale(modelScale, modelScale, modelScale); | |
| app.root.addChild(modelEntity); | |
| // --- Instancier le GLB d’environnement (collision) --- | |
| envEntity = glbAsset.resource ? glbAsset.resource.instantiateRenderEntity() : null; | |
| if (envEntity) { | |
| envEntity.name = "ENV_GLTF"; | |
| app.root.addChild(envEntity); | |
| // Log du nombre de meshInstances pour vérifier la construction des colliders | |
| let meshCount = 0; | |
| traverse(envEntity, (node) => { | |
| if (node.render && node.render.meshInstances) meshCount += node.render.meshInstances.length; | |
| }); | |
| console.log("[VIEWER] env ready:", true, "meshInstances=", meshCount); | |
| } else { | |
| console.warn("[VIEWER] GLB resource missing: collisions fallback sur GSplat (moins précis)."); | |
| } | |
| // --- Caméra + scripts d’input (free-cam nommée 'orbitCamera' pour compat) --- | |
| cameraEntity = new pc.Entity("camera"); | |
| cameraEntity.addComponent("camera", { | |
| clearColor: new pc.Color(color_bg), | |
| nearClip: 0.02, | |
| farClip: 250 | |
| }); | |
| cameraEntity.setPosition(chosenCameraX, chosenCameraY, chosenCameraZ); | |
| cameraEntity.lookAt(modelEntity.getPosition()); | |
| cameraEntity.addComponent("script"); | |
| cameraEntity.script.create("orbitCamera", { | |
| attributes: { | |
| focusEntity: envEntity || modelEntity, | |
| inertiaFactor: 0.18, | |
| distanceMax: maxZoom, | |
| distanceMin: minZoom, | |
| pitchAngleMax: maxAngle, | |
| pitchAngleMin: minAngle, | |
| yawAngleMax: maxAzimuth, | |
| yawAngleMin: minAzimuth, | |
| minY: minY, | |
| frameOnStart: false, | |
| capsuleRadius: 0.30, | |
| capsuleHeight: 1.60, | |
| maxStepDistance: 0.10, | |
| maxResolveIters: 8, | |
| globalCullFrac: 0.0 // désactivé | |
| } | |
| }); | |
| cameraEntity.script.create("orbitCameraInputMouse", { | |
| attributes: { lookSensitivity: 0.28, wheelSensitivity: 0.8 } | |
| }); | |
| cameraEntity.script.create("orbitCameraInputTouch", { | |
| attributes: { lookSensitivity: 0.5, pinchDollyFactor: 0.02 } | |
| }); | |
| cameraEntity.script.create("orbitCameraInputKeyboard", { | |
| attributes: { acceleration: 1.0 } | |
| }); | |
| app.root.addChild(cameraEntity); | |
| // Taille initiale | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| // IMPORTANT : si la free-cam est active, ne pas "forcer" un reset d'orbite. | |
| app.once("update", () => resetViewerCamera()); | |
| // ---------- Perf dynamique : DPR temporairement réduit pendant interaction ---------- | |
| const setDpr = (val) => { | |
| const clamped = Math.max(0.5, Math.min(val, maxDevicePixelRatio)); | |
| if (app.graphicsDevice.maxPixelRatio !== clamped) { | |
| app.graphicsDevice.maxPixelRatio = clamped; | |
| app.resizeCanvas(viewerContainer.clientWidth, viewerContainer.clientHeight); | |
| } | |
| }; | |
| const bumpInteraction = () => { | |
| setDpr(interactDpr); | |
| if (idleTimer) clearTimeout(idleTimer); | |
| idleTimer = setTimeout(() => { | |
| setDpr(Math.min(window.devicePixelRatio || 1, maxDevicePixelRatio)); | |
| }, idleRestoreDelay); | |
| }; | |
| const interactionEvents = ["mousedown", "mousemove", "mouseup", "wheel", "touchstart", "touchmove", "keydown"]; | |
| interactionEvents.forEach((ev) => { | |
| canvas.addEventListener(ev, bumpInteraction, { passive: true }); | |
| }); | |
| viewerInitialized = true; | |
| console.log("[VIEWER] READY — physics=OFF (AABB), env=", !!envEntity, "sog=", !!modelEntity); | |
| } | |
| /* ------------------------------------------- | |
| Reset caméra (API) | |
| -------------------------------------------- */ | |
| export function resetViewerCamera() { | |
| try { | |
| if (!cameraEntity || !modelEntity || !app) return; | |
| const camScript = cameraEntity.script && cameraEntity.script.orbitCamera; | |
| if (!camScript) return; | |
| const modelPos = modelEntity.getPosition(); | |
| // Ici c'est une "free-cam", on ne remet pas une orbite : juste réaligner le regard | |
| cameraEntity.lookAt(modelPos); | |
| } catch (e) { | |
| console.error("[viewer.js] resetViewerCamera error:", e); | |
| } | |
| } | |