webXRFeaturesManager.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import { WebXRSessionManager } from "./webXRSessionManager";
  2. import { IDisposable } from "../scene";
  3. import { Tools } from "../Misc/tools";
  4. /**
  5. * Defining the interface required for a (webxr) feature
  6. */
  7. export interface IWebXRFeature extends IDisposable {
  8. /**
  9. * Is this feature attached
  10. */
  11. attached: boolean;
  12. /**
  13. * Should auto-attach be disabled?
  14. */
  15. disableAutoAttach: boolean;
  16. /**
  17. * Attach the feature to the session
  18. * Will usually be called by the features manager
  19. *
  20. * @param force should attachment be forced (even when already attached)
  21. * @returns true if successful.
  22. */
  23. attach(force?: boolean): boolean;
  24. /**
  25. * Detach the feature from the session
  26. * Will usually be called by the features manager
  27. *
  28. * @returns true if successful.
  29. */
  30. detach(): boolean;
  31. /**
  32. * This function will be executed during before enabling the feature and can be used to not-allow enabling it.
  33. * Note that at this point the session has NOT started, so this is purely checking if the browser supports it
  34. *
  35. * @returns whether or not the feature is compatible in this environment
  36. */
  37. isCompatible(): boolean;
  38. /**
  39. * Was this feature disposed;
  40. */
  41. isDisposed: boolean;
  42. /**
  43. * The name of the native xr feature name, if applicable (like anchor, hit-test, or hand-tracking)
  44. */
  45. xrNativeFeatureName?: string;
  46. /**
  47. * A list of (Babylon WebXR) features this feature depends on
  48. */
  49. dependsOn?: string[];
  50. }
  51. /**
  52. * A list of the currently available features without referencing them
  53. */
  54. export class WebXRFeatureName {
  55. /**
  56. * The name of the anchor system feature
  57. */
  58. public static readonly ANCHOR_SYSTEM = "xr-anchor-system";
  59. /**
  60. * The name of the background remover feature
  61. */
  62. public static readonly BACKGROUND_REMOVER = "xr-background-remover";
  63. /**
  64. * The name of the hit test feature
  65. */
  66. public static readonly HIT_TEST = "xr-hit-test";
  67. /**
  68. * The name of the mesh detection feature
  69. */
  70. public static readonly MESH_DETECTION = "xr-mesh-detection";
  71. /**
  72. * physics impostors for xr controllers feature
  73. */
  74. public static readonly PHYSICS_CONTROLLERS = "xr-physics-controller";
  75. /**
  76. * The name of the plane detection feature
  77. */
  78. public static readonly PLANE_DETECTION = "xr-plane-detection";
  79. /**
  80. * The name of the pointer selection feature
  81. */
  82. public static readonly POINTER_SELECTION = "xr-controller-pointer-selection";
  83. /**
  84. * The name of the teleportation feature
  85. */
  86. public static readonly TELEPORTATION = "xr-controller-teleportation";
  87. /**
  88. * The name of the feature points feature.
  89. */
  90. public static readonly FEATURE_POINTS = "xr-feature-points";
  91. /**
  92. * The name of the hand tracking feature.
  93. */
  94. public static readonly HAND_TRACKING = "xr-hand-tracking";
  95. }
  96. /**
  97. * Defining the constructor of a feature. Used to register the modules.
  98. */
  99. export type WebXRFeatureConstructor = (xrSessionManager: WebXRSessionManager, options?: any) => () => IWebXRFeature;
  100. /**
  101. * The WebXR features manager is responsible of enabling or disabling features required for the current XR session.
  102. * It is mainly used in AR sessions.
  103. *
  104. * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version).
  105. */
  106. export class WebXRFeaturesManager implements IDisposable {
  107. private static readonly _AvailableFeatures: {
  108. [name: string]: {
  109. stable: number;
  110. latest: number;
  111. [version: number]: WebXRFeatureConstructor;
  112. };
  113. } = {};
  114. private _features: {
  115. [name: string]: {
  116. featureImplementation: IWebXRFeature;
  117. version: number;
  118. enabled: boolean;
  119. required: boolean;
  120. };
  121. } = {};
  122. /**
  123. * constructs a new features manages.
  124. *
  125. * @param _xrSessionManager an instance of WebXRSessionManager
  126. */
  127. constructor(private _xrSessionManager: WebXRSessionManager) {
  128. // when session starts / initialized - attach
  129. this._xrSessionManager.onXRSessionInit.add(() => {
  130. this.getEnabledFeatures().forEach((featureName) => {
  131. const feature = this._features[featureName];
  132. if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) {
  133. this.attachFeature(featureName);
  134. }
  135. });
  136. });
  137. // when session ends - detach
  138. this._xrSessionManager.onXRSessionEnded.add(() => {
  139. this.getEnabledFeatures().forEach((featureName) => {
  140. const feature = this._features[featureName];
  141. if (feature.enabled && feature.featureImplementation.attached) {
  142. // detach, but don't disable!
  143. this.detachFeature(featureName);
  144. }
  145. });
  146. });
  147. }
  148. /**
  149. * Used to register a module. After calling this function a developer can use this feature in the scene.
  150. * Mainly used internally.
  151. *
  152. * @param featureName the name of the feature to register
  153. * @param constructorFunction the function used to construct the module
  154. * @param version the (babylon) version of the module
  155. * @param stable is that a stable version of this module
  156. */
  157. public static AddWebXRFeature(featureName: string, constructorFunction: WebXRFeatureConstructor, version: number = 1, stable: boolean = false) {
  158. this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version };
  159. if (version > this._AvailableFeatures[featureName].latest) {
  160. this._AvailableFeatures[featureName].latest = version;
  161. }
  162. if (stable) {
  163. this._AvailableFeatures[featureName].stable = version;
  164. }
  165. this._AvailableFeatures[featureName][version] = constructorFunction;
  166. }
  167. /**
  168. * Returns a constructor of a specific feature.
  169. *
  170. * @param featureName the name of the feature to construct
  171. * @param version the version of the feature to load
  172. * @param xrSessionManager the xrSessionManager. Used to construct the module
  173. * @param options optional options provided to the module.
  174. * @returns a function that, when called, will return a new instance of this feature
  175. */
  176. public static ConstructFeature(featureName: string, version: number = 1, xrSessionManager: WebXRSessionManager, options?: any): () => IWebXRFeature {
  177. const constructorFunction = this._AvailableFeatures[featureName][version];
  178. if (!constructorFunction) {
  179. // throw an error? return nothing?
  180. throw new Error("feature not found");
  181. }
  182. return constructorFunction(xrSessionManager, options);
  183. }
  184. /**
  185. * Can be used to return the list of features currently registered
  186. *
  187. * @returns an Array of available features
  188. */
  189. public static GetAvailableFeatures() {
  190. return Object.keys(this._AvailableFeatures);
  191. }
  192. /**
  193. * Gets the versions available for a specific feature
  194. * @param featureName the name of the feature
  195. * @returns an array with the available versions
  196. */
  197. public static GetAvailableVersions(featureName: string) {
  198. return Object.keys(this._AvailableFeatures[featureName]);
  199. }
  200. /**
  201. * Return the latest unstable version of this feature
  202. * @param featureName the name of the feature to search
  203. * @returns the version number. if not found will return -1
  204. */
  205. public static GetLatestVersionOfFeature(featureName: string): number {
  206. return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1;
  207. }
  208. /**
  209. * Return the latest stable version of this feature
  210. * @param featureName the name of the feature to search
  211. * @returns the version number. if not found will return -1
  212. */
  213. public static GetStableVersionOfFeature(featureName: string): number {
  214. return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1;
  215. }
  216. /**
  217. * Attach a feature to the current session. Mainly used when session started to start the feature effect.
  218. * Can be used during a session to start a feature
  219. * @param featureName the name of feature to attach
  220. */
  221. public attachFeature(featureName: string) {
  222. const feature = this._features[featureName];
  223. if (feature && feature.enabled && !feature.featureImplementation.attached) {
  224. feature.featureImplementation.attach();
  225. }
  226. }
  227. /**
  228. * Can be used inside a session or when the session ends to detach a specific feature
  229. * @param featureName the name of the feature to detach
  230. */
  231. public detachFeature(featureName: string) {
  232. const feature = this._features[featureName];
  233. if (feature && feature.featureImplementation.attached) {
  234. feature.featureImplementation.detach();
  235. }
  236. }
  237. /**
  238. * Used to disable an already-enabled feature
  239. * The feature will be disposed and will be recreated once enabled.
  240. * @param featureName the feature to disable
  241. * @returns true if disable was successful
  242. */
  243. public disableFeature(featureName: string | { Name: string }): boolean {
  244. const name = typeof featureName === "string" ? featureName : featureName.Name;
  245. const feature = this._features[name];
  246. if (feature && feature.enabled) {
  247. feature.enabled = false;
  248. this.detachFeature(name);
  249. feature.featureImplementation.dispose();
  250. return true;
  251. }
  252. return false;
  253. }
  254. /**
  255. * dispose this features manager
  256. */
  257. public dispose(): void {
  258. this.getEnabledFeatures().forEach((feature) => {
  259. this.disableFeature(feature);
  260. this._features[feature].featureImplementation.dispose();
  261. });
  262. }
  263. /**
  264. * Enable a feature using its name and a version. This will enable it in the scene, and will be responsible to attach it when the session starts.
  265. * If used twice, the old version will be disposed and a new one will be constructed. This way you can re-enable with different configuration.
  266. *
  267. * @param featureName the name of the feature to load or the class of the feature
  268. * @param version optional version to load. if not provided the latest version will be enabled
  269. * @param moduleOptions options provided to the module. Ses the module documentation / constructor
  270. * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible
  271. * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available.
  272. * @returns a new constructed feature or throws an error if feature not found.
  273. */
  274. public enableFeature(featureName: string | { Name: string }, version: number | string = "latest", moduleOptions: any = {}, attachIfPossible: boolean = true, required: boolean = true): IWebXRFeature {
  275. const name = typeof featureName === "string" ? featureName : featureName.Name;
  276. let versionToLoad = 0;
  277. if (typeof version === "string") {
  278. if (!version) {
  279. throw new Error(`Error in provided version - ${name} (${version})`);
  280. }
  281. if (version === "stable") {
  282. versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name);
  283. } else if (version === "latest") {
  284. versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name);
  285. } else {
  286. // try loading the number the string represents
  287. versionToLoad = +version;
  288. }
  289. if (versionToLoad === -1 || isNaN(versionToLoad)) {
  290. throw new Error(`feature not found - ${name} (${version})`);
  291. }
  292. } else {
  293. versionToLoad = version;
  294. }
  295. // check if already initialized
  296. const feature = this._features[name];
  297. const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions);
  298. if (!constructFunction) {
  299. // report error?
  300. throw new Error(`feature not found - ${name}`);
  301. }
  302. /* If the feature is already enabled, detach and dispose it, and create a new one */
  303. if (feature) {
  304. this.disableFeature(name);
  305. }
  306. const constructed = constructFunction();
  307. if (constructed.dependsOn) {
  308. const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]);
  309. if (!dependentsFound) {
  310. throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(", ")}`);
  311. }
  312. }
  313. if (constructed.isCompatible()) {
  314. this._features[name] = {
  315. featureImplementation: constructed,
  316. enabled: true,
  317. version: versionToLoad,
  318. required,
  319. };
  320. if (attachIfPossible) {
  321. // if session started already, request and enable
  322. if (this._xrSessionManager.session && !this._features[name].featureImplementation.attached) {
  323. // enable feature
  324. this.attachFeature(name);
  325. }
  326. } else {
  327. // disable auto-attach when session starts
  328. this._features[name].featureImplementation.disableAutoAttach = true;
  329. }
  330. return this._features[name].featureImplementation;
  331. } else {
  332. if (required) {
  333. throw new Error("required feature not compatible");
  334. } else {
  335. Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`);
  336. return constructed;
  337. }
  338. }
  339. }
  340. /**
  341. * get the implementation of an enabled feature.
  342. * @param featureName the name of the feature to load
  343. * @returns the feature class, if found
  344. */
  345. public getEnabledFeature(featureName: string): IWebXRFeature {
  346. return this._features[featureName] && this._features[featureName].featureImplementation;
  347. }
  348. /**
  349. * Get the list of enabled features
  350. * @returns an array of enabled features
  351. */
  352. public getEnabledFeatures() {
  353. return Object.keys(this._features);
  354. }
  355. /**
  356. * This function will exten the session creation configuration object with enabled features.
  357. * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list,
  358. * according to the defined "required" variable, provided during enableFeature call
  359. * @param xrSessionInit the xr Session init object to extend
  360. *
  361. * @returns an extended XRSessionInit object
  362. */
  363. public extendXRSessionInitObject(xrSessionInit: XRSessionInit): XRSessionInit {
  364. const enabledFeatures = this.getEnabledFeatures();
  365. enabledFeatures.forEach((featureName) => {
  366. const feature = this._features[featureName];
  367. const nativeName = feature.featureImplementation.xrNativeFeatureName;
  368. if (nativeName) {
  369. if (feature.required) {
  370. xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || [];
  371. if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) {
  372. xrSessionInit.requiredFeatures.push(nativeName);
  373. }
  374. } else {
  375. xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || [];
  376. if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) {
  377. xrSessionInit.optionalFeatures.push(nativeName);
  378. }
  379. }
  380. }
  381. });
  382. return xrSessionInit;
  383. }
  384. }