babylon.windowsMotionController.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. module BABYLON {
  2. class LoadedMeshInfo {
  3. public rootNode: AbstractMesh;
  4. public pointingPoseNode: AbstractMesh;
  5. public buttonMeshes: { [id: string] : IButtonMeshInfo; } = {};
  6. public axisMeshes: { [id: number] : IAxisMeshInfo; } = {};
  7. }
  8. interface IMeshInfo {
  9. index: number;
  10. value: AbstractMesh;
  11. }
  12. interface IButtonMeshInfo extends IMeshInfo {
  13. pressed: AbstractMesh;
  14. unpressed: AbstractMesh;
  15. }
  16. interface IAxisMeshInfo extends IMeshInfo {
  17. min: AbstractMesh;
  18. max: AbstractMesh;
  19. }
  20. export class WindowsMotionController extends WebVRController {
  21. private static readonly MODEL_BASE_URL:string = 'https://controllers.babylonjs.com/microsoft/';
  22. private static readonly MODEL_LEFT_FILENAME:string = 'left.glb';
  23. private static readonly MODEL_RIGHT_FILENAME:string = 'right.glb';
  24. public static readonly GAMEPAD_ID_PREFIX:string = 'Spatial Controller (Spatial Interaction Source) ';
  25. private static readonly GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  26. private _loadedMeshInfo: Nullable<LoadedMeshInfo>;
  27. private readonly _mapping = {
  28. // Semantic button names
  29. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  30. // A mapping of the button name to glTF model node name
  31. // that should be transformed by button value.
  32. buttonMeshNames: {
  33. 'trigger': 'SELECT',
  34. 'menu': 'MENU',
  35. 'grip': 'GRASP',
  36. 'thumbstick': 'THUMBSTICK_PRESS',
  37. 'trackpad': 'TOUCHPAD_PRESS'
  38. },
  39. // This mapping is used to translate from the Motion Controller to Babylon semantics
  40. buttonObservableNames: {
  41. 'trigger': 'onTriggerStateChangedObservable',
  42. 'menu': 'onSecondaryButtonStateChangedObservable',
  43. 'grip': 'onMainButtonStateChangedObservable',
  44. 'thumbstick': 'onPadStateChangedObservable',
  45. 'trackpad': 'onTrackpadChangedObservable'
  46. },
  47. // A mapping of the axis name to glTF model node name
  48. // that should be transformed by axis value.
  49. // This array mirrors the browserGamepad.axes array, such that
  50. // the mesh corresponding to axis 0 is in this array index 0.
  51. axisMeshNames: [
  52. 'THUMBSTICK_X',
  53. 'THUMBSTICK_Y',
  54. 'TOUCHPAD_TOUCH_X',
  55. 'TOUCHPAD_TOUCH_Y'
  56. ],
  57. pointingPoseMeshName: 'POINTING_POSE'
  58. };
  59. public onTrackpadChangedObservable = new Observable<ExtendedGamepadButton>();
  60. constructor(vrGamepad: any) {
  61. super(vrGamepad);
  62. this.controllerType = PoseEnabledControllerType.WINDOWS;
  63. this._loadedMeshInfo = null;
  64. }
  65. public get onTriggerButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  66. return this.onTriggerStateChangedObservable;
  67. }
  68. public get onMenuButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  69. return this.onSecondaryButtonStateChangedObservable;
  70. }
  71. public get onGripButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  72. return this.onMainButtonStateChangedObservable;
  73. }
  74. public get onThumbstickButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  75. return this.onPadStateChangedObservable;
  76. }
  77. public get onTouchpadButtonStateChangedObservable(): Observable<ExtendedGamepadButton> {
  78. return this.onTrackpadChangedObservable;
  79. }
  80. /**
  81. * Called once per frame by the engine.
  82. */
  83. public update() {
  84. super.update();
  85. // Only need to animate axes if there is a loaded mesh
  86. if (this._loadedMeshInfo) {
  87. if (this.browserGamepad.axes) {
  88. for (let axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  89. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  90. }
  91. }
  92. }
  93. }
  94. /**
  95. * Called once for each button that changed state since the last frame
  96. * @param buttonIdx Which button index changed
  97. * @param state New state of the button
  98. * @param changes Which properties on the state changed since last frame
  99. */
  100. protected handleButtonChange(buttonIdx: number, state: ExtendedGamepadButton, changes: GamepadButtonChanges) {
  101. let buttonName = this._mapping.buttons[buttonIdx];
  102. if (!buttonName) {
  103. return;
  104. }
  105. // Only emit events for buttons that we know how to map from index to name
  106. let observable = (<any>this)[(<any>(this._mapping.buttonObservableNames))[buttonName]];
  107. if (observable) {
  108. observable.notifyObservers(state);
  109. }
  110. this.lerpButtonTransform(buttonName, state.value);
  111. }
  112. protected lerpButtonTransform(buttonName: string, buttonValue: number) {
  113. // If there is no loaded mesh, there is nothing to transform.
  114. if (!this._loadedMeshInfo) {
  115. return;
  116. }
  117. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  118. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  119. return;
  120. }
  121. BABYLON.Quaternion.SlerpToRef(
  122. meshInfo.unpressed.rotationQuaternion,
  123. meshInfo.pressed.rotationQuaternion,
  124. buttonValue,
  125. meshInfo.value.rotationQuaternion);
  126. BABYLON.Vector3.LerpToRef(
  127. meshInfo.unpressed.position,
  128. meshInfo.pressed.position,
  129. buttonValue,
  130. meshInfo.value.position);
  131. }
  132. protected lerpAxisTransform(axis:number, axisValue: number) {
  133. if (!this._loadedMeshInfo) {
  134. return;
  135. }
  136. let meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  137. if (!meshInfo) {
  138. return;
  139. }
  140. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  141. return;
  142. }
  143. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  144. let lerpValue = axisValue * 0.5 + 0.5;
  145. BABYLON.Quaternion.SlerpToRef(
  146. meshInfo.min.rotationQuaternion,
  147. meshInfo.max.rotationQuaternion,
  148. lerpValue,
  149. meshInfo.value.rotationQuaternion);
  150. BABYLON.Vector3.LerpToRef(
  151. meshInfo.min.position,
  152. meshInfo.max.position,
  153. lerpValue,
  154. meshInfo.value.position);
  155. }
  156. /**
  157. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  158. * @param scene scene in which to add meshes
  159. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  160. */
  161. public initControllerMesh(scene: Scene, meshLoaded?: (mesh: AbstractMesh) => void, forceDefault = false) {
  162. let path: string;
  163. let filename: string;
  164. // Checking if GLB loader is present
  165. if (SceneLoader.GetPluginForExtension("glb")) {
  166. // Determine the device specific folder based on the ID suffix
  167. let device = 'default';
  168. if (this.id && !forceDefault) {
  169. let match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  170. device = ((match && match[0]) || device);
  171. }
  172. // Hand
  173. if (this.hand === 'left') {
  174. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  175. }
  176. else { // Right is the default if no hand is specified
  177. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  178. }
  179. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  180. } else {
  181. Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  182. path = GenericController.MODEL_BASE_URL;
  183. filename = GenericController.MODEL_FILENAME;
  184. }
  185. SceneLoader.ImportMesh("", path, filename, scene, (meshes: AbstractMesh[]) => {
  186. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  187. this._loadedMeshInfo = this.processModel(scene, meshes);
  188. if (!this._loadedMeshInfo) {
  189. return;
  190. }
  191. this._defaultModel = this._loadedMeshInfo.rootNode;
  192. this.attachToMesh(this._defaultModel);
  193. if (meshLoaded) {
  194. meshLoaded(this._defaultModel);
  195. }
  196. }, null, (scene: Scene, message: string) => {
  197. Tools.Log(message);
  198. Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  199. if (!forceDefault) {
  200. this.initControllerMesh(scene, meshLoaded, true);
  201. }
  202. });
  203. }
  204. /**
  205. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  206. * can be transformed by button presses and axes values, based on this._mapping.
  207. *
  208. * @param scene scene in which the meshes exist
  209. * @param meshes list of meshes that make up the controller model to process
  210. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  211. */
  212. private processModel(scene: Scene, meshes: AbstractMesh[]) : Nullable<LoadedMeshInfo> {
  213. let loadedMeshInfo = null;
  214. // Create a new mesh to contain the glTF hierarchy
  215. let parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  216. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  217. let childMesh : Nullable<AbstractMesh> = null;
  218. for (let i = 0; i < meshes.length; i++) {
  219. let mesh = meshes[i];
  220. if (!mesh.parent) {
  221. // Exclude controller meshes from picking results
  222. mesh.isPickable = false;
  223. // Handle root node, attach to the new parentMesh
  224. childMesh = mesh;
  225. break;
  226. }
  227. }
  228. if (childMesh) {
  229. childMesh.setParent(parentMesh);
  230. // Create our mesh info. Note that this method will always return non-null.
  231. loadedMeshInfo = this.createMeshInfo(parentMesh);
  232. } else {
  233. Tools.Warn('Could not find root node in model file.');
  234. }
  235. return loadedMeshInfo;
  236. }
  237. private createMeshInfo(rootNode: AbstractMesh) : LoadedMeshInfo {
  238. let loadedMeshInfo = new LoadedMeshInfo();
  239. var i;
  240. loadedMeshInfo.rootNode = rootNode;
  241. // Reset the caches
  242. loadedMeshInfo.buttonMeshes = {};
  243. loadedMeshInfo.axisMeshes = {};
  244. // Button Meshes
  245. for (i = 0; i < this._mapping.buttons.length; i++) {
  246. var buttonMeshName = (<any>this._mapping.buttonMeshNames)[this._mapping.buttons[i]];
  247. if (!buttonMeshName) {
  248. Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  249. continue;
  250. }
  251. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  252. if (!buttonMesh) {
  253. Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  254. continue;
  255. }
  256. var buttonMeshInfo = {
  257. index: i,
  258. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  259. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  260. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  261. };
  262. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  263. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  264. } else {
  265. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  266. Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  267. '(VALUE: ' + !!buttonMeshInfo.value +
  268. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  269. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  270. ')');
  271. }
  272. }
  273. // Axis Meshes
  274. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  275. var axisMeshName = this._mapping.axisMeshNames[i];
  276. if (!axisMeshName) {
  277. Tools.Log('Skipping unknown axis at index: ' + i);
  278. continue;
  279. }
  280. var axisMesh = getChildByName(rootNode, axisMeshName);
  281. if (!axisMesh) {
  282. Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  283. continue;
  284. }
  285. var axisMeshInfo = {
  286. index: i,
  287. value: getImmediateChildByName(axisMesh, 'VALUE'),
  288. min: getImmediateChildByName(axisMesh, 'MIN'),
  289. max: getImmediateChildByName(axisMesh, 'MAX')
  290. };
  291. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  292. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  293. } else {
  294. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  295. Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  296. '(VALUE: ' + !!axisMeshInfo.value +
  297. ', MIN: ' + !!axisMeshInfo.min +
  298. ', MAX:' + !!axisMeshInfo.max +
  299. ')');
  300. }
  301. }
  302. // Pointing Ray
  303. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  304. if (!loadedMeshInfo.pointingPoseNode) {
  305. Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  306. }
  307. return loadedMeshInfo;
  308. // Look through all children recursively. This will return null if no mesh exists with the given name.
  309. function getChildByName(node: Node, name: string) {
  310. return node.getChildMeshes(false, n => n.name === name)[0];
  311. }
  312. // Look through only immediate children. This will return null if no mesh exists with the given name.
  313. function getImmediateChildByName (node: Node, name: string) : AbstractMesh {
  314. return node.getChildMeshes(true, n => n.name == name)[0];
  315. }
  316. }
  317. public getForwardRay(length = 100): Ray {
  318. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  319. return super.getForwardRay(length);
  320. }
  321. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  322. var origin = m.getTranslation();
  323. var forward = new BABYLON.Vector3(0, 0, -1);
  324. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  325. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  326. return new Ray(origin, direction, length);
  327. }
  328. public dispose(): void {
  329. super.dispose();
  330. this.onTrackpadChangedObservable.clear();
  331. }
  332. }
  333. }