webXRInputSource.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import { Observable } from "../Misc/observable";
  2. import { AbstractMesh } from "../Meshes/abstractMesh";
  3. import { Quaternion, Vector3 } from '../Maths/math.vector';
  4. import { Ray } from '../Culling/ray';
  5. import { Scene } from '../scene';
  6. import { WebXRAbstractMotionController } from './motionController/webXRAbstractMotionController';
  7. import { WebXRMotionControllerManager } from './motionController/webXRMotionControllerManager';
  8. let idCount = 0;
  9. /**
  10. * Configuration options for the WebXR controller creation
  11. */
  12. export interface IWebXRControllerOptions {
  13. /**
  14. * Should the controller mesh be animated when a user interacts with it
  15. * The pressed buttons / thumbstick and touchpad animations will be disabled
  16. */
  17. disableMotionControllerAnimation?: boolean;
  18. /**
  19. * Do not load the controller mesh, in case a different mesh needs to be loaded.
  20. */
  21. doNotLoadControllerMesh?: boolean;
  22. /**
  23. * Force a specific controller type for this controller.
  24. * This can be used when creating your own profile or when testing different controllers
  25. */
  26. forceControllerProfile?: string;
  27. /**
  28. * Defines a rendering group ID for meshes that will be loaded.
  29. * This is for the default controllers only.
  30. */
  31. renderingGroupId?: number;
  32. }
  33. /**
  34. * Represents an XR controller
  35. */
  36. export class WebXRInputSource {
  37. private _tmpQuaternion = new Quaternion();
  38. private _tmpVector = new Vector3();
  39. private _uniqueId: string;
  40. /**
  41. * Represents the part of the controller that is held. This may not exist if the controller is the head mounted display itself, if thats the case only the pointer from the head will be availible
  42. */
  43. public grip?: AbstractMesh;
  44. /**
  45. * If available, this is the gamepad object related to this controller.
  46. * Using this object it is possible to get click events and trackpad changes of the
  47. * webxr controller that is currently being used.
  48. */
  49. public motionController?: WebXRAbstractMotionController;
  50. /**
  51. * Event that fires when the controller is removed/disposed.
  52. * The object provided as event data is this controller, after associated assets were disposed.
  53. * uniqueId is still available.
  54. */
  55. public onDisposeObservable = new Observable<WebXRInputSource>();
  56. /**
  57. * Will be triggered when the mesh associated with the motion controller is done loading.
  58. * It is also possible that this will never trigger (!) if no mesh was loaded, or if the developer decides to load a different mesh
  59. * A shortened version of controller -> motion controller -> on mesh loaded.
  60. */
  61. public onMeshLoadedObservable = new Observable<AbstractMesh>();
  62. /**
  63. * Observers registered here will trigger when a motion controller profile was assigned to this xr controller
  64. */
  65. public onMotionControllerInitObservable = new Observable<WebXRAbstractMotionController>();
  66. /**
  67. * Pointer which can be used to select objects or attach a visible laser to
  68. */
  69. public pointer: AbstractMesh;
  70. /**
  71. * Creates the controller
  72. * @see https://doc.babylonjs.com/how_to/webxr
  73. * @param _scene the scene which the controller should be associated to
  74. * @param inputSource the underlying input source for the controller
  75. * @param _options options for this controller creation
  76. */
  77. constructor(
  78. private _scene: Scene,
  79. /** The underlying input source for the controller */
  80. public inputSource: XRInputSource,
  81. private _options: IWebXRControllerOptions = {}) {
  82. this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`;
  83. this.pointer = new AbstractMesh(`${this._uniqueId}-pointer`, _scene);
  84. this.pointer.rotationQuaternion = new Quaternion();
  85. if (this.inputSource.gripSpace) {
  86. this.grip = new AbstractMesh(`${this._uniqueId}-grip`, this._scene);
  87. this.grip.rotationQuaternion = new Quaternion();
  88. }
  89. // for now only load motion controllers if gamepad object available
  90. if (this.inputSource.gamepad) {
  91. WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => {
  92. this.motionController = motionController;
  93. this.onMotionControllerInitObservable.notifyObservers(motionController);
  94. // should the model be loaded?
  95. if (!this._options.doNotLoadControllerMesh) {
  96. this.motionController.loadModel().then((success) => {
  97. if (success && this.motionController && this.motionController.rootMesh) {
  98. if (this._options.renderingGroupId) {
  99. // anything other than 0?
  100. this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId;
  101. this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => mesh.renderingGroupId = this._options.renderingGroupId!);
  102. }
  103. this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh);
  104. this.motionController.rootMesh.parent = this.grip || this.pointer;
  105. this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation;
  106. }
  107. });
  108. }
  109. });
  110. }
  111. }
  112. /**
  113. * Get this controllers unique id
  114. */
  115. public get uniqueId() {
  116. return this._uniqueId;
  117. }
  118. /**
  119. * Disposes of the object
  120. */
  121. public dispose() {
  122. if (this.grip) {
  123. this.grip.dispose();
  124. }
  125. if (this.motionController) {
  126. this.motionController.dispose();
  127. }
  128. this.pointer.dispose();
  129. this.onMotionControllerInitObservable.clear();
  130. this.onMeshLoadedObservable.clear();
  131. this.onDisposeObservable.notifyObservers(this);
  132. this.onDisposeObservable.clear();
  133. }
  134. /**
  135. * Gets a world space ray coming from the pointer or grip
  136. * @param result the resulting ray
  137. * @param gripIfAvailable use the grip mesh instead of the pointer, if available
  138. */
  139. public getWorldPointerRayToRef(result: Ray, gripIfAvailable: boolean = false) {
  140. const object = gripIfAvailable && this.grip ? this.grip : this.pointer;
  141. let worldMatrix = object.computeWorldMatrix();
  142. worldMatrix.decompose(undefined, this._tmpQuaternion, undefined);
  143. this._tmpVector.set(0, 0, (this._scene.useRightHandedSystem ? -1.0 : 1.0));
  144. this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector);
  145. result.origin.copyFrom(object.absolutePosition);
  146. result.direction.copyFrom(this._tmpVector);
  147. result.length = 1000;
  148. }
  149. /**
  150. * Updates the controller pose based on the given XRFrame
  151. * @param xrFrame xr frame to update the pose with
  152. * @param referenceSpace reference space to use
  153. */
  154. public updateFromXRFrame(xrFrame: XRFrame, referenceSpace: XRReferenceSpace) {
  155. let pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace);
  156. // Update the pointer mesh
  157. if (pose) {
  158. this.pointer.position.copyFrom(<any>(pose.transform.position));
  159. this.pointer.rotationQuaternion!.copyFrom(<any>(pose.transform.orientation));
  160. if (!this._scene.useRightHandedSystem) {
  161. this.pointer.position.z *= -1;
  162. this.pointer.rotationQuaternion!.z *= -1;
  163. this.pointer.rotationQuaternion!.w *= -1;
  164. }
  165. }
  166. // Update the grip mesh if it exists
  167. if (this.inputSource.gripSpace && this.grip) {
  168. let pose = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace);
  169. if (pose) {
  170. this.grip.position.copyFrom(<any>(pose.transform.position));
  171. this.grip.rotationQuaternion!.copyFrom(<any>(pose.transform.orientation));
  172. if (!this._scene.useRightHandedSystem) {
  173. this.grip.position.z *= -1;
  174. this.grip.rotationQuaternion!.z *= -1;
  175. this.grip.rotationQuaternion!.w *= -1;
  176. }
  177. }
  178. }
  179. if (this.motionController) {
  180. // either update buttons only or also position, if in gamepad mode
  181. this.motionController.updateFromXRFrame(xrFrame);
  182. }
  183. }
  184. }