您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

aframe-with-encantar.js 24KB

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