Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

demo.js 8.5KB

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