WebXRControllerPointerSelection.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. import { WebXRFeaturesManager, IWebXRFeature } from "../webXRFeaturesManager";
  2. import { WebXRSessionManager } from '../webXRSessionManager';
  3. import { AbstractMesh } from '../../../Meshes/abstractMesh';
  4. import { Observer } from '../../../Misc/observable';
  5. import { WebXRInput } from '../webXRInput';
  6. import { WebXRController } from '../webXRController';
  7. import { Scene } from '../../../scene';
  8. import { WebXRControllerComponent } from '../motionController/webXRControllerComponent';
  9. import { Nullable } from '../../../types';
  10. import { Vector3 } from '../../../Maths/math.vector';
  11. import { Color3 } from '../../../Maths/math.color';
  12. import { Axis } from '../../../Maths/math.axis';
  13. import { StandardMaterial } from '../../../Materials/standardMaterial';
  14. import { CylinderBuilder } from '../../../Meshes/Builders/cylinderBuilder';
  15. import { TorusBuilder } from '../../../Meshes/Builders/torusBuilder';
  16. import { Ray } from '../../../Culling/ray';
  17. import { PickingInfo } from '../../../Collisions/pickingInfo';
  18. import { WebXRAbstractFeature } from './WebXRAbstractFeature';
  19. const Name = "xr-controller-pointer-selection";
  20. /**
  21. * Options interface for the pointer selection module
  22. */
  23. export interface IWebXRControllerPointerSelectionOptions {
  24. /**
  25. * the xr input to use with this pointer selection
  26. */
  27. xrInput: WebXRInput;
  28. /**
  29. * Different button type to use instead of the main component
  30. */
  31. overrideButtonId?: string;
  32. /**
  33. * The amount of time in miliseconds it takes between pick found something to a pointer down event.
  34. * Used in gaze modes. Tracked pointer uses the trigger, screen uses touch events
  35. * 3000 means 3 seconds between pointing at something and selecting it
  36. */
  37. timeToSelect?: number;
  38. /**
  39. * Disable the pointer up event when the xr controller in screen and gaze mode is disposed (meaning - when the user removed the finger from the screen)
  40. * If not disabled, the last picked point will be used to execute a pointer up event
  41. * If disabled, pointer up event will be triggered right after the pointer down event.
  42. * Used in screen and gaze target ray mode only
  43. */
  44. disablePointerUpOnTouchOut: boolean;
  45. /**
  46. * For gaze mode (time to select instead of press)
  47. */
  48. forceGazeMode: boolean;
  49. /**
  50. * Factor to be applied to the pointer-moved function in the gaze mode. How sensitive should the gaze mode be when checking if the pointer moved
  51. * to start a new countdown to the pointer down event.
  52. * Defaults to 1.
  53. */
  54. gazeModePointerMovedFactor?: number;
  55. }
  56. /**
  57. * A module that will enable pointer selection for motion controllers of XR Input Sources
  58. */
  59. export class WebXRControllerPointerSelection extends WebXRAbstractFeature implements IWebXRFeature {
  60. /**
  61. * The module's name
  62. */
  63. public static readonly Name = Name;
  64. /**
  65. * The (Babylon) version of this module.
  66. * This is an integer representing the implementation version.
  67. * This number does not correspond to the webxr specs version
  68. */
  69. public static readonly Version = 1;
  70. /**
  71. * This color will be set to the laser pointer when selection is triggered
  72. */
  73. public laserPointerPickedColor: Color3 = new Color3(0.9, 0.9, 0.9);
  74. /**
  75. * This color will be applied to the selection ring when selection is triggered
  76. */
  77. public selectionMeshPickedColor: Color3 = new Color3(0.3, 0.3, 1.0);
  78. /**
  79. * default color of the selection ring
  80. */
  81. public selectionMeshDefaultColor: Color3 = new Color3(0.8, 0.8, 0.8);
  82. /**
  83. * Default color of the laser pointer
  84. */
  85. public lasterPointerDefaultColor: Color3 = new Color3(0.7, 0.7, 0.7);
  86. /**
  87. * Should the laser pointer be displayed
  88. */
  89. public displayLaserPointer: boolean = true;
  90. /**
  91. * Should the selection mesh be displayed (The ring at the end of the laser pointer)
  92. */
  93. public displaySelectionMesh: boolean = true;
  94. /**
  95. * Disable lighting on the laser pointer (so it will always be visible)
  96. */
  97. public disablePointerLighting: boolean = true;
  98. /**
  99. * Disable lighting on the selection mesh (so it will always be visible)
  100. */
  101. public disableSelectionMeshLighting: boolean = true;
  102. private static _idCounter = 0;
  103. private _tmpRay = new Ray(new Vector3(), new Vector3());
  104. private _controllers: {
  105. [controllerUniqueId: string]: {
  106. xrController: WebXRController;
  107. selectionComponent?: WebXRControllerComponent;
  108. onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
  109. onFrameObserver?: Nullable<Observer<XRFrame>>;
  110. laserPointer: AbstractMesh;
  111. selectionMesh: AbstractMesh;
  112. pick: Nullable<PickingInfo>;
  113. id: number;
  114. };
  115. } = {};
  116. private _scene: Scene;
  117. /**
  118. * constructs a new background remover module
  119. * @param _xrSessionManager the session manager for this module
  120. * @param _options read-only options to be used in this module
  121. */
  122. constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
  123. super(_xrSessionManager);
  124. this._scene = this._xrSessionManager.scene;
  125. }
  126. /**
  127. * attach this feature
  128. * Will usually be called by the features manager
  129. *
  130. * @returns true if successful.
  131. */
  132. attach(): boolean {
  133. if (!super.attach()) {
  134. return false;
  135. }
  136. this._options.xrInput.controllers.forEach(this._attachController);
  137. this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
  138. this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
  139. // REMOVE the controller
  140. this._detachController(controller.uniqueId);
  141. });
  142. return true;
  143. }
  144. /**
  145. * detach this feature.
  146. * Will usually be called by the features manager
  147. *
  148. * @returns true if successful.
  149. */
  150. detach(): boolean {
  151. if (!super.detach()) {
  152. return false;
  153. }
  154. Object.keys(this._controllers).forEach((controllerId) => {
  155. this._detachController(controllerId);
  156. });
  157. return true;
  158. }
  159. /**
  160. * Get the xr controller that correlates to the pointer id in the pointer event
  161. *
  162. * @param id the pointer id to search for
  163. * @returns the controller that correlates to this id or null if not found
  164. */
  165. public getXRControllerByPointerId(id: number): Nullable<WebXRController> {
  166. const keys = Object.keys(this._controllers);
  167. for (let i = 0; i < keys.length; ++i) {
  168. if (this._controllers[keys[i]].id === id) {
  169. return this._controllers[keys[i]].xrController;
  170. }
  171. }
  172. return null;
  173. }
  174. protected _onXRFrame(_xrFrame: XRFrame) {
  175. Object.keys(this._controllers).forEach((id) => {
  176. const controllerData = this._controllers[id];
  177. // Every frame check collisions/input
  178. controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);
  179. controllerData.pick = this._scene.pickWithRay(this._tmpRay);
  180. const pick = controllerData.pick;
  181. if (pick && pick.pickedPoint && pick.hit) {
  182. // Update laser state
  183. this._updatePointerDistance(controllerData.laserPointer, pick.distance);
  184. // Update cursor state
  185. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  186. controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
  187. controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
  188. controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
  189. // To avoid z-fighting
  190. let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), this._tmpRay);
  191. let deltaFighting = 0.001;
  192. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  193. if (pickNormal) {
  194. let axis1 = Vector3.Cross(Axis.Y, pickNormal);
  195. let axis2 = Vector3.Cross(pickNormal, axis1);
  196. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
  197. controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
  198. }
  199. controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
  200. } else {
  201. controllerData.selectionMesh.isVisible = false;
  202. }
  203. });
  204. }
  205. private _attachController = (xrController: WebXRController) => {
  206. if (this._controllers[xrController.uniqueId]) {
  207. // already attached
  208. return;
  209. }
  210. // only support tracker pointer
  211. const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
  212. // get two new meshes
  213. this._controllers[xrController.uniqueId] = {
  214. xrController,
  215. laserPointer,
  216. selectionMesh,
  217. pick: null,
  218. id: WebXRControllerPointerSelection._idCounter++
  219. };
  220. switch (xrController.inputSource.targetRayMode) {
  221. case "tracked-pointer":
  222. return this._attachTrackedPointerRayMode(xrController);
  223. case "gaze":
  224. return this._attachGazeMode(xrController);
  225. case "screen":
  226. return this._attachScreenRayMode(xrController);
  227. }
  228. }
  229. private _attachScreenRayMode(xrController: WebXRController) {
  230. const controllerData = this._controllers[xrController.uniqueId];
  231. let downTriggered = false;
  232. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  233. if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
  234. if (!downTriggered) {
  235. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  236. downTriggered = true;
  237. if (this._options.disablePointerUpOnTouchOut) {
  238. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  239. }
  240. } else {
  241. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  242. }
  243. });
  244. xrController.onDisposeObservable.addOnce(() => {
  245. if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
  246. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  247. }
  248. });
  249. }
  250. private _attachGazeMode(xrController: WebXRController) {
  251. const controllerData = this._controllers[xrController.uniqueId];
  252. // attached when touched, detaches when raised
  253. const timeToSelect = this._options.timeToSelect || 3000;
  254. let oldPick = new PickingInfo();
  255. let discMesh = TorusBuilder.CreateTorus("selection", {
  256. diameter: 0.0035 * 15,
  257. thickness: 0.0025 * 6,
  258. tessellation: 20
  259. }, this._scene);
  260. discMesh.isVisible = false;
  261. discMesh.isPickable = false;
  262. discMesh.parent = controllerData.selectionMesh;
  263. let timer = 0;
  264. let downTriggered = false;
  265. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  266. if (!controllerData.pick) { return; }
  267. discMesh.isVisible = false;
  268. if (controllerData.pick.hit) {
  269. if (!this._pickingMoved(oldPick, controllerData.pick)) {
  270. if (timer > timeToSelect / 10) {
  271. discMesh.isVisible = true;
  272. }
  273. timer += this._scene.getEngine().getDeltaTime();
  274. if (timer >= timeToSelect) {
  275. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  276. downTriggered = true;
  277. // pointer up right after down, if disable on touch out
  278. if (this._options.disablePointerUpOnTouchOut) {
  279. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  280. }
  281. discMesh.isVisible = false;
  282. } else {
  283. const scaleFactor = 1 - (timer / timeToSelect);
  284. discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
  285. }
  286. } else {
  287. if (downTriggered) {
  288. if (!this._options.disablePointerUpOnTouchOut) {
  289. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  290. }
  291. }
  292. downTriggered = false;
  293. timer = 0;
  294. }
  295. } else {
  296. downTriggered = false;
  297. timer = 0;
  298. }
  299. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  300. oldPick = controllerData.pick;
  301. });
  302. xrController.onDisposeObservable.addOnce(() => {
  303. if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
  304. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  305. }
  306. discMesh.dispose();
  307. });
  308. }
  309. private _tmpVectorForPickCompare = new Vector3();
  310. private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
  311. if (!oldPick.hit || !newPick.hit) { return true; }
  312. if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
  313. if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
  314. oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
  315. this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
  316. const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
  317. const length = this._tmpVectorForPickCompare.length();
  318. if (length > delta) { return true; }
  319. return false;
  320. }
  321. private _attachTrackedPointerRayMode(xrController: WebXRController) {
  322. if (!xrController.motionController) {
  323. return;
  324. }
  325. if (this._options.forceGazeMode) {
  326. return this._attachGazeMode(xrController);
  327. }
  328. const controllerData = this._controllers[xrController.uniqueId];
  329. if (this._options.overrideButtonId) {
  330. controllerData.selectionComponent = xrController.motionController.getComponent(this._options.overrideButtonId);
  331. }
  332. if (!controllerData.selectionComponent) {
  333. controllerData.selectionComponent = xrController.motionController.getMainComponent();
  334. }
  335. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  336. if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
  337. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
  338. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
  339. } else {
  340. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
  341. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
  342. }
  343. controllerData.laserPointer.isVisible = this.displayLaserPointer;
  344. (<StandardMaterial>controllerData.laserPointer.material).disableLighting = this.disablePointerLighting;
  345. (<StandardMaterial>controllerData.selectionMesh.material).disableLighting = this.disableSelectionMeshLighting;
  346. if (controllerData.pick) {
  347. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  348. }
  349. });
  350. controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChanged.add((component) => {
  351. if (component.changes.pressed) {
  352. const pressed = component.changes.pressed.current;
  353. if (controllerData.pick) {
  354. if (pressed) {
  355. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  356. } else {
  357. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  358. }
  359. }
  360. }
  361. });
  362. }
  363. private _detachController(xrControllerUniqueId: string) {
  364. const controllerData = this._controllers[xrControllerUniqueId];
  365. if (!controllerData) { return; }
  366. if (controllerData.selectionComponent) {
  367. if (controllerData.onButtonChangedObserver) {
  368. controllerData.selectionComponent.onButtonStateChanged.remove(controllerData.onButtonChangedObserver);
  369. }
  370. }
  371. if (controllerData.onFrameObserver) {
  372. this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
  373. }
  374. controllerData.selectionMesh.dispose();
  375. controllerData.laserPointer.dispose();
  376. // remove from the map
  377. delete this._controllers[xrControllerUniqueId];
  378. }
  379. private _generateNewMeshPair(xrController: WebXRController) {
  380. const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
  381. height: 1,
  382. diameterTop: 0.0002,
  383. diameterBottom: 0.004,
  384. tessellation: 20,
  385. subdivisions: 1
  386. }, this._scene);
  387. laserPointer.parent = xrController.pointer;
  388. let laserPointerMaterial = new StandardMaterial("laserPointerMat", this._scene);
  389. laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
  390. laserPointerMaterial.alpha = 0.7;
  391. laserPointer.material = laserPointerMaterial;
  392. laserPointer.rotation.x = Math.PI / 2;
  393. this._updatePointerDistance(laserPointer, 1);
  394. laserPointer.isPickable = false;
  395. // Create a gaze tracker for the XR controller
  396. const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
  397. diameter: 0.0035 * 3,
  398. thickness: 0.0025 * 3,
  399. tessellation: 20
  400. }, this._scene);
  401. selectionMesh.bakeCurrentTransformIntoVertices();
  402. selectionMesh.isPickable = false;
  403. selectionMesh.isVisible = false;
  404. let targetMat = new StandardMaterial("targetMat", this._scene);
  405. targetMat.specularColor = Color3.Black();
  406. targetMat.emissiveColor = this.selectionMeshDefaultColor;
  407. targetMat.backFaceCulling = false;
  408. selectionMesh.material = targetMat;
  409. return {
  410. laserPointer,
  411. selectionMesh
  412. };
  413. }
  414. private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
  415. if (normal) {
  416. let angle = Math.acos(Vector3.Dot(normal, ray.direction));
  417. if (angle < Math.PI / 2) {
  418. normal.scaleInPlace(-1);
  419. }
  420. }
  421. return normal;
  422. }
  423. private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
  424. _laserPointer.scaling.y = distance;
  425. _laserPointer.position.z = distance / 2;
  426. }
  427. }
  428. //register the plugin
  429. WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  430. return () => new WebXRControllerPointerSelection(xrSessionManager, options);
  431. }, WebXRControllerPointerSelection.Version, true);