WebXRControllerPointerSelection.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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.7, 0.7, 0.7);
  74. /**
  75. * This color will be applied to the selection ring when selection is triggered
  76. */
  77. public selectionMeshPickedColor: Color3 = new Color3(0.7, 0.7, 0.7);
  78. /**
  79. * default color of the selection ring
  80. */
  81. public selectionMeshDefaultColor: Color3 = new Color3(0.5, 0.5, 0.5);
  82. /**
  83. * Default color of the laser pointer
  84. */
  85. public lasterPointerDefaultColor: Color3 = new Color3(0.5, 0.5, 0.5);
  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. private static _idCounter = 0;
  95. private _tmpRay = new Ray(new Vector3(), new Vector3());
  96. private _controllers: {
  97. [controllerUniqueId: string]: {
  98. xrController: WebXRController;
  99. selectionComponent?: WebXRControllerComponent;
  100. onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
  101. onFrameObserver?: Nullable<Observer<XRFrame>>;
  102. laserPointer: AbstractMesh;
  103. selectionMesh: AbstractMesh;
  104. pick: Nullable<PickingInfo>;
  105. id: number;
  106. };
  107. } = {};
  108. private _scene: Scene;
  109. /**
  110. * constructs a new background remover module
  111. * @param _xrSessionManager the session manager for this module
  112. * @param _options read-only options to be used in this module
  113. */
  114. constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRControllerPointerSelectionOptions) {
  115. super(_xrSessionManager);
  116. this._scene = this._xrSessionManager.scene;
  117. }
  118. /**
  119. * attach this feature
  120. * Will usually be called by the features manager
  121. *
  122. * @returns true if successful.
  123. */
  124. attach(): boolean {
  125. if (!super.attach()) {
  126. return false;
  127. }
  128. this._options.xrInput.controllers.forEach(this._attachController);
  129. this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
  130. this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
  131. // REMOVE the controller
  132. this._detachController(controller.uniqueId);
  133. });
  134. return true;
  135. }
  136. /**
  137. * detach this feature.
  138. * Will usually be called by the features manager
  139. *
  140. * @returns true if successful.
  141. */
  142. detach(): boolean {
  143. if (!super.detach()) {
  144. return false;
  145. }
  146. Object.keys(this._controllers).forEach((controllerId) => {
  147. this._detachController(controllerId);
  148. });
  149. return true;
  150. }
  151. /**
  152. * Get the xr controller that correlates to the pointer id in the pointer event
  153. *
  154. * @param id the pointer id to search for
  155. * @returns the controller that correlates to this id or null if not found
  156. */
  157. public getXRControllerByPointerId(id: number): Nullable<WebXRController> {
  158. const keys = Object.keys(this._controllers);
  159. for (let i = 0; i < keys.length; ++i) {
  160. if (this._controllers[keys[i]].id === id) {
  161. return this._controllers[keys[i]].xrController;
  162. }
  163. }
  164. return null;
  165. }
  166. protected _onXRFrame(_xrFrame: XRFrame) {
  167. Object.keys(this._controllers).forEach((id) => {
  168. const controllerData = this._controllers[id];
  169. // Every frame check collisions/input
  170. controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);
  171. controllerData.pick = this._scene.pickWithRay(this._tmpRay);
  172. const pick = controllerData.pick;
  173. if (pick && pick.pickedPoint && pick.hit) {
  174. // Update laser state
  175. this._updatePointerDistance(controllerData.laserPointer, pick.distance);
  176. // Update cursor state
  177. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  178. controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);
  179. controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);
  180. controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);
  181. // To avoid z-fighting
  182. let pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), this._tmpRay);
  183. let deltaFighting = 0.001;
  184. controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);
  185. if (pickNormal) {
  186. let axis1 = Vector3.Cross(Axis.Y, pickNormal);
  187. let axis2 = Vector3.Cross(pickNormal, axis1);
  188. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);
  189. controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));
  190. }
  191. controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;
  192. } else {
  193. controllerData.selectionMesh.isVisible = false;
  194. }
  195. });
  196. }
  197. private _attachController = (xrController: WebXRController) => {
  198. if (this._controllers[xrController.uniqueId]) {
  199. // already attached
  200. return;
  201. }
  202. // only support tracker pointer
  203. const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController);
  204. // get two new meshes
  205. this._controllers[xrController.uniqueId] = {
  206. xrController,
  207. laserPointer,
  208. selectionMesh,
  209. pick: null,
  210. id: WebXRControllerPointerSelection._idCounter++
  211. };
  212. switch (xrController.inputSource.targetRayMode) {
  213. case "tracked-pointer":
  214. return this._attachTrackedPointerRayMode(xrController);
  215. case "gaze":
  216. return this._attachGazeMode(xrController);
  217. case "screen":
  218. return this._attachScreenRayMode(xrController);
  219. }
  220. }
  221. private _attachScreenRayMode(xrController: WebXRController) {
  222. const controllerData = this._controllers[xrController.uniqueId];
  223. let downTriggered = false;
  224. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  225. if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { return; }
  226. if (!downTriggered) {
  227. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  228. downTriggered = true;
  229. if (this._options.disablePointerUpOnTouchOut) {
  230. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  231. }
  232. } else {
  233. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  234. }
  235. });
  236. xrController.onDisposeObservable.addOnce(() => {
  237. if (controllerData.pick && downTriggered && !this._options.disablePointerUpOnTouchOut) {
  238. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  239. }
  240. });
  241. }
  242. private _attachGazeMode(xrController: WebXRController) {
  243. const controllerData = this._controllers[xrController.uniqueId];
  244. // attached when touched, detaches when raised
  245. const timeToSelect = this._options.timeToSelect || 3000;
  246. let oldPick = new PickingInfo();
  247. let discMesh = TorusBuilder.CreateTorus("selection", {
  248. diameter: 0.0035 * 15,
  249. thickness: 0.0025 * 6,
  250. tessellation: 20
  251. }, this._scene);
  252. discMesh.isVisible = false;
  253. discMesh.isPickable = false;
  254. discMesh.parent = controllerData.selectionMesh;
  255. let timer = 0;
  256. let downTriggered = false;
  257. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  258. if (!controllerData.pick) { return; }
  259. discMesh.isVisible = false;
  260. if (controllerData.pick.hit) {
  261. if (!this._pickingMoved(oldPick, controllerData.pick)) {
  262. if (timer > timeToSelect / 10) {
  263. discMesh.isVisible = true;
  264. }
  265. timer += this._scene.getEngine().getDeltaTime();
  266. if (timer >= timeToSelect) {
  267. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  268. downTriggered = true;
  269. // pointer up right after down, if disable on touch out
  270. if (this._options.disablePointerUpOnTouchOut) {
  271. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  272. }
  273. discMesh.isVisible = false;
  274. } else {
  275. const scaleFactor = 1 - (timer / timeToSelect);
  276. discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);
  277. }
  278. } else {
  279. if (downTriggered) {
  280. if (!this._options.disablePointerUpOnTouchOut) {
  281. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  282. }
  283. }
  284. downTriggered = false;
  285. timer = 0;
  286. }
  287. } else {
  288. downTriggered = false;
  289. timer = 0;
  290. }
  291. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  292. oldPick = controllerData.pick;
  293. });
  294. xrController.onDisposeObservable.addOnce(() => {
  295. if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {
  296. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  297. }
  298. discMesh.dispose();
  299. });
  300. }
  301. private _tmpVectorForPickCompare = new Vector3();
  302. private _pickingMoved(oldPick: PickingInfo, newPick: PickingInfo) {
  303. if (!oldPick.hit || !newPick.hit) { return true; }
  304. if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { return true; }
  305. if (oldPick.pickedMesh !== newPick.pickedMesh) { return true; }
  306. oldPick.pickedPoint?.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);
  307. this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));
  308. const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 / newPick.distance;
  309. const length = this._tmpVectorForPickCompare.length();
  310. if (length > delta) { return true; }
  311. return false;
  312. }
  313. private _attachTrackedPointerRayMode(xrController: WebXRController) {
  314. if (!xrController.motionController) {
  315. return;
  316. }
  317. if (this._options.forceGazeMode) {
  318. return this._attachGazeMode(xrController);
  319. }
  320. const controllerData = this._controllers[xrController.uniqueId];
  321. if (this._options.overrideButtonId) {
  322. controllerData.selectionComponent = xrController.motionController.getComponent(this._options.overrideButtonId);
  323. }
  324. if (!controllerData.selectionComponent) {
  325. controllerData.selectionComponent = xrController.motionController.getMainComponent();
  326. }
  327. controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
  328. if (controllerData.selectionComponent && controllerData.selectionComponent.pressed) {
  329. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshPickedColor;
  330. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.laserPointerPickedColor;
  331. } else {
  332. (<StandardMaterial>controllerData.selectionMesh.material).emissiveColor = this.selectionMeshDefaultColor;
  333. (<StandardMaterial>controllerData.laserPointer.material).emissiveColor = this.lasterPointerDefaultColor;
  334. }
  335. controllerData.laserPointer.isVisible = this.displayLaserPointer;
  336. if (controllerData.pick) {
  337. this._scene.simulatePointerMove(controllerData.pick, { pointerId: controllerData.id });
  338. }
  339. });
  340. controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChanged.add((component) => {
  341. if (component.changes.pressed) {
  342. const pressed = component.changes.pressed.current;
  343. if (controllerData.pick) {
  344. if (pressed) {
  345. this._scene.simulatePointerDown(controllerData.pick, { pointerId: controllerData.id });
  346. } else {
  347. this._scene.simulatePointerUp(controllerData.pick, { pointerId: controllerData.id });
  348. }
  349. }
  350. }
  351. });
  352. }
  353. private _detachController(xrControllerUniqueId: string) {
  354. const controllerData = this._controllers[xrControllerUniqueId];
  355. if (!controllerData) { return; }
  356. if (controllerData.selectionComponent) {
  357. if (controllerData.onButtonChangedObserver) {
  358. controllerData.selectionComponent.onButtonStateChanged.remove(controllerData.onButtonChangedObserver);
  359. }
  360. }
  361. if (controllerData.onFrameObserver) {
  362. this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
  363. }
  364. controllerData.selectionMesh.dispose();
  365. controllerData.laserPointer.dispose();
  366. // remove from the map
  367. delete this._controllers[xrControllerUniqueId];
  368. }
  369. private _generateNewMeshPair(xrController: WebXRController) {
  370. const laserPointer = CylinderBuilder.CreateCylinder("laserPointer", {
  371. height: 1,
  372. diameterTop: 0.0002,
  373. diameterBottom: 0.004,
  374. tessellation: 20,
  375. subdivisions: 1
  376. }, this._scene);
  377. laserPointer.parent = xrController.pointer;
  378. let laserPointerMaterial = new StandardMaterial("laserPointerMat", this._scene);
  379. laserPointerMaterial.emissiveColor = this.lasterPointerDefaultColor;
  380. laserPointerMaterial.alpha = 0.6;
  381. laserPointer.material = laserPointerMaterial;
  382. laserPointer.rotation.x = Math.PI / 2;
  383. this._updatePointerDistance(laserPointer, 1);
  384. laserPointer.isPickable = false;
  385. // Create a gaze tracker for the XR controller
  386. const selectionMesh = TorusBuilder.CreateTorus("gazeTracker", {
  387. diameter: 0.0035 * 3,
  388. thickness: 0.0025 * 3,
  389. tessellation: 20
  390. }, this._scene);
  391. selectionMesh.bakeCurrentTransformIntoVertices();
  392. selectionMesh.isPickable = false;
  393. selectionMesh.isVisible = false;
  394. let targetMat = new StandardMaterial("targetMat", this._scene);
  395. targetMat.specularColor = Color3.Black();
  396. targetMat.emissiveColor = this.selectionMeshDefaultColor;
  397. targetMat.backFaceCulling = false;
  398. selectionMesh.material = targetMat;
  399. return {
  400. laserPointer,
  401. selectionMesh
  402. };
  403. }
  404. private _convertNormalToDirectionOfRay(normal: Nullable<Vector3>, ray: Ray) {
  405. if (normal) {
  406. let angle = Math.acos(Vector3.Dot(normal, ray.direction));
  407. if (angle < Math.PI / 2) {
  408. normal.scaleInPlace(-1);
  409. }
  410. }
  411. return normal;
  412. }
  413. private _updatePointerDistance(_laserPointer: AbstractMesh, distance: number = 100) {
  414. _laserPointer.scaling.y = distance;
  415. _laserPointer.position.z = distance / 2;
  416. }
  417. }
  418. //register the plugin
  419. WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {
  420. return () => new WebXRControllerPointerSelection(xrSessionManager, options);
  421. }, WebXRControllerPointerSelection.Version, true);