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 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. * 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 BABYLON Vector2
  71. * @param {Vector2} v
  72. * @returns {BABYLON.Vector2}
  73. */
  74. convertVector2(v)
  75. {
  76. return new BABYLON.Vector2(v.x, v.y);
  77. }
  78. /**
  79. * Convert an AR Vector3 to a BABYLON Vector3
  80. * @param {Vector3} v
  81. * @returns {BABYLON.Vector3}
  82. */
  83. convertVector3(v)
  84. {
  85. return new BABYLON.Vector3(v.x, v.y, v.z);
  86. }
  87. /**
  88. * Convert an AR Quaternion to a BABYLON Quaternion
  89. * @param {Quaternion} q
  90. * @returns {BABYLON.Quaternion}
  91. */
  92. convertQuaternion(q)
  93. {
  94. return new BABYLON.Quaternion(q.x, q.y, q.z, q.w);
  95. }
  96. /**
  97. * Convert an AR Ray to a BABYLON Ray
  98. * @param {Ray} r
  99. * @returns {BABYLON.Ray}
  100. */
  101. convertRay(r)
  102. {
  103. const origin = this.convertVector3(r.origin);
  104. const direction = this.convertVector3(r.direction);
  105. return new BABYLON.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 {BABYLON.TransformNode}
  151. */
  152. get root()
  153. {
  154. return this._root;
  155. }
  156. /**
  157. * The babylon.js scene
  158. * @returns {BABYLON.Scene}
  159. */
  160. get scene()
  161. {
  162. return this._scene;
  163. }
  164. /**
  165. * A camera that is automatically adjusted for AR
  166. * @returns {BABYLON.Camera}
  167. */
  168. get camera()
  169. {
  170. return this._camera;
  171. }
  172. /**
  173. * The babylon.js engine
  174. * @returns {BABYLON.Engine}
  175. */
  176. get engine()
  177. {
  178. return this._engine;
  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._engine = null;
  202. this._utils = new ARUtils();
  203. }
  204. }
  205. /**
  206. * Enchant babylon.js with encantar.js!
  207. * @param {ARDemo} demo
  208. * @returns {Promise<ARSystem>}
  209. */
  210. function encantar(demo)
  211. {
  212. const ar = new ARSystem();
  213. const flipZAxis = new BABYLON.Matrix().copyFromFloats(
  214. 1, 0, 0, 0,
  215. 0, 1, 0, 0,
  216. 0, 0,-1, 0,
  217. 0, 0, 0, 1
  218. );
  219. function animate(time, frame)
  220. {
  221. ar._frame = frame;
  222. mix(frame);
  223. demo.update(ar);
  224. ar._scene.render(false);
  225. ar._session.requestAnimationFrame(animate);
  226. }
  227. function mix(frame)
  228. {
  229. let found = false;
  230. ar._viewer = null;
  231. ar._pointers.length = 0;
  232. for(const result of frame.results) {
  233. if(result.tracker.type == 'image-tracker') {
  234. if(result.trackables.length > 0) {
  235. const trackable = result.trackables[0];
  236. const projectionMatrix = result.viewer.view.projectionMatrix;
  237. const viewMatrix = result.viewer.pose.viewMatrix;
  238. const modelMatrix = trackable.pose.transform.matrix;
  239. align(projectionMatrix, viewMatrix, modelMatrix);
  240. ar._origin.setEnabled(true);
  241. ar._viewer = result.viewer;
  242. found = true;
  243. }
  244. }
  245. else if(result.tracker.type == 'pointer-tracker') {
  246. if(result.trackables.length > 0)
  247. ar._pointers.push.apply(ar._pointers, result.trackables);
  248. }
  249. }
  250. if(!found)
  251. ar._origin.setEnabled(false);
  252. }
  253. function align(projectionMatrix, viewMatrix, modelMatrix)
  254. {
  255. if(ar._scene.useRightHandedSystem)
  256. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  257. else
  258. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZAxis));
  259. ar._camera.setViewMatrix(convert(viewMatrix));
  260. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  261. }
  262. function convert(matrix)
  263. {
  264. // encantar.js uses column vectors stored in column-major format,
  265. // whereas babylon.js uses row vectors stored in row-major format
  266. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  267. return new BABYLON.Matrix().fromArray(matrix.read());
  268. }
  269. return Promise.resolve()
  270. .then(() => demo.preload())
  271. .then(() => demo.startSession()) // Promise or SpeedyPromise
  272. .then(session => {
  273. ar._session = session;
  274. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  275. premultipliedAlpha: true
  276. });
  277. ar._engine.resize = function(forceSetSize = false) {
  278. // make babylon.js respect the resolution of the viewport
  279. const size = session.viewport.virtualSize;
  280. this.setSize(size.width, size.height, forceSetSize);
  281. };
  282. ar._scene = new BABYLON.Scene(ar._engine);
  283. ar._scene.useRightHandedSystem = true;
  284. ar._scene.clearColor.set(0, 0, 0, 0);
  285. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  286. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  287. ar._root.parent = ar._origin;
  288. ar._origin.setEnabled(false);
  289. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  290. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  291. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  292. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  293. ar._camera.setViewMatrix = function(matrix) {
  294. this._customViewMatrix = matrix;
  295. this.getViewMatrix(true);
  296. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  297. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  298. this._globalPosition.copyFrom(this.position);
  299. };
  300. session.addEventListener('end', event => {
  301. ar._origin.setEnabled(false);
  302. ar._viewer = null;
  303. ar._frame = null;
  304. ar._pointers.length = 0;
  305. });
  306. session.viewport.addEventListener('resize', event => {
  307. ar._engine.resize();
  308. });
  309. return Promise.resolve()
  310. .then(() => {
  311. return demo.init(ar);
  312. })
  313. .then(() => {
  314. session.addEventListener('end', event => { demo.release(ar); });
  315. session.requestAnimationFrame(animate);
  316. return ar;
  317. })
  318. .catch(error => {
  319. session.end();
  320. throw error;
  321. });
  322. })
  323. .catch(error => {
  324. console.error(error);
  325. throw error;
  326. });
  327. }
  328. /**
  329. * Version check
  330. * @param {object} libs
  331. */
  332. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  333. {
  334. window.addEventListener('load', () => {
  335. try { AR, BABYLON;
  336. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  337. 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;
  338. for(const [lib, expected] of Object.entries(libs))
  339. check(lib, expected.version, versionOf[lib]);
  340. }
  341. catch(e) {
  342. alert(e.message);
  343. }
  344. });
  345. }