babylon.vrExperienceHelper.ts 78 KB

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