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

demo.js 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /**
  2. * Augmented Reality demo using the three.js plugin for encantar.js
  3. * https://alemart.github.io/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)
  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. const clip = (name !== null) ? THREE.AnimationClip.findByName(clips, name) : clips[0];
  30. const action = mixer.clipAction(clip);
  31. return action;
  32. }
  33. createImagePlane(imagepath)
  34. {
  35. const texture = new THREE.TextureLoader().load(imagepath);
  36. const geometry = new THREE.PlaneGeometry(1, 1);
  37. const material = new THREE.MeshBasicMaterial({
  38. map: texture,
  39. side: THREE.DoubleSide,
  40. });
  41. const mesh = new THREE.Mesh(geometry, material);
  42. return mesh;
  43. }
  44. switchToFrontView(ar)
  45. {
  46. // top view is the default
  47. ar.root.rotation.set(-Math.PI / 2, 0, 0);
  48. }
  49. referenceImage(ar)
  50. {
  51. if(ar.frame === null)
  52. return null;
  53. for(const result of ar.frame.results) {
  54. if(result.tracker.type == 'image-tracker') {
  55. if(result.trackables.length > 0) {
  56. const trackable = result.trackables[0];
  57. return trackable.referenceImage;
  58. }
  59. }
  60. }
  61. return null;
  62. }
  63. }
  64. /**
  65. * Demo scene
  66. */
  67. class DemoScene extends ARScene
  68. {
  69. /**
  70. * Constructor
  71. */
  72. constructor()
  73. {
  74. super();
  75. this._utils = new DemoUtils();
  76. this._objects = { };
  77. }
  78. /**
  79. * Start the AR session
  80. * @returns {Promise<Session>}
  81. */
  82. async startSession()
  83. {
  84. if(!AR.isSupported()) {
  85. throw new Error(
  86. 'This device is not compatible with this AR experience.\n\n' +
  87. 'User agent: ' + navigator.userAgent
  88. );
  89. }
  90. //AR.Settings.powerPreference = 'low-power';
  91. const tracker = AR.Tracker.ImageTracker();
  92. await tracker.database.add([{
  93. name: 'my-reference-image',
  94. image: document.getElementById('my-reference-image')
  95. }]);
  96. const viewport = AR.Viewport({
  97. container: document.getElementById('ar-viewport'),
  98. hudContainer: document.getElementById('ar-hud')
  99. });
  100. const video = document.getElementById('my-video');
  101. const useWebcam = (video === null);
  102. const source = useWebcam ?
  103. AR.Source.Camera({ resolution: 'md' }) :
  104. AR.Source.Video(video);
  105. const session = await AR.startSession({
  106. mode: 'immersive',
  107. viewport: viewport,
  108. trackers: [ tracker ],
  109. sources: [ source ],
  110. stats: true,
  111. gizmos: true,
  112. });
  113. const scan = document.getElementById('scan');
  114. tracker.addEventListener('targetfound', event => {
  115. session.gizmos.visible = false;
  116. if(scan)
  117. scan.hidden = true;
  118. });
  119. tracker.addEventListener('targetlost', event => {
  120. session.gizmos.visible = true;
  121. if(scan)
  122. scan.hidden = false;
  123. });
  124. return session;
  125. }
  126. /**
  127. * Initialize the augmented scene
  128. * @param {ARPluginSystem} ar
  129. * @returns {Promise<void>}
  130. */
  131. async init(ar)
  132. {
  133. // Change the point of view. All virtual objects are descendants of
  134. // ar.root, a node that is automatically aligned to the physical scene.
  135. // Adjusting ar.root will adjust all virtual objects.
  136. this._utils.switchToFrontView(ar);
  137. ar.root.position.set(0, -0.5, 0);
  138. ar.root.scale.set(0.7, 0.7, 0.7);
  139. // add lights
  140. const ambientLight = new THREE.AmbientLight(0xffffff);
  141. ar.scene.add(ambientLight);
  142. const directionalLight = new THREE.DirectionalLight(0xffffff);
  143. directionalLight.position.set(0, 0, 3);
  144. ar.root.add(directionalLight);
  145. // create the magic circle
  146. const magicCircle = this._utils.createImagePlane('../assets/magic-circle.png');
  147. magicCircle.material.color = new THREE.Color(0xbeefff);
  148. magicCircle.material.transparent = true;
  149. magicCircle.material.opacity = 0.85;
  150. magicCircle.scale.set(6, 6, 1);
  151. ar.root.add(magicCircle);
  152. // load the mage
  153. const gltf = await this._utils.loadGLTF('../assets/mage.glb');
  154. const mage = gltf.scene;
  155. ar.root.add(mage);
  156. // prepare the animation of the mage
  157. const animationAction = this._utils.createAnimationAction(gltf);
  158. animationAction.loop = THREE.LoopRepeat;
  159. animationAction.play();
  160. // save objects
  161. this._objects.mage = mage;
  162. this._objects.magicCircle = magicCircle;
  163. this._objects.animationAction = animationAction;
  164. }
  165. /**
  166. * Update / animate the augmented scene
  167. * @param {ARPluginSystem} ar
  168. * @returns {void}
  169. */
  170. update(ar)
  171. {
  172. const TWO_PI = 2.0 * Math.PI;
  173. const ROTATIONS_PER_SECOND = 0.25;
  174. const delta = ar.session.time.delta; // given in seconds
  175. // animate the mage
  176. const animationAction = this._objects.animationAction;
  177. const mixer = animationAction.getMixer();
  178. mixer.update(delta);
  179. // animate the magic circle
  180. const magicCircle = this._objects.magicCircle;
  181. magicCircle.rotateZ(TWO_PI * ROTATIONS_PER_SECOND * delta);
  182. }
  183. }
  184. /**
  185. * Enchant the scene
  186. * @returns {void}
  187. */
  188. function main()
  189. {
  190. const scene = new DemoScene();
  191. encantar(scene);
  192. }
  193. document.addEventListener('DOMContentLoaded', main);
  194. })();