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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. tracker.addEventListener('targetfound', event => {
  61. session.gizmos.visible = false;
  62. if(scan)
  63. scan.hidden = true;
  64. this._onTargetFound(event.referenceImage);
  65. });
  66. tracker.addEventListener('targetlost', event => {
  67. session.gizmos.visible = true;
  68. if(scan)
  69. scan.hidden = false;
  70. this._onTargetLost(event.referenceImage);
  71. });
  72. return session;
  73. }
  74. /**
  75. * Preload resources before starting the AR session
  76. * @returns {Promise<void>}
  77. */
  78. preload()
  79. {
  80. console.log('Preloading assets...');
  81. return this._assetManager.preload([
  82. '../assets/mage.glb',
  83. '../assets/cat.glb',
  84. '../assets/magic-circle.png',
  85. '../assets/it-works.png',
  86. ]);
  87. }
  88. /**
  89. * Initialization
  90. * @returns {Promise<void>}
  91. */
  92. async init()
  93. {
  94. // Do not automatically play an animation when loading GLTF models
  95. BABYLON.SceneLoader.OnPluginActivatedObservable.add(loader => {
  96. if(loader.name == 'gltf') {
  97. loader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  98. }
  99. });
  100. // Change the point of view - slightly
  101. const ar = this.ar;
  102. ar.root.position.y = -0.8;
  103. // Initialize objects
  104. this._initLight();
  105. this._initText();
  106. this._initMagicCircle();
  107. await Promise.all([
  108. this._initMage(),
  109. this._initCat(),
  110. ]);
  111. // done!
  112. this._initialized = true;
  113. }
  114. /**
  115. * Animation loop
  116. * @returns {void}
  117. */
  118. update()
  119. {
  120. const ar = this.ar;
  121. const delta = ar.session.time.delta; // given in seconds
  122. this._animateMagicCircle(delta);
  123. }
  124. // ------------------------------------------------------------------------
  125. _initLight()
  126. {
  127. const light = new BABYLON.HemisphericLight('light', BABYLON.Vector3.Up());
  128. light.intensity = 1.0;
  129. light.diffuse.set(1, 1, 1);
  130. light.groundColor.set(1, 1, 1);
  131. light.specular.set(0, 0, 0);
  132. }
  133. _initMagicCircle()
  134. {
  135. // create a magic circle
  136. const material = new BABYLON.StandardMaterial('magic-circle-material');
  137. const url = this._assetManager.url('magic-circle.png');
  138. material.diffuseTexture = new BABYLON.Texture(url);
  139. material.diffuseTexture.hasAlpha = true;
  140. material.useAlphaFromDiffuseTexture = true;
  141. material.diffuseColor.set(0, 0, 0);
  142. material.emissiveColor.set(1, 1, 1);
  143. material.unlit = true;
  144. const magicCircle = BABYLON.MeshBuilder.CreatePlane('magic-circle', {
  145. width: 1,
  146. height: 1,
  147. sideOrientation: BABYLON.Mesh.DOUBLESIDE
  148. });
  149. magicCircle.rotation.set(-Math.PI / 2, 0, 0);
  150. magicCircle.scaling.set(4, 4, 1);
  151. magicCircle.material = material;
  152. // make it a child of ar.root
  153. const ar = this.ar;
  154. magicCircle.parent = ar.root;
  155. // save a reference
  156. this._objects.magicCircle = magicCircle;
  157. }
  158. _initText()
  159. {
  160. const material = new BABYLON.StandardMaterial('text-material');
  161. const url = this._assetManager.url('it-works.png');
  162. material.diffuseTexture = new BABYLON.Texture(url);
  163. material.diffuseTexture.hasAlpha = true;
  164. material.useAlphaFromDiffuseTexture = true;
  165. material.diffuseColor.set(0, 0, 0);
  166. material.emissiveColor.set(1, 1, 1);
  167. material.unlit = true;
  168. const text = BABYLON.MeshBuilder.CreatePlane('text', {
  169. width: 1,
  170. height: 1,
  171. sideOrientation: BABYLON.Mesh.DOUBLESIDE
  172. });
  173. text.position.set(0, 2, 0.5);
  174. text.scaling.set(3, 1.5, 1);
  175. text.material = material;
  176. const ar = this.ar;
  177. text.parent = ar.root;
  178. this._objects.text = text;
  179. }
  180. async _initMage()
  181. {
  182. // load the mage
  183. const file = this._assetManager.file('mage.glb');
  184. const gltf = await BABYLON.SceneLoader.ImportMeshAsync('', '', file);
  185. const mage = gltf.meshes[0];
  186. mage.scaling.set(0.7, 0.7, 0.7);
  187. // play an animation
  188. const anim = gltf.animationGroups.find(anim => anim.name == 'Idle');
  189. if(anim)
  190. anim.play(true);
  191. // make the mage a child of ar.root
  192. const ar = this.ar;
  193. mage.parent = ar.root;
  194. // save a reference
  195. this._objects.mage = mage;
  196. }
  197. async _initCat()
  198. {
  199. const file = this._assetManager.file('cat.glb');
  200. const gltf = await BABYLON.SceneLoader.ImportMeshAsync('', '', file);
  201. const cat = gltf.meshes[0];
  202. cat.scaling.set(0.7, 0.7, 0.7);
  203. const anim = gltf.animationGroups.find(anim => anim.name == 'Cheer');
  204. if(anim)
  205. anim.play(true);
  206. const ar = this.ar;
  207. cat.parent = ar.root;
  208. this._objects.cat = cat;
  209. }
  210. _animateMagicCircle(delta)
  211. {
  212. const TWO_PI = 2.0 * Math.PI;
  213. const ROTATIONS_PER_SECOND = 1.0 / 8.0;
  214. this._objects.magicCircle.rotate(BABYLON.Axis.Z, -TWO_PI * ROTATIONS_PER_SECOND * delta);
  215. }
  216. _onTargetFound(referenceImage)
  217. {
  218. // make sure that the scene is initialized
  219. if(!this._initialized) {
  220. alert(`Target \"${referenceImage.name}\" was found, but the 3D scene is not yet initialized!`);
  221. return;
  222. }
  223. // change the scene based on the tracked image
  224. switch(referenceImage.name) {
  225. case 'mage':
  226. this._objects.mage.setEnabled(true);
  227. this._objects.cat.setEnabled(false);
  228. this._objects.text.setEnabled(false);
  229. this._objects.magicCircle.material.emissiveColor.fromHexString('#beefff');
  230. break;
  231. case 'cat':
  232. this._objects.mage.setEnabled(false);
  233. this._objects.cat.setEnabled(true);
  234. this._objects.text.setEnabled(true);
  235. this._objects.magicCircle.material.emissiveColor.fromHexString('#ffffaa');
  236. break;
  237. }
  238. }
  239. _onTargetLost(referenceImage)
  240. {
  241. }
  242. }
  243. /**
  244. * Start the Demo
  245. * @returns {void}
  246. */
  247. function main()
  248. {
  249. const demo = new EnchantedDemo();
  250. if(typeof encantar === 'undefined')
  251. throw new Error(`Can't find the babylon.js plugin for encantar.js`);
  252. encantar(demo).catch(error => {
  253. alert(error.message);
  254. });
  255. }
  256. document.addEventListener('DOMContentLoaded', main);
  257. })();