WebXRAnchorSystem.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import { WebXRFeatureName, WebXRFeaturesManager } from '../webXRFeaturesManager';
  2. import { WebXRSessionManager } from '../webXRSessionManager';
  3. import { Observable } from '../../Misc/observable';
  4. import { Matrix, Vector3, Quaternion } from '../../Maths/math.vector';
  5. import { TransformNode } from '../../Meshes/transformNode';
  6. import { WebXRAbstractFeature } from './WebXRAbstractFeature';
  7. import { IWebXRHitResult } from './WebXRHitTest';
  8. import { Tools } from '../../Misc/tools';
  9. /**
  10. * Configuration options of the anchor system
  11. */
  12. export interface IWebXRAnchorSystemOptions {
  13. /**
  14. * a node that will be used to convert local to world coordinates
  15. */
  16. worldParentNode?: TransformNode;
  17. /**
  18. * If set to true a reference of the created anchors will be kept until the next session starts
  19. * If not defined, anchors will be removed from the array when the feature is detached or the session ended.
  20. */
  21. doNotRemoveAnchorsOnSessionEnded?: boolean;
  22. }
  23. /**
  24. * A babylon container for an XR Anchor
  25. */
  26. export interface IWebXRAnchor {
  27. /**
  28. * A babylon-assigned ID for this anchor
  29. */
  30. id: number;
  31. /**
  32. * Transformation matrix to apply to an object attached to this anchor
  33. */
  34. transformationMatrix: Matrix;
  35. /**
  36. * The native anchor object
  37. */
  38. xrAnchor: XRAnchor;
  39. /**
  40. * if defined, this object will be constantly updated by the anchor's position and rotation
  41. */
  42. attachedNode?: TransformNode;
  43. }
  44. /**
  45. * An internal interface for a future (promise based) anchor
  46. */
  47. interface IWebXRFutureAnchor {
  48. /**
  49. * A resolve function
  50. */
  51. resolve: (xrAnchor: XRAnchor) => void;
  52. /**
  53. * A reject function
  54. */
  55. reject: (msg?: string) => void;
  56. /**
  57. * The XR Transformation of the future anchor
  58. */
  59. xrTransformation: XRRigidTransform;
  60. }
  61. let anchorIdProvider = 0;
  62. /**
  63. * An implementation of the anchor system for WebXR.
  64. * For further information see https://github.com/immersive-web/anchors/
  65. */
  66. export class WebXRAnchorSystem extends WebXRAbstractFeature {
  67. private _lastFrameDetected: XRAnchorSet = new Set();
  68. private _trackedAnchors: Array<IWebXRAnchor> = [];
  69. private _referenceSpaceForFrameAnchors: XRReferenceSpace;
  70. private _futureAnchors: IWebXRFutureAnchor[] = [];
  71. /**
  72. * The module's name
  73. */
  74. public static readonly Name = WebXRFeatureName.ANCHOR_SYSTEM;
  75. /**
  76. * The (Babylon) version of this module.
  77. * This is an integer representing the implementation version.
  78. * This number does not correspond to the WebXR specs version
  79. */
  80. public static readonly Version = 1;
  81. /**
  82. * Observers registered here will be executed when a new anchor was added to the session
  83. */
  84. public onAnchorAddedObservable: Observable<IWebXRAnchor> = new Observable();
  85. /**
  86. * Observers registered here will be executed when an anchor was removed from the session
  87. */
  88. public onAnchorRemovedObservable: Observable<IWebXRAnchor> = new Observable();
  89. /**
  90. * Observers registered here will be executed when an existing anchor updates
  91. * This can execute N times every frame
  92. */
  93. public onAnchorUpdatedObservable: Observable<IWebXRAnchor> = new Observable();
  94. /**
  95. * Set the reference space to use for anchor creation, when not using a hit test.
  96. * Will default to the session's reference space if not defined
  97. */
  98. public set referenceSpaceForFrameAnchors(referenceSpace: XRReferenceSpace) {
  99. this._referenceSpaceForFrameAnchors = referenceSpace;
  100. }
  101. /**
  102. * constructs a new anchor system
  103. * @param _xrSessionManager an instance of WebXRSessionManager
  104. * @param _options configuration object for this feature
  105. */
  106. constructor(_xrSessionManager: WebXRSessionManager, private _options: IWebXRAnchorSystemOptions = {}) {
  107. super(_xrSessionManager);
  108. }
  109. private _tmpVector = new Vector3();
  110. private _tmpQuaternion = new Quaternion();
  111. private _populateTmpTransformation(position: Vector3, rotationQuaternion: Quaternion) {
  112. this._tmpVector.copyFrom(position);
  113. this._tmpQuaternion.copyFrom(rotationQuaternion);
  114. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  115. this._tmpVector.z *= -1;
  116. this._tmpQuaternion.z *= -1;
  117. this._tmpQuaternion.w *= -1;
  118. }
  119. return {
  120. position: this._tmpVector,
  121. rotationQuaternion: this._tmpQuaternion
  122. };
  123. }
  124. /**
  125. * Create a new anchor point using a hit test result at a specific point in the scene
  126. * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.
  127. * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.
  128. *
  129. * @param hitTestResult The hit test result to use for this anchor creation
  130. * @param position an optional position offset for this anchor
  131. * @param rotationQuaternion an optional rotation offset for this anchor
  132. * @returns A promise that fulfills when the XR anchor was registered in the system (but not necessarily added to the tracked anchors)
  133. */
  134. public async addAnchorPointUsingHitTestResultAsync(hitTestResult: IWebXRHitResult, position: Vector3 = new Vector3(), rotationQuaternion: Quaternion = new Quaternion()): Promise<XRAnchor> {
  135. // convert to XR space (right handed) if needed
  136. this._populateTmpTransformation(position, rotationQuaternion);
  137. // the matrix that we'll use
  138. const m = new XRRigidTransform({...this._tmpVector}, {...this._tmpQuaternion});
  139. if (!hitTestResult.xrHitResult.createAnchor) {
  140. throw new Error('Anchors not enabled in this browsed. Add "anchors" to optional features');
  141. } else {
  142. try {
  143. return hitTestResult.xrHitResult.createAnchor(m);
  144. }
  145. catch (error) {
  146. throw new Error(error);
  147. }
  148. }
  149. }
  150. /**
  151. * Add a new anchor at a specific position and rotation
  152. * This function will add a new anchor per default in the next available frame. Unless forced, the createAnchor function
  153. * will be called in the next xrFrame loop to make sure that the anchor can be created correctly.
  154. * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.
  155. * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.
  156. *
  157. * @param position the position in which to add an anchor
  158. * @param rotationQuaternion an optional rotation for the anchor transformation
  159. * @param forceCreateInCurrentFrame force the creation of this anchor in the current frame. Must be called inside xrFrame loop!
  160. * @returns A promise that fulfills when the XR anchor was registered in the system (but not necessarily added to the tracked anchors)
  161. */
  162. public addAnchorAtPositionAndRotationAsync(position: Vector3, rotationQuaternion: Quaternion = new Quaternion(), forceCreateInCurrentFrame = false): Promise<XRAnchor> {
  163. // convert to XR space (right handed) if needed
  164. this._populateTmpTransformation(position, rotationQuaternion);
  165. // the matrix that we'll use
  166. const xrTransformation = new XRRigidTransform({...this._tmpVector}, {...this._tmpQuaternion});
  167. if (forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame) {
  168. return this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame);
  169. } else {
  170. // add the transformation to the future anchors list
  171. return new Promise<XRAnchor>((resolve, reject) => {
  172. this._futureAnchors.push({
  173. xrTransformation,
  174. resolve,
  175. reject
  176. });
  177. });
  178. }
  179. }
  180. /**
  181. * detach this feature.
  182. * Will usually be called by the features manager
  183. *
  184. * @returns true if successful.
  185. */
  186. public detach(): boolean {
  187. if (!super.detach()) {
  188. return false;
  189. }
  190. if (!this._options.doNotRemoveAnchorsOnSessionEnded) {
  191. while (this._trackedAnchors.length) {
  192. const toRemove = this._trackedAnchors.pop();
  193. if (toRemove) {
  194. this.onAnchorRemovedObservable.notifyObservers(toRemove);
  195. }
  196. }
  197. }
  198. return true;
  199. }
  200. /**
  201. * Dispose this feature and all of the resources attached
  202. */
  203. public dispose(): void {
  204. super.dispose();
  205. this.onAnchorAddedObservable.clear();
  206. this.onAnchorRemovedObservable.clear();
  207. this.onAnchorUpdatedObservable.clear();
  208. }
  209. protected _onXRFrame(frame: XRFrame) {
  210. if (!this.attached || !frame) { return; }
  211. const trackedAnchors = frame.trackedAnchors;
  212. if (trackedAnchors) {
  213. const toRemove = this._trackedAnchors.filter((anchor) => !trackedAnchors.has(anchor.xrAnchor)).map((anchor) => {
  214. const index = this._trackedAnchors.indexOf(anchor);
  215. return index;
  216. });
  217. let idxTracker = 0;
  218. toRemove.forEach((index) => {
  219. const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0];
  220. this.onAnchorRemovedObservable.notifyObservers(anchor);
  221. idxTracker--;
  222. });
  223. // now check for new ones
  224. trackedAnchors.forEach((xrAnchor) => {
  225. if (!this._lastFrameDetected.has(xrAnchor)) {
  226. const newAnchor: Partial<IWebXRAnchor> = {
  227. id: anchorIdProvider++,
  228. xrAnchor: xrAnchor
  229. };
  230. const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame);
  231. this._trackedAnchors.push(anchor);
  232. this.onAnchorAddedObservable.notifyObservers(anchor);
  233. } else {
  234. let index = this._findIndexInAnchorArray(xrAnchor);
  235. const anchor = this._trackedAnchors[index];
  236. try {
  237. // anchors update every frame
  238. this._updateAnchorWithXRFrame(xrAnchor, anchor, frame);
  239. if (anchor.attachedNode) {
  240. anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new Quaternion();
  241. anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position);
  242. }
  243. this.onAnchorUpdatedObservable.notifyObservers(anchor);
  244. } catch (e) {
  245. Tools.Warn(`Anchor could not be updated`);
  246. }
  247. }
  248. });
  249. this._lastFrameDetected = trackedAnchors;
  250. }
  251. // process future anchors
  252. while (this._futureAnchors.length) {
  253. const futureAnchor = this._futureAnchors.pop();
  254. if (!futureAnchor) {
  255. return;
  256. }
  257. if (!frame.createAnchor) {
  258. futureAnchor.reject('Anchors not enabled in this browser');
  259. }
  260. this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame).then(futureAnchor.resolve, futureAnchor.reject);
  261. }
  262. }
  263. /**
  264. * avoiding using Array.find for global support.
  265. * @param xrAnchor the plane to find in the array
  266. */
  267. private _findIndexInAnchorArray(xrAnchor: XRAnchor) {
  268. for (let i = 0; i < this._trackedAnchors.length; ++i) {
  269. if (this._trackedAnchors[i].xrAnchor === xrAnchor) {
  270. return i;
  271. }
  272. }
  273. return -1;
  274. }
  275. private _updateAnchorWithXRFrame(xrAnchor: XRAnchor, anchor: Partial<IWebXRAnchor>, xrFrame: XRFrame): IWebXRAnchor {
  276. // matrix
  277. const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace);
  278. if (pose) {
  279. const mat = anchor.transformationMatrix || new Matrix();
  280. Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
  281. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  282. mat.toggleModelMatrixHandInPlace();
  283. }
  284. anchor.transformationMatrix = mat;
  285. if (!this._options.worldParentNode) {
  286. // Logger.Warn("Please provide a world parent node to apply world transformation");
  287. } else {
  288. mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
  289. }
  290. }
  291. return <IWebXRAnchor>anchor;
  292. }
  293. private async _createAnchorAtTransformation(xrTransformation: XRRigidTransform, xrFrame: XRFrame) {
  294. if (xrFrame.createAnchor) {
  295. try {
  296. return xrFrame.createAnchor(xrTransformation, this._referenceSpaceForFrameAnchors ?? this._xrSessionManager.referenceSpace);
  297. }
  298. catch (error) {
  299. throw new Error(error);
  300. }
  301. } else {
  302. throw new Error('Anchors are not enabled in your browser');
  303. }
  304. }
  305. }
  306. // register the plugin
  307. WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => {
  308. return () => new WebXRAnchorSystem(xrSessionManager, options);
  309. }, WebXRAnchorSystem.Version);