You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

three-with-encantar.js 8.4KB

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