Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

babylon-with-encantar.js 10KB

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