You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

demo.js 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /**
  2. * Augmented Reality demo using the babylon.js plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. */
  5. (function() {
  6. /**
  7. * Augmented Reality Demo
  8. */
  9. class EnchantedDemo extends ARDemo
  10. {
  11. /**
  12. * Constructor
  13. */
  14. constructor()
  15. {
  16. super();
  17. this._assetManager = new AssetManager();
  18. this._objects = { };
  19. this._initialized = false;
  20. }
  21. /**
  22. * Start the AR session
  23. * @returns {Promise<Session>}
  24. */
  25. async startSession()
  26. {
  27. if(!AR.isSupported()) {
  28. throw new Error(
  29. 'This device is not compatible with this AR experience.\n\n' +
  30. 'User agent: ' + navigator.userAgent
  31. );
  32. }
  33. const tracker = AR.Tracker.Image();
  34. await tracker.database.add([
  35. {
  36. name: 'mage',
  37. image: document.getElementById('mage')
  38. },
  39. {
  40. name: 'cat',
  41. image: document.getElementById('cat')
  42. }
  43. ]);
  44. const viewport = AR.Viewport({
  45. container: document.getElementById('ar-viewport'),
  46. hudContainer: document.getElementById('ar-hud')
  47. });
  48. const video = document.getElementById('my-video');
  49. const useWebcam = (video === null);
  50. const source = useWebcam ? AR.Source.Camera() : AR.Source.Video(video);
  51. const session = await AR.startSession({
  52. mode: 'immersive',
  53. viewport: viewport,
  54. trackers: [ tracker ],
  55. sources: [ source ],
  56. stats: true,
  57. gizmos: true,
  58. });
  59. const scan = document.getElementById('scan');
  60. if(scan)
  61. scan.style.pointerEvents = 'none';
  62. tracker.addEventListener('targetfound', event => {
  63. session.gizmos.visible = false;
  64. if(scan)
  65. scan.hidden = true;
  66. this._onTargetFound(event.referenceImage);
  67. });
  68. tracker.addEventListener('targetlost', event => {
  69. session.gizmos.visible = true;
  70. if(scan)
  71. scan.hidden = false;
  72. this._onTargetLost(event.referenceImage);
  73. });
  74. return session;
  75. }
  76. /**
  77. * Preload resources before starting the AR session
  78. * @returns {Promise<void>}
  79. */
  80. preload()
  81. {
  82. console.log('Preloading assets...');
  83. return this._assetManager.preload([
  84. '../assets/mage.glb',
  85. '../assets/cat.glb',
  86. '../assets/magic-circle.png',
  87. '../assets/it-works.png',
  88. ], { timeout: 20 });
  89. }
  90. /**
  91. * Initialization
  92. * @returns {Promise<void>}
  93. */
  94. async init()
  95. {
  96. // Do not automatically play an animation when loading GLTF models
  97. BABYLON.SceneLoader.OnPluginActivatedObservable.add(loader => {
  98. if(loader.name == 'gltf') {
  99. loader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  100. }
  101. });
  102. // Change the point of view - slightly
  103. const ar = this.ar;
  104. ar.root.position.y = -0.8;
  105. // Initialize objects
  106. this._initLight();
  107. this._initText();
  108. this._initMagicCircle();
  109. await Promise.all([
  110. this._initMage(),
  111. this._initCat(),
  112. ]);
  113. // done!
  114. this._initialized = true;
  115. }
  116. /**
  117. * Animation loop
  118. * @returns {void}
  119. */
  120. update()
  121. {
  122. const ar = this.ar;
  123. const delta = ar.session.time.delta; // given in seconds
  124. this._animateMagicCircle(delta);
  125. }
  126. // ------------------------------------------------------------------------
  127. _initLight()
  128. {
  129. const light = new BABYLON.HemisphericLight('light', BABYLON.Vector3.Up());
  130. light.intensity = 1.0;
  131. light.diffuse.set(1, 1, 1);
  132. light.groundColor.set(1, 1, 1);
  133. light.specular.set(0, 0, 0);
  134. }
  135. _initMagicCircle()
  136. {
  137. // create a magic circle
  138. const material = new BABYLON.StandardMaterial('magic-circle-material');
  139. const url = this._assetManager.url('magic-circle.png');
  140. material.diffuseTexture = new BABYLON.Texture(url);
  141. material.diffuseTexture.hasAlpha = true;
  142. material.useAlphaFromDiffuseTexture = true;
  143. material.diffuseColor.set(0, 0, 0);
  144. material.emissiveColor.set(1, 1, 1);
  145. material.unlit = true;
  146. const magicCircle = BABYLON.MeshBuilder.CreatePlane('magic-circle', {
  147. width: 1,
  148. height: 1,
  149. sideOrientation: BABYLON.Mesh.DOUBLESIDE
  150. });
  151. magicCircle.rotation.set(-Math.PI / 2, 0, 0);
  152. magicCircle.scaling.set(4, 4, 1);
  153. magicCircle.material = material;
  154. // make it a child of ar.root
  155. const ar = this.ar;
  156. magicCircle.parent = ar.root;
  157. // save a reference
  158. this._objects.magicCircle = magicCircle;
  159. }
  160. _initText()
  161. {
  162. const material = new BABYLON.StandardMaterial('text-material');
  163. const url = this._assetManager.url('it-works.png');
  164. material.diffuseTexture = new BABYLON.Texture(url);
  165. material.diffuseTexture.hasAlpha = true;
  166. material.useAlphaFromDiffuseTexture = true;
  167. material.diffuseColor.set(0, 0, 0);
  168. material.emissiveColor.set(1, 1, 1);
  169. material.unlit = true;
  170. const text = BABYLON.MeshBuilder.CreatePlane('text', {
  171. width: 1,
  172. height: 1,
  173. sideOrientation: BABYLON.Mesh.DOUBLESIDE
  174. });
  175. text.position.set(0, 2, 0.5);
  176. text.scaling.set(3, 1.5, 1);
  177. text.material = material;
  178. const ar = this.ar;
  179. text.parent = ar.root;
  180. this._objects.text = text;
  181. }
  182. async _initMage()
  183. {
  184. // load the mage
  185. const file = this._assetManager.file('mage.glb');
  186. const gltf = await BABYLON.SceneLoader.ImportMeshAsync('', '', file);
  187. const mage = gltf.meshes[0];
  188. mage.scaling.set(0.7, 0.7, 0.7);
  189. // play an animation
  190. const anim = gltf.animationGroups.find(anim => anim.name == 'Idle');
  191. if(anim)
  192. anim.play(true);
  193. // make the mage a child of ar.root
  194. const ar = this.ar;
  195. mage.parent = ar.root;
  196. // save a reference
  197. this._objects.mage = mage;
  198. }
  199. async _initCat()
  200. {
  201. const file = this._assetManager.file('cat.glb');
  202. const gltf = await BABYLON.SceneLoader.ImportMeshAsync('', '', file);
  203. const cat = gltf.meshes[0];
  204. cat.scaling.set(0.7, 0.7, 0.7);
  205. const anim = gltf.animationGroups.find(anim => anim.name == 'Cheer');
  206. if(anim)
  207. anim.play(true);
  208. const ar = this.ar;
  209. cat.parent = ar.root;
  210. this._objects.cat = cat;
  211. }
  212. _animateMagicCircle(delta)
  213. {
  214. const TWO_PI = 2.0 * Math.PI;
  215. const ROTATIONS_PER_SECOND = 1.0 / 8.0;
  216. this._objects.magicCircle.rotate(BABYLON.Axis.Z, -TWO_PI * ROTATIONS_PER_SECOND * delta);
  217. }
  218. _onTargetFound(referenceImage)
  219. {
  220. // make sure that the scene is initialized
  221. if(!this._initialized) {
  222. alert(`Target \"${referenceImage.name}\" was found, but the 3D scene is not yet initialized!`);
  223. return;
  224. }
  225. // change the scene based on the tracked image
  226. switch(referenceImage.name) {
  227. case 'mage':
  228. this._objects.mage.setEnabled(true);
  229. this._objects.cat.setEnabled(false);
  230. this._objects.text.setEnabled(false);
  231. this._objects.magicCircle.material.emissiveColor.fromHexString('#beefff');
  232. break;
  233. case 'cat':
  234. this._objects.mage.setEnabled(false);
  235. this._objects.cat.setEnabled(true);
  236. this._objects.text.setEnabled(true);
  237. this._objects.magicCircle.material.emissiveColor.fromHexString('#ffffaa');
  238. break;
  239. }
  240. }
  241. _onTargetLost(referenceImage)
  242. {
  243. }
  244. }
  245. /**
  246. * Start the Demo
  247. * @returns {void}
  248. */
  249. function main()
  250. {
  251. const demo = new EnchantedDemo();
  252. if(typeof encantar === 'undefined')
  253. throw new Error(`Can't find the babylon.js plugin for encantar.js`);
  254. encantar(demo).catch(error => {
  255. alert(error.message);
  256. });
  257. }
  258. document.addEventListener('DOMContentLoaded', main);
  259. })();