poseEnabledController.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { Observable } from "Misc/observable";
  2. import { Nullable } from "types";
  3. import { Quaternion, Matrix, Vector3, Tmp } from "Maths/math";
  4. import { Node } from "node";
  5. import { TransformNode } from "Meshes/transformNode";
  6. import { AbstractMesh } from "Meshes/abstractMesh";
  7. import { Ray } from "Culling/ray";
  8. import { _TimeToken } from "Instrumentation/timeToken";
  9. import { _DepthCullingState, _StencilState, _AlphaState } from "States";
  10. import { Engine } from "Engines/engine";
  11. import { Gamepad } from "Gamepads/gamepad";
  12. import { ExtendedGamepadButton } from "./poseEnabledController";
  13. import { OculusTouchController } from "Gamepads/Controllers/oculusTouchController";
  14. import { WindowsMotionController } from "Gamepads/Controllers/windowsMotionController";
  15. import { ViveController } from "Gamepads/Controllers/viveController";
  16. import { GearVRController } from "Gamepads/Controllers/gearVRController";
  17. import { DaydreamController } from "Gamepads/Controllers/daydreamController";
  18. import { GenericController } from "Gamepads/Controllers/genericController";
  19. import { WebVRFreeCamera, PoseControlled, DevicePose } from "Cameras/VR/webVRCamera";
  20. import { TargetCamera } from "Cameras/targetCamera";
  21. /**
  22. * Defines the types of pose enabled controllers that are supported
  23. */
  24. export enum PoseEnabledControllerType {
  25. /**
  26. * HTC Vive
  27. */
  28. VIVE,
  29. /**
  30. * Oculus Rift
  31. */
  32. OCULUS,
  33. /**
  34. * Windows mixed reality
  35. */
  36. WINDOWS,
  37. /**
  38. * Samsung gear VR
  39. */
  40. GEAR_VR,
  41. /**
  42. * Google Daydream
  43. */
  44. DAYDREAM,
  45. /**
  46. * Generic
  47. */
  48. GENERIC
  49. }
  50. /**
  51. * Defines the MutableGamepadButton interface for the state of a gamepad button
  52. */
  53. export interface MutableGamepadButton {
  54. /**
  55. * Value of the button/trigger
  56. */
  57. value: number;
  58. /**
  59. * If the button/trigger is currently touched
  60. */
  61. touched: boolean;
  62. /**
  63. * If the button/trigger is currently pressed
  64. */
  65. pressed: boolean;
  66. }
  67. /**
  68. * Defines the ExtendedGamepadButton interface for a gamepad button which includes state provided by a pose controller
  69. * @hidden
  70. */
  71. export interface ExtendedGamepadButton extends GamepadButton {
  72. /**
  73. * If the button/trigger is currently pressed
  74. */
  75. readonly pressed: boolean;
  76. /**
  77. * If the button/trigger is currently touched
  78. */
  79. readonly touched: boolean;
  80. /**
  81. * Value of the button/trigger
  82. */
  83. readonly value: number;
  84. }
  85. /**
  86. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  87. */
  88. export class PoseEnabledControllerHelper {
  89. /**
  90. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  91. * @param vrGamepad the gamepad to initialized
  92. * @returns a vr controller of the type the gamepad identified as
  93. */
  94. public static InitiateController(vrGamepad: any) {
  95. // Oculus Touch
  96. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  97. return new OculusTouchController(vrGamepad);
  98. }
  99. // Windows Mixed Reality controllers
  100. else if (vrGamepad.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  101. return new WindowsMotionController(vrGamepad);
  102. }
  103. // HTC Vive
  104. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  105. return new ViveController(vrGamepad);
  106. }
  107. // Samsung/Oculus Gear VR or Oculus Go
  108. else if (vrGamepad.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  109. return new GearVRController(vrGamepad);
  110. }
  111. // Google Daydream
  112. else if (vrGamepad.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  113. return new DaydreamController(vrGamepad);
  114. }
  115. // Generic
  116. else {
  117. return new GenericController(vrGamepad);
  118. }
  119. }
  120. }
  121. /**
  122. * Defines the PoseEnabledController object that contains state of a vr capable controller
  123. */
  124. export class PoseEnabledController extends Gamepad implements PoseControlled {
  125. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  126. private _deviceRoomPosition = Vector3.Zero();
  127. private _deviceRoomRotationQuaternion = new Quaternion();
  128. /**
  129. * The device position in babylon space
  130. */
  131. public devicePosition = Vector3.Zero();
  132. /**
  133. * The device rotation in babylon space
  134. */
  135. public deviceRotationQuaternion = new Quaternion();
  136. /**
  137. * The scale factor of the device in babylon space
  138. */
  139. public deviceScaleFactor: number = 1;
  140. /**
  141. * (Likely devicePosition should be used instead) The device position in its room space
  142. */
  143. public position: Vector3;
  144. /**
  145. * (Likely deviceRotationQuaternion should be used instead) The device rotation in its room space
  146. */
  147. public rotationQuaternion: Quaternion;
  148. /**
  149. * The type of controller (Eg. Windows mixed reality)
  150. */
  151. public controllerType: PoseEnabledControllerType;
  152. protected _calculatedPosition: Vector3;
  153. private _calculatedRotation: Quaternion;
  154. /**
  155. * The raw pose from the device
  156. */
  157. public rawPose: DevicePose; //GamepadPose;
  158. // Used to convert 6dof controllers to 3dof
  159. private _trackPosition = true;
  160. private _maxRotationDistFromHeadset = Math.PI / 5;
  161. private _draggedRoomRotation = 0;
  162. /**
  163. * @hidden
  164. */
  165. public _disableTrackPosition(fixedPosition: Vector3) {
  166. if (this._trackPosition) {
  167. this._calculatedPosition.copyFrom(fixedPosition);
  168. this._trackPosition = false;
  169. }
  170. }
  171. /**
  172. * Internal, the mesh attached to the controller
  173. * @hidden
  174. */
  175. public _mesh: Nullable<AbstractMesh>; // a node that will be attached to this Gamepad
  176. private _poseControlledCamera: TargetCamera;
  177. private _leftHandSystemQuaternion: Quaternion = new Quaternion();
  178. /**
  179. * Internal, matrix used to convert room space to babylon space
  180. * @hidden
  181. */
  182. public _deviceToWorld = Matrix.Identity();
  183. /**
  184. * Node to be used when casting a ray from the controller
  185. * @hidden
  186. */
  187. public _pointingPoseNode: Nullable<TransformNode> = null;
  188. /**
  189. * Name of the child mesh that can be used to cast a ray from the controller
  190. */
  191. public static readonly POINTING_POSE = "POINTING_POSE";
  192. /**
  193. * Creates a new PoseEnabledController from a gamepad
  194. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  195. */
  196. constructor(browserGamepad: any) {
  197. super(browserGamepad.id, browserGamepad.index, browserGamepad);
  198. this.type = Gamepad.POSE_ENABLED;
  199. this.controllerType = PoseEnabledControllerType.GENERIC;
  200. this.position = Vector3.Zero();
  201. this.rotationQuaternion = new Quaternion();
  202. this._calculatedPosition = Vector3.Zero();
  203. this._calculatedRotation = new Quaternion();
  204. Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, this._leftHandSystemQuaternion);
  205. }
  206. private _workingMatrix = Matrix.Identity();
  207. /**
  208. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  209. */
  210. public update() {
  211. super.update();
  212. this._updatePoseAndMesh();
  213. }
  214. /**
  215. * Updates only the pose device and mesh without doing any button event checking
  216. */
  217. protected _updatePoseAndMesh() {
  218. var pose: GamepadPose = this.browserGamepad.pose;
  219. this.updateFromDevice(pose);
  220. if (!this._trackPosition && Engine.LastCreatedScene && Engine.LastCreatedScene.activeCamera && (<WebVRFreeCamera>Engine.LastCreatedScene.activeCamera).devicePosition) {
  221. var camera = <WebVRFreeCamera>Engine.LastCreatedScene.activeCamera;
  222. camera._computeDevicePosition();
  223. this._deviceToWorld.setTranslation(camera.devicePosition);
  224. if (camera.deviceRotationQuaternion) {
  225. var camera = camera;
  226. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(Tmp.Vector3[0]);
  227. // Find the radian distance away that the headset is from the controllers rotation
  228. var distanceAway = Math.atan2(Math.sin(Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(Tmp.Vector3[0].y - this._draggedRoomRotation));
  229. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  230. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  231. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  232. this._draggedRoomRotation += rotationAmount;
  233. // Rotate controller around headset
  234. var sin = Math.sin(-rotationAmount);
  235. var cos = Math.cos(-rotationAmount);
  236. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  237. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  238. }
  239. }
  240. }
  241. Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  242. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  243. Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  244. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  245. if (this._mesh) {
  246. this._mesh.position.copyFrom(this.devicePosition);
  247. if (this._mesh.rotationQuaternion) {
  248. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  249. }
  250. }
  251. }
  252. /**
  253. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  254. * @param poseData raw pose fromthe device
  255. */
  256. updateFromDevice(poseData: DevicePose) {
  257. if (poseData) {
  258. this.rawPose = poseData;
  259. if (poseData.position) {
  260. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  261. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  262. this._deviceRoomPosition.z *= -1;
  263. }
  264. if (this._trackPosition) {
  265. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  266. }
  267. this._calculatedPosition.addInPlace(this.position);
  268. }
  269. let pose = this.rawPose;
  270. if (poseData.orientation && pose.orientation) {
  271. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  272. if (this._mesh) {
  273. if (this._mesh.getScene().useRightHandedSystem) {
  274. this._deviceRoomRotationQuaternion.z *= -1;
  275. this._deviceRoomRotationQuaternion.w *= -1;
  276. } else {
  277. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  278. }
  279. }
  280. // if the camera is set, rotate to the camera's rotation
  281. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  282. }
  283. }
  284. }
  285. /**
  286. * @hidden
  287. */
  288. public _meshAttachedObservable = new Observable<AbstractMesh>();
  289. /**
  290. * Attaches a mesh to the controller
  291. * @param mesh the mesh to be attached
  292. */
  293. public attachToMesh(mesh: AbstractMesh) {
  294. if (this._mesh) {
  295. this._mesh.parent = null;
  296. }
  297. this._mesh = mesh;
  298. if (this._poseControlledCamera) {
  299. this._mesh.parent = this._poseControlledCamera;
  300. }
  301. if (!this._mesh.rotationQuaternion) {
  302. this._mesh.rotationQuaternion = new Quaternion();
  303. }
  304. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  305. this._updatePoseAndMesh();
  306. if (this._pointingPoseNode) {
  307. var parents = [];
  308. var obj: Node = this._pointingPoseNode;
  309. while (obj.parent) {
  310. parents.push(obj.parent);
  311. obj = obj.parent;
  312. }
  313. parents.reverse().forEach((p) => { p.computeWorldMatrix(true); });
  314. }
  315. this._meshAttachedObservable.notifyObservers(mesh);
  316. }
  317. /**
  318. * Attaches the controllers mesh to a camera
  319. * @param camera the camera the mesh should be attached to
  320. */
  321. public attachToPoseControlledCamera(camera: TargetCamera) {
  322. this._poseControlledCamera = camera;
  323. if (this._mesh) {
  324. this._mesh.parent = this._poseControlledCamera;
  325. }
  326. }
  327. /**
  328. * Disposes of the controller
  329. */
  330. public dispose() {
  331. if (this._mesh) {
  332. this._mesh.dispose();
  333. }
  334. this._mesh = null;
  335. super.dispose();
  336. }
  337. /**
  338. * The mesh that is attached to the controller
  339. */
  340. public get mesh(): Nullable<AbstractMesh> {
  341. return this._mesh;
  342. }
  343. /**
  344. * Gets the ray of the controller in the direction the controller is pointing
  345. * @param length the length the resulting ray should be
  346. * @returns a ray in the direction the controller is pointing
  347. */
  348. public getForwardRay(length = 100): Ray {
  349. if (!this.mesh) {
  350. return new Ray(Vector3.Zero(), new Vector3(0, 0, 1), length);
  351. }
  352. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  353. var origin = m.getTranslation();
  354. var forward = new Vector3(0, 0, -1);
  355. var forwardWorld = Vector3.TransformNormal(forward, m);
  356. var direction = Vector3.Normalize(forwardWorld);
  357. return new Ray(origin, direction, length);
  358. }
  359. }