Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

babylon-with-encantar.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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.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. * @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 BABYLON Vector2
  83. * @param {Vector2} v
  84. * @returns {BABYLON.Vector2}
  85. */
  86. convertVector2(v)
  87. {
  88. return new BABYLON.Vector2(v.x, v.y);
  89. }
  90. /**
  91. * Convert an AR Vector3 to a BABYLON Vector3
  92. * @param {Vector3} v
  93. * @returns {BABYLON.Vector3}
  94. */
  95. convertVector3(v)
  96. {
  97. return new BABYLON.Vector3(v.x, v.y, v.z);
  98. }
  99. /**
  100. * Convert an AR Quaternion to a BABYLON Quaternion
  101. * @param {Quaternion} q
  102. * @returns {BABYLON.Quaternion}
  103. */
  104. convertQuaternion(q)
  105. {
  106. return new BABYLON.Quaternion(q.x, q.y, q.z, q.w);
  107. }
  108. /**
  109. * Convert an AR Ray to a BABYLON Ray
  110. * @param {Ray} r
  111. * @returns {BABYLON.Ray}
  112. */
  113. convertRay(r)
  114. {
  115. const origin = this.convertVector3(r.origin);
  116. const direction = this.convertVector3(r.direction);
  117. return new BABYLON.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 {BABYLON.TransformNode}
  163. */
  164. get root()
  165. {
  166. return this._root;
  167. }
  168. /**
  169. * The babylon.js scene
  170. * @returns {BABYLON.Scene}
  171. */
  172. get scene()
  173. {
  174. return this._scene;
  175. }
  176. /**
  177. * A camera that is automatically adjusted for AR
  178. * @returns {BABYLON.Camera}
  179. */
  180. get camera()
  181. {
  182. return this._camera;
  183. }
  184. /**
  185. * The babylon.js engine
  186. * @returns {BABYLON.Engine}
  187. */
  188. get engine()
  189. {
  190. return this._engine;
  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._engine = null;
  214. this._utils = new ARUtils();
  215. }
  216. }
  217. /**
  218. * Enchant babylon.js with encantar.js!
  219. * @param {ARDemo} demo
  220. * @returns {Promise<ARSystem>}
  221. */
  222. function encantar(demo)
  223. {
  224. const ar = new ARSystem();
  225. const flipZ = new BABYLON.Matrix().copyFromFloats(
  226. 1, 0, 0, 0,
  227. 0, 1, 0, 0,
  228. 0, 0,-1, 0,
  229. 0, 0, 0, 1
  230. );
  231. function animate(time, frame)
  232. {
  233. ar._frame = frame;
  234. mix(frame);
  235. ar._engine.beginFrame();
  236. demo.update();
  237. ar._scene.render(false);
  238. ar._engine.endFrame();
  239. ar._session.requestAnimationFrame(animate);
  240. }
  241. function mix(frame)
  242. {
  243. let found = false;
  244. ar._viewer = null;
  245. ar._pointers.length = 0;
  246. for(const result of frame.results) {
  247. if(result.tracker.type == 'image-tracker') {
  248. if(result.trackables.length > 0) {
  249. const trackable = result.trackables[0];
  250. const projectionMatrix = result.viewer.view.projectionMatrix;
  251. const viewMatrix = result.viewer.pose.viewMatrix;
  252. const modelMatrix = trackable.pose.transform.matrix;
  253. align(projectionMatrix, viewMatrix, modelMatrix);
  254. ar._origin.setEnabled(true);
  255. ar._viewer = result.viewer;
  256. found = true;
  257. }
  258. }
  259. else if(result.tracker.type == 'pointer-tracker') {
  260. if(result.trackables.length > 0)
  261. ar._pointers.push.apply(ar._pointers, result.trackables);
  262. }
  263. }
  264. if(!found)
  265. ar._origin.setEnabled(false);
  266. }
  267. function align(projectionMatrix, viewMatrix, modelMatrix)
  268. {
  269. if(ar._scene.useRightHandedSystem)
  270. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  271. else
  272. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZ));
  273. ar._camera.setViewMatrix(convert(viewMatrix));
  274. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  275. }
  276. function convert(matrix)
  277. {
  278. // encantar.js uses column vectors stored in column-major format,
  279. // whereas babylon.js uses row vectors stored in row-major format
  280. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  281. return new BABYLON.Matrix().fromArray(matrix.read());
  282. }
  283. return Promise.resolve()
  284. .then(() => demo.preload())
  285. .then(() => demo.startSession()) // Promise or SpeedyPromise
  286. .then(session => {
  287. demo._ar = ar;
  288. ar._session = session;
  289. BABYLON.Engine.prototype.resize = function(forceSetSize = false) {
  290. // make babylon.js respect the resolution of the viewport
  291. const size = session.viewport.virtualSize;
  292. this.setSize(size.width, size.height, forceSetSize);
  293. };
  294. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  295. premultipliedAlpha: true
  296. });
  297. ar._scene = new BABYLON.Scene(ar._engine);
  298. ar._scene.useRightHandedSystem = true;
  299. ar._scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  300. ar._scene._inputManager._updatePointerPosition = function(evt) {
  301. // adjust babylon.js pointers to the resolution of the viewport
  302. const engine = this._scene.getEngine();
  303. const canvasRect = engine.getInputElementClientRect();
  304. if(!canvasRect)
  305. return;
  306. this._pointerX = (evt.clientX - canvasRect.left) * (engine.getRenderWidth() / canvasRect.width);
  307. this._pointerY = (evt.clientY - canvasRect.top) * (engine.getRenderHeight() / canvasRect.height);
  308. this._unTranslatedPointerX = this._pointerX;
  309. this._unTranslatedPointerY = this._pointerY;
  310. };
  311. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  312. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  313. ar._root.parent = ar._origin;
  314. ar._origin.setEnabled(false);
  315. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  316. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  317. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  318. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  319. ar._camera.setViewMatrix = function(matrix) {
  320. this._customViewMatrix = matrix;
  321. this.getViewMatrix(true);
  322. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  323. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  324. this._globalPosition.copyFrom(this.position);
  325. };
  326. session.addEventListener('end', event => {
  327. ar._origin.setEnabled(false);
  328. ar._viewer = null;
  329. ar._frame = null;
  330. ar._pointers.length = 0;
  331. });
  332. session.viewport.addEventListener('resize', event => {
  333. ar._engine.resize();
  334. });
  335. return Promise.resolve()
  336. .then(() => {
  337. return demo.init();
  338. })
  339. .then(() => {
  340. session.addEventListener('end', event => { demo.release(); });
  341. session.requestAnimationFrame(animate);
  342. return ar;
  343. })
  344. .catch(error => {
  345. session.end();
  346. throw error;
  347. });
  348. })
  349. .catch(error => {
  350. console.error(error);
  351. throw error;
  352. });
  353. }
  354. /**
  355. * Version check
  356. * @param {object} libs
  357. */
  358. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  359. {
  360. window.addEventListener('load', () => {
  361. try { AR, BABYLON;
  362. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  363. 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;
  364. for(const [lib, expected] of Object.entries(libs))
  365. check(lib, expected.version, versionOf[lib]);
  366. }
  367. catch(e) {
  368. alert(e.message);
  369. }
  370. });
  371. }