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.

babylon-with-encantar.js 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /**
  2. * babylon.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. 'babylon.js': { version: '7.29.0' }
  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. /**
  56. * Helper for creating Augmented Reality experiences
  57. */
  58. class ARSystem
  59. {
  60. /**
  61. * AR Session
  62. * @returns {Session}
  63. */
  64. get session()
  65. {
  66. return this._session;
  67. }
  68. /**
  69. * Current frame: an object holding data to augment the physical scene.
  70. * If the AR scene is not initialized, this will be null.
  71. * @returns {Frame | null}
  72. */
  73. get frame()
  74. {
  75. return this._frame;
  76. }
  77. /**
  78. * AR Viewer
  79. * @returns {Viewer | null}
  80. */
  81. get viewer()
  82. {
  83. return this._viewer;
  84. }
  85. /**
  86. * Pointer-based input (current frame)
  87. * Make sure to add a PointerTracker to your session in order to use these
  88. * @returns {TrackablePointer[]}
  89. */
  90. get pointers()
  91. {
  92. return this._pointers;
  93. }
  94. /**
  95. * The root is a node that is automatically aligned to the physical scene.
  96. * Objects of your virtual scene should be descendants of this node.
  97. * @returns {BABYLON.TransformNode}
  98. */
  99. get root()
  100. {
  101. return this._root;
  102. }
  103. /**
  104. * The babylon.js scene
  105. * @returns {BABYLON.Scene}
  106. */
  107. get scene()
  108. {
  109. return this._scene;
  110. }
  111. /**
  112. * A camera that is automatically adjusted for AR
  113. * @returns {BABYLON.Camera}
  114. */
  115. get camera()
  116. {
  117. return this._camera;
  118. }
  119. /**
  120. * The babylon.js engine
  121. * @returns {BABYLON.Engine}
  122. */
  123. get engine()
  124. {
  125. return this._engine;
  126. }
  127. /**
  128. * Convert an AR Vector2 to a BABYLON Vector2
  129. * @param {Vector2} v
  130. * @returns {BABYLON.Vector2}
  131. */
  132. convertVector2(v)
  133. {
  134. return new BABYLON.Vector2(v.x, v.y);
  135. }
  136. /**
  137. * Convert an AR Vector3 to a BABYLON Vector3
  138. * @param {Vector3} v
  139. * @returns {BABYLON.Vector3}
  140. */
  141. convertVector3(v)
  142. {
  143. return new BABYLON.Vector3(v.x, v.y, v.z);
  144. }
  145. /**
  146. * Convert an AR Quaternion to a BABYLON Quaternion
  147. * @param {Quaternion} q
  148. * @returns {BABYLON.Quaternion}
  149. */
  150. convertQuaternion(q)
  151. {
  152. return new BABYLON.Quaternion(q.x, q.y, q.z, q.w);
  153. }
  154. /**
  155. * Convert an AR Ray to a BABYLON Ray
  156. * @param {Ray} r
  157. * @returns {BABYLON.Ray}
  158. */
  159. convertRay(r)
  160. {
  161. const origin = this.convertVector3(r.origin);
  162. const direction = this.convertVector3(r.direction);
  163. return new BABYLON.Ray(origin, direction);
  164. }
  165. /**
  166. * Constructor
  167. */
  168. constructor()
  169. {
  170. this._session = null;
  171. this._frame = null;
  172. this._viewer = null;
  173. this._pointers = [];
  174. this._origin = null;
  175. this._root = null;
  176. this._scene = null;
  177. this._camera = null;
  178. this._engine = null;
  179. }
  180. }
  181. /**
  182. * Enchant babylon.js with encantar.js!
  183. * @param {ARDemo} demo
  184. * @returns {Promise<ARSystem>}
  185. */
  186. function encantar(demo)
  187. {
  188. const ar = new ARSystem();
  189. const flipZAxis = new BABYLON.Matrix().copyFromFloats(
  190. 1, 0, 0, 0,
  191. 0, 1, 0, 0,
  192. 0, 0,-1, 0,
  193. 0, 0, 0, 1
  194. );
  195. function animate(time, frame)
  196. {
  197. ar._frame = frame;
  198. mix(frame);
  199. demo.update(ar);
  200. ar._scene.render(false);
  201. ar._session.requestAnimationFrame(animate);
  202. }
  203. function mix(frame)
  204. {
  205. let found = false;
  206. ar._viewer = null;
  207. ar._pointers.length = 0;
  208. for(const result of frame.results) {
  209. if(result.tracker.type == 'image-tracker') {
  210. if(result.trackables.length > 0) {
  211. const trackable = result.trackables[0];
  212. const projectionMatrix = result.viewer.view.projectionMatrix;
  213. const viewMatrix = result.viewer.pose.viewMatrix;
  214. const modelMatrix = trackable.pose.transform.matrix;
  215. align(projectionMatrix, viewMatrix, modelMatrix);
  216. ar._origin.setEnabled(true);
  217. ar._viewer = result.viewer;
  218. found = true;
  219. }
  220. }
  221. else if(result.tracker.type == 'pointer-tracker') {
  222. if(result.trackables.length > 0)
  223. ar._pointers.push.apply(ar._pointers, result.trackables);
  224. }
  225. }
  226. if(!found)
  227. ar._origin.setEnabled(false);
  228. }
  229. function align(projectionMatrix, viewMatrix, modelMatrix)
  230. {
  231. if(ar._scene.useRightHandedSystem)
  232. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  233. else
  234. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZAxis));
  235. ar._camera.setViewMatrix(convert(viewMatrix));
  236. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  237. }
  238. function convert(matrix)
  239. {
  240. // encantar.js uses column vectors stored in column-major format,
  241. // whereas babylon.js uses row vectors stored in row-major format
  242. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  243. return new BABYLON.Matrix().fromArray(matrix.read());
  244. }
  245. return Promise.resolve()
  246. .then(() => {
  247. return demo.startSession(); // Promise or SpeedyPromise
  248. })
  249. .then(session => {
  250. ar._session = session;
  251. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  252. premultipliedAlpha: true
  253. });
  254. ar._engine.resize = function(forceSetSize = false) {
  255. // make babylon.js respect the resolution of the viewport
  256. const size = session.viewport.virtualSize;
  257. this.setSize(size.width, size.height, forceSetSize);
  258. };
  259. ar._scene = new BABYLON.Scene(ar._engine);
  260. ar._scene.useRightHandedSystem = true;
  261. ar._scene.clearColor.set(0, 0, 0, 0);
  262. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  263. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  264. ar._root.parent = ar._origin;
  265. ar._origin.setEnabled(false);
  266. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  267. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  268. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  269. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  270. ar._camera.setViewMatrix = function(matrix) {
  271. this._customViewMatrix = matrix;
  272. this.getViewMatrix(true);
  273. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  274. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  275. this._globalPosition.copyFrom(this.position);
  276. };
  277. session.addEventListener('end', event => {
  278. ar._origin.setEnabled(false);
  279. ar._viewer = null;
  280. ar._frame = null;
  281. ar._pointers.length = 0;
  282. });
  283. session.viewport.addEventListener('resize', event => {
  284. ar._engine.resize();
  285. });
  286. return Promise.resolve()
  287. .then(() => {
  288. return demo.init(ar);
  289. })
  290. .then(() => {
  291. session.addEventListener('end', event => { demo.release(ar); });
  292. session.requestAnimationFrame(animate);
  293. return ar;
  294. })
  295. .catch(error => {
  296. session.end();
  297. throw error;
  298. });
  299. })
  300. .catch(error => {
  301. console.error(error);
  302. throw error;
  303. });
  304. }
  305. /**
  306. * Version check
  307. * @param {object} libs
  308. */
  309. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  310. {
  311. window.addEventListener('load', () => {
  312. try { AR, BABYLON;
  313. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  314. 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;
  315. for(const [lib, expected] of Object.entries(libs))
  316. check(lib, expected.version, versionOf[lib]);
  317. }
  318. catch(e) {
  319. alert(e.message);
  320. }
  321. });
  322. }