WebXRHandTracking.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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, Scene } from "../../scene";
  14. import { Observable } from "../../Misc/observable";
  15. import { InstancedMesh } from "../../Meshes/instancedMesh";
  16. import { SceneLoader } from "../../Loading/sceneLoader";
  17. import { Color3 } from "../../Maths/math.color";
  18. import { NodeMaterial } from "../../Materials/Node/nodeMaterial";
  19. import { InputBlock } from "../../Materials/Node/Blocks/Input/inputBlock";
  20. import { Material } from "../../Materials/material";
  21. import { Engine } from "../../Engines/engine";
  22. import { Tools } from "../../Misc/tools";
  23. import { Axis } from "../../Maths/math.axis";
  24. import { TransformNode } from "../../Meshes/transformNode";
  25. import { Tags } from "../../Misc/tags";
  26. import { Bone } from "../../Bones/bone";
  27. declare const XRHand: XRHand;
  28. /**
  29. * Configuration interface for the hand tracking feature
  30. */
  31. export interface IWebXRHandTrackingOptions {
  32. /**
  33. * The xrInput that will be used as source for new hands
  34. */
  35. xrInput: WebXRInput;
  36. /**
  37. * Configuration object for the joint meshes
  38. */
  39. jointMeshes?: {
  40. /**
  41. * Should the meshes created be invisible (defaults to false)
  42. */
  43. invisible?: boolean;
  44. /**
  45. * A source mesh to be used to create instances. Defaults to a sphere.
  46. * This mesh will be the source for all other (25) meshes.
  47. * It should have the general size of a single unit, as the instances will be scaled according to the provided radius
  48. */
  49. sourceMesh?: Mesh;
  50. /**
  51. * This function will be called after a mesh was created for a specific joint.
  52. * Using this function you can either manipulate the instance or return a new mesh.
  53. * When returning a new mesh the instance created before will be disposed
  54. */
  55. onHandJointMeshGenerated?: (meshInstance: InstancedMesh, jointId: number, controllerId: string) => Mesh | undefined;
  56. /**
  57. * Should the source mesh stay visible. Defaults to false
  58. */
  59. keepOriginalVisible?: boolean;
  60. /**
  61. * Scale factor for all instances (defaults to 2)
  62. */
  63. scaleFactor?: number;
  64. /**
  65. * Should each instance have its own physics impostor
  66. */
  67. enablePhysics?: boolean;
  68. /**
  69. * If enabled, override default physics properties
  70. */
  71. physicsProps?: { friction?: number; restitution?: number; impostorType?: number };
  72. /**
  73. * Should the default hand mesh be disabled. In this case, the spheres will be visible (unless set invisible).
  74. */
  75. disableDefaultHandMesh?: boolean;
  76. /**
  77. * a rigged hand-mesh that will be updated according to the XRHand data provided. This will override the default hand mesh
  78. */
  79. handMeshes?: {
  80. right: AbstractMesh;
  81. left: AbstractMesh;
  82. };
  83. /**
  84. * Are the meshes prepared for a left-handed system. Default hand meshes are right-handed.
  85. */
  86. leftHandedSystemMeshes?: boolean;
  87. /**
  88. * If a hand mesh was provided, this array will define what axis will update which node. This will override the default hand mesh
  89. */
  90. rigMapping?: {
  91. right: string[];
  92. left: string[];
  93. };
  94. /**
  95. * The utilityLayer scene that contains the 3D UI elements. Passing this in turns on near interactions with the index finger tip
  96. */
  97. sceneForNearInteraction?: Scene;
  98. };
  99. }
  100. /**
  101. * Parts of the hands divided to writs and finger names
  102. */
  103. export const enum HandPart {
  104. /**
  105. * HandPart - Wrist
  106. */
  107. WRIST = "wrist",
  108. /**
  109. * HandPart - The thumb
  110. */
  111. THUMB = "thumb",
  112. /**
  113. * HandPart - Index finger
  114. */
  115. INDEX = "index",
  116. /**
  117. * HandPart - Middle finger
  118. */
  119. MIDDLE = "middle",
  120. /**
  121. * HandPart - Ring finger
  122. */
  123. RING = "ring",
  124. /**
  125. * HandPart - Little finger
  126. */
  127. LITTLE = "little",
  128. }
  129. /**
  130. * Representing a single hand (with its corresponding native XRHand object)
  131. */
  132. export class WebXRHand implements IDisposable {
  133. private _scene: Scene;
  134. private _defaultHandMesh: boolean = false;
  135. private _transformNodeMapping: TransformNode[] = [];
  136. private _boneMapping: Bone[] = [];
  137. private _useBones = false;
  138. /**
  139. * Hand-parts definition (key is HandPart)
  140. */
  141. public handPartsDefinition: { [key: string]: number[] };
  142. /**
  143. * Observers will be triggered when the mesh for this hand was initialized.
  144. */
  145. public onHandMeshReadyObservable: Observable<WebXRHand> = new Observable();
  146. /**
  147. * Populate the HandPartsDefinition object.
  148. * This is called as a side effect since certain browsers don't have XRHand defined.
  149. */
  150. private generateHandPartsDefinition(hand: XRHand) {
  151. return {
  152. [HandPart.WRIST]: [hand.WRIST],
  153. [HandPart.THUMB]: [hand.THUMB_METACARPAL, hand.THUMB_PHALANX_PROXIMAL, hand.THUMB_PHALANX_DISTAL, hand.THUMB_PHALANX_TIP],
  154. [HandPart.INDEX]: [hand.INDEX_METACARPAL, hand.INDEX_PHALANX_PROXIMAL, hand.INDEX_PHALANX_INTERMEDIATE, hand.INDEX_PHALANX_DISTAL, hand.INDEX_PHALANX_TIP],
  155. [HandPart.MIDDLE]: [hand.MIDDLE_METACARPAL, hand.MIDDLE_PHALANX_PROXIMAL, hand.MIDDLE_PHALANX_INTERMEDIATE, hand.MIDDLE_PHALANX_DISTAL, hand.MIDDLE_PHALANX_TIP],
  156. [HandPart.RING]: [hand.RING_METACARPAL, hand.RING_PHALANX_PROXIMAL, hand.RING_PHALANX_INTERMEDIATE, hand.RING_PHALANX_DISTAL, hand.RING_PHALANX_TIP],
  157. [HandPart.LITTLE]: [hand.LITTLE_METACARPAL, hand.LITTLE_PHALANX_PROXIMAL, hand.LITTLE_PHALANX_INTERMEDIATE, hand.LITTLE_PHALANX_DISTAL, hand.LITTLE_PHALANX_TIP],
  158. };
  159. }
  160. /**
  161. * Construct a new hand object
  162. * @param xrController the controller to which the hand correlates
  163. * @param trackedMeshes the meshes to be used to track the hand joints
  164. * @param _handMesh an optional hand mesh. if not provided, ours will be used
  165. * @param _rigMapping an optional rig mapping for the hand mesh. if not provided, ours will be used
  166. * @param disableDefaultHandMesh should the default mesh creation be disabled
  167. * @param _nearInteractionMesh as optional mesh used for near interaction collision checking
  168. * @param _leftHandedMeshes are the hand meshes left-handed-system meshes
  169. */
  170. constructor(
  171. /** the controller to which the hand correlates */
  172. public readonly xrController: WebXRInputSource,
  173. /** the meshes to be used to track the hand joints */
  174. public readonly trackedMeshes: AbstractMesh[],
  175. private _handMesh?: AbstractMesh,
  176. private _rigMapping?: string[],
  177. disableDefaultHandMesh?: boolean,
  178. private _nearInteractionMesh?: Nullable<AbstractMesh>,
  179. private _leftHandedMeshes?: boolean
  180. ) {
  181. this.handPartsDefinition = this.generateHandPartsDefinition(xrController.inputSource.hand!);
  182. this._scene = trackedMeshes[0].getScene();
  183. this.onHandMeshReadyObservable.add(() => {
  184. // check if we should use bones or transform nodes
  185. if (!this._rigMapping) {
  186. return;
  187. }
  188. const transformNode = this._scene.getTransformNodeByName(this._rigMapping[0]);
  189. if (!transformNode) {
  190. const bone = this._scene.getBoneByName(this._rigMapping[0]);
  191. if (bone) {
  192. this._useBones = true;
  193. }
  194. }
  195. });
  196. if (this._handMesh && this._rigMapping) {
  197. this._defaultHandMesh = false;
  198. this._handMesh.alwaysSelectAsActiveMesh = true;
  199. this._handMesh.getChildMeshes().forEach((m) => (m.alwaysSelectAsActiveMesh = true));
  200. this.onHandMeshReadyObservable.notifyObservers(this);
  201. } else {
  202. if (!disableDefaultHandMesh) {
  203. this._generateDefaultHandMesh();
  204. }
  205. }
  206. // hide the motion controller, if available/loaded
  207. if (this.xrController.motionController) {
  208. if (this.xrController.motionController.rootMesh) {
  209. this.xrController.motionController.rootMesh.setEnabled(false);
  210. } else {
  211. this.xrController.motionController.onModelLoadedObservable.add((controller) => {
  212. if (controller.rootMesh) {
  213. controller.rootMesh.setEnabled(false);
  214. }
  215. });
  216. }
  217. }
  218. this.xrController.onMotionControllerInitObservable.add((motionController) => {
  219. motionController.onModelLoadedObservable.add((controller) => {
  220. if (controller.rootMesh) {
  221. controller.rootMesh.setEnabled(false);
  222. }
  223. });
  224. if (motionController.rootMesh) {
  225. motionController.rootMesh.setEnabled(false);
  226. }
  227. });
  228. }
  229. /**
  230. * Get the hand mesh. It is possible that the hand mesh is not yet ready!
  231. */
  232. public get handMesh() {
  233. return this._handMesh;
  234. }
  235. /**
  236. * Update this hand from the latest xr frame
  237. * @param xrFrame xrFrame to update from
  238. * @param referenceSpace The current viewer reference space
  239. * @param scaleFactor optional scale factor for the meshes
  240. */
  241. public updateFromXRFrame(xrFrame: XRFrame, referenceSpace: XRReferenceSpace, scaleFactor: number = 2) {
  242. const hand = this.xrController.inputSource.hand;
  243. if (!hand) {
  244. return;
  245. }
  246. this.trackedMeshes.forEach((mesh, idx) => {
  247. const xrJoint = hand[idx];
  248. if (xrJoint) {
  249. let pose = xrFrame.getJointPose!(xrJoint, referenceSpace);
  250. if (!pose || !pose.transform) {
  251. return;
  252. }
  253. // get the transformation. can be done with matrix decomposition as well
  254. const pos = pose.transform.position;
  255. const orientation = pose.transform.orientation;
  256. mesh.position.set(pos.x, pos.y, pos.z);
  257. mesh.rotationQuaternion!.set(orientation.x, orientation.y, orientation.z, orientation.w);
  258. // left handed system conversion
  259. // get the radius of the joint. In general it is static, but just in case it does change we update it on each frame.
  260. const radius = (pose.radius || 0.008) * scaleFactor;
  261. mesh.scaling.set(radius, radius, radius);
  262. // if we are using left-handed meshes, transform before applying to the hand mesh
  263. if (this._leftHandedMeshes && !mesh.getScene().useRightHandedSystem) {
  264. mesh.position.z *= -1;
  265. mesh.rotationQuaternion!.z *= -1;
  266. mesh.rotationQuaternion!.w *= -1;
  267. }
  268. // now check for the hand mesh
  269. if (this._handMesh && this._rigMapping) {
  270. if (this._rigMapping[idx]) {
  271. if (this._useBones) {
  272. this._boneMapping[idx] = this._boneMapping[idx] || this._scene.getBoneByName(this._rigMapping[idx]);
  273. if (this._boneMapping[idx]) {
  274. this._boneMapping[idx].setPosition(mesh.position);
  275. this._boneMapping[idx].setRotationQuaternion(mesh.rotationQuaternion!);
  276. mesh.isVisible = false;
  277. }
  278. } else {
  279. this._transformNodeMapping[idx] = this._transformNodeMapping[idx] || this._scene.getTransformNodeByName(this._rigMapping[idx]);
  280. if (this._transformNodeMapping[idx]) {
  281. this._transformNodeMapping[idx].position.copyFrom(mesh.position);
  282. this._transformNodeMapping[idx].rotationQuaternion!.copyFrom(mesh.rotationQuaternion!);
  283. // no scaling at the moment
  284. // this._transformNodeMapping[idx].scaling.copyFrom(mesh.scaling).scaleInPlace(20);
  285. mesh.isVisible = false;
  286. }
  287. }
  288. }
  289. }
  290. if (!this._leftHandedMeshes && !mesh.getScene().useRightHandedSystem) {
  291. mesh.position.z *= -1;
  292. mesh.rotationQuaternion!.z *= -1;
  293. mesh.rotationQuaternion!.w *= -1;
  294. }
  295. }
  296. });
  297. // Update the invisible fingertip collidable
  298. if (this._nearInteractionMesh) {
  299. const indexTipPose = this.trackedMeshes[hand.INDEX_PHALANX_TIP].position;
  300. this._nearInteractionMesh.position.set(indexTipPose.x, indexTipPose.y, indexTipPose.z);
  301. }
  302. }
  303. /**
  304. * Get meshes of part of the hand
  305. * @param part the part of hand to get
  306. * @returns An array of meshes that correlate to the hand part requested
  307. */
  308. public getHandPartMeshes(part: HandPart): AbstractMesh[] {
  309. return this.handPartsDefinition[part].map((idx) => this.trackedMeshes[idx]);
  310. }
  311. /**
  312. * Dispose this Hand object
  313. */
  314. public dispose() {
  315. this.trackedMeshes.forEach((mesh) => mesh.dispose());
  316. this._nearInteractionMesh?.dispose();
  317. this.onHandMeshReadyObservable.clear();
  318. // dispose the hand mesh, if it is the default one
  319. if (this._defaultHandMesh && this._handMesh) {
  320. this._handMesh.dispose();
  321. }
  322. }
  323. private async _generateDefaultHandMesh() {
  324. try {
  325. const handedness = this.xrController.inputSource.handedness === "right" ? "right" : "left";
  326. const filename = `${handedness === "right" ? "r" : "l"}_hand_${this._scene.useRightHandedSystem ? "r" : "l"}hs.glb`;
  327. const loaded = await SceneLoader.ImportMeshAsync("", "https://assets.babylonjs.com/meshes/HandMeshes/", filename, this._scene);
  328. // shader
  329. const handColors = {
  330. base: Color3.FromInts(116, 63, 203),
  331. fresnel: Color3.FromInts(149, 102, 229),
  332. fingerColor: Color3.FromInts(177, 130, 255),
  333. tipFresnel: Color3.FromInts(220, 200, 255),
  334. };
  335. const handShader = new NodeMaterial("leftHandShader", this._scene, { emitComments: false });
  336. await handShader.loadAsync("https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json");
  337. // build node materials
  338. handShader.build(false);
  339. // depth prepass and alpha mode
  340. handShader.needDepthPrePass = true;
  341. handShader.transparencyMode = Material.MATERIAL_ALPHABLEND;
  342. handShader.alphaMode = Engine.ALPHA_COMBINE;
  343. const handNodes = {
  344. base: handShader.getBlockByName("baseColor") as InputBlock,
  345. fresnel: handShader.getBlockByName("fresnelColor") as InputBlock,
  346. fingerColor: handShader.getBlockByName("fingerColor") as InputBlock,
  347. tipFresnel: handShader.getBlockByName("tipFresnelColor") as InputBlock,
  348. };
  349. handNodes.base.value = handColors.base;
  350. handNodes.fresnel.value = handColors.fresnel;
  351. handNodes.fingerColor.value = handColors.fingerColor;
  352. handNodes.tipFresnel.value = handColors.tipFresnel;
  353. loaded.meshes[1].material = handShader;
  354. loaded.meshes[1].alwaysSelectAsActiveMesh = true;
  355. this._defaultHandMesh = true;
  356. this._handMesh = loaded.meshes[0];
  357. this._rigMapping = [
  358. "wrist_",
  359. "thumb_metacarpal_",
  360. "thumb_proxPhalanx_",
  361. "thumb_distPhalanx_",
  362. "thumb_tip_",
  363. "index_metacarpal_",
  364. "index_proxPhalanx_",
  365. "index_intPhalanx_",
  366. "index_distPhalanx_",
  367. "index_tip_",
  368. "middle_metacarpal_",
  369. "middle_proxPhalanx_",
  370. "middle_intPhalanx_",
  371. "middle_distPhalanx_",
  372. "middle_tip_",
  373. "ring_metacarpal_",
  374. "ring_proxPhalanx_",
  375. "ring_intPhalanx_",
  376. "ring_distPhalanx_",
  377. "ring_tip_",
  378. "little_metacarpal_",
  379. "little_proxPhalanx_",
  380. "little_intPhalanx_",
  381. "little_distPhalanx_",
  382. "little_tip_",
  383. ].map((joint) => `${joint}${handedness === "right" ? "R" : "L"}`);
  384. // single change for left handed systems
  385. const tm = this._scene.getTransformNodeByName(this._rigMapping[0]);
  386. if (!tm) {
  387. throw new Error("could not find the wrist node");
  388. } else {
  389. tm.parent && (tm.parent as AbstractMesh).rotate(Axis.Y, Math.PI);
  390. }
  391. this.onHandMeshReadyObservable.notifyObservers(this);
  392. } catch (e) {
  393. Tools.Error("error loading hand mesh");
  394. console.log(e);
  395. }
  396. }
  397. }
  398. /**
  399. * WebXR Hand Joint tracking feature, available for selected browsers and devices
  400. */
  401. export class WebXRHandTracking extends WebXRAbstractFeature {
  402. private static _idCounter = 0;
  403. /**
  404. * The module's name
  405. */
  406. public static readonly Name = WebXRFeatureName.HAND_TRACKING;
  407. /**
  408. * The (Babylon) version of this module.
  409. * This is an integer representing the implementation version.
  410. * This number does not correspond to the WebXR specs version
  411. */
  412. public static readonly Version = 1;
  413. /**
  414. * This observable will notify registered observers when a new hand object was added and initialized
  415. */
  416. public onHandAddedObservable: Observable<WebXRHand> = new Observable();
  417. /**
  418. * This observable will notify its observers right before the hand object is disposed
  419. */
  420. public onHandRemovedObservable: Observable<WebXRHand> = new Observable();
  421. private _hands: {
  422. [controllerId: string]: {
  423. id: number;
  424. handObject: WebXRHand;
  425. };
  426. } = {};
  427. /**
  428. * Creates a new instance of the hit test feature
  429. * @param _xrSessionManager an instance of WebXRSessionManager
  430. * @param options options to use when constructing this feature
  431. */
  432. constructor(
  433. _xrSessionManager: WebXRSessionManager,
  434. /**
  435. * options to use when constructing this feature
  436. */
  437. public readonly options: IWebXRHandTrackingOptions
  438. ) {
  439. super(_xrSessionManager);
  440. this.xrNativeFeatureName = "hand-tracking";
  441. }
  442. /**
  443. * Check if the needed objects are defined.
  444. * This does not mean that the feature is enabled, but that the objects needed are well defined.
  445. */
  446. public isCompatible(): boolean {
  447. return typeof XRHand !== "undefined";
  448. }
  449. /**
  450. * attach this feature
  451. * Will usually be called by the features manager
  452. *
  453. * @returns true if successful.
  454. */
  455. public attach(): boolean {
  456. if (!super.attach()) {
  457. return false;
  458. }
  459. this.options.xrInput.controllers.forEach(this._attachHand);
  460. this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);
  461. this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, (controller) => {
  462. // REMOVE the controller
  463. this._detachHand(controller.uniqueId);
  464. });
  465. return true;
  466. }
  467. /**
  468. * detach this feature.
  469. * Will usually be called by the features manager
  470. *
  471. * @returns true if successful.
  472. */
  473. public detach(): boolean {
  474. if (!super.detach()) {
  475. return false;
  476. }
  477. Object.keys(this._hands).forEach((controllerId) => {
  478. this._detachHand(controllerId);
  479. });
  480. return true;
  481. }
  482. /**
  483. * Dispose this feature and all of the resources attached
  484. */
  485. public dispose(): void {
  486. super.dispose();
  487. this.onHandAddedObservable.clear();
  488. }
  489. /**
  490. * Get the hand object according to the controller id
  491. * @param controllerId the controller id to which we want to get the hand
  492. * @returns null if not found or the WebXRHand object if found
  493. */
  494. public getHandByControllerId(controllerId: string): Nullable<WebXRHand> {
  495. return this._hands[controllerId]?.handObject || null;
  496. }
  497. /**
  498. * Get a hand object according to the requested handedness
  499. * @param handedness the handedness to request
  500. * @returns null if not found or the WebXRHand object if found
  501. */
  502. public getHandByHandedness(handedness: XRHandedness): Nullable<WebXRHand> {
  503. const handednesses = Object.keys(this._hands).map((key) => this._hands[key].handObject.xrController.inputSource.handedness);
  504. const found = handednesses.indexOf(handedness);
  505. if (found !== -1) {
  506. return this._hands[found].handObject;
  507. }
  508. return null;
  509. }
  510. protected _onXRFrame(_xrFrame: XRFrame): void {
  511. // iterate over the hands object
  512. Object.keys(this._hands).forEach((id) => {
  513. this._hands[id].handObject.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace, this.options.jointMeshes?.scaleFactor);
  514. });
  515. }
  516. private _attachHand = (xrController: WebXRInputSource) => {
  517. if (!xrController.inputSource.hand || this._hands[xrController.uniqueId]) {
  518. // already attached
  519. return;
  520. }
  521. const hand = xrController.inputSource.hand;
  522. const trackedMeshes: AbstractMesh[] = [];
  523. const originalMesh = this.options.jointMeshes?.sourceMesh || SphereBuilder.CreateSphere("jointParent", { diameter: 1 });
  524. originalMesh.scaling.set(0.01, 0.01, 0.01);
  525. originalMesh.isVisible = !!this.options.jointMeshes?.keepOriginalVisible;
  526. for (let i = 0; i < hand.length; ++i) {
  527. let newInstance: AbstractMesh = originalMesh.createInstance(`${xrController.uniqueId}-handJoint-${i}`);
  528. if (this.options.jointMeshes?.onHandJointMeshGenerated) {
  529. const returnedMesh = this.options.jointMeshes.onHandJointMeshGenerated(newInstance as InstancedMesh, i, xrController.uniqueId);
  530. if (returnedMesh) {
  531. if (returnedMesh !== newInstance) {
  532. newInstance.dispose();
  533. newInstance = returnedMesh;
  534. }
  535. }
  536. }
  537. newInstance.isPickable = false;
  538. if (this.options.jointMeshes?.enablePhysics) {
  539. const props = this.options.jointMeshes.physicsProps || {};
  540. const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;
  541. newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, { mass: 0, ...props });
  542. }
  543. newInstance.rotationQuaternion = new Quaternion();
  544. if (this.options.jointMeshes?.invisible) {
  545. newInstance.isVisible = false;
  546. }
  547. trackedMeshes.push(newInstance);
  548. }
  549. let touchMesh: Nullable<AbstractMesh> = null;
  550. if (this.options.jointMeshes?.sceneForNearInteraction) {
  551. touchMesh = SphereBuilder.CreateSphere(`${xrController.uniqueId}-handJoint-indexCollidable`, {}, this.options.jointMeshes.sceneForNearInteraction);
  552. touchMesh.isVisible = false;
  553. Tags.AddTagsTo(touchMesh, "touchEnabled");
  554. }
  555. const handedness = xrController.inputSource.handedness === "right" ? "right" : "left";
  556. const handMesh = this.options.jointMeshes?.handMeshes && this.options.jointMeshes?.handMeshes[handedness];
  557. const rigMapping = this.options.jointMeshes?.rigMapping && this.options.jointMeshes?.rigMapping[handedness];
  558. const webxrHand = new WebXRHand(xrController, trackedMeshes, handMesh, rigMapping, this.options.jointMeshes?.disableDefaultHandMesh, touchMesh, this.options.jointMeshes?.leftHandedSystemMeshes);
  559. // get two new meshes
  560. this._hands[xrController.uniqueId] = {
  561. handObject: webxrHand,
  562. id: WebXRHandTracking._idCounter++,
  563. };
  564. this.onHandAddedObservable.notifyObservers(webxrHand);
  565. };
  566. private _detachHand(controllerId: string) {
  567. if (this._hands[controllerId]) {
  568. this.onHandRemovedObservable.notifyObservers(this._hands[controllerId].handObject);
  569. this._hands[controllerId].handObject.dispose();
  570. }
  571. }
  572. }
  573. //register the plugin
  574. WebXRFeaturesManager.AddWebXRFeature(
  575. WebXRHandTracking.Name,
  576. (xrSessionManager, options) => {
  577. return () => new WebXRHandTracking(xrSessionManager, options);
  578. },
  579. WebXRHandTracking.Version,
  580. false
  581. );