Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

three-with-encantar.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /**
  2. * three.js plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. * @license LGPL-3.0-or-later
  5. */
  6. /* Usage of the indicated versions is encouraged */
  7. __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__({
  8. 'encantar.js': { version: '0.4.0' },
  9. 'three.js': { version: '147' }
  10. });
  11. /**
  12. * Base class for Augmented Reality experiences
  13. */
  14. class ARDemo
  15. {
  16. /**
  17. * Start the AR session
  18. * @abstract
  19. * @returns {Promise<Session> | SpeedyPromise<Session>}
  20. */
  21. startSession()
  22. {
  23. throw new Error('Abstract method');
  24. }
  25. /**
  26. * Initialization
  27. * @returns {void | Promise<void> | SpeedyPromise<void>}
  28. * @abstract
  29. */
  30. init()
  31. {
  32. throw new Error('Abstract method');
  33. }
  34. /**
  35. * Animation loop
  36. * @returns {void}
  37. * @abstract
  38. */
  39. update()
  40. {
  41. throw new Error('Abstract method');
  42. }
  43. /**
  44. * Release resources
  45. * @returns {void}
  46. */
  47. release()
  48. {
  49. // optional implementation
  50. }
  51. /**
  52. * Preload resources before starting the AR session
  53. * @returns {Promise<void> | SpeedyPromise<void>}
  54. */
  55. preload()
  56. {
  57. // optional implementation
  58. return Promise.resolve();
  59. }
  60. /**
  61. * A reference to the ARSystem
  62. * @returns {ARSystem | null}
  63. */
  64. get ar()
  65. {
  66. return this._ar;
  67. }
  68. /**
  69. * Constructor
  70. */
  71. constructor()
  72. {
  73. this._ar = null;
  74. }
  75. }
  76. /**
  77. * AR Utilities
  78. */
  79. class ARUtils
  80. {
  81. /**
  82. * Convert an AR Vector2 to a THREE Vector2
  83. * @param {Vector2} v
  84. * @returns {THREE.Vector2}
  85. */
  86. convertVector2(v)
  87. {
  88. return new THREE.Vector2(v.x, v.y);
  89. }
  90. /**
  91. * Convert an AR Vector3 to a THREE Vector3
  92. * @param {Vector3} v
  93. * @returns {THREE.Vector3}
  94. */
  95. convertVector3(v)
  96. {
  97. return new THREE.Vector3(v.x, v.y, v.z);
  98. }
  99. /**
  100. * Convert an AR Quaternion to a THREE Quaternion
  101. * @param {Quaternion} q
  102. * @returns {THREE.Quaternion}
  103. */
  104. convertQuaternion(q)
  105. {
  106. return new THREE.Quaternion(q.x, q.y, q.z, q.w);
  107. }
  108. /**
  109. * Convert an AR Ray to a THREE Ray
  110. * @param {Ray} r
  111. * @returns {THREE.Ray}
  112. */
  113. convertRay(r)
  114. {
  115. const origin = this.convertVector3(r.origin);
  116. const direction = this.convertVector3(r.direction);
  117. return new THREE.Ray(origin, direction);
  118. }
  119. }
  120. /**
  121. * Helper for creating Augmented Reality experiences
  122. */
  123. class ARSystem
  124. {
  125. /**
  126. * AR Session
  127. * @returns {Session}
  128. */
  129. get session()
  130. {
  131. return this._session;
  132. }
  133. /**
  134. * Current frame: an object holding data to augment the physical scene.
  135. * If the AR scene is not initialized, this will be null.
  136. * @returns {Frame | null}
  137. */
  138. get frame()
  139. {
  140. return this._frame;
  141. }
  142. /**
  143. * AR Viewer
  144. * @returns {Viewer | null}
  145. */
  146. get viewer()
  147. {
  148. return this._viewer;
  149. }
  150. /**
  151. * Pointer-based input (current frame)
  152. * Make sure to add a PointerTracker to your session in order to use these
  153. * @returns {TrackablePointer[]}
  154. */
  155. get pointers()
  156. {
  157. return this._pointers;
  158. }
  159. /**
  160. * The root is a node that is automatically aligned to the physical scene.
  161. * Objects of your virtual scene should be descendants of this node.
  162. * @returns {THREE.Group}
  163. */
  164. get root()
  165. {
  166. return this._root;
  167. }
  168. /**
  169. * The three.js scene
  170. * @returns {THREE.Scene}
  171. */
  172. get scene()
  173. {
  174. return this._scene;
  175. }
  176. /**
  177. * A camera that is automatically adjusted for AR
  178. * @returns {THREE.Camera}
  179. */
  180. get camera()
  181. {
  182. return this._camera;
  183. }
  184. /**
  185. * The three.js renderer
  186. * @returns {THREE.WebGLRenderer}
  187. */
  188. get renderer()
  189. {
  190. return this._renderer;
  191. }
  192. /**
  193. * AR Utilities
  194. * @returns {ARUtils}
  195. */
  196. get utils()
  197. {
  198. return this._utils;
  199. }
  200. /**
  201. * Constructor
  202. */
  203. constructor()
  204. {
  205. this._session = null;
  206. this._frame = null;
  207. this._viewer = null;
  208. this._pointers = [];
  209. this._origin = null;
  210. this._root = null;
  211. this._scene = null;
  212. this._camera = null;
  213. this._renderer = null;
  214. this._utils = new ARUtils();
  215. }
  216. }
  217. /**
  218. * Enchant three.js with encantar.js!
  219. * @param {ARDemo} demo
  220. * @returns {Promise<ARSystem>}
  221. */
  222. function encantar(demo)
  223. {
  224. const ar = new ARSystem();
  225. function animate(time, frame)
  226. {
  227. ar._frame = frame;
  228. mix(frame);
  229. demo.update();
  230. ar._renderer.render(ar._scene, ar._camera);
  231. ar._session.requestAnimationFrame(animate);
  232. }
  233. function mix(frame)
  234. {
  235. let found = false;
  236. ar._viewer = null;
  237. ar._pointers.length = 0;
  238. for(const result of frame.results) {
  239. if(result.tracker.type == 'image-tracker') {
  240. if(result.trackables.length > 0) {
  241. const trackable = result.trackables[0];
  242. const projectionMatrix = result.viewer.view.projectionMatrix;
  243. const viewMatrixInverse = result.viewer.pose.transform.matrix;
  244. const modelMatrix = trackable.pose.transform.matrix;
  245. align(projectionMatrix, viewMatrixInverse, modelMatrix);
  246. ar._origin.visible = true;
  247. ar._viewer = result.viewer;
  248. found = true;
  249. }
  250. }
  251. else if(result.tracker.type == 'pointer-tracker') {
  252. if(result.trackables.length > 0)
  253. ar._pointers.push.apply(ar._pointers, result.trackables);
  254. }
  255. }
  256. if(!found)
  257. ar._origin.visible = false;
  258. }
  259. function align(projectionMatrix, viewMatrixInverse, modelMatrix)
  260. {
  261. ar._camera.projectionMatrix.fromArray(projectionMatrix.read());
  262. ar._camera.projectionMatrixInverse.copy(ar._camera.projectionMatrix).invert();
  263. ar._camera.matrix.fromArray(viewMatrixInverse.read());
  264. ar._camera.updateMatrixWorld(true);
  265. ar._origin.matrix.fromArray(modelMatrix.read());
  266. ar._origin.updateMatrixWorld(true);
  267. }
  268. return Promise.resolve()
  269. .then(() => demo.preload())
  270. .then(() => demo.startSession()) // Promise or SpeedyPromise
  271. .then(session => {
  272. demo._ar = ar;
  273. ar._session = session;
  274. ar._scene = new THREE.Scene();
  275. ar._origin = new THREE.Group();
  276. ar._origin.matrixAutoUpdate = false;
  277. ar._origin.visible = false;
  278. ar._scene.add(ar._origin);
  279. ar._root = new THREE.Group();
  280. ar._origin.add(ar._root);
  281. ar._camera = new THREE.PerspectiveCamera();
  282. ar._camera.matrixAutoUpdate = false;
  283. ar._renderer = new THREE.WebGLRenderer({
  284. canvas: session.viewport.canvas,
  285. alpha: true,
  286. });
  287. session.addEventListener('end', event => {
  288. ar._origin.visible = false;
  289. ar._viewer = null;
  290. ar._frame = null;
  291. ar._pointers.length = 0;
  292. });
  293. session.viewport.addEventListener('resize', event => {
  294. const size = session.viewport.virtualSize;
  295. ar._renderer.setPixelRatio(1.0);
  296. ar._renderer.setSize(size.width, size.height, false);
  297. });
  298. return Promise.resolve()
  299. .then(() => {
  300. return demo.init();
  301. })
  302. .then(() => {
  303. session.addEventListener('end', event => { demo.release(); });
  304. session.requestAnimationFrame(animate);
  305. return ar;
  306. })
  307. .catch(error => {
  308. session.end();
  309. throw error;
  310. });
  311. })
  312. .catch(error => {
  313. console.error(error);
  314. throw error;
  315. });
  316. }
  317. /**
  318. * Version check
  319. * @param {object} libs
  320. */
  321. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  322. {
  323. window.addEventListener('load', () => {
  324. try { AR, __THREE__;
  325. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'three.js': __THREE__ };
  326. const check = (x,v,w) => v != w ? console.warn(`\n\n\nWARNING\n\nThis plugin has been tested with ${x} version ${v}. The version in use is ${w}. Usage of ${x} version ${v} is recommended instead.\n\n\n`) : void 0;
  327. for(const [lib, expected] of Object.entries(libs))
  328. check(lib, expected.version, versionOf[lib]);
  329. }
  330. catch(e) {
  331. alert(e.message);
  332. }
  333. });
  334. }