Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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