Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

babylon-with-encantar.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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.1' },
  9. 'babylon.js': { version: '7.38.0' }
  10. });
  11. /**
  12. * Base class for Augmented Reality experiences
  13. * @abstract
  14. */
  15. class ARDemo
  16. {
  17. /**
  18. * Start the AR session
  19. * @returns {Promise<Session> | SpeedyPromise<Session>}
  20. * @abstract
  21. */
  22. startSession()
  23. {
  24. throw new Error('Abstract method');
  25. }
  26. /**
  27. * Initialization
  28. * @returns {void | Promise<void> | SpeedyPromise<void>}
  29. */
  30. init()
  31. {
  32. return Promise.resolve();
  33. }
  34. /**
  35. * Animation step - called every frame
  36. * @returns {void}
  37. */
  38. update()
  39. {
  40. }
  41. /**
  42. * Release resources
  43. * @returns {void}
  44. */
  45. release()
  46. {
  47. }
  48. /**
  49. * Preload resources before starting the AR session
  50. * @returns {Promise<void> | SpeedyPromise<void>}
  51. */
  52. preload()
  53. {
  54. return Promise.resolve();
  55. }
  56. /**
  57. * A reference to the ARSystem
  58. * @returns {ARSystem | null}
  59. */
  60. get ar()
  61. {
  62. return this._ar;
  63. }
  64. /**
  65. * Constructor
  66. */
  67. constructor()
  68. {
  69. this._ar = null;
  70. }
  71. }
  72. /**
  73. * AR Utilities
  74. */
  75. class ARUtils
  76. {
  77. /**
  78. * Convert an AR Vector2 to a BABYLON Vector2
  79. * @param {Vector2} v
  80. * @returns {BABYLON.Vector2}
  81. */
  82. convertVector2(v)
  83. {
  84. return new BABYLON.Vector2(v.x, v.y);
  85. }
  86. /**
  87. * Convert an AR Vector3 to a BABYLON Vector3
  88. * @param {Vector3} v
  89. * @returns {BABYLON.Vector3}
  90. */
  91. convertVector3(v)
  92. {
  93. return new BABYLON.Vector3(v.x, v.y, v.z);
  94. }
  95. /**
  96. * Convert an AR Quaternion to a BABYLON Quaternion
  97. * @param {Quaternion} q
  98. * @returns {BABYLON.Quaternion}
  99. */
  100. convertQuaternion(q)
  101. {
  102. return new BABYLON.Quaternion(q.x, q.y, q.z, q.w);
  103. }
  104. /**
  105. * Convert an AR Ray to a BABYLON Ray
  106. * @param {Ray} r
  107. * @returns {BABYLON.Ray}
  108. */
  109. convertRay(r)
  110. {
  111. const origin = this.convertVector3(r.origin);
  112. const direction = this.convertVector3(r.direction);
  113. return new BABYLON.Ray(origin, direction);
  114. }
  115. }
  116. /**
  117. * Helper for creating Augmented Reality experiences
  118. */
  119. class ARSystem
  120. {
  121. /**
  122. * AR Session
  123. * @returns {Session}
  124. */
  125. get session()
  126. {
  127. return this._session;
  128. }
  129. /**
  130. * Current frame: an object holding data to augment the physical scene.
  131. * If the AR scene is not initialized, this will be null.
  132. * @returns {Frame | null}
  133. */
  134. get frame()
  135. {
  136. return this._frame;
  137. }
  138. /**
  139. * AR Viewer
  140. * @returns {Viewer | null}
  141. */
  142. get viewer()
  143. {
  144. return this._viewer;
  145. }
  146. /**
  147. * Pointer-based input (current frame)
  148. * Make sure to add a PointerTracker to your session in order to use these
  149. * @returns {TrackablePointer[]}
  150. */
  151. get pointers()
  152. {
  153. return this._pointers;
  154. }
  155. /**
  156. * The root is a node that is automatically aligned to the physical scene.
  157. * Objects of your virtual scene should be descendants of this node.
  158. * @returns {BABYLON.TransformNode}
  159. */
  160. get root()
  161. {
  162. return this._root;
  163. }
  164. /**
  165. * The babylon.js scene
  166. * @returns {BABYLON.Scene}
  167. */
  168. get scene()
  169. {
  170. return this._scene;
  171. }
  172. /**
  173. * A camera that is automatically adjusted for AR
  174. * @returns {BABYLON.Camera}
  175. */
  176. get camera()
  177. {
  178. return this._camera;
  179. }
  180. /**
  181. * The babylon.js engine
  182. * @returns {BABYLON.Engine}
  183. */
  184. get engine()
  185. {
  186. return this._engine;
  187. }
  188. /**
  189. * AR Utilities
  190. * @returns {ARUtils}
  191. */
  192. get utils()
  193. {
  194. return this._utils;
  195. }
  196. /**
  197. * Constructor
  198. */
  199. constructor()
  200. {
  201. this._session = null;
  202. this._frame = null;
  203. this._viewer = null;
  204. this._pointers = [];
  205. this._origin = null;
  206. this._root = null;
  207. this._scene = null;
  208. this._camera = null;
  209. this._engine = null;
  210. this._utils = new ARUtils();
  211. }
  212. }
  213. /**
  214. * Enchant babylon.js with encantar.js!
  215. * @param {ARDemo} demo
  216. * @returns {Promise<ARSystem>}
  217. */
  218. function encantar(demo)
  219. {
  220. const ar = new ARSystem();
  221. const flipZ = new BABYLON.Matrix().copyFromFloats(
  222. 1, 0, 0, 0,
  223. 0, 1, 0, 0,
  224. 0, 0,-1, 0,
  225. 0, 0, 0, 1
  226. );
  227. function animate(time, frame)
  228. {
  229. ar._frame = frame;
  230. mix(frame);
  231. ar._engine.beginFrame();
  232. demo.update();
  233. ar._scene.render(false);
  234. ar._engine.endFrame();
  235. ar._session.requestAnimationFrame(animate);
  236. }
  237. function mix(frame)
  238. {
  239. let found = false;
  240. ar._viewer = null;
  241. ar._pointers.length = 0;
  242. for(const result of frame.results) {
  243. if(result.tracker.type == 'image-tracker') {
  244. if(result.trackables.length > 0) {
  245. const trackable = result.trackables[0];
  246. const projectionMatrix = result.viewer.view.projectionMatrix;
  247. const viewMatrix = result.viewer.pose.viewMatrix;
  248. const modelMatrix = trackable.pose.transform.matrix;
  249. align(projectionMatrix, viewMatrix, modelMatrix);
  250. ar._origin.setEnabled(true);
  251. ar._viewer = result.viewer;
  252. found = true;
  253. }
  254. }
  255. else if(result.tracker.type == 'pointer-tracker') {
  256. if(result.trackables.length > 0)
  257. ar._pointers.push.apply(ar._pointers, result.trackables);
  258. }
  259. }
  260. if(!found)
  261. ar._origin.setEnabled(false);
  262. }
  263. function align(projectionMatrix, viewMatrix, modelMatrix)
  264. {
  265. if(ar._scene.useRightHandedSystem)
  266. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  267. else
  268. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZ));
  269. ar._camera.setViewMatrix(convert(viewMatrix));
  270. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  271. }
  272. function convert(matrix)
  273. {
  274. // encantar.js uses column vectors stored in column-major format,
  275. // whereas babylon.js uses row vectors stored in row-major format
  276. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  277. return new BABYLON.Matrix().fromArray(matrix.read());
  278. }
  279. return Promise.resolve()
  280. .then(() => demo.preload())
  281. .then(() => demo.startSession()) // Promise or SpeedyPromise
  282. .then(session => {
  283. demo._ar = ar;
  284. ar._session = session;
  285. BABYLON.Engine.prototype.resize = function(forceSetSize = false) {
  286. // make babylon.js respect the resolution of the viewport
  287. const size = session.viewport.virtualSize;
  288. this.setSize(size.width, size.height, forceSetSize);
  289. };
  290. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  291. premultipliedAlpha: true
  292. });
  293. ar._scene = new BABYLON.Scene(ar._engine);
  294. ar._scene.useRightHandedSystem = true;
  295. ar._scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  296. ar._scene._inputManager._updatePointerPosition = function(evt) {
  297. // adjust babylon.js pointers to the resolution of the viewport
  298. const engine = this._scene.getEngine();
  299. const canvasRect = engine.getInputElementClientRect();
  300. if(!canvasRect)
  301. return;
  302. this._pointerX = (evt.clientX - canvasRect.left) * (engine.getRenderWidth() / canvasRect.width);
  303. this._pointerY = (evt.clientY - canvasRect.top) * (engine.getRenderHeight() / canvasRect.height);
  304. this._unTranslatedPointerX = this._pointerX;
  305. this._unTranslatedPointerY = this._pointerY;
  306. };
  307. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  308. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  309. ar._root.parent = ar._origin;
  310. ar._origin.setEnabled(false);
  311. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  312. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  313. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  314. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  315. ar._camera.setViewMatrix = function(matrix) {
  316. this._customViewMatrix.copyFrom(matrix);
  317. this.getViewMatrix(true);
  318. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  319. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  320. this._globalPosition.copyFrom(this.position);
  321. };
  322. session.addEventListener('end', event => {
  323. ar._origin.setEnabled(false);
  324. ar._viewer = null;
  325. ar._frame = null;
  326. ar._pointers.length = 0;
  327. });
  328. session.viewport.addEventListener('resize', event => {
  329. ar._engine.resize();
  330. });
  331. return Promise.resolve()
  332. .then(() => {
  333. return demo.init();
  334. })
  335. .then(() => {
  336. session.addEventListener('end', event => { demo.release(); });
  337. session.requestAnimationFrame(animate);
  338. return ar;
  339. })
  340. .catch(error => {
  341. session.end();
  342. throw error;
  343. });
  344. })
  345. .catch(error => {
  346. console.error(error);
  347. throw error;
  348. });
  349. }
  350. /**
  351. * Version check
  352. * @param {object} libs
  353. */
  354. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  355. {
  356. window.addEventListener('load', () => {
  357. try { AR, BABYLON;
  358. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  359. 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;
  360. for(const [lib, expected] of Object.entries(libs))
  361. check(lib, expected.version, versionOf[lib]);
  362. }
  363. catch(e) {
  364. alert(e.message);
  365. }
  366. });
  367. }