WebXRHandTracking.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
  2. import { WebXRSessionManager } from "../webXRSessionManager";
  3. import { WebXRFeatureName } from "../webXRFeaturesManager";
  4. import { AbstractMesh } from "../../Meshes/abstractMesh";
  5. import { Mesh } from "../../Meshes/mesh";
  6. import { SphereBuilder } from "../../Meshes/Builders/sphereBuilder";
  7. import { WebXRInput } from "../webXRInput";
  8. import { WebXRInputSource } from "../webXRInputSource";
  9. import { Quaternion } from "../../Maths/math.vector";
  10. import { Nullable } from "../../types";
  11. import { PhysicsImpostor } from "../../Physics/physicsImpostor";
  12. import { WebXRFeaturesManager } from "../webXRFeaturesManager";
  13. import { IDisposable } from "../../scene";
  14. import { Observable } from "../../Misc/observable";
  15. /**
  16. * Configuration interface for the hand tracking feature
  17. */
  18. export interface IWebXRHandTrackingOptions {
  19. /**
  20. * The xrInput that will be used as source for new hands
  21. */
  22. xrInput: WebXRInput;
  23. /**
  24. * Configuration object for the joint meshes
  25. */
  26. jointMeshes?: {
  27. /**
  28. * Should the meshes created be invisible (defaults to false)
  29. */
  30. invisible?: boolean;
  31. /**
  32. * A source mesh to be used to create instances. Defaults to a sphere.
  33. * This mesh will be the source for all other (25) meshes.
  34. * It should have the general size of a single unit, as the instances will be scaled according to the provided radius
  35. */
  36. sourceMesh?: Mesh;
  37. /**
  38. * Should the source mesh stay visible. Defaults to false
  39. */
  40. keepOriginalVisible?: boolean;
  41. /**
  42. * Scale factor for all instances (defaults to 2)
  43. */
  44. scaleFactor?: number;
  45. /**
  46. * Should each instance have its own physics impostor
  47. */
  48. enablePhysics?: boolean;
  49. /**
  50. * If enabled, override default physics properties
  51. */
  52. physicsProps?: { friction?: number; restitution?: number; impostorType?: number };
  53. /**
  54. * For future use - a single hand-mesh that will be updated according to the XRHand data provided
  55. */
  56. handMesh?: AbstractMesh;
  57. };
  58. }
  59. /**
  60. * Parts of the hands divided to writs and finger names
  61. */
  62. export const enum HandPart {
  63. /**
  64. * HandPart - Wrist
  65. */
  66. WRIST = "wrist",
  67. /**
  68. * HandPart - The THumb
  69. */
  70. THUMB = "thumb",
  71. /**
  72. * HandPart - Index finger
  73. */
  74. INDEX = "index",
  75. /**
  76. * HandPart - Middle finger
  77. */
  78. MIDDLE = "middle",
  79. /**
  80. * HandPart - Ring finger
  81. */
  82. RING = "ring",
  83. /**
  84. * HandPart - Little finger
  85. */
  86. LITTLE = "little",
  87. }
  88. /**
  89. * Representing a single hand (with its corresponding native XRHand object)
  90. */
  91. export class WebXRHand implements IDisposable {
  92. /**
  93. * Hand-parts definition (key is HandPart)
  94. */
  95. public static HandPartsDefinition: { [key: string]: number[] };
  96. /**
  97. * Populate the HandPartsDefinition object.
  98. * This is called as a side effect since certain browsers don't have XRHand defined.
  99. */
  100. public static _PopulateHandPartsDefinition() {
  101. if (typeof XRHand !== "undefined") {
  102. WebXRHand.HandPartsDefinition = {
  103. [HandPart.WRIST]: [XRHand.WRIST],
  104. [HandPart.THUMB]: [XRHand.THUMB_METACARPAL, XRHand.THUMB_PHALANX_PROXIMAL, XRHand.THUMB_PHALANX_DISTAL, XRHand.THUMB_PHALANX_TIP],
  105. [HandPart.INDEX]: [XRHand.INDEX_METACARPAL, XRHand.INDEX_PHALANX_PROXIMAL, XRHand.INDEX_PHALANX_INTERMEDIATE, XRHand.INDEX_PHALANX_DISTAL, XRHand.INDEX_PHALANX_TIP],
  106. [HandPart.MIDDLE]: [XRHand.MIDDLE_METACARPAL, XRHand.MIDDLE_PHALANX_PROXIMAL, XRHand.MIDDLE_PHALANX_INTERMEDIATE, XRHand.MIDDLE_PHALANX_DISTAL, XRHand.MIDDLE_PHALANX_TIP],
  107. [HandPart.RING]: [XRHand.RING_METACARPAL, XRHand.RING_PHALANX_PROXIMAL, XRHand.RING_PHALANX_INTERMEDIATE, XRHand.RING_PHALANX_DISTAL, XRHand.RING_PHALANX_TIP],
  108. [HandPart.LITTLE]: [XRHand.LITTLE_METACARPAL, XRHand.LITTLE_PHALANX_PROXIMAL, XRHand.LITTLE_PHALANX_INTERMEDIATE, XRHand.LITTLE_PHALANX_DISTAL, XRHand.LITTLE_PHALANX_TIP],
  109. };
  110. }
  111. }
  112. /**
  113. * Construct a new hand object
  114. * @param xrController the controller to which the hand correlates
  115. * @param trackedMeshes the meshes to be used to track the hand joints
  116. */
  117. constructor(
  118. /** the controller to which the hand correlates */
  119. public readonly xrController: WebXRInputSource,
  120. /** the meshes to be used to track the hand joints */
  121. public readonly trackedMeshes: AbstractMesh[]) {}
  122. /**
  123. * Update this hand from the latest xr frame
  124. * @param xrFrame xrFrame to update from
  125. * @param referenceSpace The current viewer reference space
  126. * @param scaleFactor optional scale factor for the meshes
  127. */
  128. public updateFromXRFrame(xrFrame: XRFrame, referenceSpace: XRReferenceSpace, scaleFactor: number = 2) {
  129. const hand = this.xrController.inputSource.hand as XRJointSpace[];
  130. if (!hand) {
  131. return;
  132. }
  133. this.trackedMeshes.forEach((mesh, idx) => {
  134. const xrJoint = hand[idx];
  135. if (xrJoint) {
  136. let pose = xrFrame.getJointPose(xrJoint, referenceSpace);
  137. if (!pose || !pose.transform) {
  138. return;
  139. }
  140. // get the transformation. can be done with matrix decomposition as well
  141. const pos = pose.transform.position;
  142. const orientation = pose.transform.orientation;
  143. mesh.position.set(pos.x, pos.y, pos.z);
  144. mesh.rotationQuaternion!.set(orientation.x, orientation.y, orientation.z, orientation.w);
  145. // left handed system conversion
  146. if (!mesh.getScene().useRightHandedSystem) {
  147. mesh.position.z *= -1;
  148. mesh.rotationQuaternion!.z *= -1;
  149. mesh.rotationQuaternion!.w *= -1;
  150. }
  151. // get the radius of the joint. In general it is static, but just in case it does change we update it on each frame.
  152. const radius = (pose.radius || 0.008) * scaleFactor;
  153. mesh.scaling.set(radius, radius, radius);
  154. }
  155. });
  156. }
  157. /**
  158. * Get meshes of part of the hand
  159. * @param part the part of hand to get
  160. * @returns An array of meshes that correlate to the hand part requested
  161. */
  162. public getHandPartMeshes(part: HandPart): AbstractMesh[] {
  163. return WebXRHand.HandPartsDefinition[part].map((idx) => this.trackedMeshes[idx]);
  164. }
  165. /**
  166. * Dispose this Hand object
  167. */
  168. public dispose() {
  169. this.trackedMeshes.forEach((mesh) => mesh.dispose());
  170. }
  171. }
  172. // Populate the hand parts definition
  173. WebXRHand._PopulateHandPartsDefinition();
  174. /**
  175. * WebXR Hand Joint tracking feature, available for selected browsers and devices
  176. */
  177. export class WebXRHandTracking extends WebXRAbstractFeature {
  178. private static _idCounter = 0;
  179. /**
  180. * The module's name
  181. */
  182. public static readonly Name = WebXRFeatureName.HAND_TRACKING;
  183. /**
  184. * The (Babylon) version of this module.
  185. * This is an integer representing the implementation version.
  186. * This number does not correspond to the WebXR specs version
  187. */
  188. public static readonly Version = 1;
  189. /**
  190. * This observable will notify registered observers when a new hand object was added and initialized
  191. */
  192. public onHandAddedObservable: Observable<WebXRHand> = new Observable();
  193. /**
  194. * This observable will notify its observers right before the hand object is disposed
  195. */
  196. public onHandRemovedObservable: Observable<WebXRHand> = new Observable();
  197. private _hands: {
  198. [controllerId: string]: {
  199. id: number;
  200. handObject: WebXRHand;
  201. };
  202. } = {};
  203. /**
  204. * Creates a new instance of the hit test feature
  205. * @param _xrSessionManager an instance of WebXRSessionManager
  206. * @param options options to use when constructing this feature
  207. */
  208. constructor(
  209. _xrSessionManager: WebXRSessionManager,
  210. /**
  211. * options to use when constructing this feature
  212. */
  213. public readonly options: IWebXRHandTrackingOptions
  214. ) {
  215. super(_xrSessionManager);
  216. this.xrNativeFeatureName = "hand-tracking";
  217. }
  218. /**
  219. * Check if the needed objects are defined.
  220. * This does not mean that the feature is enabled, but that the objects needed are well defined.
  221. */
  222. public isCompatible(): boolean {
  223. return typeof XRHand !== "undefined";
  224. }
  225. /**
  226. * attach this feature
  227. * Will usually be called by the features manager
  228. *
  229. * @returns true if successful.
  230. */
  231. public attach(): boolean {
  232. if (!super.attach()) {
  233. return false;
  234. }
  235. this.options.xrInput.controllers.forEach(this._attachHand);
  236. this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);
  237. this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, (controller) => {
  238. // REMOVE the controller
  239. this._detachHand(controller.uniqueId);
  240. });
  241. return true;
  242. }
  243. /**
  244. * detach this feature.
  245. * Will usually be called by the features manager
  246. *
  247. * @returns true if successful.
  248. */
  249. public detach(): boolean {
  250. if (!super.detach()) {
  251. return false;
  252. }
  253. Object.keys(this._hands).forEach((controllerId) => {
  254. this._detachHand(controllerId);
  255. });
  256. return true;
  257. }
  258. /**
  259. * Dispose this feature and all of the resources attached
  260. */
  261. public dispose(): void {
  262. super.dispose();
  263. this.onHandAddedObservable.clear();
  264. }
  265. /**
  266. * Get the hand object according to the controller id
  267. * @param controllerId the controller id to which we want to get the hand
  268. * @returns null if not found or the WebXRHand object if found
  269. */
  270. public getHandByControllerId(controllerId: string): Nullable<WebXRHand> {
  271. return this._hands[controllerId]?.handObject || null;
  272. }
  273. /**
  274. * Get a hand object according to the requested handedness
  275. * @param handedness the handedness to request
  276. * @returns null if not found or the WebXRHand object if found
  277. */
  278. public getHandByHandedness(handedness: XRHandedness): Nullable<WebXRHand> {
  279. const handednesses = Object.keys(this._hands).map((key) => this._hands[key].handObject.xrController.inputSource.handedness);
  280. const found = handednesses.indexOf(handedness);
  281. if (found !== -1) {
  282. return this._hands[found].handObject;
  283. }
  284. return null;
  285. }
  286. protected _onXRFrame(_xrFrame: XRFrame): void {
  287. // iterate over the hands object
  288. Object.keys(this._hands).forEach((id) => {
  289. this._hands[id].handObject.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace, this.options.jointMeshes?.scaleFactor);
  290. });
  291. }
  292. private _attachHand = (xrController: WebXRInputSource) => {
  293. if (!xrController.inputSource.hand || this._hands[xrController.uniqueId]) {
  294. // already attached
  295. return;
  296. }
  297. const hand = xrController.inputSource.hand;
  298. const trackedMeshes: AbstractMesh[] = [];
  299. const originalMesh = this.options.jointMeshes?.sourceMesh || SphereBuilder.CreateSphere("jointParent", { diameter: 1 });
  300. originalMesh.isVisible = !!this.options.jointMeshes?.keepOriginalVisible;
  301. for (let i = 0; i < hand.length; ++i) {
  302. const newInstance = originalMesh.createInstance(`${xrController.uniqueId}-handJoint-${i}`);
  303. newInstance.isPickable = false;
  304. if (this.options.jointMeshes?.enablePhysics) {
  305. const props = this.options.jointMeshes.physicsProps || {};
  306. const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;
  307. newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, { mass: 0, ...props });
  308. }
  309. newInstance.rotationQuaternion = new Quaternion();
  310. trackedMeshes.push(newInstance);
  311. }
  312. const webxrHand = new WebXRHand(xrController, trackedMeshes);
  313. // get two new meshes
  314. this._hands[xrController.uniqueId] = {
  315. handObject: webxrHand,
  316. id: WebXRHandTracking._idCounter++,
  317. };
  318. this.onHandAddedObservable.notifyObservers(webxrHand);
  319. };
  320. private _detachHand(controllerId: string) {
  321. if (this._hands[controllerId]) {
  322. this.onHandRemovedObservable.notifyObservers(this._hands[controllerId].handObject);
  323. this._hands[controllerId].handObject.dispose();
  324. }
  325. }
  326. }
  327. //register the plugin
  328. WebXRFeaturesManager.AddWebXRFeature(
  329. WebXRHandTracking.Name,
  330. (xrSessionManager, options) => {
  331. return () => new WebXRHandTracking(xrSessionManager, options);
  332. },
  333. WebXRHandTracking.Version,
  334. false
  335. );