Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

aframe-with-encantar.js 26KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. /**
  2. * A-Frame plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. * @license LGPL-3.0-or-later
  5. */
  6. (function() {
  7. /* Usage of the indicated versions is encouraged */
  8. __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__({
  9. 'encantar.js': { version: '0.4.0' },
  10. 'A-Frame': { version: '1.4.2' }
  11. });
  12. /**
  13. * AR Base System
  14. * @mixin ARBaseSystem
  15. */
  16. const ARBaseSystem = () => ({
  17. /**
  18. * AR Session
  19. * @type {Session | null}
  20. */
  21. session: null,
  22. /**
  23. * Current frame: an object holding data to augment the physical scene.
  24. * If the AR scene is not initialized, this will be null.
  25. * @type {Frame | null}
  26. */
  27. frame: null,
  28. /**
  29. * AR Viewer
  30. * @type {Viewer | null}
  31. */
  32. viewer: null,
  33. /**
  34. * Pointer-based input (current frame)
  35. * Make sure to add a PointerTracker to your session in order to use these
  36. * @returns {TrackablePointer[]}
  37. */
  38. pointers: [],
  39. /**
  40. * Convert an AR Vector2 to a THREE Vector2
  41. * @param {Vector2} v
  42. * @returns {THREE.Vector2}
  43. */
  44. convertVector2(v)
  45. {
  46. return new THREE.Vector2(v.x, v.y);
  47. },
  48. /**
  49. * Convert an AR Vector3 to a THREE Vector3
  50. * @param {Vector3} v
  51. * @returns {THREE.Vector3}
  52. */
  53. convertVector3(v)
  54. {
  55. return new THREE.Vector3(v.x, v.y, v.z);
  56. },
  57. /**
  58. * Convert an AR Quaternion to a THREE Quaternion
  59. * @param {Quaternion} q
  60. * @returns {THREE.Quaternion}
  61. */
  62. convertQuaternion(q)
  63. {
  64. return new THREE.Quaternion(q.x, q.y, q.z, q.w);
  65. },
  66. /**
  67. * Convert an AR Ray to a THREE Ray
  68. * @param {Ray} r
  69. * @returns {THREE.Ray}
  70. */
  71. convertRay(r)
  72. {
  73. const origin = this.convertVector3(r.origin);
  74. const direction = this.convertVector3(r.direction);
  75. return new THREE.Ray(origin, direction);
  76. },
  77. });
  78. /**
  79. * AR Utilities
  80. */
  81. const ARUtils = () => ({
  82. findTrackedImage(frame, name = '')
  83. {
  84. if(frame === null)
  85. return null;
  86. for(const result of frame.results) {
  87. if(result.tracker.type == 'image-tracker') {
  88. for(const trackable of result.trackables) {
  89. if(name === '' || name === trackable.referenceImage.name) {
  90. return {
  91. projectionMatrix: result.viewer.view.projectionMatrix,
  92. viewMatrixInverse: result.viewer.pose.transform.matrix,
  93. modelMatrix: trackable.pose.transform.matrix,
  94. };
  95. }
  96. }
  97. }
  98. }
  99. return null;
  100. },
  101. findViewer(frame)
  102. {
  103. if(frame === null)
  104. return null;
  105. for(const result of frame.results) {
  106. if(result.tracker.type == 'image-tracker') {
  107. if(result.trackables.length > 0)
  108. return result.viewer;
  109. }
  110. }
  111. return null;
  112. },
  113. findTrackablePointers(frame)
  114. {
  115. if(frame === null)
  116. return [];
  117. for(const result of frame.results) {
  118. if(result.tracker.type == 'pointer-tracker')
  119. return result.trackables;
  120. }
  121. return [];
  122. },
  123. });
  124. /* ========================================================================= */
  125. /**
  126. * AR System
  127. * @name ARSystem
  128. * @type {object}
  129. * @mixes ARBaseSystem
  130. */
  131. AFRAME.registerSystem('ar', Object.assign(ARBaseSystem(), {
  132. // el;
  133. // data;
  134. // schema;
  135. _utils: ARUtils(),
  136. _started: false,
  137. _components: [],
  138. _roots: [],
  139. init()
  140. {
  141. const scene = this.el;
  142. // validate
  143. if(!scene.getAttribute('ar-session')) {
  144. scene.setAttribute('ar-session', {}); // use a default ar-session
  145. //throw new Error('Missing ar-session in a-scene'); // other errors will appear
  146. }
  147. // initial setup
  148. scene.setAttribute('vr-mode-ui', { enabled: false });
  149. scene.setAttribute('embedded', true);
  150. scene.setAttribute('renderer', { alpha: true });
  151. // pause the scene until we're ready
  152. scene.addEventListener('ar-started', () => {
  153. scene.play();
  154. });
  155. scene.addEventListener('loaded', () => {
  156. //scene.pause();
  157. Promise.resolve().then(() => scene.pause());
  158. });
  159. /*
  160. // we take control of the rendering
  161. scene.addEventListener('loaded', () => {
  162. scene.renderer.setAnimationLoop(null);
  163. });
  164. */
  165. },
  166. tick()
  167. {
  168. const scene = this.el;
  169. // we take control of the rendering
  170. scene.renderer.setAnimationLoop(null);
  171. // manually update the roots
  172. for(let i = 0; i < this._roots.length; i++)
  173. this._roots[i].teek();
  174. },
  175. startSession()
  176. {
  177. if(this._started)
  178. throw new Error('Can\'t start an AR session twice');
  179. this._started = true;
  180. for(const component of this._components)
  181. component.validate();
  182. return Speedy.Promise.all([
  183. this._loadSources(),
  184. this._loadTrackers(),
  185. this._loadViewport(),
  186. this._loadPreferences(),
  187. ])
  188. .then(([
  189. sources,
  190. trackers,
  191. viewport,
  192. preferences,
  193. ]) => AR.startSession(
  194. Object.assign({}, preferences, {
  195. sources,
  196. trackers,
  197. viewport
  198. })
  199. ))
  200. .then(session => {
  201. // setup
  202. this.session = session;
  203. this._configureSession();
  204. this._startAnimationLoop();
  205. // we're done!
  206. const scene = this.el;
  207. scene.emit('ar-started', { ar: this });
  208. return session;
  209. })
  210. .catch(error => {
  211. console.error(error);
  212. throw error;
  213. });
  214. },
  215. register(component)
  216. {
  217. this._register(this._components, component);
  218. },
  219. unregister(component)
  220. {
  221. this._unregister(this._components, component);
  222. },
  223. registerRoot(component)
  224. {
  225. this._register(this._roots, component);
  226. },
  227. unregisterRoot(component)
  228. {
  229. this._unregister(this._roots, component);
  230. },
  231. _register(arr, component)
  232. {
  233. const j = arr.indexOf(component);
  234. if(j < 0)
  235. arr.push(component);
  236. },
  237. _unregister(arr, component)
  238. {
  239. const j = arr.indexOf(component);
  240. if(j >= 0)
  241. arr.splice(j, 1);
  242. },
  243. _configureSession()
  244. {
  245. const scene = this.el;
  246. const session = this.session;
  247. if(session.viewport.canvas !== scene.canvas) {
  248. session.end();
  249. throw new Error('Invalid A-Frame canvas');
  250. }
  251. session.addEventListener('end', () => {
  252. this.viewer = null;
  253. this.frame = null;
  254. this.pointers.length = 0;
  255. });
  256. session.viewport.addEventListener('resize', () => {
  257. // timeout : internals of aframe (a-scene.js)
  258. setTimeout(() => this._resize(), 200);
  259. this._resize();
  260. });
  261. this._resize(); // initial setup
  262. },
  263. _startAnimationLoop()
  264. {
  265. const scene = this.el;
  266. const session = this.session;
  267. scene.object3D.background = null;
  268. // animation loop
  269. const animate = (time, frame) => {
  270. this.frame = frame;
  271. this.viewer = this._utils.findViewer(frame);
  272. this._updateTrackablePointers();
  273. scene.render();
  274. session.requestAnimationFrame(animate);
  275. };
  276. session.requestAnimationFrame(animate);
  277. },
  278. _resize()
  279. {
  280. const scene = this.el;
  281. const size = this.session.viewport.virtualSize;
  282. scene.renderer.setPixelRatio(1.0);
  283. scene.renderer.setSize(size.width, size.height, false);
  284. },
  285. _loadTrackers()
  286. {
  287. const scene = this.el;
  288. const groups = Array.from(
  289. scene.querySelectorAll('[ar-trackers]'),
  290. el => el.components['ar-trackers']
  291. );
  292. if(groups.length > 1)
  293. throw new Error('Can\'t define multiple groups of ar-trackers');
  294. else if(groups.length == 0)
  295. throw new Error('Missing ar-trackers');
  296. return groups[0].trackers();
  297. },
  298. _loadSources()
  299. {
  300. const scene = this.el;
  301. const groups = Array.from(
  302. scene.querySelectorAll('[ar-sources]'),
  303. el => el.components['ar-sources']
  304. );
  305. if(groups.length > 1)
  306. throw new Error('Can\'t define multiple groups of ar-sources');
  307. else if(groups.length == 0)
  308. throw new Error('Missing ar-sources');
  309. return groups[0].sources();
  310. },
  311. _loadViewport()
  312. {
  313. const scene = this.el;
  314. const viewports = Array.from(
  315. scene.querySelectorAll('[ar-viewport]'),
  316. el => el.components['ar-viewport']
  317. );
  318. if(viewports.length > 1)
  319. throw new Error('Can\'t define multiple ar-viewport\'s');
  320. else if(viewports.length == 0)
  321. throw new Error('Missing ar-viewport');
  322. return viewports[0].viewport();
  323. },
  324. _loadPreferences()
  325. {
  326. const scene = this.el;
  327. const sessionComponent = scene.components['ar-session'];
  328. if(sessionComponent === undefined)
  329. throw new Error('Missing ar-session in a-scene');
  330. return sessionComponent.preferences();
  331. },
  332. _updateTrackablePointers()
  333. {
  334. this.pointers.length = 0;
  335. const newPointers = this._utils.findTrackablePointers(this.frame);
  336. if(newPointers.length > 0)
  337. this.pointers.push.apply(this.pointers, newPointers);
  338. },
  339. }));
  340. /**
  341. * AR Component
  342. * @mixin ARComponent
  343. */
  344. const ARComponent = obj => Object.assign({}, obj, {
  345. // el;
  346. // data;
  347. // id;
  348. init()
  349. {
  350. Object.defineProperty(this, 'ar', {
  351. get: function() { return this.el.sceneEl.systems.ar; }
  352. });
  353. this.ar.register(this);
  354. if(obj.init !== undefined)
  355. obj.init.call(this);
  356. if(this.el.sceneEl.hasLoaded)
  357. this.validate();
  358. },
  359. remove()
  360. {
  361. if(obj.remove !== undefined)
  362. obj.remove.call(this);
  363. this.ar.unregister(this);
  364. },
  365. validate()
  366. {
  367. if(obj.validate !== undefined)
  368. obj.validate.call(this);
  369. }
  370. });
  371. /**
  372. * AR Session
  373. */
  374. AFRAME.registerComponent('ar-session', ARComponent({
  375. schema: {
  376. /** session mode: "immersive" | "inline" */
  377. 'mode': { type: 'string', default: 'immersive' },
  378. /** show stats panel? */
  379. 'stats': { type: 'boolean', default: false },
  380. /** show gizmos? */
  381. 'gizmos': { type: 'boolean', default: false },
  382. /** start the session automatically? */
  383. 'autoplay': { type: 'boolean', default: true },
  384. },
  385. sceneOnly: true,
  386. _started: false,
  387. init()
  388. {
  389. this._started = false;
  390. },
  391. play()
  392. {
  393. // start the session (run once)
  394. if(!this._started) {
  395. this._started = true;
  396. if(this.data.autoplay)
  397. this.startSession();
  398. }
  399. },
  400. remove()
  401. {
  402. // end the session
  403. if(this.ar.session !== null)
  404. this.ar.session.end();
  405. },
  406. preferences()
  407. {
  408. return {
  409. mode: this.data.mode,
  410. stats: this.data.stats,
  411. gizmos: this.data.gizmos
  412. };
  413. },
  414. startSession()
  415. {
  416. return this.ar.startSession();
  417. },
  418. }));
  419. /* ========================================================================= */
  420. /**
  421. * AR Camera
  422. */
  423. AFRAME.registerComponent('ar-camera', ARComponent({
  424. dependencies: ['camera'],
  425. init()
  426. {
  427. const el = this.el;
  428. el.setAttribute('camera', { active: true });
  429. el.setAttribute('wasd-controls', { enabled: false });
  430. el.setAttribute('look-controls', { enabled: false });
  431. el.setAttribute('position', { x: 0, y: 0, z: 0 }); // A-Frame sets y = 1.6m for VR
  432. const camera = el.getObject3D('camera');
  433. camera.matrixAutoUpdate = false;
  434. },
  435. tick()
  436. {
  437. const ar = this.ar;
  438. const el = this.el;
  439. const tracked = ar._utils.findTrackedImage(ar.frame);
  440. if(tracked === null)
  441. return;
  442. const camera = el.getObject3D('camera');
  443. camera.projectionMatrix.fromArray(tracked.projectionMatrix.read());
  444. camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
  445. camera.matrix.fromArray(tracked.viewMatrixInverse.read());
  446. camera.updateMatrixWorld(true);
  447. //console.log('projectionMatrix', tracked.projectionMatrix.read());
  448. //console.log('viewMatrixInverse', tracked.viewMatrixInverse.read());
  449. },
  450. validate()
  451. {
  452. if(!this.el.getAttribute('camera'))
  453. throw new Error('Incorrect ar-camera');
  454. if(this.el.parentNode !== this.el.sceneEl)
  455. throw new Error('ar-camera must be a direct child of a-scene');
  456. },
  457. }));
  458. AFRAME.registerPrimitive('ar-camera', {
  459. defaultComponents: {
  460. 'ar-camera': {},
  461. 'camera': {}
  462. }
  463. });
  464. /**
  465. * AR Root node
  466. */
  467. AFRAME.registerComponent('ar-root', ARComponent({
  468. schema: {
  469. /** the name of a reference image (target) or the empty string (to match any target) */
  470. 'referenceImage': { type: 'string', default: '' },
  471. },
  472. _origin: null,
  473. _firstRun: true,
  474. init()
  475. {
  476. const origin = new THREE.Group();
  477. origin.matrixAutoUpdate = false;
  478. const root = this.el.object3D;
  479. root.parent.add(origin);
  480. origin.add(root);
  481. this._origin = origin;
  482. this._firstRun = true;
  483. this.ar.registerRoot(this);
  484. },
  485. remove()
  486. {
  487. const origin = this._origin;
  488. const root = this.el.object3D;
  489. origin.parent.add(root);
  490. origin.removeFromParent();
  491. this._origin = null;
  492. this.ar.unregisterRoot(this);
  493. },
  494. play()
  495. {
  496. const origin = this._origin;
  497. origin.visible = true;
  498. if(this._firstRun) {
  499. this._firstRun = false;
  500. origin.visible = false;
  501. this.el.pause();
  502. }
  503. },
  504. pause()
  505. {
  506. const origin = this._origin;
  507. origin.visible = false;
  508. },
  509. teek()
  510. {
  511. const ar = this.ar;
  512. const targetName = this.data.referenceImage;
  513. const tracked = ar._utils.findTrackedImage(ar.frame, targetName);
  514. if(tracked === null) {
  515. this.el.pause();
  516. return;
  517. }
  518. const origin = this._origin;
  519. origin.matrix.fromArray(tracked.modelMatrix.read());
  520. origin.updateMatrixWorld(true);
  521. this.el.play();
  522. //console.log('modelMatrix', tracked.modelMatrix.toString());
  523. },
  524. validate()
  525. {
  526. if(this.el.parentNode !== this.el.sceneEl)
  527. throw new Error('ar-root must be a direct child of a-scene');
  528. },
  529. }));
  530. AFRAME.registerPrimitive('ar-root', {
  531. defaultComponents: {
  532. 'ar-root': {}
  533. },
  534. mappings: {
  535. 'reference-image': 'ar-root.referenceImage'
  536. }
  537. });
  538. /* ========================================================================= */
  539. /**
  540. * AR Sources
  541. */
  542. AFRAME.registerComponent('ar-sources', ARComponent({
  543. validate()
  544. {
  545. if(this.el.parentNode !== this.el.sceneEl)
  546. throw new Error('ar-sources must be a direct child of a-scene');
  547. },
  548. sources()
  549. {
  550. const sources = [];
  551. for(const child of this.el.children) {
  552. if(child.components !== undefined) {
  553. for(const name in child.components) {
  554. const component = child.components[name];
  555. if(component.ar === this.ar && typeof component.source == 'function')
  556. sources.push(component.source());
  557. }
  558. }
  559. }
  560. return sources;
  561. },
  562. }));
  563. AFRAME.registerPrimitive('ar-sources', {
  564. defaultComponents: {
  565. 'ar-sources': {}
  566. }
  567. });
  568. /**
  569. * AR Camera Source
  570. */
  571. AFRAME.registerComponent('ar-camera-source', ARComponent({
  572. schema: {
  573. /** video resolution */
  574. 'resolution': { type: 'string', default: 'md' },
  575. /** facing mode: "environment" | "user" */
  576. 'facingMode': { type: 'string', default: 'environment' },
  577. },
  578. validate()
  579. {
  580. if(!this.el.parentNode.getAttribute('ar-sources'))
  581. throw new Error('ar-camera-source must be a direct child of ar-sources');
  582. },
  583. source()
  584. {
  585. return AR.Source.Camera({
  586. resolution: this.data.resolution,
  587. constraints: {
  588. facingMode: this.data.facingMode
  589. }
  590. });
  591. },
  592. }));
  593. AFRAME.registerPrimitive('ar-camera-source', {
  594. defaultComponents: {
  595. 'ar-camera-source': {}
  596. },
  597. mappings: {
  598. 'resolution': 'ar-camera-source.resolution',
  599. 'facing-mode': 'ar-camera-source.facingMode',
  600. }
  601. });
  602. /**
  603. * AR Video Source
  604. */
  605. AFRAME.registerComponent('ar-video-source', ARComponent({
  606. schema: {
  607. /** selector for a <video> element */
  608. 'video': { type: 'selector' },
  609. },
  610. validate()
  611. {
  612. if(!this.el.parentNode.getAttribute('ar-sources'))
  613. throw new Error('ar-video-source must be a direct child of ar-sources');
  614. },
  615. source()
  616. {
  617. return AR.Source.Video(this.data.video);
  618. },
  619. }));
  620. AFRAME.registerPrimitive('ar-video-source', {
  621. defaultComponents: {
  622. 'ar-video-source': {}
  623. },
  624. mappings: {
  625. 'video': 'ar-video-source.video'
  626. }
  627. });
  628. /**
  629. * AR Canvas Source
  630. */
  631. AFRAME.registerComponent('ar-canvas-source', ARComponent({
  632. schema: {
  633. /** selector for a <canvas> element */
  634. 'canvas': { type: 'selector' },
  635. },
  636. validate()
  637. {
  638. if(!this.el.parentNode.getAttribute('ar-sources'))
  639. throw new Error('ar-canvas-source must be a direct child of ar-sources');
  640. },
  641. source()
  642. {
  643. return AR.Source.Canvas(this.data.canvas);
  644. },
  645. }));
  646. AFRAME.registerPrimitive('ar-canvas-source', {
  647. defaultComponents: {
  648. 'ar-canvas-source': {}
  649. },
  650. mappings: {
  651. 'canvas': 'ar-canvas-source.canvas'
  652. }
  653. });
  654. /**
  655. * AR Pointer Source
  656. */
  657. AFRAME.registerComponent('ar-pointer-source', ARComponent({
  658. schema: {
  659. },
  660. validate()
  661. {
  662. if(!this.el.parentNode.getAttribute('ar-sources'))
  663. throw new Error('ar-pointer-source must be a direct child of ar-sources');
  664. },
  665. source()
  666. {
  667. return AR.Source.Pointer();
  668. },
  669. }));
  670. AFRAME.registerPrimitive('ar-pointer-source', {
  671. defaultComponents: {
  672. 'ar-pointer-source': {}
  673. },
  674. mappings: {
  675. }
  676. });
  677. /* ========================================================================= */
  678. /**
  679. * AR Trackers
  680. */
  681. AFRAME.registerComponent('ar-trackers', ARComponent({
  682. validate()
  683. {
  684. if(this.el.parentNode !== this.el.sceneEl)
  685. throw new Error('ar-trackers must be a direct child of a-scene');
  686. },
  687. /* async */ trackers()
  688. {
  689. const trackers = [];
  690. for(const child of this.el.children) {
  691. if(child.components !== undefined) {
  692. for(const name in child.components) {
  693. const component = child.components[name];
  694. if(component.ar === this.ar && typeof component.tracker == 'function')
  695. trackers.push(component.tracker());
  696. }
  697. }
  698. }
  699. return Speedy.Promise.all(trackers);
  700. },
  701. }));
  702. AFRAME.registerPrimitive('ar-trackers', {
  703. defaultComponents: {
  704. 'ar-trackers': {}
  705. }
  706. });
  707. /**
  708. * AR Image Tracker
  709. */
  710. AFRAME.registerComponent('ar-image-tracker', ARComponent({
  711. schema: {
  712. /** resolution of the tracker */
  713. 'resolution': { type: 'string', default: 'sm' },
  714. },
  715. validate()
  716. {
  717. if(!this.el.parentNode.getAttribute('ar-trackers'))
  718. throw new Error('ar-image-tracker must be a direct child of ar-trackers');
  719. },
  720. /* async */ tracker()
  721. {
  722. const tracker = AR.Tracker.ImageTracker();
  723. const referenceImages = [];
  724. tracker.resolution = this.data.resolution;
  725. for(const child of this.el.children) {
  726. if(child.components !== undefined) {
  727. for(const name in child.components) {
  728. const component = child.components[name];
  729. if(component.ar === this.ar && typeof component.referenceImage == 'function')
  730. referenceImages.push(component.referenceImage());
  731. }
  732. }
  733. }
  734. return tracker.database.add(referenceImages).then(() => tracker);
  735. },
  736. }));
  737. AFRAME.registerPrimitive('ar-image-tracker', {
  738. defaultComponents: {
  739. 'ar-image-tracker': {}
  740. }
  741. });
  742. /**
  743. * AR Reference Image
  744. */
  745. AFRAME.registerComponent('ar-reference-image', ARComponent({
  746. schema: {
  747. /** the name of the reference image */
  748. 'name': { type: 'string', default: '' },
  749. /** URL of an image */
  750. 'src': { type: 'string', default: '' }
  751. },
  752. validate()
  753. {
  754. if(!this.el.parentNode.getAttribute('ar-image-tracker'))
  755. throw new Error('ar-reference-image must be a direct child of ar-image-tracker');
  756. },
  757. referenceImage()
  758. {
  759. if(this.data.src == '')
  760. throw new Error('Unspecified src attribute of ar-reference-image');
  761. const img = new Image();
  762. img.src = this.data.src;
  763. return {
  764. name: this.data.name != '' ? this.data.name : undefined,
  765. image: img
  766. };
  767. }
  768. }));
  769. AFRAME.registerPrimitive('ar-reference-image', {
  770. defaultComponents: {
  771. 'ar-reference-image': {}
  772. },
  773. mappings: {
  774. 'name': 'ar-reference-image.name',
  775. 'src': 'ar-reference-image.src'
  776. }
  777. });
  778. /**
  779. * AR Pointer Tracker
  780. */
  781. AFRAME.registerComponent('ar-pointer-tracker', ARComponent({
  782. schema: {
  783. },
  784. validate()
  785. {
  786. if(!this.el.parentNode.getAttribute('ar-trackers'))
  787. throw new Error('ar-pointer-tracker must be a direct child of ar-trackers');
  788. },
  789. tracker()
  790. {
  791. return AR.Tracker.Pointer();
  792. },
  793. }));
  794. AFRAME.registerPrimitive('ar-pointer-tracker', {
  795. defaultComponents: {
  796. 'ar-pointer-tracker': {}
  797. }
  798. });
  799. /* ========================================================================= */
  800. /**
  801. * AR Viewport
  802. */
  803. AFRAME.registerComponent('ar-viewport', ARComponent({
  804. schema: {
  805. /** viewport resolution */
  806. 'resolution': { type: 'string', default: 'lg' },
  807. /** viewport style: "best-fit" | "stretch" | "inline" */
  808. 'style': { type: 'string', default: 'best-fit' },
  809. },
  810. validate()
  811. {
  812. if(this.el.parentNode !== this.el.sceneEl)
  813. throw new Error('ar-viewport must be a direct child of a-scene');
  814. },
  815. viewport()
  816. {
  817. const scene = this.el.sceneEl;
  818. const huds = [];
  819. const fullscreenUI = this.el.components['ar-viewport-fullscreen-ui'];
  820. for(const child of this.el.children) {
  821. if(child.components !== undefined) {
  822. for(const name in child.components) {
  823. const component = child.components[name];
  824. if(component.ar === this.ar && typeof component.hudContainer == 'function')
  825. huds.push(component.hudContainer());
  826. }
  827. }
  828. }
  829. if(huds.length > 1)
  830. throw new Error('Can\'t define multiple ar-hud\'s in an ar-viewport');
  831. else if(huds.length == 0)
  832. huds.push(undefined);
  833. return AR.Viewport(Object.assign(
  834. {
  835. container: this.el,
  836. hudContainer: huds[0],
  837. canvas: scene.canvas,
  838. resolution: this.data.resolution,
  839. style: this.data.style,
  840. },
  841. !fullscreenUI ? {} : { fullscreenUI: fullscreenUI.data.enabled }
  842. ));
  843. },
  844. }));
  845. AFRAME.registerPrimitive('ar-viewport', {
  846. defaultComponents: {
  847. 'ar-viewport': {}
  848. },
  849. mappings: {
  850. 'resolution': 'ar-viewport.resolution',
  851. 'style': 'ar-viewport.style',
  852. 'fullscreen-ui': 'ar-viewport-fullscreen-ui'
  853. }
  854. });
  855. AFRAME.registerComponent('ar-viewport-fullscreen-ui', ARComponent({
  856. schema: {
  857. /** whether or not to include the built-in fullscreen button */
  858. 'enabled': { type: 'boolean', default: true },
  859. }
  860. }));
  861. /**
  862. * AR Heads-Up Display
  863. */
  864. let hudStyle = (function() { // hide on page load
  865. const style = document.createElement('style');
  866. style.textContent = 'ar-hud, [ar-hud] { display: none; }';
  867. document.head.appendChild(style);
  868. return style;
  869. })();
  870. AFRAME.registerComponent('ar-hud', ARComponent({
  871. init()
  872. {
  873. if(hudStyle !== null) {
  874. document.head.removeChild(hudStyle);
  875. hudStyle = null;
  876. }
  877. this.el.hidden = true;
  878. },
  879. validate()
  880. {
  881. if(!this.el.parentNode.getAttribute('ar-viewport'))
  882. throw new Error('ar-hud must be a direct child of ar-viewport');
  883. },
  884. hudContainer()
  885. {
  886. return this.el;
  887. },
  888. }));
  889. AFRAME.registerPrimitive('ar-hud', {
  890. defaultComponents: {
  891. 'ar-hud': {}
  892. }
  893. });
  894. /* ========================================================================= */
  895. /**
  896. * Version check
  897. * @param {object} libs
  898. */
  899. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  900. {
  901. window.addEventListener('load', () => {
  902. try { AR, AFRAME;
  903. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'A-Frame': AFRAME.version };
  904. 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;
  905. for(const [lib, expected] of Object.entries(libs))
  906. check(lib, expected.version, versionOf[lib]);
  907. }
  908. catch(e) {
  909. alert(e.message);
  910. }
  911. });
  912. }
  913. })();