Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

demo.js 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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)
  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. return action;
  36. }
  37. 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. switchToFrontView(ar)
  49. {
  50. // top view is the default
  51. ar.root.rotation.set(-Math.PI / 2, 0, 0);
  52. }
  53. referenceImage(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;
  62. }
  63. }
  64. }
  65. return null;
  66. }
  67. referenceImageName(ar)
  68. {
  69. const referenceImage = this.referenceImage(ar);
  70. if(referenceImage === null)
  71. return null;
  72. return referenceImage.name;
  73. }
  74. }
  75. /**
  76. * Demo scene
  77. */
  78. class DemoScene extends ARScene
  79. {
  80. /**
  81. * Constructor
  82. */
  83. constructor()
  84. {
  85. super();
  86. this._utils = new DemoUtils();
  87. this._objects = { };
  88. }
  89. /**
  90. * Start the AR session
  91. * @returns {Promise<Session>}
  92. */
  93. async startSession()
  94. {
  95. if(!AR.isSupported()) {
  96. throw new Error(
  97. 'This device is not compatible with this AR experience.\n\n' +
  98. 'User agent: ' + navigator.userAgent
  99. );
  100. }
  101. const tracker = AR.Tracker.ImageTracker();
  102. await tracker.database.add([{
  103. name: 'my-reference-image',
  104. image: document.getElementById('my-reference-image')
  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 ?
  113. AR.Source.Camera({ resolution: 'md' }) :
  114. AR.Source.Video(video);
  115. const session = await AR.startSession({
  116. mode: 'immersive',
  117. viewport: viewport,
  118. trackers: [ tracker ],
  119. sources: [ source ],
  120. stats: true,
  121. gizmos: true,
  122. });
  123. const scan = document.getElementById('scan');
  124. tracker.addEventListener('targetfound', event => {
  125. session.gizmos.visible = false;
  126. if(scan)
  127. scan.hidden = true;
  128. });
  129. tracker.addEventListener('targetlost', event => {
  130. session.gizmos.visible = true;
  131. if(scan)
  132. scan.hidden = false;
  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. ar.root.scale.set(0.7, 0.7, 0.7);
  149. // add light
  150. const ambientLight = new THREE.AmbientLight(0xffffff);
  151. ambientLight.intensity = 1.5;
  152. ar.scene.add(ambientLight);
  153. // create the magic circle
  154. const magicCircle = this._utils.createImagePlane('../assets/magic-circle.png');
  155. magicCircle.material.color = new THREE.Color(0xbeefff);
  156. magicCircle.material.transparent = true;
  157. magicCircle.material.opacity = 1;
  158. magicCircle.scale.set(6, 6, 1);
  159. ar.root.add(magicCircle);
  160. // load the mage
  161. const gltf = await this._utils.loadGLTF('../assets/mage.glb');
  162. const mage = gltf.scene;
  163. ar.root.add(mage);
  164. // prepare the animation of the mage
  165. const animationAction = this._utils.createAnimationAction(gltf, 'Idle');
  166. animationAction.loop = THREE.LoopRepeat;
  167. animationAction.play();
  168. // save objects
  169. this._objects.mage = mage;
  170. this._objects.magicCircle = magicCircle;
  171. this._objects.animationAction = animationAction;
  172. }
  173. /**
  174. * Update / animate the augmented scene
  175. * @param {ARSystem} ar
  176. * @returns {void}
  177. */
  178. update(ar)
  179. {
  180. const TWO_PI = 2.0 * Math.PI;
  181. const ROTATIONS_PER_SECOND = 0.25;
  182. const delta = ar.session.time.delta; // given in seconds
  183. // animate the mage
  184. const animationAction = this._objects.animationAction;
  185. const mixer = animationAction.getMixer();
  186. mixer.update(delta);
  187. // animate the magic circle
  188. const magicCircle = this._objects.magicCircle;
  189. magicCircle.rotateZ(-TWO_PI * ROTATIONS_PER_SECOND * delta);
  190. }
  191. }
  192. /**
  193. * Enchant the scene
  194. * @returns {void}
  195. */
  196. function main()
  197. {
  198. const scene = new DemoScene();
  199. encantar(scene).catch(error => {
  200. alert(error.message);
  201. });
  202. }
  203. document.addEventListener('DOMContentLoaded', main);
  204. })();