babylon.vrExperienceHelper.ts 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  1. module BABYLON {
  2. /**
  3. * Options to modify the vr teleportation behavior.
  4. */
  5. export interface VRTeleportationOptions {
  6. /**
  7. * The name of the mesh which should be used as the teleportation floor. (default: null)
  8. */
  9. floorMeshName?: string;
  10. /**
  11. * A list of meshes to be used as the teleportation floor. (default: empty)
  12. */
  13. floorMeshes?: Mesh[];
  14. }
  15. /**
  16. * Options to modify the vr experience helper's behavior.
  17. */
  18. export interface VRExperienceHelperOptions extends WebVROptions {
  19. /**
  20. * Create a DeviceOrientationCamera to be used as your out of vr camera.
  21. */
  22. createDeviceOrientationCamera?: boolean;
  23. /**
  24. * Create a VRDeviceOrientationFreeCamera to be used for VR when no external HMD is found.
  25. */
  26. createFallbackVRDeviceOrientationFreeCamera?: boolean;
  27. }
  28. class VRExperienceHelperGazer implements IDisposable {
  29. public _gazeTracker:Mesh;
  30. public _currentMeshSelected:Nullable<AbstractMesh>;
  31. public _currentHit:Nullable<PickingInfo>;
  32. public static _idCounter = 0;
  33. public _id:number;
  34. public _pointerDownOnMeshAsked:boolean = false;
  35. public _isActionableMesh:boolean = false;
  36. public _interactionsEnabled: boolean;
  37. public _teleportationEnabled: boolean;
  38. public _teleportationRequestInitiated = false;
  39. public _teleportationBackRequestInitiated = false;
  40. public _rotationRightAsked = false;
  41. public _rotationLeftAsked = false;
  42. public _dpadPressed = true;
  43. public _activePointer = false;
  44. constructor(public scene: Scene, gazeTrackerToClone:Nullable<Mesh> = null){
  45. this._id = VRExperienceHelperGazer._idCounter++;
  46. // Gaze tracker
  47. if(!gazeTrackerToClone){
  48. this._gazeTracker = Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  49. this._gazeTracker.bakeCurrentTransformIntoVertices();
  50. this._gazeTracker.isPickable = false;
  51. this._gazeTracker.isVisible = false;
  52. var targetMat = new StandardMaterial("targetMat", scene);
  53. targetMat.specularColor = Color3.Black();
  54. targetMat.emissiveColor = new Color3(0.7, 0.7, 0.7)
  55. targetMat.backFaceCulling = false;
  56. this._gazeTracker.material = targetMat;
  57. }else{
  58. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  59. }
  60. }
  61. public _getForwardRay(length:number):Ray{
  62. return new Ray(Vector3.Zero(),new Vector3(0,0,length));
  63. }
  64. public _selectionPointerDown() {
  65. this._pointerDownOnMeshAsked = true;
  66. if (this._currentMeshSelected && this._currentHit) {
  67. this.scene.simulatePointerDown(this._currentHit, {pointerId: this._id});
  68. }
  69. }
  70. public _selectionPointerUp() {
  71. if (this._currentMeshSelected && this._currentHit) {
  72. this.scene.simulatePointerUp(this._currentHit, {pointerId: this._id});
  73. }
  74. this._pointerDownOnMeshAsked = false;
  75. }
  76. public _activatePointer() {
  77. this._activePointer = true;
  78. }
  79. public _deactivatePointer() {
  80. this._activePointer = false;
  81. }
  82. public _updatePointerDistance(distance:number = 100) {
  83. }
  84. public dispose(){
  85. this._interactionsEnabled = false;
  86. this._teleportationEnabled = false;
  87. if(this._gazeTracker){
  88. this._gazeTracker.dispose()
  89. }
  90. }
  91. }
  92. class VRExperienceHelperControllerGazer extends VRExperienceHelperGazer{
  93. private _laserPointer: Mesh;
  94. private _meshAttachedObserver: Nullable<Observer<AbstractMesh>>;
  95. constructor(public webVRController: WebVRController, scene: Scene, gazeTrackerToClone:Mesh){
  96. super(scene, gazeTrackerToClone);
  97. // Laser pointer
  98. this._laserPointer = Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  99. var laserPointerMaterial = new StandardMaterial("laserPointerMat", scene);
  100. laserPointerMaterial.emissiveColor = new Color3(0.7, 0.7, 0.7);
  101. laserPointerMaterial.alpha = 0.6;
  102. this._laserPointer.material = laserPointerMaterial;
  103. this._laserPointer.rotation.x = Math.PI / 2;
  104. this._laserPointer.position.z = -0.5;
  105. this._laserPointer.isVisible = false;
  106. if(!webVRController.mesh){
  107. // Create an empty mesh that is used prior to loading the high quality model
  108. var preloadMesh = new Mesh("preloadControllerMesh", scene);
  109. var preloadPointerPose = new Mesh(PoseEnabledController.POINTING_POSE, scene);
  110. preloadPointerPose.rotation.x = -0.7;
  111. preloadMesh.addChild(preloadPointerPose);
  112. webVRController.attachToMesh(preloadMesh);
  113. }
  114. this._setLaserPointerParent(webVRController.mesh!);
  115. this._meshAttachedObserver = webVRController._meshAttachedObservable.add((mesh)=>{
  116. this._setLaserPointerParent(mesh);
  117. });
  118. }
  119. _getForwardRay(length:number):Ray{
  120. return this.webVRController.getForwardRay(length);
  121. }
  122. public _activatePointer() {
  123. super._activatePointer();
  124. this._laserPointer.isVisible = true;
  125. }
  126. public _deactivatePointer() {
  127. super._deactivatePointer();
  128. this._laserPointer.isVisible = false;
  129. }
  130. public _setLaserPointerColor(color:Color3){
  131. (<StandardMaterial>this._laserPointer.material).emissiveColor = color;
  132. }
  133. public _setLaserPointerParent(mesh:AbstractMesh){
  134. var makeNotPick = (root: AbstractMesh) => {
  135. root.name += " laserPointer";
  136. root.getChildMeshes().forEach((c) => {
  137. makeNotPick(c);
  138. });
  139. }
  140. makeNotPick(mesh);
  141. var childMeshes = mesh.getChildMeshes();
  142. this.webVRController._pointingPoseNode = null;
  143. for (var i = 0; i < childMeshes.length; i++) {
  144. if (childMeshes[i].name && childMeshes[i].name.indexOf(PoseEnabledController.POINTING_POSE) >= 0) {
  145. mesh = childMeshes[i];
  146. this.webVRController._pointingPoseNode = mesh;
  147. break;
  148. }
  149. }
  150. this._laserPointer.parent = mesh;
  151. }
  152. public _updatePointerDistance(distance:number = 100) {
  153. this._laserPointer.scaling.y = distance;
  154. this._laserPointer.position.z = -distance / 2;
  155. }
  156. dispose(){
  157. super.dispose();
  158. this._laserPointer.dispose();
  159. if(this._meshAttachedObserver){
  160. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  161. }
  162. }
  163. }
  164. class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer{
  165. constructor(private getCamera:()=>Nullable<Camera>, scene: Scene){
  166. super(scene);
  167. }
  168. _getForwardRay(length:number):Ray{
  169. var camera = this.getCamera();
  170. if(camera){
  171. return camera.getForwardRay(length);
  172. }else{
  173. return new Ray(Vector3.Zero(), Vector3.Forward());
  174. }
  175. }
  176. }
  177. /**
  178. * Helps to quickly add VR support to an existing scene.
  179. * See http://doc.babylonjs.com/how_to/webvr_helper
  180. */
  181. export class VRExperienceHelper {
  182. private _scene: Scene;
  183. private _position: Vector3;
  184. private _btnVR: HTMLButtonElement;
  185. private _btnVRDisplayed: boolean;
  186. // Can the system support WebVR, even if a headset isn't plugged in?
  187. private _webVRsupported = false;
  188. // If WebVR is supported, is a headset plugged in and are we ready to present?
  189. private _webVRready = false;
  190. // Are we waiting for the requestPresent callback to complete?
  191. private _webVRrequesting = false;
  192. // Are we presenting to the headset right now?
  193. private _webVRpresenting = false;
  194. // Are we presenting in the fullscreen fallback?
  195. private _fullscreenVRpresenting = false;
  196. private _canvas: Nullable<HTMLCanvasElement>;
  197. private _webVRCamera: WebVRFreeCamera;
  198. private _vrDeviceOrientationCamera: Nullable<VRDeviceOrientationFreeCamera>;
  199. private _deviceOrientationCamera: Nullable<DeviceOrientationCamera>;
  200. private _existingCamera: Camera;
  201. private _onKeyDown: (event: KeyboardEvent) => void;
  202. private _onVrDisplayPresentChange: any;
  203. private _onVRDisplayChanged: (eventArgs: IDisplayChangedEventArgs) => void;
  204. private _onVRRequestPresentStart: () => void;
  205. private _onVRRequestPresentComplete: (success: boolean) => void;
  206. /**
  207. * Observable raised when entering VR.
  208. */
  209. public onEnteringVRObservable = new Observable<VRExperienceHelper>();
  210. /**
  211. * Observable raised when exiting VR.
  212. */
  213. public onExitingVRObservable = new Observable<VRExperienceHelper>();
  214. /**
  215. * Observable raised when controller mesh is loaded.
  216. */
  217. public onControllerMeshLoadedObservable = new Observable<WebVRController>();
  218. /** Return this.onEnteringVRObservable
  219. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  220. */
  221. public get onEnteringVR(): Observable<VRExperienceHelper> {
  222. return this.onEnteringVRObservable;
  223. }
  224. /** Return this.onExitingVRObservable
  225. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  226. */
  227. public get onExitingVR(): Observable<VRExperienceHelper> {
  228. return this.onExitingVRObservable;
  229. }
  230. /** Return this.onControllerMeshLoadedObservable
  231. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  232. */
  233. public get onControllerMeshLoaded(): Observable<WebVRController> {
  234. return this.onControllerMeshLoadedObservable;
  235. }
  236. private _rayLength: number;
  237. private _useCustomVRButton: boolean = false;
  238. private _teleportationRequested: boolean = false;
  239. private _teleportActive = false;
  240. private _floorMeshName: string;
  241. private _floorMeshesCollection: Mesh[] = [];
  242. private _rotationAllowed: boolean = true;
  243. private _teleportBackwardsVector = new Vector3(0, -1, -1);
  244. private _teleportationTarget: Mesh;
  245. private _isDefaultTeleportationTarget = true;
  246. private _postProcessMove: ImageProcessingPostProcess;
  247. private _teleportationFillColor: string = "#444444";
  248. private _teleportationBorderColor: string = "#FFFFFF";
  249. private _rotationAngle: number = 0;
  250. private _haloCenter = new Vector3(0, 0, 0);
  251. private _cameraGazer: VRExperienceHelperCameraGazer;
  252. private _padSensibilityUp = 0.65;
  253. private _padSensibilityDown = 0.35;
  254. private leftController:Nullable<VRExperienceHelperControllerGazer> = null;
  255. private rightController:Nullable<VRExperienceHelperControllerGazer> = null;
  256. /**
  257. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  258. */
  259. public onNewMeshSelected = new Observable<AbstractMesh>();
  260. /**
  261. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  262. */
  263. public onNewMeshPicked = new Observable<PickingInfo>();
  264. private _circleEase: CircleEase;
  265. /**
  266. * Observable raised before camera teleportation
  267. */
  268. public onBeforeCameraTeleport = new Observable<Vector3>();
  269. /**
  270. * Observable raised after camera teleportation
  271. */
  272. public onAfterCameraTeleport = new Observable<Vector3>();
  273. /**
  274. * Observable raised when current selected mesh gets unselected
  275. */
  276. public onSelectedMeshUnselected = new Observable<AbstractMesh>();
  277. private _raySelectionPredicate: (mesh: AbstractMesh) => boolean;
  278. /**
  279. * To be optionaly changed by user to define custom ray selection
  280. */
  281. public raySelectionPredicate: (mesh: AbstractMesh) => boolean;
  282. /**
  283. * To be optionaly changed by user to define custom selection logic (after ray selection)
  284. */
  285. public meshSelectionPredicate: (mesh: AbstractMesh) => boolean;
  286. /**
  287. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  288. */
  289. public teleportationEnabled: boolean = true;
  290. private _defaultHeight: number;
  291. private _teleportationInitialized = false;
  292. private _interactionsEnabled = false;
  293. private _interactionsRequested = false;
  294. private _displayGaze = true;
  295. private _displayLaserPointer = true;
  296. /**
  297. * The mesh used to display where the user is going to teleport.
  298. */
  299. public get teleportationTarget(): Mesh {
  300. return this._teleportationTarget;
  301. }
  302. /**
  303. * Sets the mesh to be used to display where the user is going to teleport.
  304. */
  305. public set teleportationTarget(value: Mesh) {
  306. if (value) {
  307. value.name = "teleportationTarget";
  308. this._isDefaultTeleportationTarget = false;
  309. this._teleportationTarget = value;
  310. }
  311. }
  312. /**
  313. * The mesh used to display where the user is selecting,
  314. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  315. * See http://doc.babylonjs.com/resources/baking_transformations
  316. */
  317. public get gazeTrackerMesh(): Mesh {
  318. return this._cameraGazer._gazeTracker;
  319. }
  320. public set gazeTrackerMesh(value: Mesh) {
  321. if (value) {
  322. this._cameraGazer._gazeTracker = value;
  323. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  324. this._cameraGazer._gazeTracker.isPickable = false;
  325. this._cameraGazer._gazeTracker.isVisible = false;
  326. this._cameraGazer._gazeTracker.name = "gazeTracker";
  327. if(this.leftController){
  328. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  329. }
  330. if(this.rightController){
  331. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  332. }
  333. }
  334. }
  335. /**
  336. * If the ray of the gaze should be displayed.
  337. */
  338. public get displayGaze(): boolean {
  339. return this._displayGaze;
  340. }
  341. /**
  342. * Sets if the ray of the gaze should be displayed.
  343. */
  344. public set displayGaze(value: boolean) {
  345. this._displayGaze = value;
  346. if (!value) {
  347. this._cameraGazer._gazeTracker.isVisible = false;
  348. if(this.leftController){
  349. this.leftController._gazeTracker.isVisible = false;
  350. }
  351. if(this.rightController){
  352. this.rightController._gazeTracker.isVisible = false;
  353. }
  354. }
  355. }
  356. /**
  357. * If the ray of the LaserPointer should be displayed.
  358. */
  359. public get displayLaserPointer(): boolean {
  360. return this._displayLaserPointer;
  361. }
  362. /**
  363. * Sets if the ray of the LaserPointer should be displayed.
  364. */
  365. public set displayLaserPointer(value: boolean) {
  366. this._displayLaserPointer = value;
  367. if (!value) {
  368. if (this.rightController) {
  369. this.rightController._deactivatePointer();
  370. this.rightController._gazeTracker.isVisible = false;
  371. }
  372. if (this.leftController) {
  373. this.leftController._deactivatePointer();
  374. this.leftController._gazeTracker.isVisible = false;
  375. }
  376. }
  377. else {
  378. if (this.rightController) {
  379. this.rightController._activatePointer();
  380. }
  381. if (this.leftController) {
  382. this.leftController._activatePointer();
  383. }
  384. }
  385. }
  386. /**
  387. * The deviceOrientationCamera used as the camera when not in VR.
  388. */
  389. public get deviceOrientationCamera(): Nullable<DeviceOrientationCamera> {
  390. return this._deviceOrientationCamera;
  391. }
  392. /**
  393. * Based on the current WebVR support, returns the current VR camera used.
  394. */
  395. public get currentVRCamera(): Nullable<Camera> {
  396. if (this._webVRready) {
  397. return this._webVRCamera;
  398. }
  399. else {
  400. return this._scene.activeCamera;
  401. }
  402. }
  403. /**
  404. * The webVRCamera which is used when in VR.
  405. */
  406. public get webVRCamera(): WebVRFreeCamera {
  407. return this._webVRCamera;
  408. }
  409. /**
  410. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  411. */
  412. public get vrDeviceOrientationCamera(): Nullable<VRDeviceOrientationFreeCamera> {
  413. return this._vrDeviceOrientationCamera;
  414. }
  415. private get _teleportationRequestInitiated(): boolean {
  416. var result = this._cameraGazer._teleportationRequestInitiated
  417. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  418. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  419. return result;
  420. }
  421. /**
  422. * Instantiates a VRExperienceHelper.
  423. * Helps to quickly add VR support to an existing scene.
  424. * @param scene The scene the VRExperienceHelper belongs to.
  425. * @param webVROptions Options to modify the vr experience helper's behavior.
  426. */
  427. constructor(scene: Scene, /** Options to modify the vr experience helper's behavior. */public webVROptions: VRExperienceHelperOptions = {}) {
  428. this._scene = scene;
  429. this._canvas = scene.getEngine().getRenderingCanvas();
  430. // Parse options
  431. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  432. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  433. }
  434. if (webVROptions.createDeviceOrientationCamera === undefined) {
  435. webVROptions.createDeviceOrientationCamera = true;
  436. }
  437. if (webVROptions.defaultHeight === undefined) {
  438. webVROptions.defaultHeight = 1.7;
  439. }
  440. if (webVROptions.useCustomVRButton) {
  441. this._useCustomVRButton = true;
  442. if (webVROptions.customVRButton) {
  443. this._btnVR = webVROptions.customVRButton;
  444. }
  445. }
  446. if (webVROptions.rayLength) {
  447. this._rayLength = webVROptions.rayLength
  448. }
  449. this._defaultHeight = webVROptions.defaultHeight;
  450. if(webVROptions.positionScale){
  451. this._rayLength *= webVROptions.positionScale;
  452. this._defaultHeight *= webVROptions.positionScale;
  453. }
  454. // Set position
  455. if (this._scene.activeCamera) {
  456. this._position = this._scene.activeCamera.position.clone();
  457. } else {
  458. this._position = new Vector3(0, this._defaultHeight, 0);
  459. }
  460. // Set non-vr camera
  461. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  462. this._deviceOrientationCamera = new DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  463. // Copy data from existing camera
  464. if (this._scene.activeCamera) {
  465. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  466. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  467. // Set rotation from previous camera
  468. if (this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation) {
  469. var targetCamera = this._scene.activeCamera;
  470. if (targetCamera.rotationQuaternion) {
  471. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  472. } else {
  473. this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  474. }
  475. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  476. }
  477. }
  478. this._scene.activeCamera = this._deviceOrientationCamera;
  479. if (this._canvas) {
  480. this._scene.activeCamera.attachControl(this._canvas);
  481. }
  482. } else {
  483. this._existingCamera = this._scene.activeCamera;
  484. }
  485. // Create VR cameras
  486. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  487. this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  488. }
  489. this._webVRCamera = new WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  490. this._webVRCamera.useStandingMatrix()
  491. this._cameraGazer = new VRExperienceHelperCameraGazer(()=>{return this.currentVRCamera;}, scene);
  492. // Create default button
  493. if (!this._useCustomVRButton) {
  494. this._btnVR = <HTMLButtonElement>document.createElement("BUTTON");
  495. this._btnVR.className = "babylonVRicon";
  496. this._btnVR.id = "babylonVRiconbtn";
  497. this._btnVR.title = "Click to switch to VR";
  498. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  499. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  500. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  501. // css += ".babylonVRicon.vrdisplaysupported { }";
  502. // css += ".babylonVRicon.vrdisplayready { }";
  503. // css += ".babylonVRicon.vrdisplayrequesting { }";
  504. var style = document.createElement('style');
  505. style.appendChild(document.createTextNode(css));
  506. document.getElementsByTagName('head')[0].appendChild(style);
  507. this.moveButtonToBottomRight();
  508. }
  509. // VR button click event
  510. if (this._btnVR) {
  511. this._btnVR.addEventListener("click", () => {
  512. if (!this.isInVRMode) {
  513. this.enterVR();
  514. } else {
  515. this.exitVR();
  516. }
  517. });
  518. }
  519. // Window events
  520. window.addEventListener("resize", this._onResize);
  521. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  522. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  523. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  524. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  525. // Display vr button when headset is connected
  526. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  527. this.displayVRButton();
  528. } else {
  529. this._scene.getEngine().onVRDisplayChangedObservable.add((e) => {
  530. if (e.vrDisplay) {
  531. this.displayVRButton();
  532. }
  533. })
  534. }
  535. // Exiting VR mode using 'ESC' key on desktop
  536. this._onKeyDown = (event: KeyboardEvent) => {
  537. if (event.keyCode === 27 && this.isInVRMode) {
  538. this.exitVR();
  539. }
  540. };
  541. document.addEventListener("keydown", this._onKeyDown);
  542. // Exiting VR mode double tapping the touch screen
  543. this._scene.onPrePointerObservable.add((pointerInfo, eventState) => {
  544. if (this.isInVRMode) {
  545. this.exitVR();
  546. if (this._fullscreenVRpresenting) {
  547. this._scene.getEngine().switchFullscreen(true);
  548. }
  549. }
  550. }, PointerEventTypes.POINTERDOUBLETAP, false);
  551. // Listen for WebVR display changes
  552. this._onVRDisplayChanged = (eventArgs: IDisplayChangedEventArgs) => this.onVRDisplayChanged(eventArgs);
  553. this._onVrDisplayPresentChange = () => this.onVrDisplayPresentChange();
  554. this._onVRRequestPresentStart = () => {
  555. this._webVRrequesting = true;
  556. this.updateButtonVisibility();
  557. }
  558. this._onVRRequestPresentComplete = (success: boolean) => {
  559. this._webVRrequesting = false;
  560. this.updateButtonVisibility();
  561. };
  562. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  563. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  564. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  565. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  566. scene.onDisposeObservable.add(() => {
  567. this.dispose();
  568. })
  569. // Gamepad connection events
  570. this._webVRCamera.onControllerMeshLoadedObservable.add((webVRController) => this._onDefaultMeshLoaded(webVRController));
  571. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  572. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  573. this.updateButtonVisibility();
  574. //create easing functions
  575. this._circleEase = new CircleEase();
  576. this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
  577. }
  578. // Raised when one of the controller has loaded successfully its associated default mesh
  579. private _onDefaultMeshLoaded(webVRController: WebVRController) {
  580. if(this.leftController && this.leftController.webVRController == webVRController){
  581. if(webVRController.mesh){
  582. this.leftController._setLaserPointerParent(webVRController.mesh)
  583. }
  584. }
  585. if(this.rightController && this.rightController.webVRController == webVRController){
  586. if(webVRController.mesh){
  587. this.rightController._setLaserPointerParent(webVRController.mesh)
  588. }
  589. }
  590. try {
  591. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  592. }
  593. catch (err) {
  594. Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  595. }
  596. }
  597. private _onResize = () => {
  598. this.moveButtonToBottomRight();
  599. if (this._fullscreenVRpresenting && this._webVRready) {
  600. this.exitVR();
  601. }
  602. }
  603. private _onFullscreenChange = () => {
  604. if (document.fullscreen !== undefined) {
  605. this._fullscreenVRpresenting = document.fullscreen;
  606. } else if (document.mozFullScreen !== undefined) {
  607. this._fullscreenVRpresenting = document.mozFullScreen;
  608. } else if (document.webkitIsFullScreen !== undefined) {
  609. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  610. } else if (document.msIsFullScreen !== undefined) {
  611. this._fullscreenVRpresenting = document.msIsFullScreen;
  612. }
  613. if (!this._fullscreenVRpresenting && this._canvas) {
  614. this.exitVR();
  615. if (!this._useCustomVRButton) {
  616. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  617. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  618. }
  619. }
  620. }
  621. /**
  622. * Gets a value indicating if we are currently in VR mode.
  623. */
  624. public get isInVRMode(): boolean {
  625. return this._webVRpresenting || this._fullscreenVRpresenting;
  626. }
  627. private onVrDisplayPresentChange() {
  628. var vrDisplay = this._scene.getEngine().getVRDevice();
  629. if (vrDisplay) {
  630. var wasPresenting = this._webVRpresenting;
  631. // A VR display is connected
  632. this._webVRpresenting = vrDisplay.isPresenting;
  633. if (wasPresenting && !this._webVRpresenting)
  634. this.exitVR();
  635. } else {
  636. Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  637. }
  638. this.updateButtonVisibility();
  639. }
  640. private onVRDisplayChanged(eventArgs: IDisplayChangedEventArgs) {
  641. this._webVRsupported = eventArgs.vrSupported;
  642. this._webVRready = !!eventArgs.vrDisplay;
  643. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  644. this.updateButtonVisibility();
  645. }
  646. private moveButtonToBottomRight() {
  647. if (this._canvas && !this._useCustomVRButton) {
  648. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  649. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  650. }
  651. }
  652. private displayVRButton() {
  653. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  654. document.body.appendChild(this._btnVR);
  655. this._btnVRDisplayed = true;
  656. }
  657. }
  658. private updateButtonVisibility() {
  659. if (!this._btnVR || this._useCustomVRButton) {
  660. return;
  661. }
  662. this._btnVR.className = "babylonVRicon";
  663. if (this.isInVRMode) {
  664. this._btnVR.className += " vrdisplaypresenting";
  665. } else {
  666. if (this._webVRready) this._btnVR.className += " vrdisplayready";
  667. if (this._webVRsupported) this._btnVR.className += " vrdisplaysupported";
  668. if (this._webVRrequesting) this._btnVR.className += " vrdisplayrequesting";
  669. }
  670. }
  671. /**
  672. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  673. * Otherwise, will use the fullscreen API.
  674. */
  675. public enterVR() {
  676. if (this.onEnteringVRObservable) {
  677. try {
  678. this.onEnteringVRObservable.notifyObservers(this);
  679. }
  680. catch (err) {
  681. Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  682. }
  683. }
  684. if (this._scene.activeCamera) {
  685. this._position = this._scene.activeCamera.position.clone();
  686. // make sure that we return to the last active camera
  687. this._existingCamera = this._scene.activeCamera;
  688. }
  689. if (this._webVRrequesting)
  690. return;
  691. // If WebVR is supported and a headset is connected
  692. if (this._webVRready) {
  693. if (!this._webVRpresenting) {
  694. this._webVRCamera.position = this._position;
  695. this._scene.activeCamera = this._webVRCamera;
  696. }
  697. }
  698. else if (this._vrDeviceOrientationCamera) {
  699. this._vrDeviceOrientationCamera.position = this._position;
  700. if(this._scene.activeCamera){
  701. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ
  702. }
  703. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  704. this._scene.getEngine().switchFullscreen(true);
  705. this.updateButtonVisibility();
  706. }
  707. if (this._scene.activeCamera && this._canvas) {
  708. this._scene.activeCamera.attachControl(this._canvas);
  709. }
  710. if (this._interactionsEnabled) {
  711. this._scene.registerBeforeRender(this.beforeRender);
  712. }
  713. }
  714. /**
  715. * Attempt to exit VR, or fullscreen.
  716. */
  717. public exitVR() {
  718. if (this.onExitingVRObservable) {
  719. try {
  720. this.onExitingVRObservable.notifyObservers(this);
  721. }
  722. catch (err) {
  723. Tools.Warn("Error in your custom logic onExitingVR: " + err);
  724. }
  725. }
  726. if (this._webVRpresenting) {
  727. this._scene.getEngine().disableVR();
  728. }
  729. if (this._scene.activeCamera) {
  730. this._position = this._scene.activeCamera.position.clone();
  731. }
  732. if (this._deviceOrientationCamera) {
  733. this._deviceOrientationCamera.position = this._position;
  734. this._scene.activeCamera = this._deviceOrientationCamera;
  735. if (this._canvas) {
  736. this._scene.activeCamera.attachControl(this._canvas);
  737. }
  738. } else if (this._existingCamera) {
  739. this._existingCamera.position = this._position;
  740. this._scene.activeCamera = this._existingCamera;
  741. }
  742. this.updateButtonVisibility();
  743. if (this._interactionsEnabled) {
  744. this._scene.unregisterBeforeRender(this.beforeRender);
  745. }
  746. // resize to update width and height when exiting vr exits fullscreen
  747. this._scene.getEngine().resize();
  748. }
  749. /**
  750. * The position of the vr experience helper.
  751. */
  752. public get position(): Vector3 {
  753. return this._position;
  754. }
  755. /**
  756. * Sets the position of the vr experience helper.
  757. */
  758. public set position(value: Vector3) {
  759. this._position = value;
  760. if (this._scene.activeCamera) {
  761. this._scene.activeCamera.position = value;
  762. }
  763. }
  764. /**
  765. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  766. */
  767. public enableInteractions() {
  768. if (!this._interactionsEnabled) {
  769. this._interactionsRequested = true;
  770. if (this.leftController) {
  771. this._enableInteractionOnController(this.leftController)
  772. }
  773. if (this.rightController) {
  774. this._enableInteractionOnController(this.rightController)
  775. }
  776. this.raySelectionPredicate = (mesh) => {
  777. return mesh.isVisible;
  778. }
  779. this.meshSelectionPredicate = (mesh) => {
  780. return true;
  781. }
  782. this._raySelectionPredicate = (mesh) => {
  783. if (this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  784. && mesh.name.indexOf("teleportationTarget") === -1
  785. && mesh.name.indexOf("torusTeleportation") === -1
  786. && mesh.name.indexOf("laserPointer") === -1)) {
  787. return this.raySelectionPredicate(mesh);
  788. }
  789. return false;
  790. }
  791. this._interactionsEnabled = true;
  792. }
  793. }
  794. private beforeRender = () => {
  795. if(this.leftController && this.leftController._activePointer){
  796. this._castRayAndSelectObject(this.leftController);
  797. }
  798. if(this.rightController && this.rightController._activePointer){
  799. this._castRayAndSelectObject(this.rightController);
  800. }
  801. if(!(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer)){
  802. this._castRayAndSelectObject(this._cameraGazer);
  803. }else{
  804. this._cameraGazer._gazeTracker.isVisible = false;
  805. }
  806. }
  807. private _isTeleportationFloor(mesh: AbstractMesh): boolean {
  808. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  809. if (this._floorMeshesCollection[i].id === mesh.id) {
  810. return true;
  811. }
  812. }
  813. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  814. return true;
  815. }
  816. return false;
  817. }
  818. /**
  819. * Adds a floor mesh to be used for teleportation.
  820. * @param floorMesh the mesh to be used for teleportation.
  821. */
  822. public addFloorMesh(floorMesh: Mesh): void {
  823. if (!this._floorMeshesCollection) {
  824. return;
  825. }
  826. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  827. return;
  828. }
  829. this._floorMeshesCollection.push(floorMesh);
  830. }
  831. /**
  832. * Removes a floor mesh from being used for teleportation.
  833. * @param floorMesh the mesh to be removed.
  834. */
  835. public removeFloorMesh(floorMesh: Mesh): void {
  836. if (!this._floorMeshesCollection) {
  837. return
  838. }
  839. const meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  840. if (meshIndex !== -1) {
  841. this._floorMeshesCollection.splice(meshIndex, 1);
  842. }
  843. }
  844. /**
  845. * Enables interactions and teleportation using the VR controllers and gaze.
  846. * @param vrTeleportationOptions options to modify teleportation behavior.
  847. */
  848. public enableTeleportation(vrTeleportationOptions: VRTeleportationOptions = {}) {
  849. if (!this._teleportationInitialized) {
  850. this._teleportationRequested = true;
  851. this.enableInteractions();
  852. if (vrTeleportationOptions.floorMeshName) {
  853. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  854. }
  855. if (vrTeleportationOptions.floorMeshes) {
  856. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  857. }
  858. if (this.leftController != null) {
  859. this._enableTeleportationOnController(this.leftController)
  860. }
  861. if (this.rightController != null) {
  862. this._enableTeleportationOnController(this.rightController)
  863. }
  864. // Creates an image processing post process for the vignette not relying
  865. // on the main scene configuration for image processing to reduce setup and spaces
  866. // (gamma/linear) conflicts.
  867. const imageProcessingConfiguration = new ImageProcessingConfiguration();
  868. imageProcessingConfiguration.vignetteColor = new Color4(0, 0, 0, 0);
  869. imageProcessingConfiguration.vignetteEnabled = true;
  870. this._postProcessMove = new ImageProcessingPostProcess("postProcessMove",
  871. 1.0,
  872. this._webVRCamera,
  873. undefined,
  874. undefined,
  875. undefined,
  876. undefined,
  877. imageProcessingConfiguration);
  878. this._webVRCamera.detachPostProcess(this._postProcessMove)
  879. this._teleportationInitialized = true;
  880. if (this._isDefaultTeleportationTarget) {
  881. this._createTeleportationCircles();
  882. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  883. }
  884. }
  885. }
  886. private _onNewGamepadConnected = (gamepad: Gamepad) => {
  887. if (gamepad.type !== Gamepad.POSE_ENABLED) {
  888. if (gamepad.leftStick) {
  889. gamepad.onleftstickchanged((stickValues) => {
  890. if (this._teleportationInitialized && this.teleportationEnabled) {
  891. // Listening to classic/xbox gamepad only if no VR controller is active
  892. if ((!this.leftController && !this.rightController) ||
  893. ((this.leftController && !this.leftController._activePointer) &&
  894. (this.rightController && !this.rightController._activePointer))) {
  895. this._checkTeleportWithRay(stickValues, this._cameraGazer);
  896. this._checkTeleportBackwards(stickValues, this._cameraGazer);
  897. }
  898. }
  899. });
  900. }
  901. if (gamepad.rightStick) {
  902. gamepad.onrightstickchanged((stickValues) => {
  903. if (this._teleportationInitialized) {
  904. this._checkRotate(stickValues, this._cameraGazer);
  905. }
  906. });
  907. }
  908. if (gamepad.type === Gamepad.XBOX) {
  909. (<Xbox360Pad>gamepad).onbuttondown((buttonPressed: Xbox360Button) => {
  910. if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {
  911. this._cameraGazer._selectionPointerDown();
  912. }
  913. });
  914. (<Xbox360Pad>gamepad).onbuttonup((buttonPressed: Xbox360Button) => {
  915. if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {
  916. this._cameraGazer._selectionPointerUp();
  917. }
  918. });
  919. }
  920. } else {
  921. var webVRController = <WebVRController>gamepad;
  922. var controller = new VRExperienceHelperControllerGazer(webVRController, this._scene, this._cameraGazer._gazeTracker);
  923. if (webVRController.hand === "right" || (this.leftController && this.leftController.webVRController != webVRController)) {
  924. this.rightController = controller;
  925. }else{
  926. this.leftController = controller;
  927. }
  928. this._tryEnableInteractionOnController(controller);
  929. }
  930. }
  931. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  932. private _tryEnableInteractionOnController = (controller: VRExperienceHelperControllerGazer) => {
  933. if (this._interactionsRequested && !controller._interactionsEnabled) {
  934. this._enableInteractionOnController(controller);
  935. }
  936. if (this._teleportationRequested && !controller._teleportationEnabled) {
  937. this._enableTeleportationOnController(controller);
  938. }
  939. }
  940. private _onNewGamepadDisconnected = (gamepad: Gamepad) => {
  941. if (gamepad instanceof WebVRController) {
  942. if (gamepad.hand === "left" && this.leftController != null) {
  943. this.leftController.dispose();
  944. this.leftController = null;
  945. }
  946. if (gamepad.hand === "right" && this.rightController != null) {
  947. this.rightController.dispose();
  948. this.rightController = null;
  949. }
  950. }
  951. }
  952. private _enableInteractionOnController(controller: VRExperienceHelperControllerGazer) {
  953. var controllerMesh = controller.webVRController.mesh;
  954. if (controllerMesh) {
  955. controller._interactionsEnabled = true;
  956. controller._activatePointer();
  957. controller.webVRController.onMainButtonStateChangedObservable.add((stateObject) => {
  958. // Enabling / disabling laserPointer
  959. if (this._displayLaserPointer && stateObject.value === 1) {
  960. if(controller._activePointer){
  961. controller._deactivatePointer();
  962. }else{
  963. controller._activatePointer();
  964. }
  965. if(this.displayGaze){
  966. controller._gazeTracker.isVisible = controller._activePointer;
  967. }
  968. }
  969. });
  970. controller.webVRController.onTriggerStateChangedObservable.add((stateObject) => {
  971. if (!controller._pointerDownOnMeshAsked) {
  972. if (stateObject.value > this._padSensibilityUp) {
  973. controller._selectionPointerDown();
  974. }
  975. } else if (stateObject.value < this._padSensibilityDown) {
  976. controller._selectionPointerUp();
  977. }
  978. });
  979. }
  980. }
  981. private _checkTeleportWithRay(stateObject: StickValues, gazer: VRExperienceHelperGazer) {
  982. // Dont teleport if another gaze already requested teleportation
  983. if(this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated){
  984. return;
  985. }
  986. if (!gazer._teleportationRequestInitiated) {
  987. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  988. gazer._activatePointer();
  989. gazer._teleportationRequestInitiated = true;
  990. }
  991. } else {
  992. // Listening to the proper controller values changes to confirm teleportation
  993. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  994. if(this._teleportActive){
  995. this._teleportCamera(this._haloCenter);
  996. }
  997. gazer._teleportationRequestInitiated = false;
  998. }
  999. }
  1000. }
  1001. private _checkRotate(stateObject: StickValues, gazer:VRExperienceHelperGazer) {
  1002. // Only rotate when user is not currently selecting a teleportation location
  1003. if (gazer._teleportationRequestInitiated) {
  1004. return;
  1005. }
  1006. if (!gazer._rotationLeftAsked) {
  1007. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  1008. gazer._rotationLeftAsked = true;
  1009. if (this._rotationAllowed) {
  1010. this._rotateCamera(false);
  1011. }
  1012. }
  1013. } else {
  1014. if (stateObject.x > -this._padSensibilityDown) {
  1015. gazer._rotationLeftAsked = false;
  1016. }
  1017. }
  1018. if (!gazer._rotationRightAsked) {
  1019. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  1020. gazer._rotationRightAsked = true;
  1021. if (this._rotationAllowed) {
  1022. this._rotateCamera(true);
  1023. }
  1024. }
  1025. } else {
  1026. if (stateObject.x < this._padSensibilityDown) {
  1027. gazer._rotationRightAsked = false;
  1028. }
  1029. }
  1030. }
  1031. private _checkTeleportBackwards(stateObject: StickValues, gazer:VRExperienceHelperGazer) {
  1032. // Only teleport backwards when user is not currently selecting a teleportation location
  1033. if (gazer._teleportationRequestInitiated) {
  1034. return;
  1035. }
  1036. // Teleport backwards
  1037. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  1038. if (!gazer._teleportationBackRequestInitiated) {
  1039. if (!this.currentVRCamera) {
  1040. return;
  1041. }
  1042. // Get rotation and position of the current camera
  1043. var rotation = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  1044. var position = this.currentVRCamera.position;
  1045. // If the camera has device position, use that instead
  1046. if ((<WebVRFreeCamera>this.currentVRCamera).devicePosition && (<WebVRFreeCamera>this.currentVRCamera).deviceRotationQuaternion) {
  1047. rotation = (<WebVRFreeCamera>this.currentVRCamera).deviceRotationQuaternion;
  1048. position = (<WebVRFreeCamera>this.currentVRCamera).devicePosition;
  1049. }
  1050. // Get matrix with only the y rotation of the device rotation
  1051. rotation.toEulerAnglesToRef(this._workingVector);
  1052. this._workingVector.z = 0;
  1053. this._workingVector.x = 0;
  1054. Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  1055. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  1056. // Rotate backwards ray by device rotation to cast at the ground behind the user
  1057. Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  1058. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  1059. var ray = new Ray(position, this._workingVector);
  1060. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  1061. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  1062. this._teleportCamera(hit.pickedPoint);
  1063. }
  1064. gazer._teleportationBackRequestInitiated = true;
  1065. }
  1066. } else {
  1067. gazer._teleportationBackRequestInitiated = false;
  1068. }
  1069. }
  1070. private _enableTeleportationOnController(controller: VRExperienceHelperControllerGazer) {
  1071. var controllerMesh = controller.webVRController.mesh;
  1072. if (controllerMesh) {
  1073. if (!controller._interactionsEnabled) {
  1074. this._enableInteractionOnController(controller);
  1075. }
  1076. controller._interactionsEnabled = true;
  1077. controller._teleportationEnabled = true;
  1078. if (controller.webVRController.controllerType === PoseEnabledControllerType.VIVE) {
  1079. controller._dpadPressed = false;
  1080. controller.webVRController.onPadStateChangedObservable.add((stateObject) => {
  1081. controller._dpadPressed = stateObject.pressed;
  1082. if (!controller._dpadPressed) {
  1083. controller._rotationLeftAsked = false;
  1084. controller._rotationRightAsked = false;
  1085. controller._teleportationBackRequestInitiated = false;
  1086. }
  1087. });
  1088. }
  1089. controller.webVRController.onPadValuesChangedObservable.add((stateObject) => {
  1090. if (this.teleportationEnabled) {
  1091. this._checkTeleportBackwards(stateObject, controller);
  1092. this._checkTeleportWithRay(stateObject, controller);
  1093. }
  1094. this._checkRotate(stateObject, controller);
  1095. });
  1096. }
  1097. }
  1098. private _createTeleportationCircles() {
  1099. this._teleportationTarget = Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  1100. this._teleportationTarget.isPickable = false;
  1101. var length = 512;
  1102. var dynamicTexture = new DynamicTexture("DynamicTexture", length, this._scene, true);
  1103. dynamicTexture.hasAlpha = true;
  1104. var context = dynamicTexture.getContext();
  1105. var centerX = length / 2;
  1106. var centerY = length / 2;
  1107. var radius = 200;
  1108. context.beginPath();
  1109. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  1110. context.fillStyle = this._teleportationFillColor;
  1111. context.fill();
  1112. context.lineWidth = 10;
  1113. context.strokeStyle = this._teleportationBorderColor;
  1114. context.stroke();
  1115. context.closePath();
  1116. dynamicTexture.update();
  1117. var teleportationCircleMaterial = new StandardMaterial("TextPlaneMaterial", this._scene);
  1118. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  1119. this._teleportationTarget.material = teleportationCircleMaterial;
  1120. var torus = Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  1121. torus.isPickable = false;
  1122. torus.parent = this._teleportationTarget;
  1123. var animationInnerCircle = new Animation("animationInnerCircle", "position.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);
  1124. var keys = [];
  1125. keys.push({
  1126. frame: 0,
  1127. value: 0
  1128. });
  1129. keys.push({
  1130. frame: 30,
  1131. value: 0.4
  1132. });
  1133. keys.push({
  1134. frame: 60,
  1135. value: 0
  1136. });
  1137. animationInnerCircle.setKeys(keys);
  1138. var easingFunction = new SineEase();
  1139. easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);
  1140. animationInnerCircle.setEasingFunction(easingFunction);
  1141. torus.animations = [];
  1142. torus.animations.push(animationInnerCircle);
  1143. this._scene.beginAnimation(torus, 0, 60, true);
  1144. this._hideTeleportationTarget();
  1145. }
  1146. private _displayTeleportationTarget() {
  1147. this._teleportActive = true;
  1148. if (this._teleportationInitialized) {
  1149. this._teleportationTarget.isVisible = true;
  1150. if (this._isDefaultTeleportationTarget) {
  1151. (<Mesh>this._teleportationTarget.getChildren()[0]).isVisible = true;
  1152. }
  1153. }
  1154. }
  1155. private _hideTeleportationTarget() {
  1156. this._teleportActive = false;
  1157. if (this._teleportationInitialized) {
  1158. this._teleportationTarget.isVisible = false;
  1159. if (this._isDefaultTeleportationTarget) {
  1160. (<Mesh>this._teleportationTarget.getChildren()[0]).isVisible = false;
  1161. }
  1162. }
  1163. }
  1164. private _rotateCamera(right: boolean) {
  1165. if (!(this.currentVRCamera instanceof FreeCamera)) {
  1166. return;
  1167. }
  1168. if (right) {
  1169. this._rotationAngle++;
  1170. }
  1171. else {
  1172. this._rotationAngle--;
  1173. }
  1174. this.currentVRCamera.animations = [];
  1175. var target = Quaternion.FromRotationMatrix(Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  1176. var animationRotation = new Animation("animationRotation", "rotationQuaternion", 90, Animation.ANIMATIONTYPE_QUATERNION,
  1177. Animation.ANIMATIONLOOPMODE_CONSTANT);
  1178. var animationRotationKeys = [];
  1179. animationRotationKeys.push({
  1180. frame: 0,
  1181. value: this.currentVRCamera.rotationQuaternion
  1182. });
  1183. animationRotationKeys.push({
  1184. frame: 6,
  1185. value: target
  1186. });
  1187. animationRotation.setKeys(animationRotationKeys);
  1188. animationRotation.setEasingFunction(this._circleEase);
  1189. this.currentVRCamera.animations.push(animationRotation);
  1190. this._postProcessMove.animations = [];
  1191. var animationPP = new Animation("animationPP", "vignetteWeight", 90, Animation.ANIMATIONTYPE_FLOAT,
  1192. Animation.ANIMATIONLOOPMODE_CONSTANT);
  1193. var vignetteWeightKeys = [];
  1194. vignetteWeightKeys.push({
  1195. frame: 0,
  1196. value: 0
  1197. });
  1198. vignetteWeightKeys.push({
  1199. frame: 3,
  1200. value: 4
  1201. });
  1202. vignetteWeightKeys.push({
  1203. frame: 6,
  1204. value: 0
  1205. });
  1206. animationPP.setKeys(vignetteWeightKeys);
  1207. animationPP.setEasingFunction(this._circleEase);
  1208. this._postProcessMove.animations.push(animationPP);
  1209. var animationPP2 = new Animation("animationPP2", "vignetteStretch", 90, Animation.ANIMATIONTYPE_FLOAT,
  1210. Animation.ANIMATIONLOOPMODE_CONSTANT);
  1211. var vignetteStretchKeys = [];
  1212. vignetteStretchKeys.push({
  1213. frame: 0,
  1214. value: 0
  1215. });
  1216. vignetteStretchKeys.push({
  1217. frame: 3,
  1218. value: 10
  1219. });
  1220. vignetteStretchKeys.push({
  1221. frame: 6,
  1222. value: 0
  1223. });
  1224. animationPP2.setKeys(vignetteStretchKeys);
  1225. animationPP2.setEasingFunction(this._circleEase);
  1226. this._postProcessMove.animations.push(animationPP2);
  1227. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  1228. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  1229. this._postProcessMove.samples = 4;
  1230. this._webVRCamera.attachPostProcess(this._postProcessMove)
  1231. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, () => {
  1232. this._webVRCamera.detachPostProcess(this._postProcessMove)
  1233. });
  1234. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  1235. }
  1236. private _moveTeleportationSelectorTo(hit: PickingInfo, gazer:VRExperienceHelperGazer, ray: Ray) {
  1237. if (hit.pickedPoint) {
  1238. if (gazer._teleportationRequestInitiated) {
  1239. this._displayTeleportationTarget();
  1240. this._haloCenter.copyFrom(hit.pickedPoint);
  1241. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  1242. }
  1243. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  1244. if (pickNormal) {
  1245. var axis1 = Vector3.Cross(Axis.Y, pickNormal);
  1246. var axis2 = Vector3.Cross(pickNormal, axis1);
  1247. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  1248. }
  1249. this._teleportationTarget.position.y += 0.1;
  1250. }
  1251. }
  1252. private _workingVector = Vector3.Zero();
  1253. private _workingQuaternion = Quaternion.Identity();
  1254. private _workingMatrix = Matrix.Identity();
  1255. private _teleportCamera(location: Vector3) {
  1256. if (!(this.currentVRCamera instanceof FreeCamera)) {
  1257. return;
  1258. }
  1259. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  1260. // offset of the headset from the anchor.
  1261. if (this.webVRCamera.leftCamera) {
  1262. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  1263. this._workingVector.subtractInPlace(this.webVRCamera.position);
  1264. location.subtractToRef(this._workingVector, this._workingVector);
  1265. } else {
  1266. this._workingVector.copyFrom(location);
  1267. }
  1268. // Add height to account for user's height offset
  1269. if (this.isInVRMode) {
  1270. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  1271. } else {
  1272. this._workingVector.y += this._defaultHeight;
  1273. }
  1274. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  1275. // Create animation from the camera's position to the new location
  1276. this.currentVRCamera.animations = [];
  1277. var animationCameraTeleportation = new Animation("animationCameraTeleportation", "position", 90, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
  1278. var animationCameraTeleportationKeys = [{
  1279. frame: 0,
  1280. value: this.currentVRCamera.position
  1281. },
  1282. {
  1283. frame: 11,
  1284. value: this._workingVector
  1285. }
  1286. ];
  1287. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  1288. animationCameraTeleportation.setEasingFunction(this._circleEase);
  1289. this.currentVRCamera.animations.push(animationCameraTeleportation);
  1290. this._postProcessMove.animations = [];
  1291. var animationPP = new Animation("animationPP", "vignetteWeight", 90, Animation.ANIMATIONTYPE_FLOAT,
  1292. Animation.ANIMATIONLOOPMODE_CONSTANT);
  1293. var vignetteWeightKeys = [];
  1294. vignetteWeightKeys.push({
  1295. frame: 0,
  1296. value: 0
  1297. });
  1298. vignetteWeightKeys.push({
  1299. frame: 5,
  1300. value: 8
  1301. });
  1302. vignetteWeightKeys.push({
  1303. frame: 11,
  1304. value: 0
  1305. });
  1306. animationPP.setKeys(vignetteWeightKeys);
  1307. this._postProcessMove.animations.push(animationPP);
  1308. var animationPP2 = new Animation("animationPP2", "vignetteStretch", 90, Animation.ANIMATIONTYPE_FLOAT,
  1309. Animation.ANIMATIONLOOPMODE_CONSTANT);
  1310. var vignetteStretchKeys = [];
  1311. vignetteStretchKeys.push({
  1312. frame: 0,
  1313. value: 0
  1314. });
  1315. vignetteStretchKeys.push({
  1316. frame: 5,
  1317. value: 10
  1318. });
  1319. vignetteStretchKeys.push({
  1320. frame: 11,
  1321. value: 0
  1322. });
  1323. animationPP2.setKeys(vignetteStretchKeys);
  1324. this._postProcessMove.animations.push(animationPP2);
  1325. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  1326. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  1327. this._webVRCamera.attachPostProcess(this._postProcessMove)
  1328. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, () => {
  1329. this._webVRCamera.detachPostProcess(this._postProcessMove)
  1330. });
  1331. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, () => {
  1332. this.onAfterCameraTeleport.notifyObservers(this._workingVector);
  1333. });
  1334. this._hideTeleportationTarget();
  1335. }
  1336. private _convertNormalToDirectionOfRay(normal:Nullable<Vector3>, ray:Ray){
  1337. if(normal){
  1338. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  1339. if(angle < Math.PI/2){
  1340. normal.scaleInPlace(-1);
  1341. }
  1342. }
  1343. return normal;
  1344. }
  1345. private _castRayAndSelectObject(gazer:VRExperienceHelperGazer) {
  1346. if (!(this.currentVRCamera instanceof FreeCamera)) {
  1347. return;
  1348. }
  1349. var ray = gazer._getForwardRay(this._rayLength);
  1350. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  1351. // Moving the gazeTracker on the mesh face targetted
  1352. if (hit && hit.pickedPoint) {
  1353. if (this._displayGaze) {
  1354. let multiplier = 1;
  1355. gazer._gazeTracker.isVisible = true;
  1356. if (gazer._isActionableMesh) {
  1357. multiplier = 3;
  1358. }
  1359. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  1360. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  1361. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  1362. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  1363. // To avoid z-fighting
  1364. let deltaFighting = 0.002;
  1365. if (pickNormal) {
  1366. var axis1 = Vector3.Cross(Axis.Y, pickNormal);
  1367. var axis2 = Vector3.Cross(pickNormal, axis1);
  1368. Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  1369. }
  1370. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  1371. if (gazer._gazeTracker.position.x < 0) {
  1372. gazer._gazeTracker.position.x += deltaFighting;
  1373. }
  1374. else {
  1375. gazer._gazeTracker.position.x -= deltaFighting;
  1376. }
  1377. if (gazer._gazeTracker.position.y < 0) {
  1378. gazer._gazeTracker.position.y += deltaFighting;
  1379. }
  1380. else {
  1381. gazer._gazeTracker.position.y -= deltaFighting;
  1382. }
  1383. if (gazer._gazeTracker.position.z < 0) {
  1384. gazer._gazeTracker.position.z += deltaFighting;
  1385. }
  1386. else {
  1387. gazer._gazeTracker.position.z -= deltaFighting;
  1388. }
  1389. }
  1390. // Changing the size of the laser pointer based on the distance from the targetted point
  1391. gazer._updatePointerDistance(hit.distance);
  1392. }
  1393. else {
  1394. gazer._updatePointerDistance();
  1395. gazer._gazeTracker.isVisible = false;
  1396. }
  1397. if (hit && hit.pickedMesh) {
  1398. gazer._currentHit = hit;
  1399. if (gazer._pointerDownOnMeshAsked) {
  1400. this._scene.simulatePointerMove(gazer._currentHit, {pointerId: gazer._id});
  1401. }
  1402. // The object selected is the floor, we're in a teleportation scenario
  1403. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  1404. // Moving the teleportation area to this targetted point
  1405. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  1406. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  1407. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  1408. }
  1409. gazer._currentMeshSelected = null;
  1410. if(gazer._teleportationRequestInitiated){
  1411. this._moveTeleportationSelectorTo(hit, gazer, ray);
  1412. }
  1413. return;
  1414. }
  1415. // If not, we're in a selection scenario
  1416. //this._teleportationAllowed = false;
  1417. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  1418. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  1419. this.onNewMeshPicked.notifyObservers(hit);
  1420. gazer._currentMeshSelected = hit.pickedMesh;
  1421. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  1422. this.changeGazeColor(new Color3(0, 0, 1));
  1423. this.changeLaserColor(new Color3(0.2, 0.2, 1));
  1424. gazer._isActionableMesh = true;
  1425. }
  1426. else {
  1427. this.changeGazeColor(new Color3(0.7, 0.7, 0.7));
  1428. this.changeLaserColor(new Color3(0.7, 0.7, 0.7));
  1429. gazer._isActionableMesh = false;
  1430. }
  1431. try {
  1432. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  1433. }
  1434. catch (err) {
  1435. Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  1436. }
  1437. }
  1438. else {
  1439. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  1440. gazer._currentMeshSelected = null;
  1441. this.changeGazeColor(new Color3(0.7, 0.7, 0.7));
  1442. this.changeLaserColor(new Color3(0.7, 0.7, 0.7));
  1443. }
  1444. }
  1445. }
  1446. else {
  1447. gazer._currentHit = null;
  1448. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  1449. gazer._currentMeshSelected = null;
  1450. //this._teleportationAllowed = false;
  1451. this.changeGazeColor(new Color3(0.7, 0.7, 0.7));
  1452. this.changeLaserColor(new Color3(0.7, 0.7, 0.7));
  1453. }
  1454. }
  1455. private _notifySelectedMeshUnselected(mesh:Nullable<AbstractMesh>) {
  1456. if(mesh) {
  1457. this.onSelectedMeshUnselected.notifyObservers(mesh);
  1458. }
  1459. }
  1460. /**
  1461. * Sets the color of the laser ray from the vr controllers.
  1462. * @param color new color for the ray.
  1463. */
  1464. public changeLaserColor(color: Color3) {
  1465. if (this.leftController) {
  1466. this.leftController._setLaserPointerColor(color);
  1467. }
  1468. if (this.rightController) {
  1469. this.rightController._setLaserPointerColor(color);
  1470. }
  1471. }
  1472. /**
  1473. * Sets the color of the ray from the vr headsets gaze.
  1474. * @param color new color for the ray.
  1475. */
  1476. public changeGazeColor(color: Color3) {
  1477. if(!(<StandardMaterial>this._cameraGazer._gazeTracker.material)){
  1478. return;
  1479. }
  1480. (<StandardMaterial>this._cameraGazer._gazeTracker.material).emissiveColor = color;
  1481. if(this.leftController){
  1482. (<StandardMaterial>this.leftController._gazeTracker.material).emissiveColor = color;
  1483. }
  1484. if(this.rightController){
  1485. (<StandardMaterial>this.rightController._gazeTracker.material).emissiveColor = color;
  1486. }
  1487. }
  1488. /**
  1489. * Exits VR and disposes of the vr experience helper
  1490. */
  1491. public dispose() {
  1492. if (this.isInVRMode) {
  1493. this.exitVR();
  1494. }
  1495. if (this._postProcessMove) {
  1496. this._postProcessMove.dispose();
  1497. }
  1498. if (this._webVRCamera) {
  1499. this._webVRCamera.dispose();
  1500. }
  1501. if (this._vrDeviceOrientationCamera) {
  1502. this._vrDeviceOrientationCamera.dispose();
  1503. }
  1504. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  1505. document.body.removeChild(this._btnVR);
  1506. }
  1507. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  1508. this._deviceOrientationCamera.dispose();
  1509. }
  1510. if (this._cameraGazer) {
  1511. this._cameraGazer.dispose();
  1512. }
  1513. if (this.leftController) {
  1514. this.leftController.dispose();
  1515. }
  1516. if (this.rightController) {
  1517. this.rightController.dispose();
  1518. }
  1519. if (this._teleportationTarget) {
  1520. this._teleportationTarget.dispose();
  1521. }
  1522. this._floorMeshesCollection = [];
  1523. document.removeEventListener("keydown", this._onKeyDown);
  1524. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1525. window.removeEventListener("resize", this._onResize);
  1526. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  1527. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  1528. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  1529. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  1530. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  1531. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  1532. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  1533. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1534. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  1535. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  1536. this._scene.unregisterBeforeRender(this.beforeRender);
  1537. }
  1538. /**
  1539. * Gets the name of the VRExperienceHelper class
  1540. * @returns "VRExperienceHelper"
  1541. */
  1542. public getClassName(): string {
  1543. return "VRExperienceHelper";
  1544. }
  1545. }
  1546. }