webXRMotionControllerManager.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import {
  2. WebXRAbstractMotionController, IMotionControllerProfile,
  3. } from './webXRAbstractMotionController';
  4. import { WebXRGenericTriggerMotionController } from './webXRGenericMotionController';
  5. import { Scene } from '../../scene';
  6. import { Tools } from '../../Misc/tools';
  7. import { WebXRProfiledMotionController } from './webXRProfiledMotionController';
  8. /**
  9. * A construction function type to create a new controller based on an xrInput object
  10. */
  11. export type MotionControllerConstructor = (xrInput: XRInputSource, scene: Scene) => WebXRAbstractMotionController;
  12. /**
  13. * The MotionController Manager manages all registered motion controllers and loads the right one when needed.
  14. *
  15. * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets
  16. * it should be replaced with auto-loaded controllers.
  17. *
  18. * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes
  19. */
  20. export class WebXRMotionControllerManager {
  21. private static _AvailableControllers: { [type: string]: MotionControllerConstructor } = {};
  22. private static _Fallbacks: { [profileId: string]: string[] } = {};
  23. // cache for loading
  24. private static _ProfileLoadingPromises: { [profileName: string]: Promise<IMotionControllerProfile> } = {};
  25. private static _ProfilesList: Promise<{ [profile: string]: string }>;
  26. /**
  27. * The base URL of the online controller repository. Can be changed at any time.
  28. */
  29. public static BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist";
  30. /**
  31. * Which repository gets priority - local or online
  32. */
  33. public static PrioritizeOnlineRepository: boolean = true;
  34. /**
  35. * Use the online repository, or use only locally-defined controllers
  36. */
  37. public static UseOnlineRepository: boolean = true;
  38. /**
  39. * Clear the cache used for profile loading and reload when requested again
  40. */
  41. public static ClearProfilesCache() {
  42. delete this._ProfilesList;
  43. this._ProfileLoadingPromises = {};
  44. }
  45. /**
  46. * Register the default fallbacks.
  47. * This function is called automatically when this file is imported.
  48. */
  49. public static DefaultFallbacks() {
  50. this.RegisterFallbacksForProfileId("google-daydream", ["generic-touchpad"]);
  51. this.RegisterFallbacksForProfileId("htc-vive-focus", ["generic-trigger-touchpad"]);
  52. this.RegisterFallbacksForProfileId("htc-vive", ["generic-trigger-squeeze-touchpad"]);
  53. this.RegisterFallbacksForProfileId("magicleap-one", ["generic-trigger-squeeze-touchpad"]);
  54. this.RegisterFallbacksForProfileId("windows-mixed-reality", ["generic-trigger-squeeze-touchpad-thumbstick"]);
  55. this.RegisterFallbacksForProfileId("microsoft-mixed-reality", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
  56. this.RegisterFallbacksForProfileId("oculus-go", ["generic-trigger-touchpad"]);
  57. this.RegisterFallbacksForProfileId("oculus-touch-v2", ["oculus-touch", "generic-trigger-squeeze-thumbstick"]);
  58. this.RegisterFallbacksForProfileId("oculus-touch", ["generic-trigger-squeeze-thumbstick"]);
  59. this.RegisterFallbacksForProfileId("samsung-gearvr", ["windows-mixed-reality", "generic-trigger-squeeze-touchpad-thumbstick"]);
  60. this.RegisterFallbacksForProfileId("samsung-odyssey", ["generic-touchpad"]);
  61. this.RegisterFallbacksForProfileId("valve-index", ["generic-trigger-squeeze-touchpad-thumbstick"]);
  62. }
  63. /**
  64. * Find a fallback profile if the profile was not found. There are a few predefined generic profiles.
  65. * @param profileId the profile to which a fallback needs to be found
  66. * @return an array with corresponding fallback profiles
  67. */
  68. public static FindFallbackWithProfileId(profileId: string): string[] {
  69. const returnArray = this._Fallbacks[profileId] || [];
  70. returnArray.unshift(profileId);
  71. return returnArray;
  72. }
  73. /**
  74. * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile.
  75. * The order of search:
  76. *
  77. * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller
  78. * 2) (If not found) search in the gamepad id and try using it (legacy versions only)
  79. * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check)
  80. * 4) return the generic trigger controller if none were found
  81. *
  82. * @param xrInput the xrInput to which a new controller is initialized
  83. * @param scene the scene to which the model will be added
  84. * @param forceProfile force a certain profile for this controller
  85. * @return A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found
  86. */
  87. public static GetMotionControllerWithXRInput(xrInput: XRInputSource, scene: Scene, forceProfile?: string): Promise<WebXRAbstractMotionController> {
  88. const profileArray: string[] = [];
  89. if (forceProfile) {
  90. profileArray.push(forceProfile);
  91. }
  92. profileArray.push(...(xrInput.profiles || []));
  93. // emulator support
  94. if (profileArray.length && !profileArray[0]) {
  95. // remove the first "undefined" that the emulator is adding
  96. profileArray.pop();
  97. }
  98. // legacy support - try using the gamepad id
  99. if (xrInput.gamepad && xrInput.gamepad.id) {
  100. switch (xrInput.gamepad.id) {
  101. case (xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined):
  102. // oculus in gamepad id
  103. profileArray.push("oculus-touch-v2");
  104. break;
  105. }
  106. }
  107. // make sure microsoft/windows mixed reality works correctly
  108. const windowsMRIdx = profileArray.indexOf("windows-mixed-reality");
  109. if (windowsMRIdx !== -1) {
  110. profileArray.splice(windowsMRIdx, 0, "microsoft-mixed-reality");
  111. }
  112. if (!profileArray.length) {
  113. profileArray.push("generic-trigger");
  114. }
  115. if (this.UseOnlineRepository) {
  116. const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers;
  117. const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;
  118. return firstFunction.call(this, profileArray, xrInput, scene).catch(() => {
  119. return secondFunction.call(this, profileArray, xrInput, scene);
  120. });
  121. } else {
  122. // use only available functions
  123. return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene);
  124. }
  125. }
  126. /**
  127. * Register a new controller based on its profile. This function will be called by the controller classes themselves.
  128. *
  129. * If you are missing a profile, make sure it is imported in your source, otherwise it will not register.
  130. *
  131. * @param type the profile type to register
  132. * @param constructFunction the function to be called when loading this profile
  133. */
  134. public static RegisterController(type: string, constructFunction: MotionControllerConstructor) {
  135. this._AvailableControllers[type] = constructFunction;
  136. }
  137. /**
  138. * Register a fallback to a specific profile.
  139. * @param profileId the profileId that will receive the fallbacks
  140. * @param fallbacks A list of fallback profiles
  141. */
  142. public static RegisterFallbacksForProfileId(profileId: string, fallbacks: string[]): void {
  143. if (this._Fallbacks[profileId]) {
  144. this._Fallbacks[profileId].push(...fallbacks);
  145. } else {
  146. this._Fallbacks[profileId] = fallbacks;
  147. }
  148. }
  149. /**
  150. * Will update the list of profiles available in the repository
  151. * @return a promise that resolves to a map of profiles available online
  152. */
  153. public static UpdateProfilesList() {
  154. this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + '/profiles/profilesList.json', false).then((data) => {
  155. return JSON.parse(data.toString());
  156. });
  157. return this._ProfilesList;
  158. }
  159. private static _LoadProfileFromRepository(profileArray: string[], xrInput: XRInputSource, scene: Scene): Promise<WebXRAbstractMotionController> {
  160. return Promise.resolve().then(() => {
  161. if (!this._ProfilesList) {
  162. return this.UpdateProfilesList();
  163. } else {
  164. return this._ProfilesList;
  165. }
  166. }).then((profilesList: { [profile: string]: string }) => {
  167. // load the right profile
  168. for (let i = 0; i < profileArray.length; ++i) {
  169. // defensive
  170. if (!profileArray[i]) {
  171. continue;
  172. }
  173. if (profilesList[profileArray[i]]) {
  174. return profileArray[i];
  175. }
  176. }
  177. throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`);
  178. }).then((profileToLoad: string) => {
  179. // load the profile
  180. if (!this._ProfileLoadingPromises[profileToLoad]) {
  181. this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => <IMotionControllerProfile>JSON.parse(data as string));
  182. }
  183. return this._ProfileLoadingPromises[profileToLoad];
  184. }).then((profile: IMotionControllerProfile) => {
  185. return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl);
  186. });
  187. }
  188. private static _LoadProfilesFromAvailableControllers(profileArray: string[], xrInput: XRInputSource, scene: Scene) {
  189. // check fallbacks
  190. for (let i = 0; i < profileArray.length; ++i) {
  191. // defensive
  192. if (!profileArray[i]) {
  193. continue;
  194. }
  195. const fallbacks = this.FindFallbackWithProfileId(profileArray[i]);
  196. for (let j = 0; j < fallbacks.length; ++j) {
  197. const constructionFunction = this._AvailableControllers[fallbacks[j]];
  198. if (constructionFunction) {
  199. return Promise.resolve(constructionFunction(xrInput, scene));
  200. }
  201. }
  202. }
  203. throw new Error(`no controller requested was found in the available controllers list`);
  204. }
  205. }
  206. // register the generic profile(s) here so we will at least have them
  207. WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput: XRInputSource, scene: Scene) => {
  208. return new WebXRGenericTriggerMotionController(scene, <any>(xrInput.gamepad), xrInput.handedness);
  209. });
  210. // register fallbacks
  211. WebXRMotionControllerManager.DefaultFallbacks();