locar 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/locar.es.js +375 -544
- package/dist/locar.umd.js +2 -2
- package/dist/three/app.d.ts +32 -0
- package/dist/three/click-handler.d.ts +25 -0
- package/dist/three/device-orientation-controls.d.ts +55 -0
- package/dist/three/event-emitter.d.ts +24 -0
- package/dist/three/locar.d.ts +112 -0
- package/dist/three/main.d.ts +9 -0
- package/dist/three/sphmerc-projection.d.ts +29 -0
- package/dist/three/webcam.d.ts +27 -0
- package/dist/types/locar.d.ts +89 -0
- package/package.json +11 -17
- package/dist/locar.d.ts +0 -375
package/dist/locar.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(p,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],u):(p=typeof globalThis<"u"?globalThis:p||self,u(p.locar={},p.THREE))})(this,(function(p,u){"use strict";function _(f){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(f){for(const i in f)if(i!=="default"){const t=Object.getOwnPropertyDescriptor(f,i);Object.defineProperty(e,i,t.get?t:{enumerable:!0,get:()=>f[i]})}}return e.default=f,Object.freeze(e)}const m=_(u);class w{constructor(){this.on=(e,i)=>{this.eventHandlers[e]===void 0&&(this.eventHandlers[e]=[]),this.eventHandlers[e].push(i)},this.emit=(e,...i)=>{this.eventHandlers[e]?.forEach(t=>{t(...i)})},this.off=(e,i)=>{if(this.eventHandlers[e]){const t=this.eventHandlers[e].indexOf(i);t>-1&&this.eventHandlers[e].splice(t,1)}},this.eventHandlers={}}}class T extends w{constructor({cameraOptions:e,canvas:i,gpsOptions:t,videoConstraints:o,deviceOrientationOptions:l,serverLogger:g,projection:n}){super(),this.origHfov=e?.hFov||80;const s=0;this.cameraFeedDimensions=null;const d=window.innerWidth/window.innerHeight;this.camera=new m.PerspectiveCamera(this.origHfov/d,d,e?.near||.001,e?.far||1e3),i?(this.renderer=new m.WebGLRenderer({canvas:i,alpha:!0}),this.renderer.setClearColor(65280,s)):(this.renderer=new m.WebGLRenderer({alpha:!0}),this.renderer.setClearColor(65280,s),document.body.appendChild(this.renderer.domElement)),this.renderer.setSize(window.innerWidth,window.innerHeight),this.scene=new m.Scene;const c=l||{enabled:!0};window.addEventListener("resize",()=>{this.renderer.setSize(window.innerWidth,window.innerHeight);const a=window.innerWidth/window.innerHeight;if(this.camera.aspect=a,this.cameraFeedDimensions!==null){const h=a>1?this.cameraFeedDimensions.landWidth:this.cameraFeedDimensions.landHeight,v=a>1?this.cameraFeedDimensions.landHeight:this.cameraFeedDimensions.landWidth;this.#e(h,v,a)}this.camera.updateProjectionMatrix()}),this.locar=new y(this.scene,this.camera,t,g,n),this.webcam=new D(o),this.deviceOrientationControls=c.enabled===!0?new A(this.camera,c):null,this.renderer.setAnimationLoop(()=>{this.deviceOrientationControls?.update(),this.renderer.render(this.scene,this.camera)})}start(){return new Promise((i,t)=>{this.webcam.on("webcamstarted",o=>{const l=o.videoWidth>o.videoHeight;this.cameraFeedDimensions={landWidth:l?o.videoWidth:o.videoHeight,landHeight:l?o.videoHeight:o.videoWidth},this.#e(o.videoWidth,o.videoHeight,window.innerWidth/window.innerHeight),this.camera.updateProjectionMatrix()}),this.webcam.on("webcamerror",o=>{t({code:o.code,message:o.message})}),this.deviceOrientationControls===null?i(this.locar):(this.deviceOrientationControls?.on("deviceorientationgranted",o=>{o.target.connect(),i(this.locar)}),this.deviceOrientationControls.on("deviceorientationerror",o=>{t({code:o.code,message:o.message})}),this.deviceOrientationControls.init())})}#e(e,i,t){const o=e/i;if(t<o){const l=e*(window.innerHeight/i),g=this.origHfov*(window.innerWidth/l);this.camera.fov=g/t}else this.camera.fov=this.origHfov/t}}class b{constructor(){this.project=(e,i)=>[this.#e(e),this.#t(i)],this.unproject=e=>[this.#i(e[0]),this.#n(e[1])],this.#e=e=>e/180*this.HALF_EARTH,this.#t=e=>{var i=Math.log(Math.tan((90+e)*Math.PI/360))/(Math.PI/180);return i*this.HALF_EARTH/180},this.#i=e=>e/this.HALF_EARTH*180,this.#n=e=>{var i=e/this.HALF_EARTH*180;return i=180/Math.PI*(2*Math.atan(Math.exp(i*Math.PI/180))-Math.PI/2),i},this.getID=()=>"epsg:3857",this.EARTH=4007501668e-2,this.HALF_EARTH=2003750834e-2}#e;#t;#i;#n}class y extends w{#e;#t;#i;#n;#a;#s;#d;#r;#o;constructor(e,i,t={},o=null,l=new b){super(),this.scene=e,this.camera=i,this.#e=l,this.#t=null,this.#i=0,this.#n=100,this.#a=null,this.setGpsOptions(t),this.#s=null,this.#d=0,this.#r=0,this.#o=o}setProjection(e){this.#e=e}setGpsOptions(e={}){e.gpsMinDistance!==void 0&&(this.#i=e.gpsMinDistance),e.gpsMinAccuracy!==void 0&&(this.#n=e.gpsMinAccuracy)}async startGps(){if(this.#o){const i=await(await this.#o.sendData("/gps/start",{gpsMinDistance:this.#i,gpsMinAccuracy:this.#n})).json();this.#r=i.session}return this.#a===null?(this.#a=navigator.geolocation.watchPosition(e=>{this.#c(e)},e=>{this.emit("gpserror",e)},{enableHighAccuracy:!0}),!0):!1}stopGps(){return this.#a!==null?(navigator.geolocation.clearWatch(this.#a),this.#a=null,!0):!1}fakeGps(e,i,t=null,o=0){t!==null&&this.setElevation(t),this.#c({coords:{longitude:e,latitude:i,accuracy:o}})}lonLatToWorldCoords(e,i){const t=this.#e.project(e,i);if(this.#s)t[0]-=this.#s[0],t[1]-=this.#s[1];else throw"No initial position determined";return[t[0],-t[1]]}add(e,i,t,o,l={}){e.properties=l,this.#l(e,i,t,o||0),this.scene.add(e),this.#o?.sendData("/object/new",{position:e.position,x:e.position.x,z:e.position.z,session:this.#r,properties:l})}addGeoLine(e,i,t=1){const o=e.map((n=>{const[s,d]=this.lonLatToWorldCoords(n[0],n[1]);return new m.Vector3(s,n[2]||0,d)})),l=this.#h(o,t);i.setValues({side:m.DoubleSide});const g=new m.Mesh(l,i);return this.scene.add(g),g}#h(e,i){let t,o,l,g,n=0,s=0,d=[],c;const a=e.length-1,h=[];for(let r=0;r<a;r++)t=e[r+1].x-e[r].x,o=e[r+1].z-e[r].z,l=e[r+1].y-e[r].y,g=Math.sqrt(t*t+l*l+o*o),n=-(o*(i/2))/g,s=t*(i/2)/g,c=[e[r].x-n,e[r].y,e[r].z-s,e[r].x+n,e[r].y,e[r].z+s],r>0&&c.forEach((P,V)=>{P=(P+d[V])/2}),h.push(...c),d=[e[r+1].x-n,e[r+1].y,e[r+1].z-s,e[r+1].x+n,e[r+1].y,e[r+1].z+s];h.push(e[a].x-n),h.push(e[a].y),h.push(e[a].z-s),h.push(e[a].x+n),h.push(e[a].y),h.push(e[a].z+s);let v=[];for(let r=0;r<a;r++)v.push(r*2,r*2+1,r*2+2),v.push(r*2+1,r*2+3,r*2+2);let O=new m.BufferGeometry,z=new Float32Array(h);return O.setIndex(v),O.setAttribute("position",new m.BufferAttribute(z,3)),O.computeBoundingBox(),O}#l(e,i,t,o){const l=this.lonLatToWorldCoords(i,t);o!==void 0&&(e.position.y=o),[e.position.x,e.position.z]=l}setElevation(e){this.camera.position.y=e}#u(e,i){this.#s=this.#e.project(e,i)}#c(e){let i=Number.MAX_VALUE;this.#d++,this.#o?.sendData("/gps/new",{gpsCount:this.#d,lat:e.coords.latitude,lon:e.coords.longitude,acc:e.coords.accuracy,session:this.#r}),e.coords.accuracy<=this.#n&&(this.#t===null?this.#t={latitude:e.coords.latitude,longitude:e.coords.longitude}:i=y.haversineDist(this.#t,e.coords),i>=this.#i&&(this.#t.longitude=e.coords.longitude,this.#t.latitude=e.coords.latitude,this.#s||(this.#u(e.coords.longitude,e.coords.latitude),this.#o?.sendData("/worldorigin/new",{gpsCount:this.#d,lat:e.coords.latitude,lon:e.coords.longitude,session:this.#r,initialPosition:this.#s})),this.#l(this.camera,e.coords.longitude,e.coords.latitude),this.#o?.sendData("/gps/accepted",{gpsCount:this.#d,cameraX:this.camera.position.x,cameraZ:this.camera.position.z,session:this.#r,distMoved:i}),this.emit("gpsupdate",{position:e,distMoved:i})))}static haversineDist(e,i){const t=m.MathUtils.degToRad(i.longitude-e.longitude),o=m.MathUtils.degToRad(i.latitude-e.latitude),l=Math.sin(o/2)*Math.sin(o/2)+Math.cos(m.MathUtils.degToRad(e.latitude))*Math.cos(m.MathUtils.degToRad(i.latitude))*(Math.sin(t/2)*Math.sin(t/2));return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3}getLastKnownLocation(){return this.#t}}const R="locar-device-orientation-permission-modal",x="locar-device-orientation-permission-button",L="locar-device-orientation-permission-message",S="locar-device-orientation-permission-inner",N="locar-device-orientation-permission-button-inner",C="This immersive website requires access to your device motion sensors.",E=navigator.userAgent.match(/iPhone|iPad|iPod/i)||/Macintosh/i.test(navigator.userAgent)&&navigator.maxTouchPoints!=null&&navigator.maxTouchPoints>1,H=new u.Vector3(0,0,1),M=new u.Euler,W=new u.Quaternion,F=new u.Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5)),I=.5*Math.PI;class A extends u.EventDispatcher{constructor(e,i={}){super(),this.init=()=>{window.DeviceOrientationEvent===void 0?this.eventEmitter.emit("deviceorientationerror",{code:"LOCAR_DEVICE_ORIENTATION_NOT_SUPPORTED",message:"Device orientation API not supported"}):window.isSecureContext===!1?this.eventEmitter.emit("deviceorientationerror",{code:"LOCAR_DEVICE_ORIENTATION_NO_HTTPS",message:"DeviceOrientationEvent is only available in secure contexts (https)"}):typeof window.DeviceOrientationEvent.requestPermission=="function"&&this.enablePermissionDialog?this.obtainPermissionGesture():this.eventEmitter.emit("deviceorientationgranted",{target:this})},this.eventEmitter=new w;const t=this;this.object=e,this.object.rotation.reorder("YXZ"),this.enabled=!0,this.deviceOrientation=null,this.screenOrientation=0,this.alphaOffset=0,this.orientationOffset=0,this.initialOffset=null,this.lastQuaternion=null,this.orientationChangeEventName="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation",this.smoothingFactor=i.smoothingFactor||.2,this.enablePermissionDialog=i.enablePermissionDialog??!0,this.enableInlineStyling=i.enableStyling??!0,this.preferConfirmDialog=i.preferConfirmDialog??!1,this.orientationChangeThreshold=i.orientationChangeThreshold??0;const o=n=>{let{alpha:s,beta:d,gamma:c,webkitCompassHeading:a}=n;if(s=s??0,d=d??0,c=c??0,a=a??0,E){const h=360-a;t.alphaOffset=u.MathUtils.degToRad(h-s),t.deviceOrientation={alpha:s,beta:d,gamma:c,webkitCompassHeading:a}}else s<0&&(s+=360),t.deviceOrientation={alpha:s,beta:d,gamma:c};window.dispatchEvent(new CustomEvent("camera-rotation-change",{detail:{cameraRotation:e.rotation}}))},l=()=>{t.screenOrientation=window.screen.orientation?.angle??0,E&&(t.screenOrientation===90?t.orientationOffset=-I:t.screenOrientation===-90?t.orientationOffset=I:t.orientationOffset=0)},g=(n,s,d,c,a)=>{M.set(d,s,-c,"YXZ"),n.setFromEuler(M),n.multiply(F),n.multiply(W.setFromAxisAngle(H,-a))};this.connect=()=>{l(),window.addEventListener("orientationchange",l),window.addEventListener(t.orientationChangeEventName,o),t.enabled=!0},this.disconnect=()=>{window.removeEventListener("orientationchange",l),window.removeEventListener(t.orientationChangeEventName,o),t.enabled=!1,t.initialOffset=!1,t.deviceOrientation=null,t.lastQuaternion=null},this.requestOrientationPermissions=()=>{window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission=="function"?window.DeviceOrientationEvent.requestPermission().then(n=>{n==="granted"?this.eventEmitter.emit("deviceorientationgranted",{target:this}):this.eventEmitter.emit("deviceorientationerror",{code:"LOCAR_DEVICE_ORIENTATION_PERMISSION_DENIED",message:"Permission for device orientation denied - AR will not work correctly"})}).catch(n=>{this.eventEmitter.emit("deviceorientationerror",{code:"LOCAR_DEVICE_ORIENTATION_PERMISSION_FAILED",message:"Permission request for device orientation failed - AR will not work correctly",error:JSON.stringify(n,null,2)})}):this.eventEmitter.emit("deviceorientationerror",{code:"LOCAR_DEVICE_ORIENTATION_INTERNAL_ERROR",message:"Internal error: no requestPermission() found although requestOrientationPermissions() was called - please raise an issue on GitHub"})},this.update=()=>{if(t.enabled===!1)return;const n=t.deviceOrientation;if(n){let s=n.alpha?u.MathUtils.degToRad(n.alpha)+t.alphaOffset:0,d=n.beta?u.MathUtils.degToRad(n.beta):0,c=n.gamma?u.MathUtils.degToRad(n.gamma):0;const a=t.screenOrientation?u.MathUtils.degToRad(t.screenOrientation):0,h=new u.Quaternion;if(E){g(h,s,d,c,a);const v=new u.Euler().setFromQuaternion(h,"YXZ"),O=u.MathUtils.degToRad(360-(n.webkitCompassHeading??0));v.y=O+(t.orientationOffset||0),h.setFromEuler(v)}else g(h,s,d,c,a);if(t.lastQuaternion&&t.orientationChangeThreshold>0&&h.angleTo(t.lastQuaternion)<t.orientationChangeThreshold)return;if(t.smoothingFactor<1&&t.lastQuaternion){const v=1-t.smoothingFactor;t.object.quaternion.slerp(h,v)}else t.object.quaternion.copy(h);t.lastQuaternion=t.object.quaternion.clone(),window.dispatchEvent(new CustomEvent("camera-rotation-change",{detail:{cameraRotation:t.object.rotation}}))}},this.getCorrectedHeading=()=>{const{deviceOrientation:n}=t;if(!n)return 0;let s=0;return E?(s=360-(n.webkitCompassHeading??0),t.orientationOffset&&(s+=t.orientationOffset*(180/Math.PI),s=(s+360)%360)):(n.absolute===!0||t.orientationChangeEventName,s=n.alpha?n.alpha:0,s=(360-s)%360,s<0&&(s+=360)),s},this.updateAlphaOffset=()=>{t.initialOffset=!1},this.dispose=()=>{t.disconnect()},this.getAlpha=()=>{const{deviceOrientation:n}=t;return n&&n.alpha?u.MathUtils.degToRad(n.alpha)+t.alphaOffset:0},this.getBeta=()=>{const{deviceOrientation:n}=t;return n&&n.beta?u.MathUtils.degToRad(n.beta):0},this.getGamma=()=>{const{deviceOrientation:n}=t;return n&&n.gamma?u.MathUtils.degToRad(n.gamma):0},this.createObtainPermissionGestureDialog=()=>{const n=document.createElement("div");n.classList.add(R);const s=document.createElement("div");s.classList.add(S);const d=document.createElement("div");d.classList.add(L);const c=document.createElement("div");c.classList.add(N);const a=document.createElement("button");a.classList.add(x),document.body.appendChild(n),this.enableInlineStyling===!0&&(n.style.fontFamily="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'",n.style.display="flex",n.style.position="fixed",n.style.zIndex="100000",n.style.justifyContent="center",n.style.alignItems="center",n.style.backgroundColor="rgba(0,0,0,0.2)",n.style.inset="0",n.style.padding="20px",s.style.backgroundColor="rgba(220, 220, 220, 0.85)",s.style.padding="6px 0",s.style.borderRadius="10px",s.style.width="100%",s.style.maxWidth="400px",d.style.padding="10px 12px",d.style.textAlign="center",d.style.fontWeight="400",d.style.fontSize="13px",d.style.display="flex",d.style.justifyContent="center",d.style.alignItems="center",c.style.display="block",c.style.textAlign="center",c.style.textDecoration="none",c.style.borderTop="rgb(180,180,180) solid 1px",a.style.display="block",a.style.width="100%",a.style.textAlign="center",a.style.appearance="none",a.style.background="none",a.style.border="none",a.style.outline="none",a.style.padding="10px",a.style.fontWeight="400",a.style.fontSize="16px",a.style.color="#2e7cf1",a.style.cursor="pointer"),n.appendChild(s),s.appendChild(d),s.appendChild(c),d.appendChild(document.createTextNode(C));const h=()=>{this.requestOrientationPermissions(),n.style.display="none"};a.addEventListener("click",h),a.appendChild(document.createTextNode("OK")),c.appendChild(a),document.body.appendChild(n)},this.obtainPermissionGesture=()=>{this.preferConfirmDialog===!0?window.confirm(C)&&this.requestOrientationPermissions():this.createObtainPermissionGestureDialog()}}on(e,i){this.eventEmitter.on(e,i)}}class j{constructor(e){this.raycaster=new m.Raycaster,this.normalisedMousePosition=null,e.domElement.addEventListener("click",i=>{this.normalisedMousePosition=new m.Vector2(i.clientX/e.domElement.clientWidth*2-1,-(i.clientY/e.domElement.clientHeight*2)+1)})}raycast(e,i){if(this.normalisedMousePosition!==null){this.raycaster.setFromCamera(this.normalisedMousePosition,e);const t=this.raycaster.intersectObjects(i.children,!1);return this.normalisedMousePosition=null,t}return[]}}class D extends w{#e;constructor(e={video:{facingMode:"environment"}},i){super(),this.sceneWebcam=new m.Scene,i?this.#e=document.querySelector(i):(this.#e=document.createElement("video"),this.#e.setAttribute("autoplay","true"),this.#e.setAttribute("playsinline","true"),this.#e.style.cssText+=`
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("three")):typeof define==`function`&&define.amd?define([`exports`,`three`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.locar={},e.THREE))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=Object.create,r=Object.defineProperty,i=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,c=(e,t,n,o)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=a(t),l=0,u=c.length,d;l<u;l++)d=c[l],!s.call(e,d)&&d!==n&&r(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(o=i(t,d))||o.enumerable});return e};t=((e,t,i)=>(i=e==null?{}:n(o(e)),c(t||!e||!e.__esModule?r(i,`default`,{value:e,enumerable:!0}):i,e)))(t);var l=class{constructor(){this.on=(e,t)=>{this.eventHandlers[e]===void 0&&(this.eventHandlers[e]=[]),this.eventHandlers[e].push(t)},this.emit=(e,...t)=>{this.eventHandlers[e]?.forEach(e=>{e(...t)})},this.off=(e,t)=>{if(this.eventHandlers[e]){let n=this.eventHandlers[e].indexOf(t);n>-1&&this.eventHandlers[e].splice(n,1)}},this.eventHandlers={}}},u=class extends l{constructor({cameraOptions:e,canvas:n,gpsOptions:r,videoConstraints:i,deviceOrientationOptions:a,serverLogger:o,projection:s}){super(),this.origHfov=e?.hFov||80,this.cameraFeedDimensions=null;let c=window.innerWidth/window.innerHeight;this.camera=new t.PerspectiveCamera(this.origHfov/c,c,e?.near||.001,e?.far||1e3),n?(this.renderer=new t.WebGLRenderer({canvas:n,alpha:!0}),this.renderer.setClearColor(65280,0)):(this.renderer=new t.WebGLRenderer({alpha:!0}),this.renderer.setClearColor(65280,0),document.body.appendChild(this.renderer.domElement)),this.renderer.setSize(window.innerWidth,window.innerHeight),this.scene=new t.Scene;let l=a||{enabled:!0};window.addEventListener(`resize`,()=>{this.renderer.setSize(window.innerWidth,window.innerHeight);let e=window.innerWidth/window.innerHeight;if(this.camera.aspect=e,this.cameraFeedDimensions!==null){let t=e>1?this.cameraFeedDimensions.landWidth:this.cameraFeedDimensions.landHeight,n=e>1?this.cameraFeedDimensions.landHeight:this.cameraFeedDimensions.landWidth;this.#e(t,n,e)}this.camera.updateProjectionMatrix()}),this.locar=new f(this.scene,this.camera,r,o,s),this.webcam=new D(i),this.deviceOrientationControls=l.enabled===!0?new T(this.camera,l):null,this.renderer.setAnimationLoop(()=>{this.deviceOrientationControls?.update(),this.renderer.render(this.scene,this.camera)})}start(){return new Promise((e,t)=>{this.webcam.on(`webcamstarted`,e=>{let t=e.videoWidth>e.videoHeight;this.cameraFeedDimensions={landWidth:t?e.videoWidth:e.videoHeight,landHeight:t?e.videoHeight:e.videoWidth},this.#e(e.videoWidth,e.videoHeight,window.innerWidth/window.innerHeight),this.camera.updateProjectionMatrix()}),this.webcam.on(`webcamerror`,e=>{t({code:e.code,message:e.message})}),this.deviceOrientationControls===null?e(this.locar):(this.deviceOrientationControls?.on(`deviceorientationgranted`,t=>{t.target.connect(),e(this.locar)}),this.deviceOrientationControls.on(`deviceorientationerror`,e=>{t({code:e.code,message:e.message})}),this.deviceOrientationControls.init())})}#e(e,t,n){if(n<e/t){let r=e*(window.innerHeight/t),i=this.origHfov*(window.innerWidth/r);this.camera.fov=i/n}else this.camera.fov=this.origHfov/n}},d=class{constructor(){this.project=(e,t)=>[this.#e(e),this.#t(t)],this.unproject=e=>[this.#n(e[0]),this.#r(e[1])],this.#e=e=>e/180*this.HALF_EARTH,this.#t=e=>Math.log(Math.tan((90+e)*Math.PI/360))/(Math.PI/180)*this.HALF_EARTH/180,this.#n=e=>e/this.HALF_EARTH*180,this.#r=e=>{var t=e/this.HALF_EARTH*180;return t=180/Math.PI*(2*Math.atan(Math.exp(t*Math.PI/180))-Math.PI/2),t},this.getID=()=>`epsg:3857`,this.EARTH=40075016.68,this.HALF_EARTH=20037508.34}#e;#t;#n;#r},f=class e extends l{#e;#t;#n;#r;#i;#a;#o;#s;#c;constructor(e,t,n={},r=null,i=new d){super(),this.scene=e,this.camera=t,this.#e=i,this.#t=null,this.#n=0,this.#r=100,this.#i=null,this.setGpsOptions(n),this.#a=null,this.#o=0,this.#s=0,this.#c=r}setProjection(e){this.#e=e}setGpsOptions(e={}){e.gpsMinDistance!==void 0&&(this.#n=e.gpsMinDistance),e.gpsMinAccuracy!==void 0&&(this.#r=e.gpsMinAccuracy)}async startGps(){if(this.#c){let e=await(await this.#c.sendData(`/gps/start`,{gpsMinDistance:this.#n,gpsMinAccuracy:this.#r})).json();this.#s=e.session}return this.#i===null?(this.#i=navigator.geolocation.watchPosition(e=>{this.#f(e)},e=>{this.emit(`gpserror`,e)},{enableHighAccuracy:!0}),!0):!1}stopGps(){return this.#i===null?!1:(navigator.geolocation.clearWatch(this.#i),this.#i=null,!0)}fakeGps(e,t,n=null,r=0){n!==null&&this.setElevation(n),this.#f({coords:{longitude:e,latitude:t,accuracy:r}})}lonLatToWorldCoords(e,t){let n=this.#e.project(e,t);return this.eastNorthToWorldCoords(n)}eastNorthToWorldCoords(e){if(this.#a)e[0]-=this.#a[0],e[1]-=this.#a[1];else throw`No initial position determined`;return[e[0],-e[1]]}add(e,t,n,r,i={}){e.properties=i,this.#u(e,t,n,r||0),this.scene.add(e),this.#c?.sendData(`/object/new`,{position:e.position,x:e.position.x,z:e.position.z,session:this.#s,properties:i})}addGeoLine(e,n,r=1){let i=e.map((e=>{let[n,r]=this.lonLatToWorldCoords(e[0],e[1]);return new t.Vector3(n,e[2]||0,r)})),a=this.#l(i,r);n.setValues({side:t.DoubleSide});let o=new t.Mesh(a,n);return this.scene.add(o),o}#l(e,n){let r,i,a,o,s=0,c=0,l=[],u,d=e.length-1,f=[];for(let t=0;t<d;t++)r=e[t+1].x-e[t].x,i=e[t+1].z-e[t].z,a=e[t+1].y-e[t].y,o=Math.sqrt(r*r+a*a+i*i),s=-(n/2*i)/o,c=n/2*r/o,u=[e[t].x-s,e[t].y,e[t].z-c,e[t].x+s,e[t].y,e[t].z+c],t>0&&u.forEach((e,t)=>{e=(e+l[t])/2}),f.push(...u),l=[e[t+1].x-s,e[t+1].y,e[t+1].z-c,e[t+1].x+s,e[t+1].y,e[t+1].z+c];f.push(e[d].x-s),f.push(e[d].y),f.push(e[d].z-c),f.push(e[d].x+s),f.push(e[d].y),f.push(e[d].z+c);let p=[];for(let e=0;e<d;e++)p.push(e*2,e*2+1,e*2+2),p.push(e*2+1,e*2+3,e*2+2);let m=new t.BufferGeometry,h=new Float32Array(f);return m.setIndex(p),m.setAttribute(`position`,new t.BufferAttribute(h,3)),m.computeBoundingBox(),m}#u(e,t,n,r){let i=this.lonLatToWorldCoords(t,n);r!==void 0&&(e.position.y=r),[e.position.x,e.position.z]=i}setElevation(e){this.camera.position.y=e}#d(e,t){this.#a=this.#e.project(e,t)}#f(t){let n=Number.MAX_VALUE;this.#o++,this.#c?.sendData(`/gps/new`,{gpsCount:this.#o,lat:t.coords.latitude,lon:t.coords.longitude,acc:t.coords.accuracy,session:this.#s}),t.coords.accuracy<=this.#r&&(this.#t===null?this.#t={latitude:t.coords.latitude,longitude:t.coords.longitude}:n=e.haversineDist(this.#t,t.coords),n>=this.#n&&(this.#t.longitude=t.coords.longitude,this.#t.latitude=t.coords.latitude,this.#a||(this.#d(t.coords.longitude,t.coords.latitude),this.#c?.sendData(`/worldorigin/new`,{gpsCount:this.#o,lat:t.coords.latitude,lon:t.coords.longitude,session:this.#s,initialPosition:this.#a})),this.#u(this.camera,t.coords.longitude,t.coords.latitude),this.#c?.sendData(`/gps/accepted`,{gpsCount:this.#o,cameraX:this.camera.position.x,cameraZ:this.camera.position.z,session:this.#s,distMoved:n}),this.emit(`gpsupdate`,{position:t,distMoved:n})))}static haversineDist(e,n){let r=t.MathUtils.degToRad(n.longitude-e.longitude),i=t.MathUtils.degToRad(n.latitude-e.latitude),a=Math.sin(i/2)*Math.sin(i/2)+Math.cos(t.MathUtils.degToRad(e.latitude))*Math.cos(t.MathUtils.degToRad(n.latitude))*(Math.sin(r/2)*Math.sin(r/2));return 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))*6371e3}getLastKnownLocation(){return this.#t}},p=`locar-device-orientation-permission-modal`,m=`locar-device-orientation-permission-button`,h=`locar-device-orientation-permission-message`,g=`locar-device-orientation-permission-inner`,_=`locar-device-orientation-permission-button-inner`,v=`This immersive website requires access to your device motion sensors.`,y=navigator.userAgent.match(/iPhone|iPad|iPod/i)||/Macintosh/i.test(navigator.userAgent)&&navigator.maxTouchPoints!=null&&navigator.maxTouchPoints>1,b=new t.Vector3(0,0,1),x=new t.Euler,S=new t.Quaternion,C=new t.Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5));2*Math.PI;var w=.5*Math.PI,T=class extends t.EventDispatcher{constructor(e,n={}){super(),this.init=()=>{window.DeviceOrientationEvent===void 0?this.eventEmitter.emit(`deviceorientationerror`,{code:`LOCAR_DEVICE_ORIENTATION_NOT_SUPPORTED`,message:`Device orientation API not supported`}):window.isSecureContext===!1?this.eventEmitter.emit(`deviceorientationerror`,{code:`LOCAR_DEVICE_ORIENTATION_NO_HTTPS`,message:`DeviceOrientationEvent is only available in secure contexts (https)`}):typeof window.DeviceOrientationEvent.requestPermission==`function`&&this.enablePermissionDialog?this.obtainPermissionGesture():this.eventEmitter.emit(`deviceorientationgranted`,{target:this})},this.eventEmitter=new l;let r=this;this.object=e,this.object.rotation.reorder(`YXZ`),this.enabled=!0,this.deviceOrientation=null,this.screenOrientation=0,this.alphaOffset=0,this.orientationOffset=0,this.initialOffset=null,this.lastQuaternion=null,this.orientationChangeEventName=`ondeviceorientationabsolute`in window?`deviceorientationabsolute`:`deviceorientation`,this.smoothingFactor=n.smoothingFactor||.2,this.enablePermissionDialog=n.enablePermissionDialog??!0,this.enableInlineStyling=n.enableStyling??!0,this.preferConfirmDialog=n.preferConfirmDialog??!1,this.orientationChangeThreshold=n.orientationChangeThreshold??0;let i=n=>{let{alpha:i,beta:a,gamma:o,webkitCompassHeading:s}=n;if(i??=0,a??=0,o??=0,s??=0,y){let e=360-s;r.alphaOffset=t.MathUtils.degToRad(e-i),r.deviceOrientation={alpha:i,beta:a,gamma:o,webkitCompassHeading:s}}else i<0&&(i+=360),r.deviceOrientation={alpha:i,beta:a,gamma:o};window.dispatchEvent(new CustomEvent(`camera-rotation-change`,{detail:{cameraRotation:e.rotation}}))},a=()=>{r.screenOrientation=window.screen.orientation?.angle??0,y&&(r.screenOrientation===90?r.orientationOffset=-w:r.screenOrientation===-90?r.orientationOffset=w:r.orientationOffset=0)},o=(e,t,n,r,i)=>{x.set(n,t,-r,`YXZ`),e.setFromEuler(x),e.multiply(C),e.multiply(S.setFromAxisAngle(b,-i))};this.connect=()=>{a(),window.addEventListener(`orientationchange`,a),window.addEventListener(r.orientationChangeEventName,i),r.enabled=!0},this.disconnect=()=>{window.removeEventListener(`orientationchange`,a),window.removeEventListener(r.orientationChangeEventName,i),r.enabled=!1,r.initialOffset=!1,r.deviceOrientation=null,r.lastQuaternion=null},this.requestOrientationPermissions=()=>{window.DeviceOrientationEvent!==void 0&&typeof window.DeviceOrientationEvent.requestPermission==`function`?window.DeviceOrientationEvent.requestPermission().then(e=>{e===`granted`?this.eventEmitter.emit(`deviceorientationgranted`,{target:this}):this.eventEmitter.emit(`deviceorientationerror`,{code:`LOCAR_DEVICE_ORIENTATION_PERMISSION_DENIED`,message:`Permission for device orientation denied - AR will not work correctly`})}).catch(e=>{this.eventEmitter.emit(`deviceorientationerror`,{code:`LOCAR_DEVICE_ORIENTATION_PERMISSION_FAILED`,message:`Permission request for device orientation failed - AR will not work correctly`,error:JSON.stringify(e,null,2)})}):this.eventEmitter.emit(`deviceorientationerror`,{code:`LOCAR_DEVICE_ORIENTATION_INTERNAL_ERROR`,message:`Internal error: no requestPermission() found although requestOrientationPermissions() was called - please raise an issue on GitHub`})},this.update=()=>{if(r.enabled===!1)return;let e=r.deviceOrientation;if(e){let n=e.alpha?t.MathUtils.degToRad(e.alpha)+r.alphaOffset:0,i=e.beta?t.MathUtils.degToRad(e.beta):0,a=e.gamma?t.MathUtils.degToRad(e.gamma):0,s=r.screenOrientation?t.MathUtils.degToRad(r.screenOrientation):0,c=new t.Quaternion;if(y){o(c,n,i,a,s);let l=new t.Euler().setFromQuaternion(c,`YXZ`);l.y=t.MathUtils.degToRad(360-(e.webkitCompassHeading??0))+(r.orientationOffset||0),c.setFromEuler(l)}else o(c,n,i,a,s);if(r.lastQuaternion&&r.orientationChangeThreshold>0&&c.angleTo(r.lastQuaternion)<r.orientationChangeThreshold)return;if(r.smoothingFactor<1&&r.lastQuaternion){let e=1-r.smoothingFactor;r.object.quaternion.slerp(c,e)}else r.object.quaternion.copy(c);r.lastQuaternion=r.object.quaternion.clone(),window.dispatchEvent(new CustomEvent(`camera-rotation-change`,{detail:{cameraRotation:r.object.rotation}}))}},this.getCorrectedHeading=()=>{let{deviceOrientation:e}=r;if(!e)return 0;let t=0;return y?(t=360-(e.webkitCompassHeading??0),r.orientationOffset&&(t+=r.orientationOffset*(180/Math.PI),t=(t+360)%360)):(e.absolute===!0||r.orientationChangeEventName,t=e.alpha?e.alpha:0,t=(360-t)%360,t<0&&(t+=360)),t},this.updateAlphaOffset=()=>{r.initialOffset=!1},this.dispose=()=>{r.disconnect()},this.getAlpha=()=>{let{deviceOrientation:e}=r;return e&&e.alpha?t.MathUtils.degToRad(e.alpha)+r.alphaOffset:0},this.getBeta=()=>{let{deviceOrientation:e}=r;return e&&e.beta?t.MathUtils.degToRad(e.beta):0},this.getGamma=()=>{let{deviceOrientation:e}=r;return e&&e.gamma?t.MathUtils.degToRad(e.gamma):0},this.createObtainPermissionGestureDialog=()=>{let e=document.createElement(`div`);e.classList.add(p);let t=document.createElement(`div`);t.classList.add(g);let n=document.createElement(`div`);n.classList.add(h);let r=document.createElement(`div`);r.classList.add(_);let i=document.createElement(`button`);i.classList.add(m),document.body.appendChild(e),this.enableInlineStyling===!0&&(e.style.fontFamily=`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'`,e.style.display=`flex`,e.style.position=`fixed`,e.style.zIndex=`100000`,e.style.justifyContent=`center`,e.style.alignItems=`center`,e.style.backgroundColor=`rgba(0,0,0,0.2)`,e.style.inset=`0`,e.style.padding=`20px`,t.style.backgroundColor=`rgba(220, 220, 220, 0.85)`,t.style.padding=`6px 0`,t.style.borderRadius=`10px`,t.style.width=`100%`,t.style.maxWidth=`400px`,n.style.padding=`10px 12px`,n.style.textAlign=`center`,n.style.fontWeight=`400`,n.style.fontSize=`13px`,n.style.display=`flex`,n.style.justifyContent=`center`,n.style.alignItems=`center`,r.style.display=`block`,r.style.textAlign=`center`,r.style.textDecoration=`none`,r.style.borderTop=`rgb(180,180,180) solid 1px`,i.style.display=`block`,i.style.width=`100%`,i.style.textAlign=`center`,i.style.appearance=`none`,i.style.background=`none`,i.style.border=`none`,i.style.outline=`none`,i.style.padding=`10px`,i.style.fontWeight=`400`,i.style.fontSize=`16px`,i.style.color=`#2e7cf1`,i.style.cursor=`pointer`),e.appendChild(t),t.appendChild(n),t.appendChild(r),n.appendChild(document.createTextNode(v)),i.addEventListener(`click`,()=>{this.requestOrientationPermissions(),e.style.display=`none`}),i.appendChild(document.createTextNode(`OK`)),r.appendChild(i),document.body.appendChild(e)},this.obtainPermissionGesture=()=>{this.preferConfirmDialog===!0?window.confirm(v)&&this.requestOrientationPermissions():this.createObtainPermissionGestureDialog()}}on(e,t){this.eventEmitter.on(e,t)}},E=class{constructor(e){this.raycaster=new t.Raycaster,this.normalisedMousePosition=null,e.domElement.addEventListener(`click`,n=>{this.normalisedMousePosition=new t.Vector2(n.clientX/e.domElement.clientWidth*2-1,-(n.clientY/e.domElement.clientHeight*2)+1)})}raycast(e,t){if(this.normalisedMousePosition!==null){this.raycaster.setFromCamera(this.normalisedMousePosition,e);let n=this.raycaster.intersectObjects(t.children,!1);return this.normalisedMousePosition=null,n}return[]}},D=class extends l{#e;#t;constructor(e={video:{facingMode:`environment`}},n){super(),this.sceneWebcam=new t.Scene,n?this.#e=document.querySelector(n):(this.#e=document.createElement(`video`),this.#e.setAttribute(`autoplay`,`true`),this.#e.setAttribute(`playsinline`,`true`),this.#e.style.cssText+=`
|
|
2
2
|
width: 100%;
|
|
3
3
|
height: 100%;
|
|
4
4
|
object-fit: cover;
|
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
top: 0px;
|
|
8
8
|
left: 0px;
|
|
9
9
|
z-index: -100;
|
|
10
|
-
`,document.body.appendChild(this.#e)),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia(e).then(
|
|
10
|
+
`,document.body.appendChild(this.#e)),this.#t=null,navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia(e).then(e=>{this.#t=e,this.#e?.addEventListener(`loadedmetadata`,()=>{this.#e.play(),this.emit(`webcamstarted`,{videoWidth:this.#e.videoWidth,videoHeight:this.#e.videoHeight})}),this.#e&&(this.#e.srcObject=e)}).catch(e=>{this.emit(`webcamerror`,{code:e.name,message:e.message})}):this.emit(`webcamerror`,{code:`LOCAR_NO_MEDIA_DEVICES_API`,message:`Media devices API not supported`})}getVideoDimensions(){return`w ${this.#e.videoWidth}, h ${this.#e.videoHeight}`}dispose(){(this.#t?.getTracks()??[]).forEach(e=>{e.stop()}),this.#t=null,this.#e?.remove(),this.#e=null}};e.App=u,e.ClickHandler=E,e.DeviceOrientationControls=T,e.EventEmitter=l,e.LocAR=f,e.SphMercProjection=d,e.Webcam=D});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { LocAR, Webcam, DeviceOrientationControls } from './main';
|
|
2
|
+
import { default as EventEmitter } from './event-emitter';
|
|
3
|
+
import { AppOptions } from '../types/locar';
|
|
4
|
+
import * as THREE from 'three';
|
|
5
|
+
/** Application class to orchestrate the interaction between the individual LocAR classes and the Three.js camera, renderer and scene. */
|
|
6
|
+
declare class App extends EventEmitter {
|
|
7
|
+
#private;
|
|
8
|
+
locar: LocAR;
|
|
9
|
+
camera: THREE.PerspectiveCamera;
|
|
10
|
+
renderer: THREE.WebGLRenderer;
|
|
11
|
+
scene: THREE.Scene;
|
|
12
|
+
webcam: Webcam;
|
|
13
|
+
deviceOrientationControls: DeviceOrientationControls | null;
|
|
14
|
+
cameraFeedDimensions: {
|
|
15
|
+
landWidth: number;
|
|
16
|
+
landHeight: number;
|
|
17
|
+
} | null; /** camera feed dimensions in LANDSCAPE */
|
|
18
|
+
origHfov: number;
|
|
19
|
+
/**
|
|
20
|
+
* Create an App object.
|
|
21
|
+
* @param {AppOptions} - Startup options.
|
|
22
|
+
*/
|
|
23
|
+
constructor({ cameraOptions, canvas, gpsOptions, videoConstraints, deviceOrientationOptions, serverLogger, projection }: AppOptions);
|
|
24
|
+
/**
|
|
25
|
+
* Start the app.
|
|
26
|
+
* Must be called after construction.
|
|
27
|
+
* @returns {Promise<LocAR>}
|
|
28
|
+
* Promise resolving with LocAR object. Rejects with object containing code and message.
|
|
29
|
+
*/
|
|
30
|
+
start(): Promise<LocAR>;
|
|
31
|
+
}
|
|
32
|
+
export default App;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import * as THREE from "three";
|
|
2
|
+
/**
|
|
3
|
+
* Class to handle object detection via mouse clicks/touch events
|
|
4
|
+
* and raycasting.
|
|
5
|
+
*/
|
|
6
|
+
declare class ClickHandler {
|
|
7
|
+
raycaster: THREE.Raycaster;
|
|
8
|
+
normalisedMousePosition: THREE.Vector2 | null;
|
|
9
|
+
/**
|
|
10
|
+
* Create a ClickHandler.
|
|
11
|
+
* @param {THREE.WebGLRenderer} - The Three.js renderer on which the click
|
|
12
|
+
* events will be handled.
|
|
13
|
+
*/
|
|
14
|
+
constructor(renderer: THREE.WebGLRenderer);
|
|
15
|
+
/**
|
|
16
|
+
* Cast a ray into the scene to detect objects.
|
|
17
|
+
* @param {THREE.Camera} - The active Three.js camera, from which the ray
|
|
18
|
+
* will be cast.
|
|
19
|
+
* @param {THREE.Scene} - The active Three.js scene, which the ray will be
|
|
20
|
+
* cast into.
|
|
21
|
+
* @return {Array} - array of all intersected objects.
|
|
22
|
+
*/
|
|
23
|
+
raycast(camera: THREE.Camera, scene: THREE.Scene): THREE.Intersection[];
|
|
24
|
+
}
|
|
25
|
+
export default ClickHandler;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { EventDispatcher, Object3D, Quaternion } from 'three';
|
|
2
|
+
import { default as EventEmitter } from './event-emitter';
|
|
3
|
+
import { DeviceOrientationControlsOptions } from '../types/locar';
|
|
4
|
+
declare class DeviceOrientationControls extends EventDispatcher {
|
|
5
|
+
eventEmitter: EventEmitter;
|
|
6
|
+
object: Object3D;
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
deviceOrientation: {
|
|
9
|
+
alpha?: number;
|
|
10
|
+
beta?: number;
|
|
11
|
+
gamma?: number;
|
|
12
|
+
webkitCompassHeading?: number;
|
|
13
|
+
absolute?: boolean;
|
|
14
|
+
} | null;
|
|
15
|
+
screenOrientation: number;
|
|
16
|
+
alphaOffset: number;
|
|
17
|
+
orientationOffset: number;
|
|
18
|
+
initialOffset: boolean | null;
|
|
19
|
+
lastQuaternion: Quaternion | null;
|
|
20
|
+
orientationChangeEventName: "deviceorientation" | "deviceorientationabsolute";
|
|
21
|
+
smoothingFactor: number;
|
|
22
|
+
enablePermissionDialog: boolean;
|
|
23
|
+
enableInlineStyling: boolean;
|
|
24
|
+
preferConfirmDialog: boolean;
|
|
25
|
+
orientationChangeThreshold: number;
|
|
26
|
+
connect: () => void;
|
|
27
|
+
disconnect: () => void;
|
|
28
|
+
requestOrientationPermissions: () => void;
|
|
29
|
+
update: () => void;
|
|
30
|
+
getCorrectedHeading: () => number;
|
|
31
|
+
updateAlphaOffset: () => void;
|
|
32
|
+
dispose: () => void;
|
|
33
|
+
getAlpha: () => number;
|
|
34
|
+
getBeta: () => number;
|
|
35
|
+
getGamma: () => number;
|
|
36
|
+
createObtainPermissionGestureDialog: () => void;
|
|
37
|
+
obtainPermissionGesture: () => void;
|
|
38
|
+
/**
|
|
39
|
+
* Create an instance of DeviceOrientationControls.
|
|
40
|
+
* @param {Object} object - the object to attach the controls to
|
|
41
|
+
* (usually your Three.js camera)
|
|
42
|
+
* @param {Object} options - options for DeviceOrientationControls:
|
|
43
|
+
* currently accepts smoothingFactor (< 1), enablePermissionDialog, orientationChangeThreshold (radians)
|
|
44
|
+
*/
|
|
45
|
+
constructor(object: Object3D, options?: DeviceOrientationControlsOptions);
|
|
46
|
+
on(eventName: string, eventHandler: (event: any) => void): void;
|
|
47
|
+
/**
|
|
48
|
+
* Initialise device orientation controls.
|
|
49
|
+
* Should be called after you have created the DeviceOrientationControls
|
|
50
|
+
* object and set up the deviceorientationgranted and deviceorientationerror
|
|
51
|
+
* event handlers.
|
|
52
|
+
*/
|
|
53
|
+
init: () => void;
|
|
54
|
+
}
|
|
55
|
+
export default DeviceOrientationControls;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Event emitter class to handle events. */
|
|
2
|
+
declare class EventEmitter {
|
|
3
|
+
eventHandlers: Record<string, ((...args: any[]) => void)[]>;
|
|
4
|
+
constructor();
|
|
5
|
+
/**
|
|
6
|
+
* Add an event handler.
|
|
7
|
+
* @param {string} eventName - the event to handle.
|
|
8
|
+
* @param {Function} eventHandler - the event handler function.
|
|
9
|
+
*/
|
|
10
|
+
on: (eventName: string, eventHandler: (...args: any[]) => void) => void;
|
|
11
|
+
/**
|
|
12
|
+
* Emit an event.
|
|
13
|
+
* @param {string} eventName - the event to emit.
|
|
14
|
+
* @param ...params - parameters to pass to the event handlers.
|
|
15
|
+
*/
|
|
16
|
+
emit: (eventName: string, ...params: any[]) => void;
|
|
17
|
+
/**
|
|
18
|
+
* Remove an event handler.
|
|
19
|
+
* @param {string} eventName - the event to remove a handler from.
|
|
20
|
+
* @param {Function} eventHandler - the event handler function to remove.
|
|
21
|
+
*/
|
|
22
|
+
off: (eventName: string, eventHandler: (...args: any[]) => void) => void;
|
|
23
|
+
}
|
|
24
|
+
export default EventEmitter;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { default as EventEmitter } from './event-emitter';
|
|
2
|
+
import { LonLat, Projection, ServerLogger, GpsOptions } from '../types/locar';
|
|
3
|
+
import * as THREE from "three";
|
|
4
|
+
/** The main engine class for the LocAR.js system.
|
|
5
|
+
* Can be obtained either via App.start() - which resolves with a LocAR object - or on its own.
|
|
6
|
+
* If you use this class without App, you must set up the three.js scene yourself, as you did with locar.js 0.1.x.
|
|
7
|
+
*/
|
|
8
|
+
declare class LocAR extends EventEmitter {
|
|
9
|
+
#private;
|
|
10
|
+
scene: THREE.Scene;
|
|
11
|
+
camera: THREE.Camera;
|
|
12
|
+
/**
|
|
13
|
+
* @param {THREE.Scene} scene - The Three.js scene to use.
|
|
14
|
+
* @param {THREE.Camera} camera - The Three.js camera to use. Should usually
|
|
15
|
+
* be a THREE.PerspectiveCamera.
|
|
16
|
+
* @param {Object} options - Initialisation options for the GPS; see
|
|
17
|
+
* setGpsOptions() below.
|
|
18
|
+
* @param {Object} serverLogger - an object which can optionally log GPS position to a server for debugging. null by default, so no logging will be done. This object should implement a sendData() method to send data (2nd arg) to a given endpoint (1st arg). Please see source code for details. Ensure you comply with privacy laws (GDPR or equivalent) if implementing this.
|
|
19
|
+
*/
|
|
20
|
+
constructor(scene: THREE.Scene, camera: THREE.Camera, options?: GpsOptions, serverLogger?: ServerLogger | null, projection?: Projection);
|
|
21
|
+
/**
|
|
22
|
+
* Set the projection to use.
|
|
23
|
+
* @param {Object} any object which includes a project() method
|
|
24
|
+
* taking longitude and latitude as arguments and returning an array
|
|
25
|
+
* containing easting and northing.
|
|
26
|
+
*/
|
|
27
|
+
setProjection(proj: Projection): void;
|
|
28
|
+
/**
|
|
29
|
+
* Set the GPS options.
|
|
30
|
+
* @param {Object} object containing gpsMinDistance and/or gpsMinAccuracy
|
|
31
|
+
* properties. The former specifies the number of metres which the device
|
|
32
|
+
* must move to process a new GPS reading, and the latter specifies the
|
|
33
|
+
* minimum accuracy, in metres, for a GPS reading to be counted.
|
|
34
|
+
*/
|
|
35
|
+
setGpsOptions(options?: GpsOptions): void;
|
|
36
|
+
/**
|
|
37
|
+
* Start the GPS on a real device
|
|
38
|
+
* @return {boolean} code indicating whether the GPS was started successfully.
|
|
39
|
+
* GPS errors can be handled by handling the gpserror event.
|
|
40
|
+
*/
|
|
41
|
+
startGps(): Promise<boolean>;
|
|
42
|
+
/**
|
|
43
|
+
* Stop the GPS on a real device
|
|
44
|
+
* @return {boolean} true if the GPS was stopped, false if it could not be
|
|
45
|
+
* stopped (i.e. it was never started).
|
|
46
|
+
*/
|
|
47
|
+
stopGps(): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Send a fake GPS signal. Useful for testing on a desktop or laptop.
|
|
50
|
+
* @param {number} lon - The longitude.
|
|
51
|
+
* @param {number} lat - The latitude.
|
|
52
|
+
* @param {number} elev - The elevation in metres. (optional, set to null
|
|
53
|
+
* for no elevation).
|
|
54
|
+
* @param {number} acc - The accuracy of the GPS reading in metres. May be
|
|
55
|
+
* ignored if lower than the specified minimum accuracy.
|
|
56
|
+
*/
|
|
57
|
+
fakeGps(lon: number, lat: number, elev?: number | null, acc?: number): void;
|
|
58
|
+
/**
|
|
59
|
+
* Convert longitude and latitude to three.js/WebGL world coordinates.
|
|
60
|
+
* Uses the specified projection, and negates the northing (in typical
|
|
61
|
+
* projections, northings increase northwards, but in the WebGL coordinate
|
|
62
|
+
* system, we face negative z if the camera is at the origin with default
|
|
63
|
+
* rotation).
|
|
64
|
+
* Must not be called until an initial position is determined.
|
|
65
|
+
* @param {number} lon - The longitude.
|
|
66
|
+
* @param {number} lat - The latitude.
|
|
67
|
+
* @return {Array} a two member array containing the WebGL x and z coordinates
|
|
68
|
+
*/
|
|
69
|
+
lonLatToWorldCoords(lon: number, lat: number): [number, number];
|
|
70
|
+
/**
|
|
71
|
+
* Convert projected east/north coordinates to three.js/WebGL world coordinates.
|
|
72
|
+
* Negates the northing (in typical projections, northings increase northwards,
|
|
73
|
+
* but in the WebGL coordinate system, we face negative z if the camera is at
|
|
74
|
+
* the origin with default rotation).
|
|
75
|
+
* Must not be called until an initial position is determined.
|
|
76
|
+
* It is assumed that the projected position is in the correct projection - no check
|
|
77
|
+
* for this is made.
|
|
78
|
+
* @param {Array} projectedPos - the projected position.
|
|
79
|
+
* @return {Array} a two member array containing the WebGL x and z coordinates
|
|
80
|
+
*/
|
|
81
|
+
eastNorthToWorldCoords(projectedPos: [number, number]): [number, number];
|
|
82
|
+
/**
|
|
83
|
+
* Add a new AR object at a given latitude, longitude and elevation.
|
|
84
|
+
* @param {THREE.Mesh} object the object
|
|
85
|
+
* @param {number} lon - the longitude.
|
|
86
|
+
* @param {number} lat - the latitude.
|
|
87
|
+
* @param {number} elev - the elevation in metres
|
|
88
|
+
* (if not specified, 0 is assigned)
|
|
89
|
+
* @param {Object} properties - properties describing the object (for example,
|
|
90
|
+
* the contents of the GeoJSON properties field).
|
|
91
|
+
*/
|
|
92
|
+
add(object: THREE.Object3D, lon: number, lat: number, elev?: number | undefined, properties?: Record<string, any>): void;
|
|
93
|
+
addGeoLine(points: Array<[number, number, number?]>, material: THREE.Material, lineWidth?: number): THREE.Mesh;
|
|
94
|
+
/**
|
|
95
|
+
* Set the elevation (y coordinate) of the camera.
|
|
96
|
+
* @param {number} elev - the elevation in metres.
|
|
97
|
+
*/
|
|
98
|
+
setElevation(elev: number): void;
|
|
99
|
+
/**
|
|
100
|
+
* Calculate haversine distance between two lat/lon pairs.
|
|
101
|
+
*
|
|
102
|
+
* Taken from original A-Frame AR.js location-based components
|
|
103
|
+
*/
|
|
104
|
+
static haversineDist(src: LonLat, dest: LonLat): number;
|
|
105
|
+
/**
|
|
106
|
+
* Obtain the last known GPS location.
|
|
107
|
+
*
|
|
108
|
+
* @return {Object} object containing latitude and longitude fields, or null if no previous GPS location.
|
|
109
|
+
*/
|
|
110
|
+
getLastKnownLocation(): LonLat | null;
|
|
111
|
+
}
|
|
112
|
+
export default LocAR;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { default as App } from './app';
|
|
2
|
+
import { default as LocAR } from './locar';
|
|
3
|
+
import { default as SphMercProjection } from './sphmerc-projection';
|
|
4
|
+
import { default as DeviceOrientationControls } from './device-orientation-controls';
|
|
5
|
+
import { default as ClickHandler } from './click-handler';
|
|
6
|
+
import { default as EventEmitter } from './event-emitter';
|
|
7
|
+
import { default as Webcam } from './webcam';
|
|
8
|
+
export type { LonLat, ServerLogger, WebcamStartedEvent, WebcamErrorEvent, DeviceOrientationErrorEvent, DeviceOrientationGrantedEvent, GpsReceivedEvent, Projection, AppOptions, GpsOptions, DeviceOrientationControlsOptions } from '../types/locar';
|
|
9
|
+
export { App, LocAR, Webcam, SphMercProjection, DeviceOrientationControls, ClickHandler, EventEmitter };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Projection } from '../types/locar';
|
|
2
|
+
declare class SphMercProjection implements Projection {
|
|
3
|
+
#private;
|
|
4
|
+
EARTH: number;
|
|
5
|
+
HALF_EARTH: number;
|
|
6
|
+
/**
|
|
7
|
+
* Create a SphMercProjection.
|
|
8
|
+
*/
|
|
9
|
+
constructor();
|
|
10
|
+
/**
|
|
11
|
+
* Project a longitude and latitude into Spherical Mercator.
|
|
12
|
+
* @param {number} lon - the longitude.
|
|
13
|
+
* @param {number} lat - the latitude.
|
|
14
|
+
* @return {Array} Two-member array containing easting and northing.
|
|
15
|
+
*/
|
|
16
|
+
project: (lon: number, lat: number) => [number, number];
|
|
17
|
+
/**
|
|
18
|
+
* Unproject a Spherical Mercator easting and northing.
|
|
19
|
+
* @param {Array} projected - Two-member array containing easting and northing
|
|
20
|
+
* @return {Array} Two-member array containing longitude and latitude
|
|
21
|
+
*/
|
|
22
|
+
unproject: (projected: [number, number]) => [number, number];
|
|
23
|
+
/**
|
|
24
|
+
* Return the projection's ID.
|
|
25
|
+
* @return {string} The value "epsg:3857".
|
|
26
|
+
*/
|
|
27
|
+
getID: () => string;
|
|
28
|
+
}
|
|
29
|
+
export default SphMercProjection;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { default as EventEmitter } from './event-emitter';
|
|
2
|
+
import * as THREE from "three";
|
|
3
|
+
export type { WebcamStartedEvent, WebcamErrorEvent } from '../types/locar';
|
|
4
|
+
/** Class to setup the webcam. */
|
|
5
|
+
declare class Webcam extends EventEmitter {
|
|
6
|
+
#private;
|
|
7
|
+
sceneWebcam: THREE.Scene;
|
|
8
|
+
/**
|
|
9
|
+
* Create a Webcam.
|
|
10
|
+
* @param constraints {Object} - options to use for initialising the camera.
|
|
11
|
+
* This is the same constraints object as used by standard MediaDevices API.
|
|
12
|
+
* @param {string} videoElementSelector - selector to obtain the HTML video
|
|
13
|
+
* element to render the webcam feed. If a falsy value (e.g. null or
|
|
14
|
+
* undefined), a video element will be created.
|
|
15
|
+
*/
|
|
16
|
+
constructor(constraints?: {
|
|
17
|
+
video: {
|
|
18
|
+
facingMode: string;
|
|
19
|
+
};
|
|
20
|
+
}, videoElementSelector?: string);
|
|
21
|
+
getVideoDimensions(): string;
|
|
22
|
+
/**
|
|
23
|
+
* Free up the resources associated with the Webcam.
|
|
24
|
+
*/
|
|
25
|
+
dispose(): void;
|
|
26
|
+
}
|
|
27
|
+
export default Webcam;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { default as DeviceOrientationControls } from '../three/device-orientation-controls';
|
|
2
|
+
/** Longitude and latitude. */
|
|
3
|
+
export interface LonLat {
|
|
4
|
+
longitude: number;
|
|
5
|
+
latitude: number;
|
|
6
|
+
}
|
|
7
|
+
/** Projection interface, you can create your own custom projection by implementing project() and unproject(). */
|
|
8
|
+
export interface Projection {
|
|
9
|
+
project: (lon: number, lat: number) => [number, number];
|
|
10
|
+
unproject: (projected: [number, number]) => [number, number];
|
|
11
|
+
}
|
|
12
|
+
/** Server logger interface. */
|
|
13
|
+
export interface ServerLogger {
|
|
14
|
+
sendData(endpoint: string, data: any): Promise<Response> | Response;
|
|
15
|
+
}
|
|
16
|
+
/** Generic event. */
|
|
17
|
+
export interface Event {
|
|
18
|
+
}
|
|
19
|
+
/** Event emitted when the webcam starts. */
|
|
20
|
+
export interface WebcamStartedEvent {
|
|
21
|
+
videoWidth: number;
|
|
22
|
+
videoHeight: number;
|
|
23
|
+
}
|
|
24
|
+
/** Event emitted when the webcam encounters an error. */
|
|
25
|
+
export interface WebcamErrorEvent {
|
|
26
|
+
code: string;
|
|
27
|
+
message: string;
|
|
28
|
+
}
|
|
29
|
+
/** Event emitted when device orientation permission has been granted. */
|
|
30
|
+
export interface DeviceOrientationGrantedEvent {
|
|
31
|
+
target: DeviceOrientationControls;
|
|
32
|
+
}
|
|
33
|
+
/** Event emitted when there is an error with device orientation. */
|
|
34
|
+
export interface DeviceOrientationErrorEvent {
|
|
35
|
+
code: string;
|
|
36
|
+
message: string;
|
|
37
|
+
}
|
|
38
|
+
/** Event emitted when a GPS position is received. */
|
|
39
|
+
export interface GpsReceivedEvent {
|
|
40
|
+
/** The new GPS position */
|
|
41
|
+
position: GeolocationPosition;
|
|
42
|
+
/** distance moved in metres since last GpsReceivedEvent */
|
|
43
|
+
distMoved: number;
|
|
44
|
+
}
|
|
45
|
+
/** GPS intialisation options. */
|
|
46
|
+
export interface GpsOptions {
|
|
47
|
+
gpsMinDistance?: number;
|
|
48
|
+
gpsMinAccuracy?: number;
|
|
49
|
+
}
|
|
50
|
+
/** Options to pass into DeviceOrientationControls. */
|
|
51
|
+
export type DeviceOrientationControlsOptions = {
|
|
52
|
+
/** smoothingFactor - default 0.2. If too high, AR content movement will lag behind the sensors. If too low, the scene will be jittery. */
|
|
53
|
+
smoothingFactor?: number;
|
|
54
|
+
/** Movement threshold to detect an orientation change (radians). */
|
|
55
|
+
orientationChangeThreshold?: number;
|
|
56
|
+
/** On iOS, enable permission dialog to seek permission to use device orientation through a user gesture. Recommended to set to true */
|
|
57
|
+
enablePermissionDialog?: boolean;
|
|
58
|
+
/** Set iOS-look and feel styling for the permission dialog for device orientation */
|
|
59
|
+
enableStyling?: boolean;
|
|
60
|
+
/** Use a standard confirm dialog rather than a custom element to grant device orientation permissions */
|
|
61
|
+
preferConfirmDialog?: boolean;
|
|
62
|
+
};
|
|
63
|
+
/** Options to pass into the App object. */
|
|
64
|
+
export interface AppOptions {
|
|
65
|
+
/** the three.js camera options to use - note however we specify horizontal, not vertical, field of view */
|
|
66
|
+
cameraOptions?: {
|
|
67
|
+
hFov: number;
|
|
68
|
+
near: number;
|
|
69
|
+
far: number;
|
|
70
|
+
};
|
|
71
|
+
/** the canvas to render the AR scene into (one will be created if omitted) */
|
|
72
|
+
canvas?: HTMLCanvasElement;
|
|
73
|
+
/** GPS options, see GpsOptions documentation for details */
|
|
74
|
+
gpsOptions?: GpsOptions;
|
|
75
|
+
/** Video constraints for Media Devices API */
|
|
76
|
+
videoConstraints?: {
|
|
77
|
+
video: {
|
|
78
|
+
facingMode: string;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
/** Device orientation options for DeviceOrientationControls */
|
|
82
|
+
deviceOrientationOptions?: DeviceOrientationControlsOptions & {
|
|
83
|
+
enabled: boolean;
|
|
84
|
+
};
|
|
85
|
+
/** Projection to use (default: SphMercProjection) */
|
|
86
|
+
projection?: Projection;
|
|
87
|
+
/** Server logger to use - ensure you gain consent from the user if you are doing this, it's usually a Data Protection legal requirement */
|
|
88
|
+
serverLogger?: ServerLogger;
|
|
89
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "locar",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "Location-based AR from AR.js.",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -23,26 +23,20 @@
|
|
|
23
23
|
"makedocs": "typedoc --out docs/api lib/three/main.ts"
|
|
24
24
|
},
|
|
25
25
|
"devDependencies": {
|
|
26
|
-
"@eslint/css": "^
|
|
27
|
-
"@eslint/js": "^
|
|
28
|
-
"@eslint/json": "^0.
|
|
26
|
+
"@eslint/css": "^1.4.0",
|
|
27
|
+
"@eslint/js": "^10.0.1",
|
|
28
|
+
"@eslint/json": "^2.0.1",
|
|
29
29
|
"@types/three": "^0.181.0",
|
|
30
|
-
"
|
|
30
|
+
"esbuild":"^0.28.1",
|
|
31
|
+
"eslint": "^10.8.0",
|
|
31
32
|
"globals": "^16.4.0",
|
|
32
|
-
"typedoc": "^0.28.
|
|
33
|
-
"
|
|
34
|
-
"prettier-eslint": "^16.4.2",
|
|
33
|
+
"typedoc": "^0.28.20",
|
|
34
|
+
"prettier-eslint": "^17.1.1",
|
|
35
35
|
"typescript": "^5.9.3",
|
|
36
|
-
"vite": "^
|
|
37
|
-
"vite-plugin-dts": "^
|
|
36
|
+
"vite": "^8.1.5",
|
|
37
|
+
"vite-plugin-dts": "^5.0.3"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"
|
|
41
|
-
"three": "^0.180.0"
|
|
42
|
-
},
|
|
43
|
-
"overrides" : {
|
|
44
|
-
"prettier-eslint": {
|
|
45
|
-
"minimatch": "$minimatch"
|
|
46
|
-
}
|
|
40
|
+
"three": "^0.181.0"
|
|
47
41
|
}
|
|
48
42
|
}
|