webXRFeaturesManager.ts 15 KB

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