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 7.6KB

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