WebXRMeshDetector.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import { WebXRFeaturesManager, WebXRFeatureName } from '../webXRFeaturesManager';
  2. import { WebXRAbstractFeature } from './WebXRAbstractFeature';
  3. import { WebXRSessionManager } from '../webXRSessionManager';
  4. import { TransformNode } from '../../Meshes/transformNode';
  5. import { Matrix } from '../../Maths/math';
  6. import { Observable } from '../../Misc/observable';
  7. /**
  8. * Options used in the mesh detector module
  9. */
  10. export interface IWebXRMeshDetectorOptions {
  11. /**
  12. * The node to use to transform the local results to world coordinates
  13. */
  14. worldParentNode?: TransformNode;
  15. /**
  16. * If set to true a reference of the created meshes will be kept until the next session starts
  17. * If not defined, meshes will be removed from the array when the feature is detached or the session ended.
  18. */
  19. doNotRemoveMeshesOnSessionEnded?: boolean;
  20. /**
  21. * Preferred detector configuration, not all preferred options will be supported by all platforms.
  22. */
  23. preferredDetectorOptions?: XRGeometryDetectorOptions;
  24. /**
  25. * If set to true, WebXRMeshDetector will convert coordinate systems for meshes.
  26. * If not defined, mesh conversions from right handed to left handed coordinate systems won't be conducted.
  27. * Right handed mesh data will be available through IWebXRVertexData.xrMesh.
  28. */
  29. convertCoordinateSystems?: boolean;
  30. }
  31. /**
  32. * A babylon interface for a XR mesh's vertex data.
  33. *
  34. * Currently not supported by WebXR, available only with BabylonNative
  35. */
  36. export interface IWebXRVertexData {
  37. /**
  38. * A babylon-assigned ID for this mesh
  39. */
  40. id: number;
  41. /**
  42. * Data required for constructing a mesh in Babylon.js.
  43. */
  44. xrMesh: XRMesh;
  45. /**
  46. * The node to use to transform the local results to world coordinates.
  47. * WorldParentNode will only exist if it was declared in the IWebXRMeshDetectorOptions.
  48. */
  49. worldParentNode?: TransformNode;
  50. /**
  51. * An array of vertex positions in babylon space. right/left hand system is taken into account.
  52. * Positions will only be calculated if convertCoordinateSystems is set to true in the IWebXRMeshDetectorOptions.
  53. */
  54. positions?: Float32Array;
  55. /**
  56. * An array of indices in babylon space. right/left hand system is taken into account.
  57. * Indices will only be calculated if convertCoordinateSystems is set to true in the IWebXRMeshDetectorOptions.
  58. */
  59. indices?: Uint32Array;
  60. /**
  61. * An array of vertex normals in babylon space. right/left hand system is taken into account.
  62. * Normals will not be calculated if convertCoordinateSystems is undefined in the IWebXRMeshDetectorOptions.
  63. * Different platforms may or may not support mesh normals when convertCoordinateSystems is set to true.
  64. */
  65. normals?: Float32Array;
  66. /**
  67. * A transformation matrix to apply on the mesh that will be built using the meshDefinition.
  68. * Local vs. World are decided if worldParentNode was provided or not in the options when constructing the module.
  69. * TransformationMatrix will only be calculated if convertCoordinateSystems is set to true in the IWebXRMeshDetectorOptions.
  70. */
  71. transformationMatrix?: Matrix;
  72. }
  73. let meshIdProvider = 0;
  74. /**
  75. * The mesh detector is used to detect meshes in the real world when in AR
  76. */
  77. export class WebXRMeshDetector extends WebXRAbstractFeature {
  78. private _detectedMeshes: Map<XRMesh, IWebXRVertexData> = new Map<XRMesh, IWebXRVertexData>();
  79. /**
  80. * The module's name
  81. */
  82. public static readonly Name = WebXRFeatureName.MESH_DETECTION;
  83. /**
  84. * The (Babylon) version of this module.
  85. * This is an integer representing the implementation version.
  86. * This number does not correspond to the WebXR specs version
  87. */
  88. public static readonly Version = 1;
  89. /**
  90. * Observers registered here will be executed when a new mesh was added to the session
  91. */
  92. public onMeshAddedObservable: Observable<IWebXRVertexData> = new Observable();
  93. /**
  94. * Observers registered here will be executed when a mesh is no longer detected in the session
  95. */
  96. public onMeshRemovedObservable: Observable<IWebXRVertexData> = new Observable();
  97. /**
  98. * Observers registered here will be executed when an existing mesh updates
  99. */
  100. public onMeshUpdatedObservable: Observable<IWebXRVertexData> = new Observable();
  101. constructor(_xrSessionManager: WebXRSessionManager, private _options: IWebXRMeshDetectorOptions = {}) {
  102. super(_xrSessionManager);
  103. this.xrNativeFeatureName = "mesh-detection";
  104. if (this._xrSessionManager.session) {
  105. this._init();
  106. } else {
  107. this._xrSessionManager.onXRSessionInit.addOnce(() => {
  108. this._init();
  109. });
  110. }
  111. }
  112. public detach(): boolean {
  113. if (!super.detach()) {
  114. return false;
  115. }
  116. // Only supported by BabylonNative
  117. if (!!this._xrSessionManager.isNative &&
  118. !!this._xrSessionManager.session.trySetMeshDetectorEnabled) {
  119. this._xrSessionManager.session.trySetMeshDetectorEnabled(false);
  120. }
  121. if (!this._options.doNotRemoveMeshesOnSessionEnded) {
  122. this._detectedMeshes.forEach((mesh) => {
  123. this.onMeshRemovedObservable.notifyObservers(mesh);
  124. });
  125. this._detectedMeshes.clear();
  126. }
  127. return true;
  128. }
  129. public dispose(): void {
  130. super.dispose();
  131. this.onMeshAddedObservable.clear();
  132. this.onMeshRemovedObservable.clear();
  133. this.onMeshUpdatedObservable.clear();
  134. }
  135. protected _onXRFrame(frame: XRFrame) {
  136. // TODO remove try catch
  137. try {
  138. if (!this.attached || !frame) {
  139. return;
  140. }
  141. const detectedMeshes = frame.worldInformation?.detectedMeshes;
  142. if (!!detectedMeshes) {
  143. let toRemove = new Set<XRMesh>();
  144. this._detectedMeshes.forEach((vertexData, xrMesh) => {
  145. if (!detectedMeshes.has(xrMesh)) {
  146. toRemove.add(xrMesh);
  147. }
  148. });
  149. toRemove.forEach((xrMesh) => {
  150. const vertexData = this._detectedMeshes.get(xrMesh);
  151. if (!!vertexData) {
  152. this.onMeshRemovedObservable.notifyObservers(vertexData);
  153. this._detectedMeshes.delete(xrMesh);
  154. }
  155. });
  156. // now check for new ones
  157. detectedMeshes.forEach((xrMesh) => {
  158. if (!this._detectedMeshes.has(xrMesh)) {
  159. const partialVertexData: Partial<IWebXRVertexData> = {
  160. id: meshIdProvider++,
  161. xrMesh: xrMesh,
  162. };
  163. const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame);
  164. this._detectedMeshes.set(xrMesh, vertexData);
  165. this.onMeshAddedObservable.notifyObservers(vertexData);
  166. } else {
  167. // updated?
  168. if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) {
  169. const vertexData = this._detectedMeshes.get(xrMesh);
  170. if (!!vertexData) {
  171. this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame);
  172. this.onMeshUpdatedObservable.notifyObservers(vertexData);
  173. }
  174. }
  175. }
  176. });
  177. }
  178. } catch (error) {
  179. console.log(error.stack);
  180. }
  181. }
  182. private _init() {
  183. // Only supported by BabylonNative
  184. if (!!this._xrSessionManager.isNative) {
  185. if (!!this._xrSessionManager.session.trySetMeshDetectorEnabled) {
  186. this._xrSessionManager.session.trySetMeshDetectorEnabled(true);
  187. }
  188. if (!!this._options.preferredDetectorOptions &&
  189. !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) {
  190. this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions);
  191. }
  192. }
  193. }
  194. private _updateVertexDataWithXRMesh(xrMesh: XRMesh, mesh: Partial<IWebXRVertexData>, xrFrame: XRFrame): IWebXRVertexData {
  195. mesh.xrMesh = xrMesh;
  196. mesh.worldParentNode = this._options.worldParentNode;
  197. if (!!this._options.convertCoordinateSystems)
  198. {
  199. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  200. mesh.positions = new Float32Array(xrMesh.positions.length);
  201. for (let i = 0; i < xrMesh.positions.length; i += 3) {
  202. mesh.positions[i] = xrMesh.positions[i];
  203. mesh.positions[i + 1] = xrMesh.positions[i + 1];
  204. mesh.positions[i + 2] = -1 * xrMesh.positions[i + 2];
  205. }
  206. mesh.indices = new Uint32Array(xrMesh.indices.length);
  207. for (let i = 0; i < xrMesh.indices.length; i += 3) {
  208. mesh.indices[i] = xrMesh.indices[i];
  209. mesh.indices[i + 1] = xrMesh.indices[i + 2];
  210. mesh.indices[i + 2] = xrMesh.indices[i + 1];
  211. }
  212. if (!!xrMesh.normals) {
  213. mesh.normals = new Float32Array(xrMesh.normals.length);
  214. for (let i = 0; i < xrMesh.normals.length; i += 3) {
  215. mesh.normals[i] = xrMesh.normals[i];
  216. mesh.normals[i + 1] = xrMesh.normals[i + 1];
  217. mesh.normals[i + 2] = -1 * xrMesh.normals[i + 2];
  218. }
  219. }
  220. }
  221. else {
  222. mesh.positions = xrMesh.positions;
  223. mesh.indices = xrMesh.indices;
  224. mesh.normals = xrMesh.normals;
  225. }
  226. // matrix
  227. const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace);
  228. if (pose) {
  229. const mat = mesh.transformationMatrix || new Matrix();
  230. Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);
  231. if (!this._xrSessionManager.scene.useRightHandedSystem) {
  232. mat.toggleModelMatrixHandInPlace();
  233. }
  234. mesh.transformationMatrix = mat;
  235. if (this._options.worldParentNode) {
  236. mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);
  237. }
  238. }
  239. }
  240. return <IWebXRVertexData>mesh;
  241. }
  242. }
  243. WebXRFeaturesManager.AddWebXRFeature(
  244. WebXRMeshDetector.Name,
  245. (xrSessionManager, options) => {
  246. return () => new WebXRMeshDetector(xrSessionManager, options);
  247. },
  248. WebXRMeshDetector.Version,
  249. false
  250. );