123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170 |
- /*!
- * A-Frame plugin for encantar.js
- * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
- * @license LGPL-3.0-or-later
- */
-
- (function() {
-
- /* Usage of the indicated versions is encouraged */
- __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__({
- 'encantar.js': { version: '0.4.2' },
- 'A-Frame': { version: '1.6.0' }
- });
-
- /**
- * AR Base System
- * @mixin ARBaseSystem
- */
- const ARBaseSystem = () => ({
-
- /**
- * AR Session
- * @type {Session | null}
- */
- session: null,
-
- /**
- * Current frame: an object holding data to augment the physical scene.
- * If the AR scene is not initialized, this will be null.
- * @type {Frame | null}
- */
- frame: null,
-
- /**
- * AR Viewer
- * @type {Viewer | null}
- */
- viewer: null,
-
- /**
- * Pointer-based input (current frame)
- * Make sure to add a PointerTracker to your session in order to use these
- * @type {TrackablePointer[]}
- */
- pointers: [],
-
- /**
- * AR Utilities
- * @type {object}
- */
- utils: {
-
- /**
- * Convert an AR Vector2 to a THREE Vector2
- * @param {Vector2} v
- * @returns {THREE.Vector2}
- */
- convertVector2(v)
- {
- return new THREE.Vector2(v.x, v.y);
- },
-
- /**
- * Convert an AR Vector3 to a THREE Vector3
- * @param {Vector3} v
- * @returns {THREE.Vector3}
- */
- convertVector3(v)
- {
- return new THREE.Vector3(v.x, v.y, v.z);
- },
-
- /**
- * Convert an AR Quaternion to a THREE Quaternion
- * @param {Quaternion} q
- * @returns {THREE.Quaternion}
- */
- convertQuaternion(q)
- {
- return new THREE.Quaternion(q.x, q.y, q.z, q.w);
- },
-
- /**
- * Convert an AR Ray to a THREE Ray
- * @param {Ray} r
- * @returns {THREE.Ray}
- */
- convertRay(r)
- {
- const origin = this.convertVector3(r.origin);
- const direction = this.convertVector3(r.direction);
- return new THREE.Ray(origin, direction);
- },
-
- }
-
- });
-
- /**
- * Internal Utilities
- */
- const Utils = () => ({
-
- findTrackedImage(frame, name = '')
- {
- if(frame === null)
- return null;
-
- for(const result of frame.results) {
- if(result.tracker.type == 'image-tracker') {
- for(const trackable of result.trackables) {
- if(name === '' || name === trackable.referenceImage.name) {
- return {
- projectionMatrix: result.viewer.view.projectionMatrix,
- viewMatrixInverse: result.viewer.pose.transform.matrix,
- modelMatrix: trackable.pose.transform.matrix,
- };
- }
- }
- }
- }
-
- return null;
- },
-
- findViewer(frame)
- {
- if(frame === null)
- return null;
-
- for(const result of frame.results) {
- if(result.tracker.type == 'image-tracker') {
- if(result.trackables.length > 0)
- return result.viewer;
- }
- }
-
- return null;
- },
-
- findTrackablePointers(frame)
- {
- if(frame === null)
- return [];
-
- for(const result of frame.results) {
- if(result.tracker.type == 'pointer-tracker')
- return result.trackables;
- }
-
- return [];
- },
-
- });
-
- /* ========================================================================= */
-
- /**
- * AR System
- * @name ARSystem
- * @type {object}
- * @mixes ARBaseSystem
- */
- AFRAME.registerSystem('ar', Object.assign(ARBaseSystem(), {
-
- // el;
- // data;
- // schema;
-
- _utils: Utils(),
- _started: false,
- _components: [],
- _roots: [],
-
- init()
- {
- const scene = this.el;
-
- // validate
- if(!scene.getAttribute('encantar')) {
- scene.setAttribute('encantar', {}); // use a default encantar
- //throw new Error('Missing encantar in a-scene'); // other errors will appear
- }
-
- // initial setup
- scene.setAttribute('xr-mode-ui', { enabled: false });
- scene.setAttribute('vr-mode-ui', { enabled: false }); // deprecated
- scene.setAttribute('embedded', true);
- scene.setAttribute('renderer', { alpha: true });
-
- // pause the scene until we're ready
- scene.addEventListener('ar-started', () => {
- scene.play();
- });
- scene.addEventListener('loaded', () => {
- //scene.pause();
- Promise.resolve().then(() => scene.pause());
- });
-
- /*
- // we take control of the rendering
- scene.addEventListener('loaded', () => {
- scene.renderer.setAnimationLoop(null);
- });
- */
- },
-
- tick()
- {
- const scene = this.el;
-
- // we take control of the rendering
- scene.renderer.setAnimationLoop(null);
-
- // manually update the roots
- for(let i = 0; i < this._roots.length; i++)
- this._roots[i].teek();
- },
-
- startSession()
- {
- if(this._started)
- throw new Error('Can\'t start an AR session twice');
- this._started = true;
-
- for(const component of this._components)
- component.validate();
-
- return Speedy.Promise.all([
- this._loadSources(),
- this._loadTrackers(),
- this._loadViewport(),
- this._loadPreferences(),
- ])
- .then(([
- sources,
- trackers,
- viewport,
- preferences,
- ]) => AR.startSession(
- Object.assign({}, preferences, {
- sources,
- trackers,
- viewport
- })
- ))
- .then(session => {
- // setup
- this.session = session;
- this._configureSession();
- this._startAnimationLoop();
-
- // we're done!
- const scene = this.el;
- scene.emit('ar-started', { ar: this });
- return session;
- })
- .catch(error => {
- console.error(error);
- throw error;
- });
- },
-
- register(component)
- {
- this._register(this._components, component);
- },
-
- unregister(component)
- {
- this._unregister(this._components, component);
- },
-
- registerRoot(component)
- {
- this._register(this._roots, component);
- },
-
- unregisterRoot(component)
- {
- this._unregister(this._roots, component);
- },
-
- _register(arr, component)
- {
- const j = arr.indexOf(component);
- if(j < 0)
- arr.push(component);
- },
-
- _unregister(arr, component)
- {
- const j = arr.indexOf(component);
- if(j >= 0)
- arr.splice(j, 1);
- },
-
- _configureSession()
- {
- const scene = this.el;
- const session = this.session;
-
- if(session.viewport.canvas !== scene.canvas) {
- session.end();
- throw new Error('Invalid A-Frame canvas');
- }
-
- session.addEventListener('end', () => {
- this.viewer = null;
- this.frame = null;
- this.pointers.length = 0;
- });
-
- session.viewport.addEventListener('resize', () => {
- // timeout : internals of aframe (a-scene.js)
- setTimeout(() => this._resize(), 200);
- this._resize();
- });
-
- this._resize(); // initial setup
- },
-
- _startAnimationLoop()
- {
- const scene = this.el;
- const session = this.session;
-
- scene.object3D.background = null;
-
- // animation loop
- const animate = (time, frame) => {
- this.frame = frame;
- this.viewer = this._utils.findViewer(frame);
- this._updateTrackablePointers();
-
- scene.render();
-
- session.requestAnimationFrame(animate);
- };
-
- session.requestAnimationFrame(animate);
- },
-
- _resize()
- {
- const scene = this.el;
- const size = this.session.viewport.virtualSize;
-
- scene.renderer.setPixelRatio(1.0);
- scene.renderer.setSize(size.width, size.height, false);
- },
-
- _loadTrackers()
- {
- const scene = this.el;
- const groups = Array.from(
- scene.querySelectorAll('[ar-trackers]'),
- el => el.components['ar-trackers']
- );
-
- if(groups.length > 1)
- throw new Error('Can\'t define multiple groups of ar-trackers');
- else if(groups.length == 0)
- throw new Error('Missing ar-trackers');
-
- return groups[0].trackers();
- },
-
- _loadSources()
- {
- const scene = this.el;
- const groups = Array.from(
- scene.querySelectorAll('[ar-sources]'),
- el => el.components['ar-sources']
- );
-
- if(groups.length > 1)
- throw new Error('Can\'t define multiple groups of ar-sources');
- else if(groups.length == 0)
- throw new Error('Missing ar-sources');
-
- return groups[0].sources();
- },
-
- _loadViewport()
- {
- const scene = this.el;
- const viewports = Array.from(
- scene.querySelectorAll('[ar-viewport]'),
- el => el.components['ar-viewport']
- );
-
- if(viewports.length > 1)
- throw new Error('Can\'t define multiple ar-viewport\'s');
- else if(viewports.length == 0)
- throw new Error('Missing ar-viewport');
-
- return viewports[0].viewport();
- },
-
- _loadPreferences()
- {
- const scene = this.el;
- const sessionComponent = scene.components['encantar'];
-
- if(sessionComponent === undefined)
- throw new Error('Missing encantar in a-scene');
-
- return sessionComponent.preferences();
- },
-
- _updateTrackablePointers()
- {
- this.pointers.length = 0;
-
- const newPointers = this._utils.findTrackablePointers(this.frame);
- if(newPointers.length > 0)
- this.pointers.push.apply(this.pointers, newPointers);
- },
-
- }));
-
- /**
- * AR Component
- * @mixin ARComponent
- */
- const ARComponent = obj => Object.assign({}, obj, {
-
- // el;
- // data;
- // id;
-
- init()
- {
- Object.defineProperty(this, 'ar', {
- get: function() { return this.el.sceneEl.systems.ar; }
- });
-
- this.ar.register(this);
-
- if(obj.init !== undefined)
- obj.init.call(this);
-
- if(this.el.sceneEl.hasLoaded)
- this.validate();
- },
-
- remove()
- {
- if(obj.remove !== undefined)
- obj.remove.call(this);
-
- this.ar.unregister(this);
- },
-
- validate()
- {
- if(obj.validate !== undefined)
- obj.validate.call(this);
- }
-
- });
-
- /**
- * The encantar component enchants an a-scene with AR
- * Parameters of the AR scene are set in this component
- */
- AFRAME.registerComponent('encantar', ARComponent({
-
- schema: {
-
- /** session mode: "immersive" | "inline" */
- 'mode': { type: 'string', default: 'immersive' },
-
- /** show stats panel? */
- 'stats': { type: 'boolean', default: false },
-
- /** show gizmos? */
- 'gizmos': { type: 'boolean', default: false },
-
- /** start the session automatically? */
- 'autoplay': { type: 'boolean', default: true },
-
- },
-
- sceneOnly: true,
- _started: false,
-
- init()
- {
- this._started = false;
- },
-
- play()
- {
- // start the session (run once)
- if(!this._started) {
- this._started = true;
- if(this.data.autoplay)
- this.startSession();
- }
- },
-
- remove()
- {
- // end the session
- if(this.ar.session !== null)
- this.ar.session.end();
- },
-
- preferences()
- {
- return {
- mode: this.data.mode,
- stats: this.data.stats,
- gizmos: this.data.gizmos
- };
- },
-
- startSession()
- {
- return this.ar.startSession();
- },
-
- }));
-
- /* ========================================================================= */
-
- /**
- * AR Camera
- */
- AFRAME.registerComponent('ar-camera', ARComponent({
-
- dependencies: ['camera'],
-
- init()
- {
- const el = this.el;
-
- el.setAttribute('camera', { active: true });
- el.setAttribute('wasd-controls', { enabled: false });
- el.setAttribute('look-controls', { enabled: false });
- el.setAttribute('position', { x: 0, y: 0, z: 0 }); // A-Frame sets y = 1.6m for VR
-
- const camera = el.getObject3D('camera');
- camera.matrixAutoUpdate = false;
- },
-
- tick()
- {
- const ar = this.ar;
- const el = this.el;
-
- const tracked = ar._utils.findTrackedImage(ar.frame);
- if(tracked === null)
- return;
-
- const camera = el.getObject3D('camera');
- camera.projectionMatrix.fromArray(tracked.projectionMatrix.read());
- camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
- camera.matrix.fromArray(tracked.viewMatrixInverse.read());
- camera.updateMatrixWorld(true);
-
- //console.log('projectionMatrix', tracked.projectionMatrix.read());
- //console.log('viewMatrixInverse', tracked.viewMatrixInverse.read());
- },
-
- validate()
- {
- if(!this.el.getAttribute('camera'))
- throw new Error('Incorrect ar-camera');
-
- if(this.el.parentNode !== this.el.sceneEl)
- throw new Error('ar-camera must be a direct child of a-scene');
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-camera', {
- defaultComponents: {
- 'ar-camera': {},
- 'camera': {}
- }
- });
-
- /**
- * AR Root node
- */
- AFRAME.registerComponent('ar-root', ARComponent({
-
- schema: {
-
- /** the name of a reference image (target) or the empty string (to match any target) */
- 'referenceImage': { type: 'string', default: '' },
-
- },
-
- _origin: null,
- _firstRun: true,
-
- init()
- {
- const origin = new THREE.Group();
- origin.matrixAutoUpdate = false;
-
- const root = this.el.object3D;
- root.parent.add(origin);
- origin.add(root);
-
- this._origin = origin;
- this._firstRun = true;
-
- this.ar.registerRoot(this);
- },
-
- remove()
- {
- const origin = this._origin;
- const root = this.el.object3D;
-
- origin.parent.add(root);
- origin.removeFromParent();
- this._origin = null;
-
- this.ar.unregisterRoot(this);
- },
-
- play()
- {
- const origin = this._origin;
- origin.visible = true;
-
- if(this._firstRun) {
- this._firstRun = false;
- origin.visible = false;
- this.el.pause();
- }
- },
-
- pause()
- {
- const origin = this._origin;
- origin.visible = false;
- },
-
- teek()
- {
- const ar = this.ar;
- const targetName = this.data.referenceImage;
-
- const tracked = ar._utils.findTrackedImage(ar.frame, targetName);
- if(tracked === null) {
- this.el.pause();
- return;
- }
-
- const origin = this._origin;
- origin.matrix.fromArray(tracked.modelMatrix.read());
- origin.updateMatrixWorld(true);
- this.el.play();
-
- //console.log('modelMatrix', tracked.modelMatrix.toString());
- },
-
- validate()
- {
- if(this.el.parentNode !== this.el.sceneEl)
- throw new Error('ar-root must be a direct child of a-scene');
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-root', {
- defaultComponents: {
- 'ar-root': {}
- },
- mappings: {
- 'reference-image': 'ar-root.referenceImage'
- }
- });
-
- /* ========================================================================= */
-
- /**
- * AR Sources
- */
- AFRAME.registerComponent('ar-sources', ARComponent({
-
- validate()
- {
- if(this.el.parentNode !== this.el.sceneEl)
- throw new Error('ar-sources must be a direct child of a-scene');
- },
-
- sources()
- {
- const sources = [];
-
- for(const child of this.el.children) {
- if(child.components !== undefined) {
- for(const name in child.components) {
- const component = child.components[name];
- if(component.ar === this.ar && typeof component.source == 'function')
- sources.push(component.source());
- }
- }
- }
-
- return sources;
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-sources', {
- defaultComponents: {
- 'ar-sources': {}
- }
- });
-
- /**
- * AR Camera Source
- */
- AFRAME.registerComponent('ar-camera-source', ARComponent({
-
- schema: {
-
- /** video resolution */
- 'resolution': { type: 'string', default: 'md' },
-
- /** facing mode: "environment" | "user" */
- 'facingMode': { type: 'string', default: 'environment' },
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-sources'))
- throw new Error('ar-camera-source must be a direct child of ar-sources');
- },
-
- source()
- {
- return AR.Source.Camera({
- resolution: this.data.resolution,
- constraints: {
- facingMode: this.data.facingMode
- }
- });
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-camera-source', {
- defaultComponents: {
- 'ar-camera-source': {}
- },
- mappings: {
- 'resolution': 'ar-camera-source.resolution',
- 'facing-mode': 'ar-camera-source.facingMode',
- }
- });
-
- /**
- * AR Video Source
- */
- AFRAME.registerComponent('ar-video-source', ARComponent({
-
- schema: {
-
- /** selector for a <video> element */
- 'video': { type: 'selector' },
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-sources'))
- throw new Error('ar-video-source must be a direct child of ar-sources');
- },
-
- source()
- {
- return AR.Source.Video(this.data.video);
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-video-source', {
- defaultComponents: {
- 'ar-video-source': {}
- },
- mappings: {
- 'video': 'ar-video-source.video'
- }
- });
-
- /**
- * AR Canvas Source
- */
- AFRAME.registerComponent('ar-canvas-source', ARComponent({
-
- schema: {
-
- /** selector for a <canvas> element */
- 'canvas': { type: 'selector' },
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-sources'))
- throw new Error('ar-canvas-source must be a direct child of ar-sources');
- },
-
- source()
- {
- return AR.Source.Canvas(this.data.canvas);
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-canvas-source', {
- defaultComponents: {
- 'ar-canvas-source': {}
- },
- mappings: {
- 'canvas': 'ar-canvas-source.canvas'
- }
- });
-
- /**
- * AR Pointer Source
- */
- AFRAME.registerComponent('ar-pointer-source', ARComponent({
-
- schema: {
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-sources'))
- throw new Error('ar-pointer-source must be a direct child of ar-sources');
- },
-
- source()
- {
- return AR.Source.Pointer();
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-pointer-source', {
- defaultComponents: {
- 'ar-pointer-source': {}
- },
- mappings: {
- }
- });
-
- /* ========================================================================= */
-
- /**
- * AR Trackers
- */
- AFRAME.registerComponent('ar-trackers', ARComponent({
-
- validate()
- {
- if(this.el.parentNode !== this.el.sceneEl)
- throw new Error('ar-trackers must be a direct child of a-scene');
- },
-
- /* async */ trackers()
- {
- const trackers = [];
-
- for(const child of this.el.children) {
- if(child.components !== undefined) {
- for(const name in child.components) {
- const component = child.components[name];
- if(component.ar === this.ar && typeof component.tracker == 'function')
- trackers.push(component.tracker());
- }
- }
- }
-
- return Speedy.Promise.all(trackers);
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-trackers', {
- defaultComponents: {
- 'ar-trackers': {}
- }
- });
-
- /**
- * AR Image Tracker
- */
- AFRAME.registerComponent('ar-image-tracker', ARComponent({
-
- schema: {
-
- /** resolution of the tracker */
- 'resolution': { type: 'string', default: 'sm' },
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-trackers'))
- throw new Error('ar-image-tracker must be a direct child of ar-trackers');
- },
-
- /* async */ tracker()
- {
- const tracker = AR.Tracker.Image();
- const referenceImages = [];
-
- tracker.resolution = this.data.resolution;
-
- for(const child of this.el.children) {
- if(child.components !== undefined) {
- for(const name in child.components) {
- const component = child.components[name];
- if(component.ar === this.ar && typeof component.referenceImage == 'function')
- referenceImages.push(component.referenceImage());
- }
- }
- }
-
- return tracker.database.add(referenceImages).then(() => tracker);
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-image-tracker', {
- defaultComponents: {
- 'ar-image-tracker': {}
- }
- });
-
- /**
- * AR Reference Image
- */
- AFRAME.registerComponent('ar-reference-image', ARComponent({
-
- schema: {
-
- /** the name of the reference image */
- 'name': { type: 'string', default: '' },
-
- /** URL of an image */
- 'src': { type: 'string', default: '' }
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-image-tracker'))
- throw new Error('ar-reference-image must be a direct child of ar-image-tracker');
- },
-
- referenceImage()
- {
- if(this.data.src == '')
- throw new Error('Unspecified src attribute of ar-reference-image');
-
- const img = new Image();
- img.crossOrigin = 'anonymous';
- img.src = this.data.src;
-
- return {
- name: this.data.name != '' ? this.data.name : undefined,
- image: img
- };
- }
-
- }));
-
- AFRAME.registerPrimitive('ar-reference-image', {
- defaultComponents: {
- 'ar-reference-image': {}
- },
- mappings: {
- 'name': 'ar-reference-image.name',
- 'src': 'ar-reference-image.src'
- }
- });
-
- /**
- * AR Pointer Tracker
- */
- AFRAME.registerComponent('ar-pointer-tracker', ARComponent({
-
- schema: {
-
- /** the space in which pointers will be located */
- 'space': { type: 'string', default: 'normalized' },
-
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-trackers'))
- throw new Error('ar-pointer-tracker must be a direct child of ar-trackers');
- },
-
- tracker()
- {
- return AR.Tracker.Pointer({
- space: this.data.space
- });
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-pointer-tracker', {
- defaultComponents: {
- 'ar-pointer-tracker': {}
- },
- mappings: {
- 'space': 'ar-pointer-tracker.space'
- }
- });
-
- /* ========================================================================= */
-
- /**
- * AR Viewport
- */
- AFRAME.registerComponent('ar-viewport', ARComponent({
-
- schema: {
-
- /** viewport resolution */
- 'resolution': { type: 'string', default: 'lg' },
-
- /** viewport style: "best-fit" | "stretch" | "inline" */
- 'style': { type: 'string', default: 'best-fit' },
-
- },
-
- validate()
- {
- if(this.el.parentNode !== this.el.sceneEl)
- throw new Error('ar-viewport must be a direct child of a-scene');
- },
-
- viewport()
- {
- const scene = this.el.sceneEl;
- const huds = [];
- const fullscreenUI = this.el.components['ar-viewport-fullscreen-ui'];
-
- for(const child of this.el.children) {
- if(child.components !== undefined) {
- for(const name in child.components) {
- const component = child.components[name];
- if(component.ar === this.ar && typeof component.hudContainer == 'function')
- huds.push(component.hudContainer());
- }
- }
- }
-
- if(huds.length > 1)
- throw new Error('Can\'t define multiple ar-hud\'s in an ar-viewport');
- else if(huds.length == 0)
- huds.push(undefined);
-
- return AR.Viewport(Object.assign(
- {
- container: this.el,
- hudContainer: huds[0],
- canvas: scene.canvas,
- resolution: this.data.resolution,
- style: this.data.style,
- },
- !fullscreenUI ? {} : { fullscreenUI: fullscreenUI.data.enabled }
- ));
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-viewport', {
- defaultComponents: {
- 'ar-viewport': {}
- },
- mappings: {
- 'resolution': 'ar-viewport.resolution',
- 'style': 'ar-viewport.style',
- 'fullscreen-ui': 'ar-viewport-fullscreen-ui'
- }
- });
-
- AFRAME.registerComponent('ar-viewport-fullscreen-ui', ARComponent({
-
- schema: {
-
- /** whether or not to include the built-in fullscreen button */
- 'enabled': { type: 'boolean', default: true },
-
- }
-
- }));
-
- /**
- * AR Heads-Up Display
- */
- let hudStyle = (function() { // hide on page load
- const style = document.createElement('style');
- style.textContent = 'ar-hud, [ar-hud] { display: none; }';
- document.head.appendChild(style);
- return style;
- })();
-
- AFRAME.registerComponent('ar-hud', ARComponent({
-
- init()
- {
- if(hudStyle !== null) {
- document.head.removeChild(hudStyle);
- hudStyle = null;
- }
-
- this.el.hidden = true;
- },
-
- validate()
- {
- if(!this.el.parentNode.getAttribute('ar-viewport'))
- throw new Error('ar-hud must be a direct child of ar-viewport');
- },
-
- hudContainer()
- {
- return this.el;
- },
-
- }));
-
- AFRAME.registerPrimitive('ar-hud', {
- defaultComponents: {
- 'ar-hud': {}
- }
- });
-
- /* ========================================================================= */
-
- /**
- * Version check
- * @param {object} libs
- */
- function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
- {
- window.addEventListener('load', () => {
- try { AR, AFRAME;
- const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'A-Frame': AFRAME.version };
- const check = (x,v,w) => v != w ? console.warn(`\n\n\nWARNING\n\nThis plugin has been tested with ${x} version ${v}. The version in use is ${w}. Usage of ${x} version ${v} is recommended instead.\n\n\n`) : void 0;
- for(const [lib, expected] of Object.entries(libs))
- check(lib, expected.version, versionOf[lib]);
- }
- catch(e) {
- alert(e.message);
- }
- });
- }
-
- })();
|