您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

demo.js 9.2KB

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