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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /**
  2. * Augmented Reality demo using the three.js plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. */
  5. (function() {
  6. /**
  7. * Utilities for the Demo
  8. */
  9. class Utils
  10. {
  11. static async loadGLTF(filepath, yAxisIsUp = true)
  12. {
  13. const loader = new THREE.GLTFLoader();
  14. const gltf = await loader.loadAsync(filepath);
  15. // glTF defines +y as up. We expect +z to be up (when XY is the ground plane)
  16. if(yAxisIsUp)
  17. gltf.scene.rotateX(Math.PI / 2);
  18. return gltf;
  19. }
  20. static createAnimationAction(gltf, name = null, loop = THREE.LoopRepeat)
  21. {
  22. const mixer = new THREE.AnimationMixer(gltf.scene);
  23. const clips = gltf.animations;
  24. if(clips.length == 0)
  25. throw new Error('No animation clips');
  26. if(name === null) {
  27. const sortedNames = clips.map(clip => clip.name).sort();
  28. name = sortedNames[0];
  29. }
  30. const clip = THREE.AnimationClip.findByName(clips, name);
  31. const action = mixer.clipAction(clip);
  32. action.loop = loop;
  33. return action;
  34. }
  35. static createImagePlane(imagepath)
  36. {
  37. const texture = new THREE.TextureLoader().load(imagepath);
  38. const geometry = new THREE.PlaneGeometry(1, 1);
  39. const material = new THREE.MeshBasicMaterial({
  40. map: texture,
  41. side: THREE.DoubleSide,
  42. });
  43. const mesh = new THREE.Mesh(geometry, material);
  44. return mesh;
  45. }
  46. static switchToFrontView(ar)
  47. {
  48. // top view is the default
  49. ar.root.rotation.set(-Math.PI / 2, 0, 0);
  50. }
  51. static referenceImageName(ar)
  52. {
  53. if(ar.frame === null)
  54. return null;
  55. for(const result of ar.frame.results) {
  56. if(result.tracker.type == 'image-tracker') {
  57. if(result.trackables.length > 0) {
  58. const trackable = result.trackables[0];
  59. return trackable.referenceImage.name;
  60. }
  61. }
  62. }
  63. return null;
  64. }
  65. }
  66. /**
  67. * Augmented Reality Demo
  68. */
  69. class EnchantedDemo extends ARDemo
  70. {
  71. /**
  72. * Constructor
  73. */
  74. constructor()
  75. {
  76. super();
  77. this._objects = { };
  78. }
  79. /**
  80. * Start the AR session
  81. * @returns {Promise<Session>}
  82. */
  83. async startSession()
  84. {
  85. if(!AR.isSupported()) {
  86. throw new Error(
  87. 'This device is not compatible with this AR experience.\n\n' +
  88. 'User agent: ' + navigator.userAgent
  89. );
  90. }
  91. const tracker = AR.Tracker.ImageTracker();
  92. await tracker.database.add([
  93. {
  94. name: 'mage',
  95. image: document.getElementById('mage')
  96. },
  97. {
  98. name: 'cat',
  99. image: document.getElementById('cat')
  100. }
  101. ]);
  102. const viewport = AR.Viewport({
  103. container: document.getElementById('ar-viewport'),
  104. hudContainer: document.getElementById('ar-hud')
  105. });
  106. const video = document.getElementById('my-video');
  107. const useWebcam = (video === null);
  108. const source = useWebcam ? AR.Source.Camera() : AR.Source.Video(video);
  109. const session = await AR.startSession({
  110. mode: 'immersive',
  111. viewport: viewport,
  112. trackers: [ tracker ],
  113. sources: [ source ],
  114. stats: true,
  115. gizmos: true,
  116. });
  117. const scan = document.getElementById('scan');
  118. tracker.addEventListener('targetfound', event => {
  119. session.gizmos.visible = false;
  120. if(scan)
  121. scan.hidden = true;
  122. this._onTargetFound(event.referenceImage);
  123. });
  124. tracker.addEventListener('targetlost', event => {
  125. session.gizmos.visible = true;
  126. if(scan)
  127. scan.hidden = false;
  128. this._onTargetLost(event.referenceImage);
  129. });
  130. return session;
  131. }
  132. /**
  133. * Initialization
  134. * @param {ARSystem} ar
  135. * @returns {Promise<void>}
  136. */
  137. async init(ar)
  138. {
  139. // Change the point of view. All virtual objects are descendants of
  140. // ar.root, a node that is automatically aligned to the physical scene.
  141. // Adjusting ar.root will adjust all virtual objects.
  142. Utils.switchToFrontView(ar);
  143. ar.root.position.set(0, -0.5, 0);
  144. // initialize objects
  145. this._initLight(ar);
  146. this._initText(ar);
  147. this._initMagicCircle(ar);
  148. await Promise.all([
  149. this._initMage(ar),
  150. this._initCat(ar),
  151. ]);
  152. }
  153. /**
  154. * Animation loop
  155. * @param {ARSystem} ar
  156. * @returns {void}
  157. */
  158. update(ar)
  159. {
  160. const delta = ar.session.time.delta; // given in seconds
  161. // animate the objects of the scene
  162. this._animateMagicCircle(delta);
  163. this._animateMage(delta);
  164. this._animateCat(delta);
  165. }
  166. // ------------------------------------------------------------------------
  167. _initLight(ar)
  168. {
  169. const ambientLight = new THREE.AmbientLight(0xffffff);
  170. ambientLight.intensity = 1.5;
  171. ar.scene.add(ambientLight);
  172. }
  173. _initMagicCircle(ar)
  174. {
  175. // create a magic circle
  176. const magicCircle = Utils.createImagePlane('../assets/magic-circle.png');
  177. magicCircle.material.transparent = true;
  178. magicCircle.material.opacity = 1;
  179. magicCircle.scale.set(4, 4, 1);
  180. // make it a child of ar.root
  181. ar.root.add(magicCircle);
  182. // save a reference
  183. this._objects.magicCircle = magicCircle;
  184. }
  185. _initText(ar)
  186. {
  187. const text = Utils.createImagePlane('../assets/it-works.png');
  188. text.material.transparent = true;
  189. text.material.opacity = 1;
  190. text.position.set(0, -0.5, 2);
  191. text.scale.set(3, 1.5, 1);
  192. text.rotateX(Math.PI / 2);
  193. ar.root.add(text);
  194. this._objects.text = text;
  195. }
  196. async _initMage(ar)
  197. {
  198. // load the mage
  199. const gltf = await Utils.loadGLTF('../assets/mage.glb');
  200. const mage = gltf.scene;
  201. mage.scale.set(0.7, 0.7, 0.7);
  202. // prepare the animation of the mage
  203. const mageAction = Utils.createAnimationAction(gltf, 'Idle');
  204. mageAction.play();
  205. // make the mage a child of ar.root
  206. ar.root.add(mage);
  207. // save references
  208. this._objects.mage = mage;
  209. this._objects.mageAction = mageAction;
  210. }
  211. async _initCat(ar)
  212. {
  213. const gltf = await Utils.loadGLTF('../assets/cat.glb');
  214. const cat = gltf.scene;
  215. cat.scale.set(0.7, 0.7, 0.7);
  216. const catAction = Utils.createAnimationAction(gltf, 'Cheer');
  217. catAction.play();
  218. ar.root.add(cat);
  219. this._objects.cat = cat;
  220. this._objects.catAction = catAction;
  221. }
  222. _animate(action, delta)
  223. {
  224. const mixer = action.getMixer();
  225. mixer.update(delta);
  226. }
  227. _animateMage(delta)
  228. {
  229. this._animate(this._objects.mageAction, delta);
  230. }
  231. _animateCat(delta)
  232. {
  233. this._animate(this._objects.catAction, delta);
  234. }
  235. _animateMagicCircle(delta)
  236. {
  237. const TWO_PI = 2.0 * Math.PI;
  238. const ROTATIONS_PER_SECOND = 1.0 / 8.0;
  239. this._objects.magicCircle.rotateZ(-TWO_PI * ROTATIONS_PER_SECOND * delta);
  240. }
  241. _onTargetFound(referenceImage)
  242. {
  243. // change the scene based on the tracked image
  244. switch(referenceImage.name) {
  245. case 'mage':
  246. this._objects.mage.visible = true;
  247. this._objects.cat.visible = false;
  248. this._objects.text.visible = false;
  249. this._objects.magicCircle.material.color.set(0xbeefff);
  250. break;
  251. case 'cat':
  252. this._objects.mage.visible = false;
  253. this._objects.cat.visible = true;
  254. this._objects.text.visible = true;
  255. this._objects.magicCircle.material.color.set(0xffffaa);
  256. break;
  257. }
  258. }
  259. _onTargetLost(referenceImage)
  260. {
  261. }
  262. }
  263. /**
  264. * Start the Demo
  265. * @returns {void}
  266. */
  267. function main()
  268. {
  269. const demo = new EnchantedDemo();
  270. if(typeof encantar === 'undefined')
  271. throw new Error(`Can't find the three.js plugin for encantar.js`);
  272. encantar(demo).catch(error => {
  273. alert(error.message);
  274. });
  275. }
  276. document.addEventListener('DOMContentLoaded', main);
  277. })();