webXRMotionControllerManager.js 11 KB

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